From 7882c08bd480e3c4c2560a9c85fb4873400c2cd6 Mon Sep 17 00:00:00 2001 From: Noam Alum Date: Mon, 9 Nov 2026 16:27:05 +0200 Subject: [PATCH] fix(provider): remove provider-owned profile claims --- .claude/PROVIDER_AUTHORING_VISION.md | 43 +++------ .../scenarios/operation/admission/verify.py | 15 ---- CLAUDE.md | 6 +- docs/index.md | 5 +- docs/manifest-authoring.md | 38 ++++---- docs/operation-admission.md | 1 - docs/reference/provider.md | 2 +- pyproject.toml | 2 +- .../_services/manifest/declaration.py | 15 +--- .../_services/operation_admission/service.py | 18 ---- src/stateforge_provider/declarations.py | 7 -- tests/fixtures/manifest/response.json | 5 +- .../fixtures/manifest/revision-preimage.json | 2 +- tests/test_ci_automation.py | 1 - tests/test_manifest.py | 89 +++++++++++-------- tests/test_operation_admission.py | 80 ++++++++++++++--- uv.lock | 4 +- 17 files changed, 160 insertions(+), 173 deletions(-) diff --git a/.claude/PROVIDER_AUTHORING_VISION.md b/.claude/PROVIDER_AUTHORING_VISION.md index 9178e16..159c8ee 100644 --- a/.claude/PROVIDER_AUTHORING_VISION.md +++ b/.claude/PROVIDER_AUTHORING_VISION.md @@ -187,42 +187,25 @@ The runtime owns deadlines, cancellation, session and manifest fencing, readiness checks, deterministic result ordering, and final response validation. -## Backup and disaster-recovery compliance +## Profile matching ownership -Backup and disaster recovery are predefined compliance profiles over generic -operations, not special transport commands. Compliance is always explicit. +Providers expose concrete operations and triggers with schemas derived from +their typed models. They do not declare Profile claims or maintain a Profile +registry. The Control Plane owns Profiles, schema-based compatibility, field +mappings, Contracts, and fulfillment once schemas arrive through SF-AOP. +Compatibility depends on types and constraints rather than identical property +names. Matching names can map automatically, differing names can receive +suggested mappings, extra fields do not automatically disqualify compatibility, +and partial matches remain discoverable. -```python -@operation( - "git.create_backup_reference", - implements="stateforge.backup.v1.prepare", -) -async def create_backup_reference(...): - ... -``` - -```python -@operation( - "git.reconstruct_repository", - implements="stateforge.disaster_recovery.v1.reconstruct", -) -async def reconstruct_repository(...): - ... -``` - -The runtime validates the claimed profile and publishes it in the Provider -manifest. It must never infer compliance from a method name. - -BackupEngine remains an Agent-side tool. A compliant Provider prepares staged -data or returns a supported Provider reference. During disaster recovery, the -Agent restores stored data into an Agent-managed staging workspace and asks -the Provider to reconstruct and verify the third-party component. The Provider -does not receive a generic restore command. +The Provider runtime validates actual inputs, successful results, and trigger +events against the declared concrete schemas. Schema defaults remain +annotations and do not materialize missing request values. ## Manifest ownership Provider authors declare metadata, operations, trigger types, model schemas, -static or dynamically checked runtime requirements, and compliance roles +static or dynamically checked runtime requirements through the public Python API. They do not construct the wire manifest manually. Operation-to-check associations stay private to the Provider runtime; schema-1 manifests publish only the existing static requirement diff --git a/.github/actions/scenarios/operation/admission/verify.py b/.github/actions/scenarios/operation/admission/verify.py index 856aff6..c452673 100644 --- a/.github/actions/scenarios/operation/admission/verify.py +++ b/.github/actions/scenarios/operation/admission/verify.py @@ -119,7 +119,6 @@ async def ready(self) -> RequirementCheckResult: @operation( "stateforge.test/execute@1", requires=("runtime.ready",), - implements=("stateforge.test.v1.audited",), ) async def execute( self, @@ -149,7 +148,6 @@ def _request( value: int = 1, secret: str | None = None, generation: int | None = None, - roles: tuple[str, ...] = ("stateforge.test.v1.audited",), payload_fields: dict[str, str | int | bool | None] | None = None, mode: operation_admission_pb2.AdmissionMode.ValueType = ( operation_admission_pb2.ADMISSION_MODE_ADMIT_OR_RESOLVE @@ -189,7 +187,6 @@ def _request( ), contract=operation_admission_pb2.OperationContractContext( manifest_revision=manifest.manifest_revision, - required_implementation_roles=roles, ), execution_context=execution_context, ), @@ -703,17 +700,6 @@ async def _run( # noqa: PLR0912, PLR0915 grpc.StatusCode.FAILED_PRECONDITION, operation_admission_pb2.ADMISSION_ERROR_REASON_OPERATION_PRECONDITION_FAILED, ) - role_status = await _expect_error( - admission, - _request( - handshake, - manifest, - operation_id=str(uuid4()), - roles=("stateforge.test.v1.missing",), - ), - grpc.StatusCode.FAILED_PRECONDITION, - operation_admission_pb2.ADMISSION_ERROR_REASON_OPERATION_INCOMPATIBLE, - ) provider.requirement_satisfied = False requirement_status = await _expect_error( admission, @@ -814,7 +800,6 @@ async def _run( # noqa: PLR0912, PLR0915 "resolved_existing": len(responses) - accepted_new, "author_dispatches": provider.dispatches, "stale_fence_status": stale_status, - "missing_role_status": role_status, "requirement_status": requirement_status, "idempotency_conflict_status": conflict_status, "immutable_context": True, diff --git a/CLAUDE.md b/CLAUDE.md index bab4ecc..be472ca 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -90,9 +90,9 @@ construction, dispatch, and error translation belong to the runtime. Do not make authors pass or manipulate those internal values through the normal public API. -Backup and disaster-recovery support remains an explicit compliance claim over -generic decorated operations. Never infer compliance from method names and -never move BackupEngine behavior into a Provider. +Provider authors expose concrete operation and trigger schemas. The Control +Plane owns schema-based Profile matching and fulfillment; Providers publish +no Profile claims. Never infer compliance from method names. ## Provider runtime invariants diff --git a/docs/index.md b/docs/index.md index 9a64c27..c316520 100644 --- a/docs/index.md +++ b/docs/index.md @@ -49,7 +49,7 @@ if __name__ == "__main__": ``` See [Manifest declarations](manifest-authoring.md) for typed operation models, -triggers, configuration schemas, requirements, and explicit compliance roles. +triggers, configuration schemas, and runtime requirements. See [Health and readiness](health-reporting.md) for fail-closed lifecycle states and event-driven health updates. See [Trigger publication](trigger-publication.md) for continuous decorated @@ -57,8 +57,7 @@ sources, callback-driven events, acknowledgement receipts, and retry behavior. An application that already owns an event loop calls `await GitProvider().serve()` instead. See `.claude/PROVIDER_AUTHORING_VISION.md` for the complete intended author -experience, including operation execution and compliance profiles, which land -incrementally as their SFP procedures do. +experience and the Control Plane’s ownership of Profile matching. See [Process lifecycle and exit behavior](process-lifecycle.md) for the standard `run()` process contract, graceful signal handling, embedded diff --git a/docs/manifest-authoring.md b/docs/manifest-authoring.md index dcddb03..6feb398 100644 --- a/docs/manifest-authoring.md +++ b/docs/manifest-authoring.md @@ -120,7 +120,7 @@ at module scope or declared on the Provider class. Operation and trigger identifiers use `namespace/name@major`, with at least two lowercase dotted namespace segments and a positive major version. An incompatible input/result contract requires a new identifier version. -Use tuples for platforms, requirements, triggers, and roles. +Use tuples for platforms, requirements, and triggers. Plain `runtime_requirements` declarations are descriptive. Requirements declared by `@requirement_check` add an author-owned, dynamic inspection while publishing the same static metadata through the schema-1 @@ -178,29 +178,23 @@ duplicated, metadata exceeds Protocol bounds, the method is not async with an exact `(self)` signature and result annotation, or an operation has a missing, duplicate, or oversized requirement reference set. -## Compliance claims +## Profile matching ownership -Supply roles explicitly on the decorated operation: +Providers publish concrete operation input/result schemas and trigger payload +schemas derived from their typed models. Operation declarations contain only +`inputSchema` and `resultSchema`; Providers declare no Profile claims. -```python -@operation( - "example.reference/prepare@1", - implements=("stateforge.backup.v1.prepare",), -) -async def prepare(self, request: PrepareInput) -> PrepareResult: ... -``` - -This illustrates claim syntax: `PrepareInput` and `PrepareResult` must come -from the exact versioned profile when that profile lands. P1 transports and -structurally validates role claims; it does not define the later P6/P7 profile -schemas. R1 consequently cannot certify backup or DR compliance. Unknown -dotted roles are transported as claims too. A consumer must validate known -roles against the matching profile before using them as compliance evidence. +The Control Plane will assess Profile compatibility from these schemas once +SF-AOP supplies them. Matching uses types and constraints, without requiring +property names to equal Profile names. Matching names can be mapped +automatically; differing names can receive suggested field mappings. Extra +inputs or outputs do not automatically disqualify an operation when the +required Profile types are present, and partial matches remain discoverable. +Providers do not implement matching, mappings, or Contract fulfillment. -Names, method bodies, docstrings, and schema payloads never imply compliance. -Every operation has only input schema, result schema, and `implements` roles. -There is no separate backup source mode, BackupEngine configuration, or -storage routing declaration. +Schema defaults remain annotations. They do not materialize omitted request +values or bypass requiredness and validation of actual inputs, successful +results, or trigger events. ## Schema safety and limits @@ -222,7 +216,7 @@ numbers, and integers outside RFC 8785's exact integer range fail validation. P1 limits are 8 KiB per wire request, 2 MiB per wire response, 1 MiB per canonical revision preimage, 1,024 entries per operation/trigger/requirement -map, 256 platform pairs, 64 roles per operation, and 64 containers of embedded +map, 256 platform pairs, and 64 containers of embedded nesting. This runtime additionally caps JSON at 65,536 nodes per checked document, embedded schemas at 4,096 schema nodes each, and combined generated schema bytes at 1 MiB. It applies these bounds before diff --git a/docs/operation-admission.md b/docs/operation-admission.md index 302c51d..33e442f 100644 --- a/docs/operation-admission.md +++ b/docs/operation-admission.md @@ -50,7 +50,6 @@ class ServiceProvider(Provider): @operation( "example.systemd/restart@1", requires=("runtime.systemd.control",), - implements=("example.service.v1.restart",), cancellable=True, progress=OperationProgressPolicy.determinate(), ) diff --git a/docs/reference/provider.md b/docs/reference/provider.md index 7aa595b..3dbed89 100644 --- a/docs/reference/provider.md +++ b/docs/reference/provider.md @@ -25,7 +25,7 @@ evidence only: it neither executes nor authorizes an operation. `Provider` also registers the private P4 Operation Admission service. The runtime validates the exact endpoint, session, accepted manifest, operation -declaration, payload schema, requested implementation roles, current Health, +declaration, payload schema, current Health, execution deadline, and fresh requirement-check results. It atomically records the canonical request fingerprint before scheduling author code, so concurrent identical retries dispatch exactly once and changed content is rejected. diff --git a/pyproject.toml b/pyproject.toml index a8ee531..18164c9 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -70,7 +70,7 @@ environments = ["python_version == '3.13'"] [tool.uv.sources] -stateforge-protocol = { git = "https://github.com/stateforge-org/stateforge-protocol.git", rev = "64514b35dabfe88d49aabfb63d756e98a97fe5dc" } +stateforge-protocol = { git = "https://github.com/stateforge-org/stateforge-protocol.git", rev = "0dab0576d884ae10f3bef0135b641168234b18b6" } [tool.hatch.build.targets.wheel] diff --git a/src/stateforge_provider/_services/manifest/declaration.py b/src/stateforge_provider/_services/manifest/declaration.py index 896f222..cc2abad 100644 --- a/src/stateforge_provider/_services/manifest/declaration.py +++ b/src/stateforge_provider/_services/manifest/declaration.py @@ -55,7 +55,6 @@ class OperationDeclaration: method_name: str request_model: type[ProviderModel] result_model: type[ProviderModel] - implements: tuple[str, ...] requires: tuple[str, ...] accepts_context: bool cancellable: bool @@ -100,7 +99,7 @@ def _sequence(owner: type, name: str, limit: int) -> tuple[Any, ...]: # Keep discovery and its rejection rules adjacent. -def _operations( # noqa: PLR0912 +def _operations( owner: type, limits: ProviderRuntimeLimits, ) -> tuple[dict[str, Any], tuple[OperationDeclaration, ...]]: @@ -171,16 +170,6 @@ def _operations( # noqa: PLR0912 f"{path}: cancellation and progress policies require " "OperationContext" ) - roles = metadata.implements - if ( - not isinstance(roles, tuple) - or len(roles) > manifest_contract.MAX_PROFILE_CLAIMS_PER_OPERATION - ): - raise ManifestError(f"{path}.implements: must be a bounded tuple") - for role in roles: - validate_structure(role, "dottedIdentifier", f"{path}.implements") - if len(set(roles)) != len(roles): - raise ManifestError(f"{path}.implements: duplicate role") input_schema = _model_schema( request_model, f"{path}.input", @@ -196,7 +185,6 @@ def _operations( # noqa: PLR0912 declarations[metadata.identifier] = { "inputSchema": input_schema, "resultSchema": result_schema, - "implements": sorted(roles), } runtime_declarations.append( OperationDeclaration( @@ -204,7 +192,6 @@ def _operations( # noqa: PLR0912 method_name=method_name, request_model=request_model, result_model=result_model, - implements=tuple(sorted(roles)), requires=metadata.requires, accepts_context=accepts_context, cancellable=metadata.cancellable, diff --git a/src/stateforge_provider/_services/operation_admission/service.py b/src/stateforge_provider/_services/operation_admission/service.py index e77579c..ebf1e87 100644 --- a/src/stateforge_provider/_services/operation_admission/service.py +++ b/src/stateforge_provider/_services/operation_admission/service.py @@ -114,7 +114,6 @@ async def StartOperation( # noqa: N802, PLR0912 ), ) try: - self._validate_contract(invocation, operation) payload = self._validate_payload(invocation, operation) except AdmissionFailureError as failure: await self._reject(context, failure) @@ -277,23 +276,6 @@ async def _validate_fences( ) return session - def _validate_contract( - self, - invocation: operation_admission_pb2.OperationInvocation, - operation: BoundOperation, - ) -> None: - """Validate requested profile claims against the accepted manifest.""" - if any( - role not in operation.declaration.implements - for role in invocation.contract.required_implementation_roles - ): - raise AdmissionFailureError( - grpc.StatusCode.FAILED_PRECONDITION, - operation_admission_pb2.ADMISSION_ERROR_REASON_OPERATION_INCOMPATIBLE, - "Operation requires an undeclared implementation role", - invocation.operation_id, - ) - def _validate_payload( self, invocation: operation_admission_pb2.OperationInvocation, diff --git a/src/stateforge_provider/declarations.py b/src/stateforge_provider/declarations.py index 8a1439a..654d773 100644 --- a/src/stateforge_provider/declarations.py +++ b/src/stateforge_provider/declarations.py @@ -54,7 +54,6 @@ class Trigger: @dataclass(frozen=True, slots=True) class _Operation: identifier: str - implements: tuple[str, ...] requires: tuple[str, ...] cancellable: bool progress: OperationProgressPolicy | None @@ -106,7 +105,6 @@ def _effective_methods( def operation( identifier: str, *, - implements: tuple[str, ...] = (), requires: tuple[str, ...] = (), cancellable: bool = False, progress: OperationProgressPolicy | None = None, @@ -116,10 +114,6 @@ def operation( Annotate ``request`` and the return value with ProviderModel subclasses. The runtime derives the manifest schemas from those annotations and invokes the method only after canonical Operation Admission succeeds. - ``implements`` contains versioned semantic/compliance profile claims. Each - claim says the operation conforms to that profile's required schemas and - behavior. Claims are not permissions or Control Plane contract identifiers - and are never inferred from a method or model name. ``requires`` contains stable IDs declared by :func:`requirement_check`. The runtime evaluates each distinct check once per assessment or admission attempt. @@ -144,7 +138,6 @@ def decorate(handler: _Handler) -> _Handler: "__stateforge_operation__", _Operation( identifier, - implements, requires, cancellable, progress, diff --git a/tests/fixtures/manifest/response.json b/tests/fixtures/manifest/response.json index ba16216..e9f090b 100644 --- a/tests/fixtures/manifest/response.json +++ b/tests/fixtures/manifest/response.json @@ -19,8 +19,7 @@ "type": "object", "properties": {}, "additionalProperties": false - }, - "implements": [] + } } }, "runtimeRequirements": { @@ -54,6 +53,6 @@ }, "triggers": {} }, - "manifestRevision": "sha256:6bfdf3aedc2d4e45d77d4787cc0e744a488208b2510d81788291f51d24a623e8", + "manifestRevision": "sha256:aa27f0fddaa13df211bd3e4e4e4230cdda42d9188d4b480d196c2e0de2d20cdb", "sessionId": "manifest-session-A" } diff --git a/tests/fixtures/manifest/revision-preimage.json b/tests/fixtures/manifest/revision-preimage.json index 84936ec..9ef598b 100644 --- a/tests/fixtures/manifest/revision-preimage.json +++ b/tests/fixtures/manifest/revision-preimage.json @@ -1 +1 @@ -{"manifest":{"configurationSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"repository":{"type":"string"},"token":{"type":"string","writeOnly":true}},"required":["repository"],"type":"object"},"displayName":"Git Provider","implementationVersion":"1.0.0","operations":{"stateforge.git/reference.resolve@1":{"implements":[],"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{},"type":"object"},"resultSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{},"type":"object"}}},"platforms":[{"architecture":"x86_64","operatingSystem":"linux"}],"providerIdentity":"stateforge.git","runtimeRequirements":{"executable.git":{"description":"Git executable available to the Provider","versionConstraint":">=2.40"}},"triggers":{}},"manifestSchemaVersion":1,"providerInstanceId":"7f7db7d8-68b4-4f71-9769-065b5c4f941c"} \ No newline at end of file +{"manifest":{"configurationSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"repository":{"type":"string"},"token":{"type":"string","writeOnly":true}},"required":["repository"],"type":"object"},"displayName":"Git Provider","implementationVersion":"1.0.0","operations":{"stateforge.git/reference.resolve@1":{"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{},"type":"object"},"resultSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{},"type":"object"}}},"platforms":[{"architecture":"x86_64","operatingSystem":"linux"}],"providerIdentity":"stateforge.git","runtimeRequirements":{"executable.git":{"description":"Git executable available to the Provider","versionConstraint":">=2.40"}},"triggers":{}},"manifestSchemaVersion":1,"providerInstanceId":"7f7db7d8-68b4-4f71-9769-065b5c4f941c"} \ No newline at end of file diff --git a/tests/test_ci_automation.py b/tests/test_ci_automation.py index 244c599..b55f281 100644 --- a/tests/test_ci_automation.py +++ b/tests/test_ci_automation.py @@ -382,7 +382,6 @@ def test_operation_admission_keeps_the_focused_protocol_peer() -> None: "resolved_existing", "author_dispatches", "stale_fence_status", - "missing_role_status", "requirement_status", "idempotency_conflict_status", "immutable_context", diff --git a/tests/test_manifest.py b/tests/test_manifest.py index 75b2b36..4bfc64c 100644 --- a/tests/test_manifest.py +++ b/tests/test_manifest.py @@ -10,6 +10,7 @@ import pytest from google.protobuf.json_format import MessageToDict +from jsonschema import Draft202012Validator from pydantic import ConfigDict, Field, SecretStr from stateforge_protocol.sfp.manifest.v1 import contract as manifest_contract from stateforge_protocol.sfp.manifest.v1.validation import ( @@ -49,6 +50,10 @@ class _Result(ProviderModel): resolved: str +class _Nested(ProviderModel): + items: list[_Result] + + class _Configuration(ProviderModel): token: SecretStr endpoint: str @@ -72,20 +77,11 @@ class _Representative(_Minimal): async def resolve(self, request: _Input) -> _Result: raise AssertionError("Manifest discovery must not invoke operations") - @operation( - "example.reference/prepare@1", - implements=( - "stateforge.backup.v1.prepare", - "example.reference.custom", - ), - ) + @operation("example.reference/prepare@1") async def prepare(self, request: _Input) -> _Result: - raise AssertionError("No profile execution in R1") + raise AssertionError("Manifest discovery must not invoke operations") - @operation( - "example.reference/reconstruct@1", - implements=("stateforge.disaster_recovery.v1.reconstruct",), - ) + @operation("example.reference/reconstruct@1") async def reconstruct(self, request: _Input) -> _Result: raise AssertionError("No DR execution in R1") @@ -124,18 +120,16 @@ def test_minimal_and_representative_provider_authoring(): ]["type"] == "object" ) - assert set(declaration["operations"]["example.reference/prepare@1"]) == { - "inputSchema", - "resultSchema", - "implements", - } - assert not declaration["operations"]["example.reference/resolve@1"][ - "implements" - ] assert all( - set(operation) == {"inputSchema", "resultSchema", "implements"} + set(operation) == {"inputSchema", "resultSchema"} for operation in declaration["operations"].values() ) + assert all( + not hasattr(item, "implements") + for item in ManifestDeclaration.discover( + _Representative + ).operation_declarations + ) def test_decorated_trigger_source_joins_the_single_manifest_catalog(): @@ -258,24 +252,12 @@ def test_rejects_invalid_static_metadata(field, value): @pytest.mark.parametrize( - ("identifier", "roles"), - [ - ("wrong", ()), - ("example.reference/resolve@0", ()), - ("example.reference/resolve@01", ()), - ("example.reference/resolve@1", ("wrong",)), - ("example.reference/resolve@1", ("example.role.claim",) * 2), - ( - "example.reference/resolve@1", - ("example.role.claim",) - * (manifest_contract.MAX_PROFILE_CLAIMS_PER_OPERATION + 1), - ), - ("example.reference/resolve@1", "example.role.claim"), - ], + "identifier", + ["wrong", "example.reference/resolve@0", "example.reference/resolve@01"], ) -def test_rejects_invalid_operations_and_roles(identifier, roles): +def test_rejects_invalid_operation_identifiers(identifier): class Invalid(_Minimal): - @operation(identifier, implements=roles) + @operation(identifier) async def resolve(self, request: _Input) -> _Result: return _Result(resolved=request.reference) @@ -283,6 +265,16 @@ async def resolve(self, request: _Input) -> _Result: _response(Invalid) +def test_removed_profile_claim_keyword_fails_clearly(): + with pytest.raises( + TypeError, match="unexpected keyword argument 'implements'" + ): + operation( + "example.reference/resolve@1", + implements=("example.reference.custom",), + ) + + def test_operation_inheritance_duplicates_and_overrides(): class Duplicate(_Representative): @operation("example.reference/resolve@1") @@ -548,7 +540,7 @@ def test_matches_unmodified_p1_cross_language_revision_vector(): == (_FIXTURES / "revision-preimage.json").read_bytes() ) assert response.manifest_revision == ( - "sha256:6bfdf3aedc2d4e45d77d4787cc0e744a488208b2510d81788291f51d24a623e8" + "sha256:aa27f0fddaa13df211bd3e4e4e4230cdda42d9188d4b480d196c2e0de2d20cdb" ) @@ -768,3 +760,24 @@ def test_documented_reference_example_builds_a_valid_manifest(): response = _response(example["ReferenceProvider"]) assert "example.reference/normalize@1" in response.manifest.operations assert "example.reference/changed@1" in response.manifest.triggers + + +@pytest.mark.parametrize("schema_kind", ["input", "result", "event"]) +def test_nested_concrete_schemas_preserve_value_validation(schema_kind): + class NestedProvider(_Minimal): + triggers = (Trigger("example.reference/nested@1", _Nested),) + + @operation("example.reference/nested@1") + async def nested(self, request: _Nested) -> _Nested: + return request + + declaration = ManifestDeclaration.discover(NestedProvider) + if schema_kind == "event": + schema = declaration.trigger_schemas["example.reference/nested@1"] + else: + schemas = declaration.operation_schemas["example.reference/nested@1"] + schema = schemas[0 if schema_kind == "input" else 1] + validator = Draft202012Validator(schema) + assert validator.is_valid({"items": [{"resolved": "concrete"}]}) + assert not validator.is_valid({"items": [{"resolved": 123}]}) + assert not validator.is_valid({"items": [{}]}) diff --git a/tests/test_operation_admission.py b/tests/test_operation_admission.py index 5ac0927..5a35221 100644 --- a/tests/test_operation_admission.py +++ b/tests/test_operation_admission.py @@ -16,7 +16,7 @@ import grpc import pytest -from google.protobuf.json_format import ParseDict +from google.protobuf.json_format import MessageToDict, ParseDict from google.protobuf.struct_pb2 import Struct from google.protobuf.timestamp_pb2 import Timestamp from grpc_status import rpc_status @@ -75,6 +75,16 @@ class _Input(ProviderModel): secret: str = Field(json_schema_extra={"writeOnly": True}) +class _Detail(ProviderModel): + label: str + count: int = Field(json_schema_extra={"default": 1}) + + +class _ConcreteInput(ProviderModel): + details: list[_Detail] + provider_specific: bool + + class _Output(ProviderModel): accepted: bool @@ -115,7 +125,6 @@ async def ready(self) -> RequirementCheckResult: @operation( "example.admission/run@1", requires=("runtime.ready",), - implements=("example.operation.v1.audited",), ) async def run_operation( self, @@ -240,7 +249,6 @@ def _request( operation_identifier: str = "example.admission/run@1", payload: dict[str, object] | None = None, deadline: datetime | None = None, - roles: tuple[str, ...] = ("example.operation.v1.audited",), mode: int = operation_admission_pb2.ADMISSION_MODE_ADMIT_OR_RESOLVE, ): payload_message = Struct() @@ -262,7 +270,6 @@ def _request( ), contract=operation_admission_pb2.OperationContractContext( manifest_revision=snapshot.manifest_revision, - required_implementation_roles=roles, ), execution_context=context, ), @@ -466,11 +473,6 @@ async def test_stale_session_is_rejected_before_declaration_lookup( grpc.StatusCode.INVALID_ARGUMENT, operation_admission_pb2.ADMISSION_ERROR_REASON_INVALID_OPERATION_REQUEST, ), - ( - "role", - grpc.StatusCode.FAILED_PRECONDITION, - operation_admission_pb2.ADMISSION_ERROR_REASON_OPERATION_INCOMPATIBLE, - ), ( "session", grpc.StatusCode.FAILED_PRECONDITION, @@ -513,10 +515,6 @@ async def test_rejects_before_creating_a_record( request.invocation.payload.update( {"value": "wrong", "secret": "hidden"} ) - elif change == "role": - request.invocation.contract.required_implementation_roles[:] = [ - "example.operation.v1.missing" - ] elif change == "session": request.session_binding.expected_session_id = "stale-session" elif change == "deadline": @@ -714,3 +712,59 @@ def test_public_context_and_legacy_handler_are_both_discoverable() -> None: } assert operations["example.admission/run@1"].accepts_context assert not operations["example.admission/legacy@1"].accepts_context + + +@pytest.mark.asyncio +async def test_nested_concrete_inputs_validate_without_profile_metadata( + endpoint_directory: Path, +) -> None: + class ConcreteProvider(_AdmissionProvider): + @operation("example.admission/concrete@1") + async def concrete(self, request: _ConcreteInput) -> _Output: + self.calls += 1 + self.started.set() + assert request.details[0].count == 1 + return _Output(accepted=request.provider_specific) + + provider = ConcreteProvider(endpoint_directory) + async with _running(provider) as ( + admission, + bootstrap, + manifest, + descriptor, + ): + handshake, snapshot = await _session(bootstrap, manifest, descriptor) + declaration = snapshot.manifest.operations[ + "example.admission/concrete@1" + ] + assert set(MessageToDict(declaration)) == { + "inputSchema", + "resultSchema", + } + for detail in ({"label": 5, "count": 1}, {"label": "ok"}): + request = _request( + handshake, + snapshot, + operation_identifier="example.admission/concrete@1", + payload={"details": [detail], "provider_specific": True}, + ) + with pytest.raises(grpc.aio.AioRpcError) as captured: + await admission.StartOperation(request, timeout=2) + assert captured.value.code() is grpc.StatusCode.INVALID_ARGUMENT + assert provider.calls == 0 + request = _request( + handshake, + snapshot, + operation_identifier="example.admission/concrete@1", + payload={ + "details": [{"label": "ok", "count": 1}], + "provider_specific": True, + }, + ) + response = await admission.StartOperation(request, timeout=2) + assert ( + response.disposition + == operation_admission_pb2.ADMISSION_DISPOSITION_ACCEPTED_NEW + ) + await asyncio.wait_for(provider.started.wait(), timeout=1) + assert provider.calls == 1 diff --git a/uv.lock b/uv.lock index 024d9fc..12ea540 100644 --- a/uv.lock +++ b/uv.lock @@ -1613,7 +1613,7 @@ wheels = [ [[package]] name = "stateforge-protocol" version = "0.1.0" -source = { git = "https://github.com/stateforge-org/stateforge-protocol.git?rev=64514b35dabfe88d49aabfb63d756e98a97fe5dc#64514b35dabfe88d49aabfb63d756e98a97fe5dc" } +source = { git = "https://github.com/stateforge-org/stateforge-protocol.git?rev=0dab0576d884ae10f3bef0135b641168234b18b6#0dab0576d884ae10f3bef0135b641168234b18b6" } dependencies = [ { name = "grpcio" }, { name = "grpcio-health-checking" }, @@ -1664,7 +1664,7 @@ requires-dist = [ { name = "grpcio-status", specifier = ">=1.83" }, { name = "jsonschema", specifier = ">=4.25,<5" }, { name = "pydantic", specifier = ">=2.12,<3" }, - { name = "stateforge-protocol", git = "https://github.com/stateforge-org/stateforge-protocol.git?rev=64514b35dabfe88d49aabfb63d756e98a97fe5dc" }, + { name = "stateforge-protocol", git = "https://github.com/stateforge-org/stateforge-protocol.git?rev=0dab0576d884ae10f3bef0135b641168234b18b6" }, ] [package.metadata.requires-dev]