From cbb9745fbb22af427ec34915df796cd6a52c8a4e Mon Sep 17 00:00:00 2001 From: tercel Date: Sun, 29 Nov 2026 17:49:01 +0800 Subject: [PATCH 1/6] Complete Atlas core engineering and runtime validation Signed-off-by: tercel --- .github/workflows/sdk-rust.yml | 14 + docs/guides/runtime-profiles.md | 7 +- examples/python/durable-input/README.md | 65 + .../python/durable-input/durable_input.py | 143 +++ examples/python/durable-input/verify.py | 137 ++ examples/python/golden-path/README.md | 24 +- examples/python/golden-path/anthropic_tool.py | 29 + .../python/golden-path/pydantic_ai_tool.py | 14 + .../python/golden-path/verify_agent_tools.py | 120 ++ examples/typescript/edge/README.md | 25 + examples/typescript/edge/config.capnp | 8 + examples/typescript/edge/worker.mjs | 25 + examples/typescript/golden-path/README.md | 25 +- .../typescript/golden-path/openai-tool.ts | 30 + .../typescript/golden-path/verify-openai.ts | 100 ++ .../apcore/registry/filesystem_discovery.py | 336 +++++ .../src/apcore/registry/hot_reload_drain.py | 853 +++++++++++++ python/src/apcore/registry/registry.py | 1118 +---------------- .../test_discovery_import_boundary.py | 38 + rust/Cargo.toml | 11 +- rust/src/acl.rs | 267 +--- rust/src/acl/audit.rs | 267 ++++ rust/src/cancel.rs | 2 +- rust/src/executor.rs | 2 +- rust/src/lib.rs | 6 +- rust/src/observability/exporters.rs | 14 +- rust/src/observability/tracing_config.rs | 8 +- rust/src/registry/async_lifecycle.rs | 5 +- rust/src/registry/registry.rs | 910 ++------------ rust/src/registry/registry_discovery.rs | 599 +++++++++ rust/src/registry/registry_tests.rs | 253 ++++ rust/src/runtime.rs | 34 +- rust/tests/run-wasi.mjs | 8 + typescript/src/browser/index.ts | 2 +- typescript/src/node-api.ts | 2 +- typescript/src/registry/registry.ts | 72 +- typescript/src/registry/types.ts | 8 + .../registry/test-output-declaration.test.ts | 79 ++ 38 files changed, 3501 insertions(+), 2159 deletions(-) create mode 100644 examples/python/durable-input/README.md create mode 100644 examples/python/durable-input/durable_input.py create mode 100644 examples/python/durable-input/verify.py create mode 100644 examples/python/golden-path/anthropic_tool.py create mode 100644 examples/python/golden-path/pydantic_ai_tool.py create mode 100644 examples/python/golden-path/verify_agent_tools.py create mode 100644 examples/typescript/edge/README.md create mode 100644 examples/typescript/edge/config.capnp create mode 100644 examples/typescript/edge/worker.mjs create mode 100644 examples/typescript/golden-path/openai-tool.ts create mode 100644 examples/typescript/golden-path/verify-openai.ts create mode 100644 python/src/apcore/registry/filesystem_discovery.py create mode 100644 python/src/apcore/registry/hot_reload_drain.py create mode 100644 python/tests/registry/test_discovery_import_boundary.py create mode 100644 rust/src/acl/audit.rs create mode 100644 rust/src/registry/registry_discovery.rs create mode 100644 rust/src/registry/registry_tests.rs create mode 100644 rust/tests/run-wasi.mjs create mode 100644 typescript/tests/registry/test-output-declaration.test.ts diff --git a/.github/workflows/sdk-rust.yml b/.github/workflows/sdk-rust.yml index 9c5c84d7..3f1e121b 100644 --- a/.github/workflows/sdk-rust.yml +++ b/.github/workflows/sdk-rust.yml @@ -73,6 +73,20 @@ jobs: env: CONFORMANCE_SPEC_REPO: ${{ github.workspace }} + - uses: actions/setup-node@v4 + if: matrix.rust == 'stable' + with: + node-version: '22' + + - name: Test the in-memory Core Profile on WASI + if: matrix.rust == 'stable' + env: + CARGO_TARGET_WASM32_WASIP1_RUNNER: node tests/run-wasi.mjs + run: | + rustup target add wasm32-wasip1 + cargo test --locked --target wasm32-wasip1 --no-default-features \ + --test core_profile in_memory_assembly_invokes_streams_and_shuts_down -- --test-threads=1 + - name: Run tests run: cargo test --locked --workspace --all-features env: diff --git a/docs/guides/runtime-profiles.md b/docs/guides/runtime-profiles.md index a2462c98..aae47a3d 100644 --- a/docs/guides/runtime-profiles.md +++ b/docs/guides/runtime-profiles.md @@ -50,7 +50,12 @@ modules from files. The full assembly provides those capabilities together. === "Rust" Use the crate with its default features for in-memory execution. - Enable the `full` feature for the configured assembly. + Enable `observability` for OTLP span export, or `full` for the configured + assembly. In-memory observability is available in the default profile. + + On `wasm32-wasip1`, run the in-memory profile inside a current-thread Tokio + runtime with timers enabled. Keep synchronous stream factories and lifecycle + hooks short. They run on the same runtime thread as the call. ```rust use apcore::APCore; diff --git a/examples/python/durable-input/README.md b/examples/python/durable-input/README.md new file mode 100644 index 00000000..89ae74bc --- /dev/null +++ b/examples/python/durable-input/README.md @@ -0,0 +1,65 @@ +# Durable input before a side effect + +A delivery job needs a choice of destination before anything is recorded for +dispatch. The host stores the prompt in SQLite and returns to the caller. On a +later request, even in a new process, it validates the answer and starts a fresh +APCore invocation with the authenticated caller's current identity. The +application owns the two calls and the database. + +```python +host = DurableInput(database_path, approval_handler=review_service) +try: + prompt = host.request(authenticated_principal, "job-117", ttl_seconds=60) + # In a later request or process, construct the host again with the same database. + delivery = host.answer(authenticated_principal, prompt["request_id"], "north") +finally: + host.close() +``` + +The host authenticates each ingress request before constructing `Identity`. +It must obtain the issuer, identity type, subject and roles from verified +claims. These values never come from answer arguments. This example accepts +direct identities with an issuer and binds a prompt to the exact issuer, +identity type and subject. The request ID identifies a row and carries no +authority. APCore checks the current `dispatcher` role for both operations +and independently requires approval for the answer, including retries. + +The prompt exposes a request ID, allowed choices and a UTC Unix expiry in +seconds. A repeated request with the same principal and job key returns the +original prompt and expiry. Use a new job key to start a new attempt after +expiry. A pending request expires at `now >= expires_at`, including when the +approval check finishes after the deadline. After completion, the same answer +can recover the existing result past the prompt expiry while its row is retained, +subject to the current ACL and approval. A different answer conflicts with the +recorded choice. + +The delivery row is both the business effect and the durable completion record. +SQLite serializes competing writers with `BEGIN IMMEDIATE`, rechecks the prompt +under the write lock and commits a single row keyed by request ID. A failed +transaction allows a retry. A retry after a committed transaction returns the +same result. These guarantees apply to the single SQLite effect. External +effects need their own idempotency mechanism, such as an outbox committed with +the result and a consumer that deduplicates by request ID. A deployed host also +owns storage access controls, row retention and clock management. The verifier +uses an approval handler that returns a decision during the invocation itself. +A separate pending approval flow would use APCore's approval token contract +and a durable approval handler in addition to this input store. + +This prompt-and-answer flow uses existing APCore ACL and approval interfaces. +Its request and error names are local to the example. See the +[Durability Boundary](../../../docs/spec/design-durability-boundary.md) for +the invocation contract. + +## Verify + +Use Python 3.11 or newer with a compatible APCore wheel in a virtual environment. + +```sh +python -m pip install "$APCORE_WHEEL" +python verify.py +``` + +The verifier uses a temporary SQLite file, separate Python processes and a +local test reviewer. It checks that no delivery exists before authorized input, +then exercises expiry, identity binding, revocation, approval, duplicate and +competing answers, and retry after a forced transaction rollback. diff --git a/examples/python/durable-input/durable_input.py b/examples/python/durable-input/durable_input.py new file mode 100644 index 00000000..71dfa277 --- /dev/null +++ b/examples/python/durable-input/durable_input.py @@ -0,0 +1,143 @@ +"""A host-owned, durable destination prompt with a transactional delivery effect.""" + +import json +import sqlite3 +import time +from collections.abc import Callable, Iterator +from contextlib import closing, contextmanager +from pathlib import Path +from typing import Annotated, Any, Literal +from uuid import uuid4 + +from apcore import ACL, ACLRule, APCore, Context, ExecutionPolicy, Identity +from apcore.approval import ApprovalHandler +from apcore.errors import ModuleError +from pydantic import BaseModel, Field, StringConstraints + +REQUEST = "delivery.request_destination" +ANSWER = "delivery.confirm_destination" +Destination = Literal["north", "south"] +JobId = Annotated[str, StringConstraints(pattern=r"^[a-zA-Z0-9_-]{1,80}$")] +RequestId = Annotated[str, StringConstraints(pattern=r"^[0-9a-f]{32}$")] +TTLSeconds = Annotated[int, Field(strict=True, ge=1, le=900)] + + +class InputRequest(BaseModel): + request_id: RequestId + expires_at: float + choices: list[Destination] + + +class AnswerInput(BaseModel): + request_id: RequestId + destination: Destination + + +class Delivery(AnswerInput): + job_id: JobId + + +def principal_key(identity: Identity | None) -> str: + if identity is None or not identity.id or not identity.type or not identity.issuer or identity.on_behalf_of: + raise PermissionError("An authenticated, non-delegated principal is required") + return json.dumps((identity.issuer, identity.type, identity.id), separators=(",", ":")) + + +class DurableInput: + def __init__( + self, + path: Path, + *, + approval_handler: ApprovalHandler | None = None, + clock: Callable[[], float] = time.time, + ) -> None: + self._path = path + self._clock = clock + with self._transaction() as db: + db.execute("""CREATE TABLE IF NOT EXISTS requests ( + request_id TEXT PRIMARY KEY, owner TEXT NOT NULL, job_id TEXT NOT NULL, expires_at REAL NOT NULL, + UNIQUE (owner, job_id) + )""") + db.execute("""CREATE TABLE IF NOT EXISTS deliveries ( + request_id TEXT PRIMARY KEY REFERENCES requests(request_id), + destination TEXT NOT NULL CHECK (destination IN ('north', 'south')) + )""") + + self._core = APCore(policy=ExecutionPolicy(strict=True)) + self._core.executor.set_acl( + ACL( + [ + ACLRule( + callers=["@external"], + targets=[REQUEST, ANSWER], + effect="allow", + conditions={"roles": ["dispatcher"]}, + ), + ], + default_effect="deny", + ) + ) + if approval_handler is not None: + self._core.executor.set_approval_handler(approval_handler) + + @self._core.module(REQUEST, description="Request a delivery destination", annotations={"idempotent": True}) + def request_destination(job_id: JobId, ttl_seconds: TTLSeconds, context: Context) -> InputRequest: + owner = principal_key(context.identity) + with self._transaction() as db: + db.execute( + """INSERT INTO requests (request_id, owner, job_id, expires_at) VALUES (?, ?, ?, ?) + ON CONFLICT (owner, job_id) DO NOTHING""", + (uuid4().hex, owner, job_id, self._clock() + ttl_seconds), + ) + record = db.execute( + "SELECT request_id, expires_at FROM requests WHERE owner = ? AND job_id = ?", + (owner, job_id), + ).fetchone() + assert record is not None + return InputRequest(request_id=record[0], expires_at=record[1], choices=["north", "south"]) + + @self._core.module(ANSWER, description="Record an approved delivery destination", requires_approval=True) + def confirm_destination(request_id: RequestId, destination: Destination, context: Context) -> Delivery: + owner = principal_key(context.identity) + with self._transaction() as db: + job_id, recorded = self._load_request(db, request_id, owner) + if recorded is None: + db.execute("INSERT INTO deliveries VALUES (?, ?)", (request_id, destination)) + elif recorded != destination: + raise ModuleError("INPUT_ANSWER_CONFLICT", "The request already has a different answer") + return Delivery(request_id=request_id, job_id=job_id, destination=destination) + + @contextmanager + def _transaction(self) -> Iterator[sqlite3.Connection]: + with closing(sqlite3.connect(self._path, timeout=5)) as db, db: + db.execute("PRAGMA foreign_keys = ON") + db.execute("BEGIN IMMEDIATE") + yield db + + def _load_request(self, db: sqlite3.Connection, request_id: str, owner: str) -> tuple[str, str | None]: + row = db.execute( + """SELECT r.job_id, r.expires_at, d.destination FROM requests r + LEFT JOIN deliveries d ON d.request_id = r.request_id + WHERE r.request_id = ? AND r.owner = ?""", + (request_id, owner), + ).fetchone() + if row is None: + raise PermissionError("The request is unavailable for this principal") + job_id, expires_at, destination = row + if destination is None and self._clock() >= expires_at: + raise ModuleError("INPUT_REQUEST_EXPIRED", "The input request expired before an answer was recorded") + return job_id, destination + + def request(self, principal: Identity | None, job_id: str, *, ttl_seconds: int = 60) -> dict[str, Any]: + principal_key(principal) + return self._core.call(REQUEST, {"job_id": job_id, "ttl_seconds": ttl_seconds}, Context.create(principal)) + + def answer(self, principal: Identity | None, request_id: str, destination: str) -> dict[str, Any]: + owner = principal_key(principal) + answer = AnswerInput.model_validate({"request_id": request_id, "destination": destination}) + with closing(sqlite3.connect(self._path)) as db: + self._load_request(db, answer.request_id, owner) + return self._core.call(ANSWER, answer.model_dump(), Context.create(principal)) + + def close(self) -> None: + self._core.close() diff --git a/examples/python/durable-input/verify.py b/examples/python/durable-input/verify.py new file mode 100644 index 00000000..0848f0c3 --- /dev/null +++ b/examples/python/durable-input/verify.py @@ -0,0 +1,137 @@ +"""Verify durable requests using fresh processes and a temporary SQLite file.""" + +import json +import sqlite3 +import subprocess +import sys +from collections.abc import Callable +from concurrent.futures import ThreadPoolExecutor +from contextlib import closing +from pathlib import Path +from tempfile import TemporaryDirectory +from typing import Any + +from apcore import Identity +from apcore.approval import ApprovalRequest, ApprovalResult, CallbackApprovalHandler +from apcore.errors import ModuleError + +from durable_input import DurableInput + + +def worker(db: str, actor: str, verdict: str, now: str, operation: str, *args: str) -> None: + # In an application, the verified authentication result supplies these claims. + current_time = float(now) + principal = ( + None + if actor == "anonymous" + else Identity( + id="bob" if actor == "bob" else "alice", + issuer="other.example" if actor == "other-issuer" else "auth.example", + roles=() if actor == "revoked" else ("dispatcher",), + ) + ) + + async def review(request: ApprovalRequest) -> ApprovalResult: + nonlocal current_time + assert request.context.identity == principal + assert request.arguments["destination"] in {"north", "south"} + if verdict == "approve-late": + current_time += 1 + return ApprovalResult(status="approved" if verdict in {"approve", "approve-late"} else "rejected") + + handler = None if verdict == "missing" else CallbackApprovalHandler(review) + host = DurableInput(Path(db), approval_handler=handler, clock=lambda: current_time) + try: + result = ( + host.request(principal, args[0], ttl_seconds=int(args[1])) + if operation == "request" + else (host.answer(principal, args[0], args[1])) + ) + except (ModuleError, PermissionError, ValueError) as error: + code = error.code if isinstance(error, ModuleError) else type(error).__name__ + print(json.dumps({"error": code})) + else: + print(json.dumps(result)) + finally: + host.close() + + +def verify_rollback(db: Path, run: Callable[..., dict[str, Any]], effects: Callable[[], list[tuple[str, str]]]) -> None: + baseline = effects() + rollback = run("alice", "missing", 102, "request", "job-rollback", "10")["request_id"] + with closing(sqlite3.connect(db)) as connection, connection: + connection.execute("""CREATE TRIGGER fail_insert AFTER INSERT ON deliveries + BEGIN SELECT RAISE(ABORT, 'forced rollback'); END""") + assert run("alice", "approve", 103, "answer", rollback, "north") == {"error": "MODULE_EXECUTE_ERROR"} + assert effects() == baseline + with closing(sqlite3.connect(db)) as connection, connection: + connection.execute("DROP TRIGGER fail_insert") + assert run("alice", "approve", 104, "answer", rollback, "north")["destination"] == "north" + assert effects() == sorted([*baseline, (rollback, "north")]) + + +def check(db: Path) -> None: + def run(actor: str, verdict: str, now: int, operation: str, *args: str) -> dict[str, Any]: + result = subprocess.run( + [sys.executable, __file__, str(db), actor, verdict, str(now), operation, *args], + capture_output=True, + text=True, + check=True, + timeout=20, + ) + return json.loads(result.stdout) + + def effects() -> list[tuple[str, str]]: + with closing(sqlite3.connect(db)) as connection: + return connection.execute("SELECT request_id, destination FROM deliveries ORDER BY request_id").fetchall() + + assert run("anonymous", "approve", 100, "request", "job-1", "10") == {"error": "PermissionError"} + assert run("revoked", "approve", 100, "request", "job-1", "10") == {"error": "ACL_DENIED"} + opened = run("alice", "missing", 100, "request", "job-1", "10") + request_id = opened["request_id"] + assert opened == {"request_id": request_id, "expires_at": 110, "choices": ["north", "south"]} + assert run("alice", "missing", 101, "request", "job-1", "90") == opened + assert not effects() + + for actor in ("bob", "other-issuer"): + assert run(actor, "approve", 101, "answer", request_id, "north") == {"error": "PermissionError"} + assert run("alice", "approve", 101, "answer", request_id, "invalid") == {"error": "ValidationError"} + assert run("alice", "missing", 101, "answer", request_id, "north") == {"error": "APPROVAL_DENIED"} + assert run("alice", "deny", 101, "answer", request_id, "north") == {"error": "APPROVAL_DENIED"} + assert run("revoked", "approve", 101, "answer", request_id, "north") == {"error": "ACL_DENIED"} + assert not effects() + + timed = run("alice", "missing", 100, "request", "job-expiring", "1")["request_id"] + assert run("alice", "approve", 101, "answer", timed, "north") == {"error": "INPUT_REQUEST_EXPIRED"} + assert run("alice", "approve-late", 100, "answer", timed, "north") == {"error": "INPUT_REQUEST_EXPIRED"} + assert not effects() + + with ThreadPoolExecutor(max_workers=2) as pool: + replies = [pool.submit(run, "alice", "approve", 102, "answer", request_id, "north") for _ in range(2)] + completed = {"request_id": request_id, "job_id": "job-1", "destination": "north"} + assert [reply.result() for reply in replies] == [completed, completed] + assert effects() == [(request_id, "north")] + assert run("alice", "approve", 200, "answer", request_id, "north") == completed + assert run("alice", "approve", 102, "answer", request_id, "south") == {"error": "INPUT_ANSWER_CONFLICT"} + assert run("revoked", "approve", 103, "answer", request_id, "north") == {"error": "ACL_DENIED"} + assert run("alice", "deny", 103, "answer", request_id, "north") == {"error": "APPROVAL_DENIED"} + + contest = run("alice", "missing", 102, "request", "job-contest", "10")["request_id"] + with ThreadPoolExecutor(max_workers=2) as pool: + replies = [pool.submit(run, "alice", "approve", 103, "answer", contest, side) for side in ("north", "south")] + outcomes = [reply.result() for reply in replies] + (winner,) = (outcome for outcome in outcomes if "destination" in outcome) + (loser,) = (outcome for outcome in outcomes if "error" in outcome) + assert loser == {"error": "INPUT_ANSWER_CONFLICT"} + assert len(effects()) == 2 and (contest, winner["destination"]) in effects() + + verify_rollback(db, run, effects) + + +if __name__ == "__main__": + if len(sys.argv) > 1: + worker(*sys.argv[1:]) + else: + with TemporaryDirectory() as directory: + check(Path(directory) / "requests.sqlite") + print("Durable input passed restart, ACL, approval, expiry, concurrency, and transactional retry checks.") diff --git a/examples/python/golden-path/README.md b/examples/python/golden-path/README.md index 1ff33543..77e35338 100644 --- a/examples/python/golden-path/README.md +++ b/examples/python/golden-path/README.md @@ -26,9 +26,31 @@ Set `APCORE_WHEEL` and `APCORE_MCP_WHEEL` to the absolute paths of the Core and The in-memory stores are for this local example. A deployed application can use an authenticated review service and a persistent scoped approval store. -## In-process agent tool +## Agent tools Install `openai-agents` to use `archive_tool(archive)` from `agent_tool.py`. Pass the returned tool to `Agent(..., tools=[...])`. The tool calls the same governed handle as the direct example. The host's approval handler still decides whether an archive may run. [OpenAI Agents SDK function tools](https://openai.github.io/openai-agents-python/tools/#function-tools) + +Install `pydantic-ai-slim` to use `archive_tool(archive)` from +`pydantic_ai_tool.py` in a PydanticAI agent's `tools` list. The SDK derives the +tool's argument schema from the Python signature. [PydanticAI function tools](https://pydantic.dev/docs/ai/tools-toolsets/tools/) + +Install `anthropic` to pass `anthropic_tool.archive_tool` in the Messages +API's `tools` list. For a returned `tool_use` block, call +`dispatch_archive(archive, block)` and send the returned `tool_result` in a +user message after the assistant's tool-use message. The result carries the +original tool-use ID. [Anthropic client tool use](https://platform.claude.com/docs/en/agents-and-tools/tool-use/define-tools) + +Run the PydanticAI and Anthropic examples using a local model substitute and +mocked Messages API, respectively. No provider account or credentials are required. + +```bash +python -m pip install pydantic-ai-slim==2.77.0 anthropic==2.14.0 +python verify_agent_tools.py +``` + +The verifier checks that both tool handlers wait for Core approval. The host +resolves approval in the store, keeps the resume token private, and passes a +scoped handle to the bridge so the tool can complete the approved operation. diff --git a/examples/python/golden-path/anthropic_tool.py b/examples/python/golden-path/anthropic_tool.py new file mode 100644 index 00000000..18d847bf --- /dev/null +++ b/examples/python/golden-path/anthropic_tool.py @@ -0,0 +1,29 @@ +"""Translate Anthropic Messages tool blocks into governed archive calls.""" + +from anthropic.types import ToolParam, ToolResultBlockParam, ToolUseBlock +from apcore import BoundModule +from app import ArchiveResult +from pydantic import BaseModel, ConfigDict + + +class ArchiveArguments(BaseModel): + model_config = ConfigDict(extra="forbid", strict=True) + + note_id: str + + +archive_tool: ToolParam = { + "name": "archive_note", + "description": "Archive a note by its ID.", + "input_schema": ArchiveArguments.model_json_schema(), +} + + +async def dispatch_archive( + archive: BoundModule[[str], ArchiveResult], call: ToolUseBlock +) -> ToolResultBlockParam: + if call.name != archive_tool["name"]: + raise ValueError(f"Unknown tool: {call.name}") + args = ArchiveArguments.model_validate(call.input) + result = await archive.invoke_async(args.note_id) + return {"type": "tool_result", "tool_use_id": call.id, "content": result.model_dump_json()} diff --git a/examples/python/golden-path/pydantic_ai_tool.py b/examples/python/golden-path/pydantic_ai_tool.py new file mode 100644 index 00000000..b29231bc --- /dev/null +++ b/examples/python/golden-path/pydantic_ai_tool.py @@ -0,0 +1,14 @@ +"""Expose the governed archive operation as a PydanticAI tool.""" + +from apcore import BoundModule +from app import ArchiveResult +from pydantic_ai import Tool + + +def archive_tool(archive: BoundModule[[str], ArchiveResult]) -> Tool[None]: + async def archive_note(note_id: str) -> str: + """Archive a note by its ID.""" + result = await archive.invoke_async(note_id) + return result.model_dump_json() + + return Tool(archive_note) diff --git a/examples/python/golden-path/verify_agent_tools.py b/examples/python/golden-path/verify_agent_tools.py new file mode 100644 index 00000000..40437c1b --- /dev/null +++ b/examples/python/golden-path/verify_agent_tools.py @@ -0,0 +1,120 @@ +"""Exercise the PydanticAI and Anthropic bridges without a model service.""" + +import asyncio +import json +from collections.abc import Awaitable, Callable + +import httpx2 +from anthropic import AsyncAnthropic +from anthropic.types import MessageParam, TextBlockParam, ToolUseBlock, ToolUseBlockParam +from apcore import BoundModule +from apcore.errors import ApprovalPendingError +from apcore_mcp import InMemoryApprovalStore, StorageBackedApprovalHandler +from app import ArchiveResult, Notebook, build_app +from pydantic_ai import Agent, ModelMessage, ModelResponse, TextPart, ToolCallPart, ToolReturnPart +from pydantic_ai.models.function import AgentInfo, FunctionModel + +import anthropic_tool +import pydantic_ai_tool + + +async def call_pydantic_ai(archive: BoundModule[[str], ArchiveResult], note_id: str) -> None: + def model(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse: + (tool,) = info.function_tools + assert tool.parameters_json_schema["required"] == ["note_id"] + for part in messages[-1].parts: + if isinstance(part, ToolReturnPart): + assert part.tool_call_id == "ai-archive" + assert json.loads(part.content) == {"archived": note_id} + return ModelResponse(parts=[TextPart("Archived")]) + return ModelResponse(parts=[ToolCallPart(tool.name, {"note_id": note_id}, tool_call_id="ai-archive")]) + + agent = Agent(FunctionModel(model), tools=[pydantic_ai_tool.archive_tool(archive)]) + assert (await agent.run("Archive the note.")).output == "Archived" + + +async def call_anthropic(archive: BoundModule[[str], ArchiveResult], note_id: str) -> None: + tool = anthropic_tool.archive_tool + assert tool["input_schema"]["required"] == ["note_id"] + tool_use: ToolUseBlockParam = { + "type": "tool_use", "id": "toolu_archive", "name": tool["name"], "input": {"note_id": note_id} + } + + def messages_api(request: httpx2.Request) -> httpx2.Response: + body = json.loads(request.content) + assert body["tools"] == [tool] + content: list[ToolUseBlockParam | TextBlockParam] + if len(body["messages"]) == 1: + content = [tool_use] + stop_reason = "tool_use" + else: + assert body["messages"][1] == {"role": "assistant", "content": [tool_use]} + (result,) = body["messages"][2]["content"] + assert result["type"] == "tool_result" and result["tool_use_id"] == tool_use["id"] + assert json.loads(result["content"]) == {"archived": note_id} + content = [{"type": "text", "text": "Archived"}] + stop_reason = "end_turn" + return httpx2.Response( + 200, + json={ + "id": "msg_archive", + "type": "message", + "role": "assistant", + "model": "offline-test", + "content": content, + "stop_reason": stop_reason, + "stop_sequence": None, + "usage": {"input_tokens": 1, "output_tokens": 1}, + }, + ) + + transport = httpx2.MockTransport(messages_api) + async with AsyncAnthropic( + api_key="offline-example", http_client=httpx2.AsyncClient(transport=transport) + ) as anthropic: + messages: list[MessageParam] = [{"role": "user", "content": "Archive the note."}] + response = await anthropic.messages.create(model="offline-test", max_tokens=100, tools=[tool], messages=messages) + (call,) = response.content + assert isinstance(call, ToolUseBlock) + result = await anthropic_tool.dispatch_archive(archive, call) + echoed_call: ToolUseBlockParam = {"type": call.type, "id": call.id, "name": call.name, "input": call.input} + messages.extend([ + {"role": "assistant", "content": [echoed_call]}, + {"role": "user", "content": [result]}, + ]) + done = await anthropic.messages.create(model="offline-test", max_tokens=100, tools=[tool], messages=messages) + assert done.stop_reason == "end_turn" + + +async def verify_approval( + dispatch: Callable[[BoundModule[[str], ArchiveResult], str], Awaitable[None]], note_id: str +) -> None: + notebook = Notebook() + client, archive = build_app(notebook, []) + reviews = InMemoryApprovalStore() + client.executor.set_approval_handler(StorageBackedApprovalHandler(reviews)) + try: + try: + await dispatch(archive, note_id) + except ApprovalPendingError as pending: + approval_id = pending.result.audit_id + resume_token = pending.approval_id + assert approval_id and resume_token and approval_id != resume_token + else: + raise AssertionError("Expected approval to be pending") + assert notebook.archived == [] + assert await reviews.resolve(approval_id, approved=True) + await dispatch(archive.with_approval_token(resume_token), note_id) + assert notebook.archived == [note_id] + finally: + await client.shutdown() + + +async def main() -> None: + await verify_approval(call_pydantic_ai, "from-pydantic-ai") + await verify_approval(call_anthropic, "from-anthropic") + print("PydanticAI and Anthropic both passed the approval checks.") + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/examples/typescript/edge/README.md b/examples/typescript/edge/README.md new file mode 100644 index 00000000..bea87248 --- /dev/null +++ b/examples/typescript/edge/README.md @@ -0,0 +1,25 @@ +# APCore on Cloudflare Workers + +This Worker bundles the default `apcore-js` entry with browser package +conditions. It registers a module and exercises the in-memory executor with an +ACL. The `workerd` configuration uses a loopback socket and the standard Web +APIs available to Workers. + +Use a locally built `apcore-js` tarball. In this directory, install the tarball +and the example tools, then bundle and start the Worker. + +```sh +npm install --no-save --no-package-lock "$APCORE_JS_TARBALL" @sinclair/typebox esbuild workerd +npx esbuild worker.mjs --bundle --platform=browser --format=esm --outfile=worker.bundle.mjs +npx workerd serve config.capnp +``` + +In a separate terminal, the root path returns `{"result":42}`. `/denied` +returns `{"code":"ACL_DENIED"}` and `/invalid` returns +`{"code":"SCHEMA_VALIDATION_ERROR"}`. + +```sh +curl -sS http://127.0.0.1:49188/ +curl -sS http://127.0.0.1:49188/denied +curl -sS http://127.0.0.1:49188/invalid +``` diff --git a/examples/typescript/edge/config.capnp b/examples/typescript/edge/config.capnp new file mode 100644 index 00000000..0072f61c --- /dev/null +++ b/examples/typescript/edge/config.capnp @@ -0,0 +1,8 @@ +using Workerd = import "/workerd/workerd.capnp"; +const smoke :Workerd.Config = ( + services = [(name = "apcore", worker = ( + modules = [(name = "worker.mjs", esModule = embed "worker.bundle.mjs")], + compatibilityDate = "2025-08-01" + ))], + sockets = [(name = "http", address = "127.0.0.1:49188", http = (), service = "apcore")] +); diff --git a/examples/typescript/edge/worker.mjs b/examples/typescript/edge/worker.mjs new file mode 100644 index 00000000..cd4364b6 --- /dev/null +++ b/examples/typescript/edge/worker.mjs @@ -0,0 +1,25 @@ +import { ACL, AutoApproveHandler, Executor, FunctionModule, Registry } from 'apcore-js'; +import { Type } from '@sinclair/typebox'; + +export default { + async fetch(request) { + const { pathname } = new URL(request.url); + const moduleId = 'demo.double'; + const registry = new Registry(); + registry.register(moduleId, new FunctionModule({ + moduleId, + description: 'Double the input', + inputSchema: Type.Object({ value: Type.Number() }), + outputSchema: Type.Object({ result: Type.Number() }), + execute: async (input) => ({ result: input.value * 2 }), + })); + const rules = pathname === '/denied' ? [] : [{ callers: ['@external'], targets: [moduleId], effect: 'allow' }]; + const acl = new ACL(rules, 'deny'); + const executor = Executor.fromRegistry(registry, null, acl, null, new AutoApproveHandler()); + try { + return Response.json(await executor.call(moduleId, { value: pathname === '/invalid' ? 'wrong' : 21 })); + } catch (error) { + return Response.json({ code: error.code }, { status: 400 }); + } + }, +}; diff --git a/examples/typescript/golden-path/README.md b/examples/typescript/golden-path/README.md index 2977f267..9d51187f 100644 --- a/examples/typescript/golden-path/README.md +++ b/examples/typescript/golden-path/README.md @@ -7,7 +7,8 @@ requires approval for public lookups. The example's approval handler is a test double that records the arguments and immediately returns approval. Run this example in an ES module project with compatible `apcore-js` and -`apcore-mcp` packages, `@modelcontextprotocol/sdk`, `zod`, and TypeScript. +`apcore-mcp` packages, `@modelcontextprotocol/sdk`, `zod`, TypeScript, +`@types/node`, and `@types/jsonwebtoken`. ```sh npx tsc --strict --module NodeNext --target ES2022 --outDir dist verify.ts @@ -19,3 +20,25 @@ The optional `agent-tool.ts` example requires the `ai` package and same handle and the input schema from `core.getCallableDefinition(lookup.id)`. Use the returned tool in the `tools` option of your AI SDK call. It invokes the same executor as the MCP route. [AI SDK tool reference](https://ai-sdk.dev/docs/reference/ai-sdk-core/tool) + +## OpenAI Node SDK + +`openai-tool.ts` adapts the typed handle to an OpenAI Responses API function +tool. Pass `lookupTool(definition.inputSchema)` in `responses.create({ tools })` +using the schema returned by `core.getCallableDefinition(lookup.id)`. For a +completed `function_call`, run `dispatchLookup(lookup, call)` and send the +returned `function_call_output` in the next request's `input` along with the +original response ID as `previous_response_id`. The bridge matches the result +to the original `call_id`. The tool declaration uses the Core JSON Schema in +non-strict mode. The bridge parses the generated arguments and Core validates +and applies policy to the call. [OpenAI Node SDK tool calling](https://github.com/openai/openai-node/blob/main/docs/tools.md) + +With the dependencies above and Node.js 22 or newer, run both the SDK round +trip over mocked HTTP and the same governed lookup through in-memory MCP. +The example needs no provider credentials. + +```sh +npm install openai@7.65.0 +npx tsc --strict --module NodeNext --target ES2022 --outDir dist verify-openai.ts +node dist/verify-openai.js +``` diff --git a/examples/typescript/golden-path/openai-tool.ts b/examples/typescript/golden-path/openai-tool.ts new file mode 100644 index 00000000..31e78496 --- /dev/null +++ b/examples/typescript/golden-path/openai-tool.ts @@ -0,0 +1,30 @@ +import type { BoundModule } from 'apcore-js'; +import type { FunctionTool, ResponseFunctionToolCall, ResponseInputItem } from 'openai/resources/responses/responses'; +import { z } from 'zod/v4'; + +const lookupName = 'lookup_note'; +const lookupArguments = z.strictObject({ noteId: z.string() }); +type Note = z.infer; + +export function lookupTool(wireInputSchema: Record): FunctionTool { + return { + type: 'function', + name: lookupName, + description: 'Look up a note', + parameters: wireInputSchema, + strict: false, + }; +} + +export async function dispatchLookup( + lookup: BoundModule, + call: ResponseFunctionToolCall, +): Promise { + if (call.name !== lookupName) throw new Error(`Unknown tool: ${call.name}`); + if (call.status !== undefined && call.status !== 'completed') { + throw new Error(`Tool call is ${call.status}`); + } + const args = lookupArguments.parse(JSON.parse(call.arguments)); + const result = await lookup.invoke(args); + return { type: 'function_call_output', call_id: call.call_id, output: JSON.stringify(result) }; +} diff --git a/examples/typescript/golden-path/verify-openai.ts b/examples/typescript/golden-path/verify-openai.ts new file mode 100644 index 00000000..6b68aada --- /dev/null +++ b/examples/typescript/golden-path/verify-openai.ts @@ -0,0 +1,100 @@ +import assert from 'node:assert/strict'; +import { Client } from '@modelcontextprotocol/sdk/client/index.js'; +import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js'; +import { APCore, Executor, Registry } from 'apcore-js'; +import { ExecutionRouter, MCPServerFactory } from 'apcore-mcp'; +import OpenAI from 'openai'; +import type { ResponseFunctionToolCall } from 'openai/resources/responses/responses'; +import { z } from 'zod/v4'; +import { dispatchLookup, lookupTool } from './openai-tool.js'; + +const registry = new Registry(); +const executor = new Executor({ + registry, + policyEvaluator: { + async evaluate({ arguments: args }) { + return { decision: args['noteId'] === 'private' ? 'deny' : 'allow' }; + }, + }, +}); +const core = new APCore({ registry, executor }); +try { + let invocations = 0; + const lookup = await core.define({ + id: 'notes.lookup', + description: 'Look up a note', + readonly: true, + input: z.object({ noteId: z.string().trim().min(1) }), + output: z.object({ noteId: z.string() }), + execute: ({ noteId }) => { + invocations++; + return { noteId }; + }, + }); + const definition = core.getCallableDefinition(lookup.id); + assert.ok(definition); + const tool = lookupTool(definition.inputSchema); + assert.deepEqual(tool.parameters?.['required'], ['noteId']); + const modelCall = { + type: 'function_call', + name: tool.name, + id: 'fc_lookup', + call_id: 'call_lookup', + status: 'completed', + arguments: JSON.stringify({ noteId: ' public ' }), + } satisfies ResponseFunctionToolCall; + const openai = new OpenAI({ + apiKey: 'offline-example', + fetch: async (_url, init) => { + const request = JSON.parse(String(init?.body)); + if (request.previous_response_id === undefined) { + assert.deepEqual(request.tools, [tool]); + return Response.json({ id: 'resp_lookup', output: [modelCall] }); + } + assert.equal(request.previous_response_id, 'resp_lookup'); + assert.deepEqual(request.input, [{ + type: 'function_call_output', + call_id: modelCall.call_id, + output: JSON.stringify({ noteId: 'public' }), + }]); + return Response.json({ id: 'resp_done', output: [] }); + }, + }); + const response = await openai.responses.create({ model: 'offline-test', input: 'Find a note', tools: [tool] }); + const [call] = response.output; + assert.ok(call?.type === 'function_call'); + const output = await dispatchLookup(lookup, call); + const done = await openai.responses.create({ model: 'offline-test', previous_response_id: response.id, input: [output] }); + assert.equal(done.id, 'resp_done'); + await assert.rejects(dispatchLookup(lookup, { ...call, arguments: '{"noteId":" private "}' }), { code: 'POLICY_DENIED' }); + await assert.rejects(dispatchLookup(lookup, { ...call, arguments: '{"noteId":" "}' }), { code: 'SCHEMA_VALIDATION_ERROR' }); + await assert.rejects(dispatchLookup(lookup, { ...call, name: 'unknown' }), /Unknown tool/); + await assert.rejects(dispatchLookup(lookup, { ...call, status: 'incomplete' }), /incomplete/); + assert.equal(invocations, 1); + + const factory = new MCPServerFactory({ richDescription: false }); + const server = factory.createServer(); + const router = new ExecutionRouter({ + registry, + call: executor.call.bind(executor), + getCallableDescriptor: executor.getCallableDescriptor.bind(executor), + }); + factory.registerHandlers(server, factory.buildTools(registry), router); + const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); + const mcp = new Client({ name: 'openai-node-example', version: '1' }); + try { + await server.connect(serverTransport); + await mcp.connect(clientTransport); + const result = await mcp.callTool({ name: lookup.id, arguments: { noteId: ' public ' } }); + assert.ok(!result.isError); + assert.deepEqual(result.structuredContent, { noteId: 'public' }); + assert.ok((await mcp.callTool({ name: lookup.id, arguments: { noteId: ' private ' } })).isError); + assert.equal(invocations, 2); + } finally { + await mcp.close(); + await server.close(); + } + console.log('OpenAI Responses and MCP passed the same lookup governance checks.'); +} finally { + await core.shutdown(); +} diff --git a/python/src/apcore/registry/filesystem_discovery.py b/python/src/apcore/registry/filesystem_discovery.py new file mode 100644 index 00000000..d65f43ff --- /dev/null +++ b/python/src/apcore/registry/filesystem_discovery.py @@ -0,0 +1,336 @@ +"""Filesystem candidate selection for initial discovery and hot reload.""" + +from __future__ import annotations + +import logging +from dataclasses import dataclass +from pathlib import Path, PurePath +from typing import TYPE_CHECKING, Any + +from apcore.config import Config +from apcore.errors import ErrorCodes, InvalidInputError +from apcore.registry.metadata import load_id_map, load_metadata +from apcore.registry.registry import _is_ephemeral, _validate_module_id +from apcore.registry.scanner import scan_extensions, scan_multi_root, scan_watched_source +from apcore.registry.types import DiscoveredModule +from apcore.registry.validation import validate_module + +if TYPE_CHECKING: + from apcore.registry.registry import Registry + +# Keep existing registry log routing for discovery and watcher diagnostics. +logger = logging.getLogger("apcore.registry.registry") + + +@dataclass(frozen=True) +class _DiscoveryCandidate: + source: DiscoveredModule + entry_point: type + metadata: dict[str, Any] + + +class FilesystemDiscovery: + """Read filesystem candidates while Registry owns publication and lifecycle state.""" + + def __init__(self, registry: Registry) -> None: + self._registry = registry + + def collect(self, path_filter: str | list[str] | None) -> tuple[int, dict[str, _DiscoveryCandidate]]: + """Scan, filter, import and validate candidate classes in scan order.""" + discovered = self._scan_roots(*self.scan_params()) + if path_filter is not None: + discovered = self._apply_path_filter(discovered, path_filter) + self._apply_id_map_overrides(discovered) + valid_ids = self._filter_invalid_discovery_ids(discovered) + return len(discovered), self._index_discovered_modules(self.load_candidates(valid_ids)) + + def load_candidates(self, candidates: list[DiscoveredModule]) -> list[_DiscoveryCandidate]: + """Load and validate entry-point classes with their companion metadata.""" + return self._validate_all(self._resolve_all_entry_points(self._load_all_metadata(candidates))) + + def load_watched_entry_point(self, candidate: DiscoveredModule) -> tuple[dict[str, Any], type]: + """Load one replacement candidate without changing its registry state.""" + from apcore.registry.registry import resolve_entry_point + + metadata = load_metadata(candidate.meta_path) if candidate.meta_path is not None else {} + entry_point = resolve_entry_point( + candidate.file_path, meta=metadata, pre_approval_hook=self._registry._pre_approval_hook + ) + return metadata, entry_point + + @staticmethod + def roots_from_config(config: Config) -> list[dict[str, Any]]: + """`extensions.roots` if declared, else `extensions.root`, else the default. + + Both element shapes `$defs/ExtensionsConfig` admits are accepted: a bare + path string and an object carrying an explicit `namespace`. + + **Every entry gets a namespace here**, derived from the last path + segment when the entry does not name one — the same value + `scan_multi_root` would derive. Deriving it at this door rather than + leaving it to the scanner is what makes a ONE-element `roots` list + behave like an n-element one: the scan dispatches on "more than one root + or any namespace", so a lone `roots: ["./beta"]` would otherwise take + the single-root branch and prefix nothing. Nothing in the schema makes a + one-element list special, and `roots` versus `root` is the whole + distinction between namespaced and backward-compatible mode. + + A `roots` list that is present but yields no usable entry falls through + to the single-root branch rather than scanning nothing: an empty list is + a configuration that discovers no modules, and silently discovering none + is the failure this whole audit is about. + """ + declared = config.get("extensions.roots") + if isinstance(declared, list): + entries: list[dict[str, Any]] = [] + for item in declared: + if isinstance(item, str) and item.strip(): + entries.append({"root": config.resolve_path(item), "namespace": Path(item).name}) + elif isinstance(item, dict) and item.get("root"): + root_value = item["root"] + entries.append( + { + "root": config.resolve_path(str(root_value)), + "namespace": item.get("namespace") or Path(str(root_value)).name, + } + ) + if entries: + return entries + if declared: + logger.warning( + "extensions.roots is declared with %d entry/entries and none of them " + "names a root, so it was ignored and extensions.root is used instead. " + "An entry is either a path string or an object with a 'root' key.", + len(declared), + ) + + ext_root = config.get("extensions.root") or Config.get_default("extensions.root") + return [{"root": config.resolve_path(ext_root)}] + + @staticmethod + def id_map_from_config(config: Config | None, explicit_path: str | Path | None) -> dict[str, dict[str, Any]]: + """Resolve D-71 and D-73 overrides with the explicit path first.""" + path = explicit_path + if path is None and config is not None: + discovered_path = config.get("id_map.overrides") + if isinstance(discovered_path, str) and discovered_path.strip(): + path = config.resolve_path(discovered_path) + return load_id_map(path) if path is not None else {} + + def scan_params(self) -> tuple[int, bool, list[str]]: + """Resolve scan parameters from config, falling back to spec defaults. + + Logs a WARN on the first call with ``follow_symlinks=True`` so + operators see the trust-boundary reminder in logs when they opt + into broader filesystem traversal. The scanner itself already + refuses to follow symlinks escaping the extension root (see + ``scan_extensions``); this log is a secondary signal that the + configuration enables a potentially sensitive feature. + """ + if self._registry._config is None: + return 8, False, [] + max_depth = self._registry._config.get("extensions.max_depth", 8) + follow_symlinks = self._registry._config.get("extensions.follow_symlinks", False) + ignore_patterns = self._registry._config.get("extensions.ignore_patterns", []) or [] + if follow_symlinks and not self._registry._logged_follow_symlinks_warning: + logger.warning( + "extensions.follow_symlinks=True — scanner will traverse symlinked " + "directories (confined to the extension root). Ensure the root is " + "trusted; see apcore.registry.entry_point for the trust-boundary note." + ) + self._registry._logged_follow_symlinks_warning = True + return (max_depth, follow_symlinks, list(ignore_patterns)) + + def _scan_roots( + self, max_depth: int, follow_symlinks: bool, ignore_patterns: list[str] | None = None + ) -> list[DiscoveredModule]: + """Stage 1 — walk extension root(s) and return DiscoveredModule entries.""" + has_namespace = any("namespace" in r for r in self._registry._extension_roots) + if len(self._registry._extension_roots) > 1 or has_namespace: + discovered = scan_multi_root( + roots=self._registry._extension_roots, + max_depth=max_depth, + follow_symlinks=follow_symlinks, + ignore_patterns=ignore_patterns, + ) + else: + discovered = scan_extensions( + root=self._registry._extension_roots[0]["root"], + max_depth=max_depth, + follow_symlinks=follow_symlinks, + ignore_patterns=ignore_patterns, + ) + self._reject_ephemeral_discoveries(discovered) + return discovered + + @staticmethod + def _reject_ephemeral_discoveries(discovered: list[DiscoveredModule]) -> None: + """Reject scanned or mapped IDs in the reserved ``ephemeral.*`` namespace. + + Per protocol-spec §2.5.1, ``ephemeral.*`` is reserved + for programmatically-registered modules synthesized at runtime. Any + filesystem layout that produces such an ID is a configuration error — + either the directory is misnamed or the namespace prefix is being + misused. + """ + ids = sorted( + { + dm.canonical_id + for dm in discovered + if isinstance(dm.canonical_id, str) and _is_ephemeral(dm.canonical_id) + } + ) + if not ids: + return + raise InvalidInputError( + message=( + "Filesystem discovery produced module ID(s) in the reserved " + f"'ephemeral.*' namespace: {ids}. The ephemeral.* namespace is " + "reserved for programmatically-registered modules and may only " + "be used via Registry.register(). Rename the offending " + "directory or extension namespace, or correct the ID map." + ), + code=ErrorCodes.INVALID_MODULE_ID, + ) + + def _apply_path_filter( + self, + discovered: list[DiscoveredModule], + path_filter: str | list[str], + ) -> list[DiscoveredModule]: + """Filter ``discovered`` entries to those matching ``path_filter``. + + Each entry's ``file_path`` is tested against the supplied glob + pattern(s) using :meth:`pathlib.PurePath.match`. The match is tried + against both the absolute path and the path relative to each + configured extension root so that patterns like ``"*alpha*"`` work + as expected (PurePath.match anchors on the right-most segments). + """ + patterns: list[str] + if isinstance(path_filter, str): + patterns = [path_filter] + else: + patterns = list(path_filter) + if not patterns: + return discovered + + resolved_roots = [Path(r["root"]).resolve() for r in self._registry._extension_roots] + + def _matches(path: Path) -> bool: + candidates: list[PurePath] = [PurePath(str(path))] + for root in resolved_roots: + try: + candidates.append(PurePath(str(path.relative_to(root)))) + except ValueError: + continue + for cand in candidates: + for pat in patterns: + if cand.match(pat): + return True + return False + + return [dm for dm in discovered if _matches(dm.file_path)] + + def _apply_id_map_overrides(self, discovered: list[DiscoveredModule]) -> None: + """Apply ID-map overrides and check the resulting namespace.""" + if not self._registry._id_map: + return + resolved_roots = [Path(r["root"]).resolve() for r in self._registry._extension_roots] + for dm in discovered: + rel_path: str | None = None + for root in resolved_roots: + try: + rel_path = str(dm.file_path.relative_to(root)) + break + except ValueError: + continue + if rel_path and rel_path in self._registry._id_map: + dm.canonical_id = self._registry._id_map[rel_path]["id"] + self._reject_ephemeral_discoveries(discovered) + + @staticmethod + def _filter_invalid_discovery_ids(discovered: list[DiscoveredModule]) -> list[DiscoveredModule]: + """Check the final ID grammar before reading metadata or importing a module.""" + valid: list[DiscoveredModule] = [] + for dm in discovered: + try: + _validate_module_id(dm.canonical_id) + except InvalidInputError as exc: + logger.warning( + "Skipping discovered module with invalid ID '%s' at %s: %s", dm.canonical_id, dm.file_path, exc + ) + continue + valid.append(dm) + return valid + + @staticmethod + def _load_all_metadata(discovered: list[DiscoveredModule]) -> list[tuple[DiscoveredModule, dict[str, Any]]]: + """Read each optional companion ``*_meta.yaml`` and retain its candidate.""" + return [(dm, load_metadata(dm.meta_path) if dm.meta_path else {}) for dm in discovered] + + def _resolve_all_entry_points( + self, + candidates: list[tuple[DiscoveredModule, dict[str, Any]]], + ) -> list[_DiscoveryCandidate]: + """Resolve each discovered file with its own entry-point metadata.""" + from apcore.registry.registry import resolve_entry_point + + resolved: list[_DiscoveryCandidate] = [] + for dm, meta in candidates: + try: + entry_point = resolve_entry_point( + dm.file_path, meta=meta, pre_approval_hook=self._registry._pre_approval_hook + ) + except Exception as e: + logger.warning("Failed to resolve entry point for '%s': %s", dm.canonical_id, e) + continue + resolved.append(_DiscoveryCandidate(dm, entry_point, meta)) + return resolved + + def _validate_all(self, candidates: list[_DiscoveryCandidate]) -> list[_DiscoveryCandidate]: + """Run the custom or built-in validator over each class.""" + valid: list[_DiscoveryCandidate] = [] + for candidate in candidates: + if self._registry._custom_validator is not None: + errors = self._registry._custom_validator.validate(candidate.entry_point) + else: + errors = validate_module(candidate.entry_point) + if errors: + logger.warning("Module '%s' failed validation: %s", candidate.source.canonical_id, "; ".join(errors)) + continue + valid.append(candidate) + return valid + + @staticmethod + def _index_discovered_modules(candidates: list[_DiscoveryCandidate]) -> dict[str, _DiscoveryCandidate]: + """Keep the first valid candidate for each final ID in scan order.""" + selected: dict[str, _DiscoveryCandidate] = {} + for candidate in candidates: + module_id = candidate.source.canonical_id + previous = selected.get(module_id) + if previous is not None: + logger.warning( + "Duplicate module ID '%s' at %s, already found at %s. Skipping.", + module_id, + candidate.source.file_path, + previous.source.file_path, + ) + continue + selected[module_id] = candidate + return selected + + def reload_source_candidates(self, module_id: str) -> list[DiscoveredModule]: + candidates = self._scan_roots(*self.scan_params()) + self._apply_id_map_overrides(candidates) + return [item for item in self._filter_invalid_discovery_ids(candidates) if item.canonical_id == module_id] + + def watched_candidate(self, path: Path) -> DiscoveredModule | None: + max_depth, follow_symlinks, ignore_patterns = self.scan_params() + candidate = scan_watched_source( + path, self._registry._extension_roots, max_depth, follow_symlinks, ignore_patterns + ) + if candidate is not None: + self._reject_ephemeral_discoveries([candidate]) + self._apply_id_map_overrides([candidate]) + _validate_module_id(candidate.canonical_id) + return candidate diff --git a/python/src/apcore/registry/hot_reload_drain.py b/python/src/apcore/registry/hot_reload_drain.py new file mode 100644 index 00000000..699b89dc --- /dev/null +++ b/python/src/apcore/registry/hot_reload_drain.py @@ -0,0 +1,853 @@ +"""Registry drain coordination, watched replacement and managed reload.""" + +from __future__ import annotations + +import asyncio +import inspect +import logging +import threading +import time +from dataclasses import dataclass +from pathlib import Path +from typing import TYPE_CHECKING, Any, Callable, Literal + +from apcore.cancel import CancelToken +from apcore.errors import ErrorCodes, InvalidInputError, ModuleError, ModuleLoadError, ModuleNotFoundError +from apcore.lifecycle import ( + DrainAbortedContext, + DrainContext, + LifecycleError, + LifecycleOperation, + ReloadOptions, + _AbortReason, + _ReloadDrainAction, + _lifecycle_callback, + _validate_duration, +) +from apcore.registry.metadata import parse_dependencies +from apcore.registry.registry import ( + DEFAULT_MODULE_VERSION, + _ModuleRegistration, + _RegistrationSnapshot, + _WatchedReplacement, + _call_lifecycle_hook, + _ensure_schema_adapter, + _has_running_loop, + _prepare_discovered_module, +) + +from apcore.registry.validation import validate_module + +if TYPE_CHECKING: + from apcore.registry.registry import Registry, _PendingUnload + from apcore.registry.types import DiscoveredModule + +# Preserve the logger name consumed by existing hosts. +logger = logging.getLogger("apcore.registry.registry") + + +@dataclass +class _DrainProgress: + finished: bool = False + error: LifecycleError | None = None + + +def run_managed_drain( + registry: Registry, + operation: LifecycleOperation, + index: int, + module_id: str, + generation: object, + registration: _RegistrationSnapshot, + ready: threading.Event, + deadline: float, + drain_timeout_ms: int, + reason: Literal["unregister", "reload", "shutdown"], + *, + reload_policy: _ReloadDrainAction = "continue_waiting", + cancel_grace_ms: int | None = None, +) -> tuple[_AbortReason | None, LifecycleError | None, bool]: + token = CancelToken() + context = DrainContext(operation._id, module_id, reason, token, deadline) + registry._emit_lifecycle( + "module_drain_started", + operation, + module_id, + { + "reason_kind": reason, + "drain_timeout_ms": drain_timeout_ms, + }, + ) + progress = _begin_drain_hooks(registry, operation, index, module_id, registration, context) + with registry._lifecycle_changed: + registry._lifecycle_changed.wait_for( + lambda: progress.finished and (ready.is_set() or (reason == "reload" and progress.error is not None)), + timeout=max(0, deadline - time.monotonic()), + ) + active = registry._ref_counts.get(module_id, 0) + error_won = reason == "reload" and progress.finished and progress.error is not None + timed_out = not error_won and (not progress.finished or active > 0) + hook_running = not progress.finished + scopes = ( + tuple(registry._invocation_tokens.get(generation, ())) if timed_out and cancel_grace_ms is not None else () + ) + grace_deadline = None + if timed_out: + operation._update_module(index, drain_timed_out=True) + action = "cancel_then_force" if cancel_grace_ms is not None else reload_policy + registry._emit_lifecycle( + "module_drain_timed_out", + operation, + module_id, + { + "reason_kind": reason, + "action": action, + "active_count": active, + }, + severity="warn", + ) + if hook_running: + _signal_lifecycle_token(token) + if cancel_grace_ms is not None: + grace_deadline = time.monotonic() + cancel_grace_ms / 1000 + for scope in scopes: + _signal_lifecycle_token(scope) + with registry._lifecycle_changed: + registry._lifecycle_changed.wait_for(lambda: progress.finished) + if reason == "reload": + if timed_out and reload_policy == "abort_reload": + return "drain_timeout", LifecycleError(ErrorCodes.RELOAD_FAILED, "draining"), timed_out + if progress.error is not None: + return "drain_error", progress.error, timed_out + ready.wait(timeout=None if grace_deadline is None else max(0, grace_deadline - time.monotonic())) + return None, progress.error, timed_out + + +def _signal_lifecycle_token(token: CancelToken) -> None: + try: + token.cancel() + except Exception as error: + logger.warning("Lifecycle cancellation listener failed: %s", type(error).__name__) + + +def _begin_drain_hooks( + registry: Registry, + operation: LifecycleOperation, + index: int, + module_id: str, + registration: _RegistrationSnapshot, + context: DrainContext, +) -> _DrainProgress: + progress = _DrainProgress() + + def run() -> None: + try: + for instance in registration.instances(): + try: + hook = getattr(instance, "on_drain", None) + if callable(hook): + operation._update_module(index, active_hook="on_drain") + with _lifecycle_callback(registry, operation._id): + _call_lifecycle_hook( + hook, (context,), registration.hook_loop(instance), module_id, "on_drain" + ) + except BaseException as error: + progress.error = progress.error or LifecycleError._from_exception(error, "draining") + finally: + operation._update_module(index, active_hook=None) + with registry._lifecycle_changed: + progress.finished = True + registry._lifecycle_changed.notify_all() + + try: + if any(callable(getattr(instance, "on_drain", None)) for instance in registration.instances()): + threading.Thread(target=run, name="apcore-module-drain", daemon=True).start() + else: + progress.finished = True + except Exception as error: + progress.error = LifecycleError._from_exception(error, "draining") + progress.finished = True + return progress + + +def start_managed_reload( + registry: Registry, + module_ids: list[str], + drain_timeout_ms: int, + policy: _ReloadDrainAction, + on_reloaded: Callable[[str, str, str, str], None], + *, + exact: bool = False, + prepared: _WatchedReplacement | None = None, +) -> LifecycleOperation: + with registry._lock: + registry._require_open() + plan = [ + (module_id, generation, registry._snapshot_registration(module_id)) + for module_id, generation in registry._snapshot_generations(iter(module_ids)) + ] + for module_id, generation, registration in plan: + if generation is None or registration is None: + if exact: + raise ModuleNotFoundError(module_id=module_id) + continue + for module in registration.instances(): + if callable(getattr(module, "on_drain", None)) and not callable(getattr(module, "on_drain_aborted", None)): + raise InvalidInputError( + message=f"Module '{module_id}' must pair on_drain with on_drain_aborted for managed reload" + ) + operation = LifecycleOperation("reload", registry=registry) + operation._set_modules(iter(module_ids)) + if not plan: + operation._complete() + return operation + + def run() -> None: + try: + for index, (module_id, generation, registration) in enumerate(plan): + _run_managed_reload( + registry, + operation, + index, + module_id, + generation, + registration, + drain_timeout_ms, + policy, + on_reloaded, + prepared, + ) + operation._complete() + finally: + if prepared is not None: + _finish_watched_replacement(registry, prepared) + + operation._start(run, "loading") + return operation + + +def _run_managed_reload( + registry: Registry, + operation: LifecycleOperation, + index: int, + module_id: str, + generation: object | None, + registration: _RegistrationSnapshot | None, + timeout_ms: int, + policy: _ReloadDrainAction, + on_reloaded: Callable[[str, str, str, str], None], + prepared: _WatchedReplacement | None, +) -> None: + with registry._lock: + if ( + registry._closed + or generation is None + or registration is None + or (prepared is not None and prepared.generation is not generation) + or registry._lease_generations.get(module_id) is not generation + or module_id in registry._draining + or module_id in registry._in_flight + or module_id in registry._unavailable + or (current := registry._snapshot_registration(module_id)) is None + or current.module is not registration.module + or current.versions.keys() != registration.versions.keys() + or any(current.versions[key] is not value for key, value in registration.versions.items()) + ): + conflict = LifecycleError(ErrorCodes.MODULE_RELOAD_CONFLICT, "draining") + operation._update_module(index, phase="done", outcome="failed", error=conflict, compensation="not_required") + return + ready = registry._mark_draining(module_id) + deadline = time.monotonic() + timeout_ms / 1000 + operation._update_module(index, phase="draining") + abort, error, timed_out = run_managed_drain( + registry, + operation, + index, + module_id, + generation, + registration, + ready, + deadline, + timeout_ms, + "reload", + reload_policy=policy, + ) + if abort is not None: + _recover_managed_reload(registry, operation, index, module_id, registration, abort, error) + return + + with registry._lifecycle_changed: + if registry._closed: + registry._draining.discard(module_id) + registry._drain_events.pop(module_id, None) + registry._lifecycle_changed.notify_all() + conflict = LifecycleError(ErrorCodes.MODULE_RELOAD_CONFLICT, "draining") + operation._update_module(index, phase="done", outcome="failed", error=conflict, compensation="not_required") + return + pending = registry._detach_registration(module_id) + registry._in_flight.add(module_id) + assert pending is not None + pending.drain_timed_out = timed_out + _replace_managed_generation(registry, operation, index, module_id, pending, on_reloaded, prepared) + + +def _recover_managed_reload( + registry: Registry, + operation: LifecycleOperation, + index: int, + module_id: str, + registration: _RegistrationSnapshot, + abort: _AbortReason, + error: LifecycleError | None, +) -> None: + operation._update_module(index, phase="recovering", abort_reason=abort) + context = DrainAbortedContext(operation._id, module_id, abort, CancelToken()) + recovery_error = None + for module in registration.instances(): + try: + hook = getattr(module, "on_drain_aborted", None) + if callable(getattr(module, "on_drain", None)) and callable(hook): + operation._update_module(index, active_hook="on_drain_aborted") + with _lifecycle_callback(registry, operation._id): + _call_lifecycle_hook( + hook, (context,), registration.hook_loop(module), module_id, "on_drain_aborted" + ) + except BaseException as failure: + recovery_error = recovery_error or LifecycleError._from_exception(failure, "recovering") + with registry._lifecycle_changed: + ready = recovery_error is None and not registry._closed + if not ready: + registry._unavailable.add(module_id) + registry._draining.discard(module_id) + registry._drain_events.pop(module_id, None) + registry._lifecycle_changed.notify_all() + outcome = "retained_ready" if ready else "retained_unavailable" + operation._update_module( + index, + phase="done", + active_hook=None, + outcome=outcome, + error=recovery_error or error, + compensation="not_required", + ) + registry._emit_lifecycle( + "module_drain_recovered", + operation, + module_id, + { + "abort_reason": abort, + "outcome": outcome, + }, + severity="info" if ready else "error", + ) + + +def _replace_managed_generation( + registry: Registry, + operation: LifecycleOperation, + index: int, + module_id: str, + pending: _PendingUnload, + on_reloaded: Callable[[str, str, str, str], None], + prepared: _WatchedReplacement | None, +) -> None: + old = pending.registration + state = None + phase = "unloading" + try: + operation._update_module(index, phase="unloading") + try: + if callable(getattr(old.module, "on_suspend", None)): + operation._update_module(index, active_hook="on_suspend") + with _lifecycle_callback(registry, operation._id): + state = registry._call_on_suspend(module_id, old.module, old.hook_loop(old.module)) + finally: + operation._update_module(index, active_hook=None) + unload_error = registry._finish_unload(pending, operation, index) + if unload_error is not None: + raise ModuleError(unload_error.code, "Module unload failed") + phase = "loading" + operation._update_module(index, phase="loading") + if prepared is None: + replacement = _replacement_snapshot(registry, module_id, old) + else: + with registry._lock: + _require_current_watched_source(registry, module_id, prepared) + replacement = prepared.registration + _activate_managed_snapshot(registry, operation, index, module_id, replacement, state, watched=prepared) + except BaseException as failure: + error = ( + LifecycleError(ErrorCodes.MODULE_LOAD_ERROR, "loading") + if phase == "loading" and not isinstance(failure, ModuleError) + else LifecycleError._from_exception(failure, phase) + ) + if prepared is not None and not prepared.source.is_file(): + # Deletion is terminal for this source. Never republish its old registration. + compensation = "not_required" + else: + restored = _compensate_managed_reload(registry, operation, index, module_id, old, state, watched=prepared) + compensation = "restored" if restored else "failed" + operation._update_module( + index, phase="done", active_hook=None, outcome="failed", error=error, compensation=compensation + ) + registry._emit_lifecycle( + "module_reload_failed", + operation, + module_id, + { + "phase": error.phase, + "error_code": error.code, + "compensation": compensation, + }, + severity="error", + ) + return + finally: + with registry._lock: + registry._clear_loading(module_id) + + previous_version = str(old.metadata.get("version") or DEFAULT_MODULE_VERSION) + new_version = str(replacement.metadata.get("version") or DEFAULT_MODULE_VERSION) + operation._update_module(index, phase="done", outcome="reloaded", compensation="not_required") + try: + on_reloaded(module_id, previous_version, new_version, operation._id) + except Exception as failure: + logger.warning("Could not record successful reload of %s: %s", module_id, type(failure).__name__) + + +def _compensate_managed_reload( + registry: Registry, + operation: LifecycleOperation, + index: int, + module_id: str, + registration: _RegistrationSnapshot, + state: dict[str, Any] | None, + *, + watched: _WatchedReplacement | None = None, +) -> bool: + try: + with registry._lock: + registry._require_open() + _activate_managed_snapshot(registry, operation, index, module_id, registration, state, watched=watched) + return True + except BaseException as failure: + logger.error("Managed reload compensation failed for %s: %s", module_id, type(failure).__name__) + return False + + +def _activate_managed_snapshot( + registry: Registry, + operation: LifecycleOperation, + index: int, + module_id: str, + registration: _RegistrationSnapshot, + state: dict[str, Any] | None, + *, + watched: _WatchedReplacement | None = None, +) -> None: + initialized = [] + try: + with _lifecycle_callback(registry, operation._id): + for module in registration.instances(): + loop = registration.hook_loop(module) + registry._validate_hook_adapter(module_id, module, loop) + hook = getattr(module, "on_load", None) + if callable(hook): + operation._update_module(index, phase="loading", active_hook="on_load") + _call_lifecycle_hook(hook, (), loop, module_id, "on_load") + initialized.append(module) + if module is registration.module and state is not None and callable(getattr(module, "on_resume", None)): + operation._update_module(index, phase="resuming", active_hook="on_resume") + registry._call_on_resume(module_id, module, state, loop) + operation._update_module(index, active_hook=None) + with registry._lock: + registry._require_open() + if watched is not None and registration is watched.registration: + _require_current_watched_source(registry, module_id, watched) + elif watched is not None and not watched.source.is_file(): + raise ModuleLoadError(module_id, "Watched module source was deleted before restoration") + registry._publish_snapshot(module_id, registration) + registry._trigger_event("register", module_id, registration.module) + except BaseException: + with _lifecycle_callback(registry, operation._id): + for module in reversed(initialized): + registry._call_on_unload(module_id, module, hook_loop=registration.hook_loop(module)) + raise + + +def _replacement_snapshot(registry: Registry, module_id: str, old: _RegistrationSnapshot) -> _RegistrationSnapshot: + loop = old.hook_loop(old.module) + source = None + metadata: dict[str, Any] = {} + if registry._custom_discoverer is not None: + roots = [str(root["root"]) for root in registry._extension_roots] + modules = registry._custom_discoverer.discover(roots) + match = next( + (entry for entry in modules if isinstance(entry, dict) and entry.get("module_id") == module_id), None + ) + if match is None or "module" not in match: + raise ModuleLoadError(module_id, "The replacement was not discovered") + module = match["module"] + errors = validate_module(module, programmatic=True) + if not errors and registry._custom_validator is not None: + errors = registry._custom_validator.validate(module) + if errors: + raise ModuleLoadError(module_id, "The replacement is not a valid module") + _ensure_schema_adapter(module, normalize_legacy_none=True) + else: + candidates = ( + [_watched_candidate(registry, old.source_path)] + if old.source_path is not None + else _reload_source_candidates(registry, module_id) + ) + target = next((item for item in candidates if item is not None and item.canonical_id == module_id), None) + if target is None: + raise ModuleLoadError(module_id, "The replacement source was not discovered") + selected = registry._filesystem_discovery().load_candidates([target]) + if not selected: + raise ModuleLoadError(module_id, "The replacement source was invalid") + source = target.file_path + metadata = selected[0].metadata + module = selected[0].entry_point() + merged = _prepare_discovered_module(module_id, module, metadata) + version = registry._effective_version(module, metadata) + deps = parse_dependencies(metadata.get("dependencies")) + with registry._lock: + failure = registry._discovery_dependency_error(module_id, deps) + if failure is not None: + raise failure + registration = _ModuleRegistration(module, merged, metadata, loop) + return _RegistrationSnapshot(module, merged, {version: registration}, source) + + +def _reload_source_candidates(registry: Registry, module_id: str) -> list[DiscoveredModule]: + return registry._filesystem_discovery().reload_source_candidates(module_id) + + +def watch(registry: Registry, *, lifecycle: ReloadOptions | None = None) -> None: + """Start watching extension directories for file changes. + + Requires the optional ``watchdog`` dependency. + Raises ImportError if watchdog is not installed. + """ + hook_loop = None + if lifecycle is not None: + if not isinstance(lifecycle, ReloadOptions): + raise InvalidInputError(message="Expected ReloadOptions for watch lifecycle") + _validate_duration("drain_timeout_ms", lifecycle.drain_timeout_ms) + if lifecycle.drain_timeout_ms is None or lifecycle.on_drain_timeout not in ( + "continue_waiting", + "abort_reload", + ): + raise InvalidInputError(message="Invalid watch lifecycle policy") + if _has_running_loop(): + hook_loop = asyncio.get_running_loop() + from apcore.registry.watcher import load_observer_factory + + create_observer = load_observer_factory() + + with registry._lock: + registry._require_open() + if registry._observer is not None: + return + observer = create_observer(registry, registry._extension_roots) + registry._watch_lifecycle = lifecycle + registry._watch_hook_loop = hook_loop + observer.start() + registry._observer = observer + + +def unwatch(registry: Registry) -> None: + """Stop watching extension directories for file changes.""" + with registry._lock: + observer = registry._observer + registry._observer = None + registry._watch_lifecycle = None + registry._watch_hook_loop = None + registry._watched_replacements.clear() + if observer is not None: + observer.stop() + observer.join() + + +def _watched_candidate(registry: Registry, path: Path) -> DiscoveredModule | None: + return registry._filesystem_discovery().watched_candidate(path) + + +def handle_file_change(registry: Registry, path: str) -> None: + """Handle a file modification or creation event. + + Performs arbitrary-Python import (``resolve_entry_point``) and user + hooks (``on_suspend``/``on_unload``/``on_resume``) OUTSIDE + ``registry._lock`` so a slow or re-entrant module cannot block unrelated + registry queries or deadlock a callback that calls back into the + registry. Lock is acquired only for the two short atomic sections: + capturing the old module's snapshot + state maps, and inserting the + new instance into all internal maps (``_modules``, ``_module_meta``, + ``_lowercase_map``, ``_versioned_modules``). + """ + if defer_watched_change(registry, path): + return + # Phase 1 (outside lock): compile + instantiate + validate new module. + try: + candidate = _watched_candidate(registry, Path(path)) + if candidate is None: + return + new_id = candidate.canonical_id + source = candidate.file_path + with registry._lock: + if new_id in registry._modules and registry._module_sources.get(new_id) != source: + logger.warning("Hot reload skipped '%s' because it is registered from another source", new_id) + return + managed = registry._watch_lifecycle is not None + revision = _source_revision(source) if managed else None + metadata, cls = registry._filesystem_discovery().load_watched_entry_point(candidate) + except Exception as e: + logger.warning("Hot reload failed to resolve entry point for %s: %s", path, e) + return + + try: + instance = cls() + except Exception as e: + logger.warning("Hot reload failed to instantiate class from %s: %s", path, e) + return + + validation_errors = validate_module(instance) + if validation_errors: + logger.warning( + "Hot reload rejected module from %s: validation failed (%s)", + path, + "; ".join(validation_errors), + ) + return + + try: + effective_version = registry._effective_version(instance, metadata) + merged_meta = _prepare_discovered_module(new_id, instance, metadata) + except Exception as error: + logger.warning("Hot reload rejected module from %s: %s", path, error) + return + + if registry._custom_validator is not None: + try: + errors = registry._custom_validator.validate(instance) + except Exception as e: + logger.warning( + "Hot reload rejected module from %s: custom validator raised: %s", + path, + e, + ) + return + if errors: + logger.warning("Hot reload rejected module from %s: %s", path, "; ".join(errors)) + return + + # Reuse the registration's adapter on the watcher thread. An opted-in + # watcher can also introduce async-capable registrations on its loop. + with registry._lock: + if registry._closed or new_id in registry._in_flight or new_id in registry._draining: + return + exists = new_id in registry._modules + current = registry._snapshot_registration(new_id) + hook_loop = current.hook_loop(current.module) if current is not None else registry._watch_hook_loop + options = registry._watch_lifecycle + if exists and options is not None: + watched_generation = registry._lease_generations.setdefault(new_id, object()) + else: + watched_generation = None + if not exists: + registry._in_flight.add(new_id) + if watched_generation is not None and options is not None: + _start_watched_replacement( + registry, + new_id, + instance, + source, + effective_version, + metadata, + merged_meta, + hook_loop, + watched_generation, + options, + revision, + ) + return + old_registration: _RegistrationSnapshot | None = None + suspended_state: dict[str, Any] | None = None + if exists: + detached = registry._detach_after_drain(new_id, reserve_replacement=True, source_path=source) + if detached is None: + return + pending, clean = detached + old_registration = pending.registration + # Phase 3: run hooks on the old module outside the registry lock. + suspended_state = registry._capture_state_and_unload(pending, clean) + + with registry._resume_on_load(new_id, suspended_state): + if not registry._invoke_on_load(new_id, instance, hook_loop=hook_loop): + _restore_after_failed_hot_reload(registry, new_id, old_registration, suspended_state) + return + with registry._ready_to_publish(new_id, instance, hook_loop=hook_loop) as admitted: + if not admitted: + return + registration = _ModuleRegistration(instance, merged_meta, metadata, hook_loop) + registry._publish_snapshot( + new_id, _RegistrationSnapshot(instance, merged_meta, {effective_version: registration}, source) + ) + + # Phase 5 (outside lock): notify observers of the initialized module. + registry._trigger_event("register", new_id, instance) + + +def _start_watched_replacement( + registry: Registry, + module_id: str, + module: Any, + source: Path, + version: str, + metadata: dict[str, Any], + merged_meta: dict[str, Any], + loop: asyncio.AbstractEventLoop | None, + generation: object, + options: ReloadOptions, + revision: tuple[int, int, int, int] | None, +) -> None: + try: + registry._validate_hook_adapter(module_id, module, loop) + if inspect.iscoroutinefunction(getattr(module, "on_load", None)) and (loop is None or not loop.is_running()): + raise ModuleLoadError(module_id, "Async on_load requires an available lifecycle event loop") + registration = _ModuleRegistration(module, merged_meta, metadata, loop) + replacement = _RegistrationSnapshot(module, merged_meta, {version: registration}, source) + watched = _WatchedReplacement(generation, replacement, source, revision) + with registry._lock: + if registry._closed or registry._watch_lifecycle is not options or source in registry._watched_replacements: + return + registry._watched_replacements[source] = watched + try: + registry._start_managed_reload( + [module_id], + options.drain_timeout_ms, + options.on_drain_timeout, + lambda *_: None, + exact=True, + prepared=watched, + ) + except BaseException: + with registry._lock: + if registry._watched_replacements.get(source) is watched: + registry._watched_replacements.pop(source) + raise + except Exception as error: + logger.warning("Watcher could not start reload for '%s': %s", module_id, type(error).__name__) + + +def _source_revision(source: Path) -> tuple[int, int, int, int] | None: + try: + details = source.stat() + except OSError: + return None + return (details.st_dev, details.st_ino, details.st_mtime_ns, details.st_size) + + +def defer_watched_change(registry: Registry, path: str) -> bool: + """Keep one pending refresh per source while its replacement owns admission.""" + with registry._lock: + if not registry._watched_replacements: + return False + try: + source = Path(path).resolve() + except (OSError, RuntimeError): + return False + with registry._lock: + watched = registry._watched_replacements.get(source) + if watched is None: + return False + watched.refresh |= _source_revision(source) != watched.revision + return True + + +def _require_current_watched_source(registry: Registry, module_id: str, watched: _WatchedReplacement) -> None: + """Check the candidate revision and watcher ownership under the Registry lock.""" + if registry._watched_replacements.get(watched.source) is not watched: + raise ModuleLoadError(module_id, "Watcher stopped before module replacement") + watched.refresh |= _source_revision(watched.source) != watched.revision + if watched.refresh or watched.revision is None: + raise ModuleLoadError(module_id, "Watched module source changed during replacement") + + +def _finish_watched_replacement(registry: Registry, watched: _WatchedReplacement) -> None: + with registry._lock: + if registry._watched_replacements.get(watched.source) is not watched: + return + registry._watched_replacements.pop(watched.source) + if registry._closed or registry._watch_lifecycle is None: + return + revision = _source_revision(watched.source) + if not watched.refresh and revision == watched.revision: + return + if revision is None: + registry._handle_file_deletion(str(watched.source)) + else: + registry._handle_file_change(str(watched.source)) + + +def _restore_after_failed_hot_reload( + registry: Registry, + module_id: str, + registration: _RegistrationSnapshot | None, + suspended_state: dict[str, Any] | None, +) -> None: + """Republish the previous instance after a hot reload failed to load. + + D-123, applying D-112 rules 2-4 to the watch-driven path. Phase 2 has + already unregistered the old instance and Phase 3 has already run its + ``on_unload``, so restoring it means re-running ``on_load`` — a module + republished without it would be visible but torn down, which D-112 rule + 2 names as the state this whole decision exists to avoid. + + When the restoring load ALSO fails the module stays unavailable + (D-112 rule 3): there is no good state left to return to, and publishing + a module whose load hook failed is the defect the deferred-publish rule + exists to prevent. Nothing is restored when the reload created a module + that did not previously exist — there is no previous instance to return + to, and the file simply failed to load. + """ + if registration is None: + logger.error( + "Hot reload of '%s' failed its on_load() and there was no previous " + "instance to restore; the module is not registered.", + module_id, + ) + return + + if not registry._restore_registration(module_id, registration, suspended_state): + logger.error( + "Hot reload of '%s' failed its on_load(), and re-loading the previous " + "instance failed as well; the module stays unavailable (D-112 rule 3).", + module_id, + ) + return + + logger.warning( + "Hot reload of '%s' failed its on_load(); the previous instance was restored.", + module_id, + ) + + +def handle_file_deletion(registry: Registry, path: str) -> None: + """Drain the module, then unload it when its source file is deleted.""" + if defer_watched_change(registry, path): + return + try: + source = Path(path).resolve() + except (OSError, RuntimeError): + logger.warning("Hot reload could not resolve deleted path %s", path) + return + if source.exists(): + return + with registry._lock: + module_ids = [module_id for module_id, file_path in registry._module_sources.items() if file_path == source] + for module_id in module_ids: + detached = registry._detach_after_drain(module_id, source_path=source) + if detached is not None: + registry._finish_unload(detached[0]) diff --git a/python/src/apcore/registry/registry.py b/python/src/apcore/registry/registry.py index 70d80486..8f496883 100644 --- a/python/src/apcore/registry/registry.py +++ b/python/src/apcore/registry/registry.py @@ -9,7 +9,7 @@ import re import threading import time -from collections.abc import Iterable +from collections.abc import Iterable, Sequence from contextlib import contextmanager from contextvars import ContextVar from copy import deepcopy @@ -29,8 +29,6 @@ StreamingInterfaceError, ) from apcore.lifecycle import ( - DrainAbortedContext, - DrainContext, LifecycleError, LifecycleOperation, ReloadOptions, @@ -45,21 +43,18 @@ ) from apcore.registry.conflicts import ConflictSeverity, detect_id_conflicts from apcore.registry.dependencies import resolve_dependencies -from apcore.registry.entry_point import resolve_entry_point +from apcore.registry.entry_point import resolve_entry_point as resolve_entry_point from apcore.schema.annotations import governance_union from apcore.registry.metadata import ( - load_id_map, - load_metadata, merge_module_metadata, parse_dependencies, ) -from apcore.registry.scanner import scan_extensions, scan_multi_root, scan_watched_source -from apcore.registry.types import DependencyInfo, DiscoveredModule, ModuleDescriptor +from apcore.registry.types import DependencyInfo, ModuleDescriptor from apcore.registry.validation import validate_module from apcore.registry.version import VersionedStore, matches_version_hint if TYPE_CHECKING: - from apcore.config import Config + from apcore.registry.filesystem_discovery import FilesystemDiscovery logger = logging.getLogger(__name__) _HookLoopFor = Callable[[str], asyncio.AbstractEventLoop | None] @@ -129,19 +124,6 @@ class _PendingUnload: error: LifecycleError | None = None -@dataclass -class _DrainProgress: - finished: bool = False - error: LifecycleError | None = None - - -@dataclass(frozen=True) -class _DiscoveryCandidate: - source: DiscoveredModule - entry_point: type - metadata: dict[str, Any] - - def _canonical_deprecation(deprecation: dict[str, Any]) -> str: """Canonical rendering of an ``x-deprecation`` block, for the D-89 key. @@ -555,7 +537,7 @@ def __init__( # `scan_multi_root` below has always been able to do the work — # including the namespace prefixing `roots` exists for — and nothing # extracted the list from a `Config` to reach it. - self._extension_roots = self._roots_from_config(config) + self._extension_roots = self._filesystem_discovery().roots_from_config(config) else: self._extension_roots = [{"root": Config.get_default("extensions.root")}] @@ -583,6 +565,7 @@ def __init__( self._id_map: dict[str, dict[str, Any]] = {} self._schema_cache: dict[str, dict[str, Any]] = {} self._config = config + self._logged_follow_symlinks_warning = False self._metrics_collector = metrics_collector self._pre_approval_hook = pre_approval_hook self._custom_discoverer: Discoverer | None = None @@ -619,6 +602,7 @@ def __init__( self._shutdown_legacy_force = False self._shutdown_cancel_grace_ms: int | None = None self._unavailable: set[str] = set() + self._observer: Any = None self._watch_lifecycle: ReloadOptions | None = None self._watch_hook_loop: asyncio.AbstractEventLoop | None = None self._watched_replacements: dict[Path, _WatchedReplacement] = {} @@ -628,76 +612,8 @@ def __init__( # Concurrent same-ID registrations see the in-flight set and raise DUPLICATE_MODULE_ID. self._in_flight: set[str] = set() - # Load the ID map: explicit argument > `id_map.overrides` > none. - # - # PROTOCOL_SPEC §9.1.1 declares `id_map.overrides` and nothing read it - # (apcore#118, decision D-71). The MECHANISM was implemented in all - # three SDKs — this class's `_apply_id_map_overrides` is stage 2 of - # discovery — and the map arrived only through this constructor's - # `id_map_path`. Measured before the fix: with `id_map.overrides` - # pointing at a map that renames `executor/orig/mod.py`, discovery still - # registered `executor.orig.mod`. - # - # The precedence is D-73's, and the same one `extensions.root` follows - # above: an API argument beats `Config`. - # - # Config paths share the project root (§9.2.2). - resolved_id_map = id_map_path - if resolved_id_map is None and config is not None: - from_config = config.get("id_map.overrides") - if isinstance(from_config, str) and from_config.strip(): - resolved_id_map = config.resolve_path(from_config) - if resolved_id_map is not None: - self._id_map = load_id_map(resolved_id_map) - - @staticmethod - def _roots_from_config(config: Config) -> list[dict[str, Any]]: - """`extensions.roots` if declared, else `extensions.root`, else the default. - - Both element shapes `$defs/ExtensionsConfig` admits are accepted: a bare - path string and an object carrying an explicit `namespace`. - - **Every entry gets a namespace here**, derived from the last path - segment when the entry does not name one — the same value - `scan_multi_root` would derive. Deriving it at this door rather than - leaving it to the scanner is what makes a ONE-element `roots` list - behave like an n-element one: the scan dispatches on "more than one root - or any namespace", so a lone `roots: ["./beta"]` would otherwise take - the single-root branch and prefix nothing. Nothing in the schema makes a - one-element list special, and `roots` versus `root` is the whole - distinction between namespaced and backward-compatible mode. - - A `roots` list that is present but yields no usable entry falls through - to the single-root branch rather than scanning nothing: an empty list is - a configuration that discovers no modules, and silently discovering none - is the failure this whole audit is about. - """ - declared = config.get("extensions.roots") - if isinstance(declared, list): - entries: list[dict[str, Any]] = [] - for item in declared: - if isinstance(item, str) and item.strip(): - entries.append({"root": config.resolve_path(item), "namespace": Path(item).name}) - elif isinstance(item, dict) and item.get("root"): - root_value = item["root"] - entries.append( - { - "root": config.resolve_path(str(root_value)), - "namespace": item.get("namespace") or Path(str(root_value)).name, - } - ) - if entries: - return entries - if declared: - logger.warning( - "extensions.roots is declared with %d entry/entries and none of them " - "names a root, so it was ignored and extensions.root is used instead. " - "An entry is either a path string or an object with a 'root' key.", - len(declared), - ) - - ext_root = config.get("extensions.root") or Config.get_default("extensions.root") - return [{"root": config.resolve_path(ext_root)}] + if id_map_path is not None or config is not None: + self._id_map = self._filesystem_discovery().id_map_from_config(config, id_map_path) # ----- Custom Discoverer / Validator ----- @@ -893,33 +809,8 @@ def _discover_default( path_filter: str | list[str] | None = None, hook_loop_for: _HookLoopFor | None = None, ) -> int: - """Run discovery using the default file-system scanning logic. - - Orchestrates 8 named stages; per-stage logic lives in the dedicated - helpers below: - - 1. ``_scan_roots`` -- walk extension root(s) for candidate files. - 2. ``_apply_path_filter`` -- narrow the candidate set (optional). - 3. ``_apply_id_map_overrides`` -- apply overrides and validate final IDs. - 4. ``_load_all_metadata`` -- read each module's metadata block. - 5. ``_resolve_all_entry_points`` -- import the entry-point classes. - 6. ``_validate_all`` then ``_index_discovered_modules`` -- validate - candidate classes and check conflicts among final IDs in the batch. - 7. ``_resolve_load_order`` -- dependency-aware ordering. - 8. ``_filter_id_conflicts`` then ``_register_in_order`` -- check the - published registry and register in order. - - Mirrors the structure of - ``apcore-typescript/src/registry/registry.ts:_discoverDefault``. - """ - max_depth, follow_symlinks, ignore_patterns = self._scan_params() - discovered = self._scan_roots(max_depth, follow_symlinks, ignore_patterns) - if path_filter is not None: - discovered = self._apply_path_filter(discovered, path_filter) - self._apply_id_map_overrides(discovered) - valid_ids = self._filter_invalid_discovery_ids(discovered) - candidates = self._resolve_all_entry_points(self._load_all_metadata(valid_ids)) - selected = self._index_discovered_modules(self._validate_all(candidates)) + """Load filesystem candidates and publish them in dependency order.""" + discovered_count, selected = self._filesystem_discovery().collect(path_filter) valid_classes = {module_id: candidate.entry_point for module_id, candidate in selected.items()} raw_metadata = {module_id: candidate.metadata for module_id, candidate in selected.items()} load_order = self._resolve_load_order(valid_classes, raw_metadata) @@ -927,215 +818,23 @@ def _discover_default( source_paths = {module_id: candidate.source.file_path for module_id, candidate in selected.items()} registered_count = self._register_in_order(load_order, valid_classes, raw_metadata, source_paths, hook_loop_for) - if registered_count == 0 and discovered: + if registered_count == 0 and discovered_count: logger.warning( "No modules successfully registered from %d discovered files", - len(discovered), + discovered_count, ) elif registered_count == 0: logger.warning("No modules discovered") return registered_count - def _scan_params(self) -> tuple[int, bool, list[str]]: - """Resolve scan parameters from config, falling back to spec defaults. - - Logs a WARN on the first call with ``follow_symlinks=True`` so - operators see the trust-boundary reminder in logs when they opt - into broader filesystem traversal. The scanner itself already - refuses to follow symlinks escaping the extension root (see - ``scan_extensions``); this log is a secondary signal that the - configuration enables a potentially sensitive feature. - """ - if self._config is None: - return 8, False, [] - max_depth = self._config.get("extensions.max_depth", 8) - follow_symlinks = self._config.get("extensions.follow_symlinks", False) - ignore_patterns = self._config.get("extensions.ignore_patterns", []) or [] - if follow_symlinks and not getattr(self, "_logged_follow_symlinks_warning", False): - logger.warning( - "extensions.follow_symlinks=True — scanner will traverse symlinked " - "directories (confined to the extension root). Ensure the root is " - "trusted; see apcore.registry.entry_point for the trust-boundary note." - ) - self._logged_follow_symlinks_warning = True - return (max_depth, follow_symlinks, list(ignore_patterns)) - - def _scan_roots( - self, max_depth: int, follow_symlinks: bool, ignore_patterns: list[str] | None = None - ) -> list[DiscoveredModule]: - """Stage 1 — walk extension root(s) and return DiscoveredModule entries.""" - has_namespace = any("namespace" in r for r in self._extension_roots) - if len(self._extension_roots) > 1 or has_namespace: - discovered = scan_multi_root( - roots=self._extension_roots, - max_depth=max_depth, - follow_symlinks=follow_symlinks, - ignore_patterns=ignore_patterns, - ) - else: - discovered = scan_extensions( - root=self._extension_roots[0]["root"], - max_depth=max_depth, - follow_symlinks=follow_symlinks, - ignore_patterns=ignore_patterns, - ) - self._reject_ephemeral_discoveries(discovered) - return discovered - - @staticmethod - def _reject_ephemeral_discoveries(discovered: list[DiscoveredModule]) -> None: - """Reject scanned or mapped IDs in the reserved ``ephemeral.*`` namespace. - - Per protocol-spec §2.5.1, ``ephemeral.*`` is reserved - for programmatically-registered modules synthesized at runtime. Any - filesystem layout that produces such an ID is a configuration error — - either the directory is misnamed or the namespace prefix is being - misused. - """ - ids = sorted( - { - dm.canonical_id - for dm in discovered - if isinstance(dm.canonical_id, str) and _is_ephemeral(dm.canonical_id) - } - ) - if not ids: - return - raise InvalidInputError( - message=( - "Filesystem discovery produced module ID(s) in the reserved " - f"'ephemeral.*' namespace: {ids}. The ephemeral.* namespace is " - "reserved for programmatically-registered modules and may only " - "be used via Registry.register(). Rename the offending " - "directory or extension namespace, or correct the ID map." - ), - code=ErrorCodes.INVALID_MODULE_ID, - ) - - def _apply_path_filter( - self, - discovered: list[DiscoveredModule], - path_filter: str | list[str], - ) -> list[DiscoveredModule]: - """Filter ``discovered`` entries to those matching ``path_filter``. - - Each entry's ``file_path`` is tested against the supplied glob - pattern(s) using :meth:`pathlib.PurePath.match`. The match is tried - against both the absolute path and the path relative to each - configured extension root so that patterns like ``"*alpha*"`` work - as expected (PurePath.match anchors on the right-most segments). - """ - from pathlib import PurePath - - patterns: list[str] - if isinstance(path_filter, str): - patterns = [path_filter] - else: - patterns = list(path_filter) - if not patterns: - return discovered + def _filesystem_discovery(self) -> FilesystemDiscovery: + from apcore.registry.filesystem_discovery import FilesystemDiscovery - resolved_roots = [Path(r["root"]).resolve() for r in self._extension_roots] + return FilesystemDiscovery(self) - def _matches(path: Path) -> bool: - candidates: list[PurePath] = [PurePath(str(path))] - for root in resolved_roots: - try: - candidates.append(PurePath(str(path.relative_to(root)))) - except ValueError: - continue - for cand in candidates: - for pat in patterns: - if cand.match(pat): - return True - return False - - return [dm for dm in discovered if _matches(dm.file_path)] - - def _apply_id_map_overrides(self, discovered: list[DiscoveredModule]) -> None: - """Apply ID-map overrides and check the resulting namespace.""" - if not self._id_map: - return - resolved_roots = [Path(r["root"]).resolve() for r in self._extension_roots] - for dm in discovered: - rel_path: str | None = None - for root in resolved_roots: - try: - rel_path = str(dm.file_path.relative_to(root)) - break - except ValueError: - continue - if rel_path and rel_path in self._id_map: - dm.canonical_id = self._id_map[rel_path]["id"] - self._reject_ephemeral_discoveries(discovered) - - @staticmethod - def _filter_invalid_discovery_ids(discovered: list[DiscoveredModule]) -> list[DiscoveredModule]: - """Check the final ID grammar before reading metadata or importing a module.""" - valid: list[DiscoveredModule] = [] - for dm in discovered: - try: - _validate_module_id(dm.canonical_id) - except InvalidInputError as exc: - logger.warning( - "Skipping discovered module with invalid ID '%s' at %s: %s", dm.canonical_id, dm.file_path, exc - ) - continue - valid.append(dm) - return valid - - @staticmethod - def _load_all_metadata(discovered: list[DiscoveredModule]) -> list[tuple[DiscoveredModule, dict[str, Any]]]: - """Read each optional companion ``*_meta.yaml`` and retain its candidate.""" - return [(dm, load_metadata(dm.meta_path) if dm.meta_path else {}) for dm in discovered] - - def _resolve_all_entry_points( - self, - candidates: list[tuple[DiscoveredModule, dict[str, Any]]], - ) -> list[_DiscoveryCandidate]: - """Resolve each discovered file with its own entry-point metadata.""" - resolved: list[_DiscoveryCandidate] = [] - for dm, meta in candidates: - try: - entry_point = resolve_entry_point(dm.file_path, meta=meta, pre_approval_hook=self._pre_approval_hook) - except Exception as e: - logger.warning("Failed to resolve entry point for '%s': %s", dm.canonical_id, e) - continue - resolved.append(_DiscoveryCandidate(dm, entry_point, meta)) - return resolved - - def _validate_all(self, candidates: list[_DiscoveryCandidate]) -> list[_DiscoveryCandidate]: - """Run the custom or built-in validator over each class.""" - valid: list[_DiscoveryCandidate] = [] - for candidate in candidates: - if self._custom_validator is not None: - errors = self._custom_validator.validate(candidate.entry_point) - else: - errors = validate_module(candidate.entry_point) - if errors: - logger.warning("Module '%s' failed validation: %s", candidate.source.canonical_id, "; ".join(errors)) - continue - valid.append(candidate) - return valid - - @staticmethod - def _index_discovered_modules(candidates: list[_DiscoveryCandidate]) -> dict[str, _DiscoveryCandidate]: - """Keep the first valid candidate for each final ID in scan order.""" - selected: dict[str, _DiscoveryCandidate] = {} - for candidate in candidates: - module_id = candidate.source.canonical_id - previous = selected.get(module_id) - if previous is not None: - logger.warning( - "Duplicate module ID '%s' at %s, already found at %s. Skipping.", - module_id, - candidate.source.file_path, - previous.source.file_path, - ) - continue - selected[module_id] = candidate - return selected + def _scan_params(self) -> tuple[int, bool, list[str]]: + return self._filesystem_discovery().scan_params() def _resolve_load_order( self, @@ -2634,7 +2333,7 @@ def start_unregister_many( ) return operation - def _snapshot_generations(self, module_ids: Iterator[str]) -> list[tuple[str, object | None]]: + def _snapshot_generations(self, module_ids: Iterator[str]) -> Sequence[tuple[str, object | None]]: """Capture registration identities under the Registry lock.""" return [ (module_id, self._lease_generations.setdefault(module_id, object()) if module_id in self._modules else None) @@ -2644,7 +2343,7 @@ def _snapshot_generations(self, module_ids: Iterator[str]) -> list[tuple[str, ob def _run_removals( self, operation: LifecycleOperation, - registrations: list[tuple[str, object | None]], + registrations: Sequence[tuple[str, object | None]], drain_timeout_ms: int, operation_deadline: float | None = None, *, @@ -2759,106 +2458,22 @@ def _run_managed_drain( reload_policy: _ReloadDrainAction = "continue_waiting", cancel_grace_ms: int | None = None, ) -> tuple[_AbortReason | None, LifecycleError | None, bool]: - token = CancelToken() - context = DrainContext(operation._id, module_id, reason, token, deadline) - self._emit_lifecycle( - "module_drain_started", + from apcore.registry.hot_reload_drain import run_managed_drain + + return run_managed_drain( + self, operation, + index, module_id, - { - "reason_kind": reason, - "drain_timeout_ms": drain_timeout_ms, - }, + generation, + registration, + ready, + deadline, + drain_timeout_ms, + reason, + reload_policy=reload_policy, + cancel_grace_ms=cancel_grace_ms, ) - progress = self._begin_drain_hooks(operation, index, module_id, registration, context) - with self._lifecycle_changed: - self._lifecycle_changed.wait_for( - lambda: progress.finished and (ready.is_set() or (reason == "reload" and progress.error is not None)), - timeout=max(0, deadline - time.monotonic()), - ) - active = self._ref_counts.get(module_id, 0) - error_won = reason == "reload" and progress.finished and progress.error is not None - timed_out = not error_won and (not progress.finished or active > 0) - hook_running = not progress.finished - scopes = ( - tuple(self._invocation_tokens.get(generation, ())) if timed_out and cancel_grace_ms is not None else () - ) - grace_deadline = None - if timed_out: - operation._update_module(index, drain_timed_out=True) - action = "cancel_then_force" if cancel_grace_ms is not None else reload_policy - self._emit_lifecycle( - "module_drain_timed_out", - operation, - module_id, - { - "reason_kind": reason, - "action": action, - "active_count": active, - }, - severity="warn", - ) - if hook_running: - self._signal_lifecycle_token(token) - if cancel_grace_ms is not None: - grace_deadline = time.monotonic() + cancel_grace_ms / 1000 - for scope in scopes: - self._signal_lifecycle_token(scope) - with self._lifecycle_changed: - self._lifecycle_changed.wait_for(lambda: progress.finished) - if reason == "reload": - if timed_out and reload_policy == "abort_reload": - return "drain_timeout", LifecycleError(ErrorCodes.RELOAD_FAILED, "draining"), timed_out - if progress.error is not None: - return "drain_error", progress.error, timed_out - ready.wait(timeout=None if grace_deadline is None else max(0, grace_deadline - time.monotonic())) - return None, progress.error, timed_out - - @staticmethod - def _signal_lifecycle_token(token: CancelToken) -> None: - try: - token.cancel() - except Exception as error: - logger.warning("Lifecycle cancellation listener failed: %s", type(error).__name__) - - def _begin_drain_hooks( - self, - operation: LifecycleOperation, - index: int, - module_id: str, - registration: _RegistrationSnapshot, - context: DrainContext, - ) -> _DrainProgress: - progress = _DrainProgress() - - def run() -> None: - try: - for instance in registration.instances(): - try: - hook = getattr(instance, "on_drain", None) - if callable(hook): - operation._update_module(index, active_hook="on_drain") - with _lifecycle_callback(self, operation._id): - _call_lifecycle_hook( - hook, (context,), registration.hook_loop(instance), module_id, "on_drain" - ) - except BaseException as error: - progress.error = progress.error or LifecycleError._from_exception(error, "draining") - finally: - operation._update_module(index, active_hook=None) - with self._lifecycle_changed: - progress.finished = True - self._lifecycle_changed.notify_all() - - try: - if any(callable(getattr(instance, "on_drain", None)) for instance in registration.instances()): - threading.Thread(target=run, name="apcore-module-drain", daemon=True).start() - else: - progress.finished = True - except Exception as error: - progress.error = LifecycleError._from_exception(error, "draining") - progress.finished = True - return progress def _emit_lifecycle( self, event: str, operation: LifecycleOperation, module_id: str, data: dict[str, Any], *, severity: str = "info" @@ -2891,352 +2506,12 @@ def _start_managed_reload( exact: bool = False, prepared: _WatchedReplacement | None = None, ) -> LifecycleOperation: - with self._lock: - self._require_open() - plan = [ - (module_id, generation, self._snapshot_registration(module_id)) - for module_id, generation in self._snapshot_generations(iter(module_ids)) - ] - for module_id, generation, registration in plan: - if generation is None or registration is None: - if exact: - raise ModuleNotFoundError(module_id=module_id) - continue - for module in registration.instances(): - if callable(getattr(module, "on_drain", None)) and not callable( - getattr(module, "on_drain_aborted", None) - ): - raise InvalidInputError( - message=f"Module '{module_id}' must pair on_drain with on_drain_aborted for managed reload" - ) - operation = LifecycleOperation("reload", registry=self) - operation._set_modules(iter(module_ids)) - if not plan: - operation._complete() - return operation - - def run() -> None: - try: - for index, (module_id, generation, registration) in enumerate(plan): - self._run_managed_reload( - operation, - index, - module_id, - generation, - registration, - drain_timeout_ms, - policy, - on_reloaded, - prepared, - ) - operation._complete() - finally: - if prepared is not None: - self._finish_watched_replacement(prepared) - - operation._start(run, "loading") - return operation - - def _run_managed_reload( - self, - operation: LifecycleOperation, - index: int, - module_id: str, - generation: object | None, - registration: _RegistrationSnapshot | None, - timeout_ms: int, - policy: _ReloadDrainAction, - on_reloaded: Callable[[str, str, str, str], None], - prepared: _WatchedReplacement | None, - ) -> None: - with self._lock: - if ( - self._closed - or generation is None - or registration is None - or (prepared is not None and prepared.generation is not generation) - or self._lease_generations.get(module_id) is not generation - or module_id in self._draining - or module_id in self._in_flight - or module_id in self._unavailable - or (current := self._snapshot_registration(module_id)) is None - or current.module is not registration.module - or current.versions.keys() != registration.versions.keys() - or any(current.versions[key] is not value for key, value in registration.versions.items()) - ): - error = LifecycleError(ErrorCodes.MODULE_RELOAD_CONFLICT, "draining") - operation._update_module( - index, phase="done", outcome="failed", error=error, compensation="not_required" - ) - return - ready = self._mark_draining(module_id) - deadline = time.monotonic() + timeout_ms / 1000 - operation._update_module(index, phase="draining") - abort, error, timed_out = self._run_managed_drain( - operation, - index, - module_id, - generation, - registration, - ready, - deadline, - timeout_ms, - "reload", - reload_policy=policy, - ) - if abort is not None: - self._recover_managed_reload(operation, index, module_id, registration, abort, error) - return + from apcore.registry.hot_reload_drain import start_managed_reload - with self._lifecycle_changed: - if self._closed: - self._draining.discard(module_id) - self._drain_events.pop(module_id, None) - self._lifecycle_changed.notify_all() - error = LifecycleError(ErrorCodes.MODULE_RELOAD_CONFLICT, "draining") - operation._update_module( - index, phase="done", outcome="failed", error=error, compensation="not_required" - ) - return - pending = self._detach_registration(module_id) - self._in_flight.add(module_id) - assert pending is not None - pending.drain_timed_out = timed_out - self._replace_managed_generation(operation, index, module_id, pending, on_reloaded, prepared) - - def _recover_managed_reload( - self, - operation: LifecycleOperation, - index: int, - module_id: str, - registration: _RegistrationSnapshot, - abort: _AbortReason, - error: LifecycleError | None, - ) -> None: - operation._update_module(index, phase="recovering", abort_reason=abort) - context = DrainAbortedContext(operation._id, module_id, abort, CancelToken()) - recovery_error = None - for module in registration.instances(): - try: - hook = getattr(module, "on_drain_aborted", None) - if callable(getattr(module, "on_drain", None)) and callable(hook): - operation._update_module(index, active_hook="on_drain_aborted") - with _lifecycle_callback(self, operation._id): - _call_lifecycle_hook( - hook, (context,), registration.hook_loop(module), module_id, "on_drain_aborted" - ) - except BaseException as failure: - recovery_error = recovery_error or LifecycleError._from_exception(failure, "recovering") - with self._lifecycle_changed: - ready = recovery_error is None and not self._closed - if not ready: - self._unavailable.add(module_id) - self._draining.discard(module_id) - self._drain_events.pop(module_id, None) - self._lifecycle_changed.notify_all() - outcome = "retained_ready" if ready else "retained_unavailable" - operation._update_module( - index, - phase="done", - active_hook=None, - outcome=outcome, - error=recovery_error or error, - compensation="not_required", - ) - self._emit_lifecycle( - "module_drain_recovered", - operation, - module_id, - { - "abort_reason": abort, - "outcome": outcome, - }, - severity="info" if ready else "error", + return start_managed_reload( + self, module_ids, drain_timeout_ms, policy, on_reloaded, exact=exact, prepared=prepared ) - def _replace_managed_generation( - self, - operation: LifecycleOperation, - index: int, - module_id: str, - pending: _PendingUnload, - on_reloaded: Callable[[str, str, str, str], None], - prepared: _WatchedReplacement | None, - ) -> None: - old = pending.registration - state = None - phase = "unloading" - try: - operation._update_module(index, phase="unloading") - try: - if callable(getattr(old.module, "on_suspend", None)): - operation._update_module(index, active_hook="on_suspend") - with _lifecycle_callback(self, operation._id): - state = self._call_on_suspend(module_id, old.module, old.hook_loop(old.module)) - finally: - operation._update_module(index, active_hook=None) - unload_error = self._finish_unload(pending, operation, index) - if unload_error is not None: - raise ModuleError(unload_error.code, "Module unload failed") - phase = "loading" - operation._update_module(index, phase="loading") - if prepared is None: - replacement = self._replacement_snapshot(module_id, old) - else: - with self._lock: - self._require_current_watched_source(module_id, prepared) - replacement = prepared.registration - self._activate_managed_snapshot(operation, index, module_id, replacement, state, watched=prepared) - except BaseException as failure: - error = ( - LifecycleError(ErrorCodes.MODULE_LOAD_ERROR, "loading") - if phase == "loading" and not isinstance(failure, ModuleError) - else LifecycleError._from_exception(failure, phase) - ) - if prepared is not None and not prepared.source.is_file(): - # Deletion is terminal for this source. Never republish its old registration. - compensation = "not_required" - else: - restored = self._compensate_managed_reload(operation, index, module_id, old, state, watched=prepared) - compensation = "restored" if restored else "failed" - operation._update_module( - index, phase="done", active_hook=None, outcome="failed", error=error, compensation=compensation - ) - self._emit_lifecycle( - "module_reload_failed", - operation, - module_id, - { - "phase": error.phase, - "error_code": error.code, - "compensation": compensation, - }, - severity="error", - ) - return - finally: - with self._lock: - self._clear_loading(module_id) - - previous_version = str(old.metadata.get("version") or DEFAULT_MODULE_VERSION) - new_version = str(replacement.metadata.get("version") or DEFAULT_MODULE_VERSION) - operation._update_module(index, phase="done", outcome="reloaded", compensation="not_required") - try: - on_reloaded(module_id, previous_version, new_version, operation._id) - except Exception as failure: - logger.warning("Could not record successful reload of %s: %s", module_id, type(failure).__name__) - - def _compensate_managed_reload( - self, - operation: LifecycleOperation, - index: int, - module_id: str, - registration: _RegistrationSnapshot, - state: dict[str, Any] | None, - *, - watched: _WatchedReplacement | None = None, - ) -> bool: - try: - with self._lock: - self._require_open() - self._activate_managed_snapshot(operation, index, module_id, registration, state, watched=watched) - return True - except BaseException as failure: - logger.error("Managed reload compensation failed for %s: %s", module_id, type(failure).__name__) - return False - - def _activate_managed_snapshot( - self, - operation: LifecycleOperation, - index: int, - module_id: str, - registration: _RegistrationSnapshot, - state: dict[str, Any] | None, - *, - watched: _WatchedReplacement | None = None, - ) -> None: - initialized = [] - try: - with _lifecycle_callback(self, operation._id): - for module in registration.instances(): - loop = registration.hook_loop(module) - self._validate_hook_adapter(module_id, module, loop) - hook = getattr(module, "on_load", None) - if callable(hook): - operation._update_module(index, phase="loading", active_hook="on_load") - _call_lifecycle_hook(hook, (), loop, module_id, "on_load") - initialized.append(module) - if ( - module is registration.module - and state is not None - and callable(getattr(module, "on_resume", None)) - ): - operation._update_module(index, phase="resuming", active_hook="on_resume") - self._call_on_resume(module_id, module, state, loop) - operation._update_module(index, active_hook=None) - with self._lock: - self._require_open() - if watched is not None and registration is watched.registration: - self._require_current_watched_source(module_id, watched) - elif watched is not None and not watched.source.is_file(): - raise ModuleLoadError(module_id, "Watched module source was deleted before restoration") - self._publish_snapshot(module_id, registration) - self._trigger_event("register", module_id, registration.module) - except BaseException: - with _lifecycle_callback(self, operation._id): - for module in reversed(initialized): - self._call_on_unload(module_id, module, hook_loop=registration.hook_loop(module)) - raise - - def _replacement_snapshot(self, module_id: str, old: _RegistrationSnapshot) -> _RegistrationSnapshot: - loop = old.hook_loop(old.module) - source = None - metadata: dict[str, Any] = {} - if self._custom_discoverer is not None: - roots = [str(root["root"]) for root in self._extension_roots] - modules = self._custom_discoverer.discover(roots) - match = next( - (entry for entry in modules if isinstance(entry, dict) and entry.get("module_id") == module_id), None - ) - if match is None or "module" not in match: - raise ModuleLoadError(module_id, "The replacement was not discovered") - module = match["module"] - errors = validate_module(module, programmatic=True) - if not errors and self._custom_validator is not None: - errors = self._custom_validator.validate(module) - if errors: - raise ModuleLoadError(module_id, "The replacement is not a valid module") - _ensure_schema_adapter(module, normalize_legacy_none=True) - else: - candidates = ( - [self._watched_candidate(old.source_path)] - if old.source_path is not None - else self._reload_source_candidates(module_id) - ) - target = next((item for item in candidates if item is not None and item.canonical_id == module_id), None) - if target is None: - raise ModuleLoadError(module_id, "The replacement source was not discovered") - selected = self._validate_all(self._resolve_all_entry_points(self._load_all_metadata([target]))) - if not selected: - raise ModuleLoadError(module_id, "The replacement source was invalid") - source = target.file_path - metadata = selected[0].metadata - module = selected[0].entry_point() - merged = _prepare_discovered_module(module_id, module, metadata) - version = self._effective_version(module, metadata) - deps = parse_dependencies(metadata.get("dependencies")) - with self._lock: - failure = self._discovery_dependency_error(module_id, deps) - if failure is not None: - raise failure - registration = _ModuleRegistration(module, merged, metadata, loop) - return _RegistrationSnapshot(module, merged, {version: registration}, source) - - def _reload_source_candidates(self, module_id: str) -> list[DiscoveredModule]: - candidates = self._scan_roots(*self._scan_params()) - self._apply_id_map_overrides(candidates) - return [item for item in self._filter_invalid_discovery_ids(candidates) if item.canonical_id == module_id] - def _stop_admission(self) -> None: with self._lock: self._closed = True @@ -3284,7 +2559,7 @@ def _start_shutdown( return operation def _track_shutdown_registrations( - self, operation: LifecycleOperation, registrations: list[tuple[str, object | None]] + self, operation: LifecycleOperation, registrations: Sequence[tuple[str, object | None]] ) -> None: for module_id, generation in registrations: if generation is not None and generation not in self._shutdown_rows: @@ -3392,43 +2667,15 @@ def watch(self, *, lifecycle: ReloadOptions | None = None) -> None: Requires the optional ``watchdog`` dependency. Raises ImportError if watchdog is not installed. """ - hook_loop = None - if lifecycle is not None: - if not isinstance(lifecycle, ReloadOptions): - raise InvalidInputError(message="Expected ReloadOptions for watch lifecycle") - _validate_duration("drain_timeout_ms", lifecycle.drain_timeout_ms) - if lifecycle.drain_timeout_ms is None or lifecycle.on_drain_timeout not in ( - "continue_waiting", - "abort_reload", - ): - raise InvalidInputError(message="Invalid watch lifecycle policy") - if _has_running_loop(): - hook_loop = asyncio.get_running_loop() - from apcore.registry.watcher import load_observer_factory + from apcore.registry.hot_reload_drain import watch - create_observer = load_observer_factory() - - with self._lock: - self._require_open() - if hasattr(self, "_observer") and self._observer is not None: - return - observer = create_observer(self, self._extension_roots) - self._watch_lifecycle = lifecycle - self._watch_hook_loop = hook_loop - observer.start() - self._observer = observer + watch(self, lifecycle=lifecycle) def unwatch(self) -> None: """Stop watching extension directories for file changes.""" - with self._lock: - observer = getattr(self, "_observer", None) - self._observer = None - self._watch_lifecycle = None - self._watch_hook_loop = None - self._watched_replacements.clear() - if observer is not None: - observer.stop() - observer.join() + from apcore.registry.hot_reload_drain import unwatch + + unwatch(self) def _detach_registration( self, mid: str, *, context: Any = None, remaining_leases: int = 0 @@ -3516,270 +2763,17 @@ def _publish_snapshot(self, module_id: str, registration: _RegistrationSnapshot) for version, entry in registration.versions.items(): self._versioned_modules.add(module_id, version, entry) - def _watched_candidate(self, path: Path) -> DiscoveredModule | None: - max_depth, follow_symlinks, ignore_patterns = self._scan_params() - candidate = scan_watched_source(path, self._extension_roots, max_depth, follow_symlinks, ignore_patterns) - if candidate is not None: - self._reject_ephemeral_discoveries([candidate]) - self._apply_id_map_overrides([candidate]) - _validate_module_id(candidate.canonical_id) - return candidate - def _handle_file_change(self, path: str) -> None: - """Handle a file modification or creation event. - - Performs arbitrary-Python import (``resolve_entry_point``) and user - hooks (``on_suspend``/``on_unload``/``on_resume``) OUTSIDE - ``self._lock`` so a slow or re-entrant module cannot block unrelated - registry queries or deadlock a callback that calls back into the - registry. Lock is acquired only for the two short atomic sections: - capturing the old module's snapshot + state maps, and inserting the - new instance into all internal maps (``_modules``, ``_module_meta``, - ``_lowercase_map``, ``_versioned_modules``). - """ - if self._defer_watched_change(path): - return - # Phase 1 (outside lock): compile + instantiate + validate new module. - try: - candidate = self._watched_candidate(Path(path)) - if candidate is None: - return - new_id = candidate.canonical_id - source = candidate.file_path - with self._lock: - if new_id in self._modules and self._module_sources.get(new_id) != source: - logger.warning("Hot reload skipped '%s' because it is registered from another source", new_id) - return - managed = self._watch_lifecycle is not None - revision = self._source_revision(source) if managed else None - metadata = load_metadata(candidate.meta_path) if candidate.meta_path is not None else {} - cls = resolve_entry_point(source, meta=metadata, pre_approval_hook=self._pre_approval_hook) - except Exception as e: - logger.warning("Hot reload failed to resolve entry point for %s: %s", path, e) - return + """Apply an extension file modification or creation event.""" + from apcore.registry.hot_reload_drain import handle_file_change - try: - instance = cls() - except Exception as e: - logger.warning("Hot reload failed to instantiate class from %s: %s", path, e) - return - - validation_errors = validate_module(instance) - if validation_errors: - logger.warning( - "Hot reload rejected module from %s: validation failed (%s)", - path, - "; ".join(validation_errors), - ) - return - - try: - effective_version = self._effective_version(instance, metadata) - merged_meta = _prepare_discovered_module(new_id, instance, metadata) - except Exception as error: - logger.warning("Hot reload rejected module from %s: %s", path, error) - return - - if self._custom_validator is not None: - try: - errors = self._custom_validator.validate(instance) - except Exception as e: - logger.warning( - "Hot reload rejected module from %s: custom validator raised: %s", - path, - e, - ) - return - if errors: - logger.warning("Hot reload rejected module from %s: %s", path, "; ".join(errors)) - return - - # Reuse the registration's adapter on the watcher thread. An opted-in - # watcher can also introduce async-capable registrations on its loop. - with self._lock: - if self._closed or new_id in self._in_flight or new_id in self._draining: - return - exists = new_id in self._modules - current = self._snapshot_registration(new_id) - hook_loop = current.hook_loop(current.module) if current is not None else self._watch_hook_loop - options = self._watch_lifecycle - if exists and options is not None: - watched_generation = self._lease_generations.setdefault(new_id, object()) - else: - watched_generation = None - if not exists: - self._in_flight.add(new_id) - if watched_generation is not None and options is not None: - self._start_watched_replacement( - new_id, - instance, - source, - effective_version, - metadata, - merged_meta, - hook_loop, - watched_generation, - options, - revision, - ) - return - old_registration: _RegistrationSnapshot | None = None - suspended_state: dict[str, Any] | None = None - if exists: - detached = self._detach_after_drain(new_id, reserve_replacement=True, source_path=source) - if detached is None: - return - pending, clean = detached - old_registration = pending.registration - # Phase 3: run hooks on the old module outside the registry lock. - suspended_state = self._capture_state_and_unload(pending, clean) - - with self._resume_on_load(new_id, suspended_state): - if not self._invoke_on_load(new_id, instance, hook_loop=hook_loop): - self._restore_after_failed_hot_reload(new_id, old_registration, suspended_state) - return - with self._ready_to_publish(new_id, instance, hook_loop=hook_loop) as admitted: - if not admitted: - return - registration = _ModuleRegistration(instance, merged_meta, metadata, hook_loop) - self._publish_snapshot( - new_id, _RegistrationSnapshot(instance, merged_meta, {effective_version: registration}, source) - ) - - # Phase 5 (outside lock): notify observers of the initialized module. - self._trigger_event("register", new_id, instance) - - def _start_watched_replacement( - self, - module_id: str, - module: Any, - source: Path, - version: str, - metadata: dict[str, Any], - merged_meta: dict[str, Any], - loop: asyncio.AbstractEventLoop | None, - generation: object, - options: ReloadOptions, - revision: tuple[int, int, int, int] | None, - ) -> None: - try: - self._validate_hook_adapter(module_id, module, loop) - if inspect.iscoroutinefunction(getattr(module, "on_load", None)) and ( - loop is None or not loop.is_running() - ): - raise ModuleLoadError(module_id, "Async on_load requires an available lifecycle event loop") - registration = _ModuleRegistration(module, merged_meta, metadata, loop) - replacement = _RegistrationSnapshot(module, merged_meta, {version: registration}, source) - watched = _WatchedReplacement(generation, replacement, source, revision) - with self._lock: - if self._closed or self._watch_lifecycle is not options or source in self._watched_replacements: - return - self._watched_replacements[source] = watched - try: - self._start_managed_reload( - [module_id], - options.drain_timeout_ms, - options.on_drain_timeout, - lambda *_: None, - exact=True, - prepared=watched, - ) - except BaseException: - with self._lock: - if self._watched_replacements.get(source) is watched: - self._watched_replacements.pop(source) - raise - except Exception as error: - logger.warning("Watcher could not start reload for '%s': %s", module_id, type(error).__name__) - - @staticmethod - def _source_revision(source: Path) -> tuple[int, int, int, int] | None: - try: - details = source.stat() - except OSError: - return None - return (details.st_dev, details.st_ino, details.st_mtime_ns, details.st_size) + handle_file_change(self, path) def _defer_watched_change(self, path: str) -> bool: """Keep one pending refresh per source while its replacement owns admission.""" - with self._lock: - if not self._watched_replacements: - return False - try: - source = Path(path).resolve() - except (OSError, RuntimeError): - return False - with self._lock: - watched = self._watched_replacements.get(source) - if watched is None: - return False - watched.refresh |= self._source_revision(source) != watched.revision - return True - - def _require_current_watched_source(self, module_id: str, watched: _WatchedReplacement) -> None: - """Check the candidate revision and watcher ownership under the Registry lock.""" - if self._watched_replacements.get(watched.source) is not watched: - raise ModuleLoadError(module_id, "Watcher stopped before module replacement") - watched.refresh |= self._source_revision(watched.source) != watched.revision - if watched.refresh or watched.revision is None: - raise ModuleLoadError(module_id, "Watched module source changed during replacement") + from apcore.registry.hot_reload_drain import defer_watched_change - def _finish_watched_replacement(self, watched: _WatchedReplacement) -> None: - with self._lock: - if self._watched_replacements.get(watched.source) is not watched: - return - self._watched_replacements.pop(watched.source) - if self._closed or self._watch_lifecycle is None: - return - revision = self._source_revision(watched.source) - if not watched.refresh and revision == watched.revision: - return - if revision is None: - self._handle_file_deletion(str(watched.source)) - else: - self._handle_file_change(str(watched.source)) - - def _restore_after_failed_hot_reload( - self, - module_id: str, - registration: _RegistrationSnapshot | None, - suspended_state: dict[str, Any] | None, - ) -> None: - """Republish the previous instance after a hot reload failed to load. - - D-123, applying D-112 rules 2-4 to the watch-driven path. Phase 2 has - already unregistered the old instance and Phase 3 has already run its - ``on_unload``, so restoring it means re-running ``on_load`` — a module - republished without it would be visible but torn down, which D-112 rule - 2 names as the state this whole decision exists to avoid. - - When the restoring load ALSO fails the module stays unavailable - (D-112 rule 3): there is no good state left to return to, and publishing - a module whose load hook failed is the defect the deferred-publish rule - exists to prevent. Nothing is restored when the reload created a module - that did not previously exist — there is no previous instance to return - to, and the file simply failed to load. - """ - if registration is None: - logger.error( - "Hot reload of '%s' failed its on_load() and there was no previous " - "instance to restore; the module is not registered.", - module_id, - ) - return - - if not self._restore_registration(module_id, registration, suspended_state): - logger.error( - "Hot reload of '%s' failed its on_load(), and re-loading the previous " - "instance failed as well; the module stays unavailable (D-112 rule 3).", - module_id, - ) - return - - logger.warning( - "Hot reload of '%s' failed its on_load(); the previous instance was restored.", - module_id, - ) + return defer_watched_change(self, path) def _call_on_suspend( self, module_id: str, module: Any, hook_loop: asyncio.AbstractEventLoop | None = None @@ -3845,21 +2839,9 @@ def _call_on_resume( def _handle_file_deletion(self, path: str) -> None: """Drain the module, then unload it when its source file is deleted.""" - if self._defer_watched_change(path): - return - try: - source = Path(path).resolve() - except (OSError, RuntimeError): - logger.warning("Hot reload could not resolve deleted path %s", path) - return - if source.exists(): - return - with self._lock: - module_ids = [module_id for module_id, file_path in self._module_sources.items() if file_path == source] - for module_id in module_ids: - detached = self._detach_after_drain(module_id, source_path=source) - if detached is not None: - self._finish_unload(detached[0]) + from apcore.registry.hot_reload_drain import handle_file_deletion + + handle_file_deletion(self, path) # ----- Public accessors for internal state ----- diff --git a/python/tests/registry/test_discovery_import_boundary.py b/python/tests/registry/test_discovery_import_boundary.py new file mode 100644 index 00000000..301fd9e1 --- /dev/null +++ b/python/tests/registry/test_discovery_import_boundary.py @@ -0,0 +1,38 @@ +"""The default Registry imports filesystem orchestration only when asked to discover.""" + +from __future__ import annotations + +import subprocess +import sys +from pathlib import Path + + +def test_in_memory_registry_does_not_load_filesystem_or_hot_reload(tmp_path: Path) -> None: + code = """ +import sys +from apcore import Registry + +class Module: + description = "An in-memory module" + input_schema = {"type": "object"} + output_schema = {"type": "object"} + + def execute(self, inputs, context): + return inputs + +registry = Registry(extensions_dir=sys.argv[1]) +registry.register("test.module", Module()) +assert registry.has("test.module") +assert registry.unregister("test.module") +assert "apcore.registry.filesystem_discovery" not in sys.modules +assert "apcore.registry.hot_reload_drain" not in sys.modules +assert "watchdog" not in sys.modules +assert "yaml" not in sys.modules + +assert registry.discover() == 0 +assert "apcore.registry.filesystem_discovery" in sys.modules +assert "apcore.registry.hot_reload_drain" not in sys.modules +assert "watchdog" not in sys.modules +""" + result = subprocess.run([sys.executable, "-c", code, str(tmp_path)], capture_output=True, text=True, check=False) + assert result.returncode == 0, result.stderr diff --git a/rust/Cargo.toml b/rust/Cargo.toml index 90511eaf..962fbb91 100644 --- a/rust/Cargo.toml +++ b/rust/Cargo.toml @@ -153,11 +153,11 @@ required-features = ["config", "discovery", "sys-modules"] [[test]] name = "test_otlp_proxy_routing" path = "tests/test_otlp_proxy_routing.rs" -required-features = ["events"] +required-features = ["observability"] [dependencies] apcore-macros = { version = "=1.0.0-beta.1", path = "apcore-macros", optional = true } -tokio = { version = "1", features = ["rt-multi-thread", "macros", "sync", "time"] } +tokio = { version = "1", features = ["rt", "macros", "sync", "time"] } serde = { version = "1", features = ["derive"] } serde_json = "1" serde_yaml_ng = { version = "0.10", optional = true } @@ -183,12 +183,17 @@ schemars = "0.8" dashmap = "6" notify = { version = "8", optional = true, default-features = false, features = ["macos_fsevent"] } +[target.'cfg(not(target_family = "wasm"))'.dependencies] +tokio = { version = "1", features = ["rt-multi-thread"] } + [features] # Retain the existing default API while consumers opt into named extensions. default = [] config = ["dep:serde_yaml_ng"] discovery = ["config", "dep:notify"] -events = ["reqwest", "dep:h2", "dep:url"] +# Existing event builds also provide the OTLP transport. +events = ["observability"] +observability = ["reqwest", "dep:h2", "dep:url"] events-file = ["tokio/fs", "tokio/io-util"] macros = ["dep:apcore-macros"] sys-modules = ["config"] diff --git a/rust/src/acl.rs b/rust/src/acl.rs index f4b872ed..a2f9454f 100644 --- a/rust/src/acl.rs +++ b/rust/src/acl.rs @@ -5,7 +5,6 @@ use chrono::Utc; use serde::{Deserialize, Serialize}; use std::collections::{HashMap, HashSet}; use std::future::Future; -use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Once}; use crate::acl_handlers::{ @@ -17,9 +16,13 @@ use crate::context::Context; use crate::errors::{ErrorCode, ModuleError}; use crate::utils::match_pattern; +mod audit; #[cfg(feature = "config")] mod file; +use audit::{warn_audit_block_overridden, AuditSink}; +pub use audit::{AuditConfig, AuditEntry, AuditLoggerFn, AUDIT_EVENT_NAME, AUDIT_FIELDS}; + /// The complete set of values a rule's `effect` may carry (PROTOCOL_SPEC §6.1). /// /// Closed at **every** entry point since spec v1.30.0 (#111), not only at file @@ -614,268 +617,6 @@ impl AccessDecision { } } -/// Audit log entry produced by ACL checks (PROTOCOL_SPEC §6.3.1). -/// -/// Marked `#[non_exhaustive]` in the same change that added -/// [`Self::approval_required`] (spec v1.28.0): the field is a breaking -/// addition for downstream struct-literal construction either way, and the -/// attribute is what makes the *next* spec-driven field non-breaking. Build -/// one with `AuditEntry::default()` and mutate, per the migration note the -/// crate uses for every other spec-derived record (apcore#24). -#[derive(Debug, Clone, Default, Serialize, Deserialize)] -#[non_exhaustive] -pub struct AuditEntry { - pub timestamp: String, - pub caller_id: String, - pub target_id: String, - pub decision: String, - pub reason: String, - #[serde(skip_serializing_if = "Option::is_none")] - pub matched_rule: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub matched_rule_index: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub identity_type: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub actor_id: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub subject_id: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub delegation_depth: Option, - #[serde(default)] - pub roles: Vec, - #[serde(skip_serializing_if = "Option::is_none")] - pub call_depth: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub trace_id: Option, - /// Error message from a condition handler that panicked or returned an error - /// during evaluation, if any. Cross-language parity with apcore-python - /// AuditEntry.handler_error and apcore-typescript AuditEntry.handlerError - /// (sync finding A-D-024). - #[serde(skip_serializing_if = "Option::is_none")] - pub handler_error: Option, - /// Whether the **decision** required this call to be put to a human - /// (PROTOCOL_SPEC §6.1.6, §6.3.1) — the final value, matching the - /// [`AccessDecision`] emitted alongside it. - /// - /// Usually the matched rule's own requirement, but since spec v1.29.0 it - /// may also be one raised by an unevaluable `allow` rule that did not - /// itself match (§6.1.1 rule 5), including on the `default_effect: allow` - /// path where `matched_rule_index` is `None`. `false` on any `deny`. - /// - /// A field **beside** `decision` rather than a third `decision` value: - /// `decision` is a string downstream consumers parse, and a third value - /// would break every existing parser (§6.9 row 7). `#[serde(default)]` so - /// an audit record written before v1.28.0 still deserializes. - #[serde(default)] - pub approval_required: bool, -} - -/// Type alias for the audit logger callback. -pub type AuditLoggerFn = dyn Fn(&AuditEntry) + Send + Sync; - -// --------------------------------------------------------------------------- -// Audit delivery (PROTOCOL_SPEC §6.3.2, apcore#118 decision D-66) -// --------------------------------------------------------------------------- - -/// The three settings of an ACL file's `audit:` block. -pub const AUDIT_FIELDS: [&str; 3] = ["enabled", "include_denied", "log_level"]; - -/// The stable name the default sink emits under (§10.3's event table). -pub const AUDIT_EVENT_NAME: &str = "apcore.acl.audit"; - -/// An ACL file's `audit:` block, as declared. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct AuditConfig { - pub enabled: bool, - pub include_denied: bool, - pub log_level: String, -} - -impl Default for AuditConfig { - fn default() -> Self { - Self { - enabled: true, - include_denied: true, - log_level: "info".to_string(), - } - } -} - -/// The ONE effective sink for an ACL, per §6.3.2 requirement 1. -/// -/// Never two. A callback supplied through [`ACL::set_audit_logger`] or the -/// constructor receives every entry and is not narrowed, levelled or silenced -/// by the `audit:` block: an API argument beats configuration, and the -/// alternative lets a file silently truncate a compliance sink a developer -/// installed deliberately. The block configures the **default sink** and -/// nothing else. -/// -/// A sink also owns its failure state. Requirement 5 suppresses diagnostics -/// after the first, scoped to one ACL instance **and one effective sink -/// configuration** — replacing the sink or reloading a configuration that -/// changes it builds a new `AuditSink`, so a new failure is never hidden behind -/// an old one. -pub(crate) struct AuditSink { - callback: Option>, - /// `None` means the document declared no `audit:` key. Requirement 2: - /// DECLARATION activates the default sink, never the default value — - /// `enabled` defaults to true, so reading the merged view would switch a - /// log record per check on for every ACL file in existence. - config: Option, - failed: AtomicBool, -} - -impl std::fmt::Debug for AuditSink { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.debug_struct("AuditSink") - .field("callback", &self.callback.as_ref().map(|_| "...")) - .field("config", &self.config) - .field("failed", &self.failed.load(Ordering::Relaxed)) - .finish() - } -} - -impl Clone for AuditSink { - fn clone(&self) -> Self { - // A clone is a NEW sink configuration for requirement 5's purposes: the - // clone delivers independently, so carrying the original's failure flag - // across would suppress the clone's first real failure. - Self::new(self.callback.clone(), self.config.clone()) - } -} - -impl AuditSink { - pub(crate) fn new(callback: Option>, config: Option) -> Self { - Self { - callback, - config, - failed: AtomicBool::new(false), - } - } - - fn is_active(&self) -> bool { - if self.callback.is_some() { - return true; - } - self.config.as_ref().is_some_and(|c| c.enabled) - } - - /// Deliver one entry. NEVER propagates (§6.3.2 requirement 3). - fn deliver(&self, entry: &AuditEntry) { - if let Some(ref callback) = self.callback { - // Requirement 3, bounded to RECOVERABLE failures. `AuditLoggerFn` is - // `Fn(&AuditEntry)` with no error channel, so an unwinding panic is - // the only failure this can contain; a build with `panic = "abort"` - // cannot be, and the specification says so rather than promising - // what the language cannot deliver. - // - // The default panic hook still prints its own message before this - // returns. That is the runtime's, not ours: requirement 5 governs - // the diagnostic THIS sink emits. - let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { - callback(entry); - })); - if outcome.is_err() { - self.report_failure(); - } - return; - } - let Some(ref config) = self.config else { - return; - }; - if !config.enabled { - return; - } - if entry.decision == "deny" && !config.include_denied { - // Requirement 6 — the load-time notice for this is emitted once, at - // load; withholding here is silent by design. - return; - } - Self::emit_default(entry, config); - } - - /// §6.3.2 requirement 2 — the default sink. - /// - /// All thirteen §6.3.1 fields go out as STRUCTURED data under their - /// `snake_case` wire names, not interpolated into the message. Without - /// that, one specification yields three different "structured records" - /// across the SDKs and nothing downstream consumes all three. - #[allow(clippy::cognitive_complexity)] // five level arms, one body each - fn emit_default(entry: &AuditEntry, config: &AuditConfig) { - macro_rules! emit { - ($level:expr) => { - tracing::event!( - $level, - timestamp = %entry.timestamp, - caller_id = %entry.caller_id, - target_id = %entry.target_id, - decision = %entry.decision, - reason = %entry.reason, - matched_rule = ?entry.matched_rule, - matched_rule_index = ?entry.matched_rule_index, - identity_type = ?entry.identity_type, - actor_id = ?entry.actor_id, - subject_id = ?entry.subject_id, - delegation_depth = ?entry.delegation_depth, - roles = ?entry.roles, - call_depth = ?entry.call_depth, - trace_id = ?entry.trace_id, - handler_error = ?entry.handler_error, - approval_required = entry.approval_required, - // The literal, because `tracing` requires one for the - // message. `audit_event_name_matches_the_constant` pins it - // against AUDIT_EVENT_NAME so the two cannot drift. - "apcore.acl.audit" - ) - }; - } - match config.log_level.as_str() { - "trace" | "debug" => emit!(tracing::Level::DEBUG), - "warn" => emit!(tracing::Level::WARN), - "error" => emit!(tracing::Level::ERROR), - _ => emit!(tracing::Level::INFO), - } - } - - fn report_failure(&self) { - if self.failed.swap(true, Ordering::Relaxed) { - return; - } - tracing::warn!( - "ACL audit delivery failed (the callback panicked). The access decision is \ - unaffected (PROTOCOL_SPEC §6.3.2 requirement 3) — auditing is a side channel \ - and does not hold a veto over access. Further failures from this sink are not \ - reported; replacing the sink or reloading the ACL starts a new report." - ); - } -} - -/// §6.3.2 requirement 1 — name EVERY field the callback overrides. -/// -/// Not only the most visible one: an operator who set `include_denied` and -/// `log_level` and hears about one of them has been told the smaller half of -/// what happened. -pub(crate) fn warn_audit_block_overridden( - callback: Option<&Arc>, - config: Option<&AuditConfig>, -) { - if callback.is_none() || config.is_none() { - return; - } - tracing::warn!( - fields = %AUDIT_FIELDS - .iter() - .map(|f| format!("audit.{f}")) - .collect::>() - .join(", "), - "An audit logger was supplied to this ACL, so it is the effective sink and the ACL \ - file's 'audit:' block does not apply. The callback receives EVERY entry, allow and \ - deny alike. The listed declared settings have no effect (PROTOCOL_SPEC §6.3.2 \ - requirement 1)." - ); -} - /// One rule that fails PROTOCOL_SPEC §6.1.4's structural and registry /// precheck. /// diff --git a/rust/src/acl/audit.rs b/rust/src/acl/audit.rs new file mode 100644 index 00000000..b0950e9e --- /dev/null +++ b/rust/src/acl/audit.rs @@ -0,0 +1,267 @@ +//! ACL audit records and delivery. + +use serde::{Deserialize, Serialize}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::Arc; + +/// Audit log entry produced by ACL checks (PROTOCOL_SPEC §6.3.1). +/// +/// Marked `#[non_exhaustive]` in the same change that added +/// [`Self::approval_required`] (spec v1.28.0): the field is a breaking +/// addition for downstream struct-literal construction either way, and the +/// attribute is what makes the *next* spec-driven field non-breaking. Build +/// one with `AuditEntry::default()` and mutate, per the migration note the +/// crate uses for every other spec-derived record (apcore#24). +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[non_exhaustive] +pub struct AuditEntry { + pub timestamp: String, + pub caller_id: String, + pub target_id: String, + pub decision: String, + pub reason: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub matched_rule: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub matched_rule_index: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub identity_type: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub actor_id: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub subject_id: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub delegation_depth: Option, + #[serde(default)] + pub roles: Vec, + #[serde(skip_serializing_if = "Option::is_none")] + pub call_depth: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub trace_id: Option, + /// Error message from a condition handler that panicked or returned an error + /// during evaluation, if any. Cross-language parity with apcore-python + /// AuditEntry.handler_error and apcore-typescript AuditEntry.handlerError + /// (sync finding A-D-024). + #[serde(skip_serializing_if = "Option::is_none")] + pub handler_error: Option, + /// Whether the **decision** required this call to be put to a human + /// (PROTOCOL_SPEC §6.1.6, §6.3.1) — the final value, matching the + /// [`AccessDecision`] emitted alongside it. + /// + /// Usually the matched rule's own requirement, but since spec v1.29.0 it + /// may also be one raised by an unevaluable `allow` rule that did not + /// itself match (§6.1.1 rule 5), including on the `default_effect: allow` + /// path where `matched_rule_index` is `None`. `false` on any `deny`. + /// + /// A field **beside** `decision` rather than a third `decision` value: + /// `decision` is a string downstream consumers parse, and a third value + /// would break every existing parser (§6.9 row 7). `#[serde(default)]` so + /// an audit record written before v1.28.0 still deserializes. + #[serde(default)] + pub approval_required: bool, +} + +/// Type alias for the audit logger callback. +pub type AuditLoggerFn = dyn Fn(&AuditEntry) + Send + Sync; + +// --------------------------------------------------------------------------- +// Audit delivery (PROTOCOL_SPEC §6.3.2, apcore#118 decision D-66) +// --------------------------------------------------------------------------- + +/// The three settings of an ACL file's `audit:` block. +pub const AUDIT_FIELDS: [&str; 3] = ["enabled", "include_denied", "log_level"]; + +/// The stable name the default sink emits under (§10.3's event table). +pub const AUDIT_EVENT_NAME: &str = "apcore.acl.audit"; + +/// An ACL file's `audit:` block, as declared. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct AuditConfig { + pub enabled: bool, + pub include_denied: bool, + pub log_level: String, +} + +impl Default for AuditConfig { + fn default() -> Self { + Self { + enabled: true, + include_denied: true, + log_level: "info".to_string(), + } + } +} + +/// The ONE effective sink for an ACL, per §6.3.2 requirement 1. +/// +/// Never two. A callback supplied through [`super::ACL::set_audit_logger`] or the +/// constructor receives every entry and is not narrowed, levelled or silenced +/// by the `audit:` block: an API argument beats configuration, and the +/// alternative lets a file silently truncate a compliance sink a developer +/// installed deliberately. The block configures the **default sink** and +/// nothing else. +/// +/// A sink also owns its failure state. Requirement 5 suppresses diagnostics +/// after the first, scoped to one ACL instance **and one effective sink +/// configuration** — replacing the sink or reloading a configuration that +/// changes it builds a new `AuditSink`, so a new failure is never hidden behind +/// an old one. +pub(super) struct AuditSink { + callback: Option>, + /// `None` means the document declared no `audit:` key. Requirement 2: + /// DECLARATION activates the default sink, never the default value — + /// `enabled` defaults to true, so reading the merged view would switch a + /// log record per check on for every ACL file in existence. + config: Option, + failed: AtomicBool, +} + +impl std::fmt::Debug for AuditSink { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("AuditSink") + .field("callback", &self.callback.as_ref().map(|_| "...")) + .field("config", &self.config) + .field("failed", &self.failed.load(Ordering::Relaxed)) + .finish() + } +} + +impl Clone for AuditSink { + fn clone(&self) -> Self { + // A clone is a NEW sink configuration for requirement 5's purposes: the + // clone delivers independently, so carrying the original's failure flag + // across would suppress the clone's first real failure. + Self::new(self.callback.clone(), self.config.clone()) + } +} + +impl AuditSink { + pub(super) fn new(callback: Option>, config: Option) -> Self { + Self { + callback, + config, + failed: AtomicBool::new(false), + } + } + + pub(super) fn is_active(&self) -> bool { + if self.callback.is_some() { + return true; + } + self.config.as_ref().is_some_and(|c| c.enabled) + } + + /// Deliver one entry. NEVER propagates (§6.3.2 requirement 3). + pub(super) fn deliver(&self, entry: &AuditEntry) { + if let Some(ref callback) = self.callback { + // Requirement 3, bounded to RECOVERABLE failures. `AuditLoggerFn` is + // `Fn(&AuditEntry)` with no error channel, so an unwinding panic is + // the only failure this can contain; a build with `panic = "abort"` + // cannot be, and the specification says so rather than promising + // what the language cannot deliver. + // + // The default panic hook still prints its own message before this + // returns. That is the runtime's, not ours: requirement 5 governs + // the diagnostic THIS sink emits. + let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + callback(entry); + })); + if outcome.is_err() { + self.report_failure(); + } + return; + } + let Some(ref config) = self.config else { + return; + }; + if !config.enabled { + return; + } + if entry.decision == "deny" && !config.include_denied { + // Requirement 6 — the load-time notice for this is emitted once, at + // load; withholding here is silent by design. + return; + } + Self::emit_default(entry, config); + } + + /// §6.3.2 requirement 2 — the default sink. + /// + /// All thirteen §6.3.1 fields go out as STRUCTURED data under their + /// `snake_case` wire names, not interpolated into the message. Without + /// that, one specification yields three different "structured records" + /// across the SDKs and nothing downstream consumes all three. + #[allow(clippy::cognitive_complexity)] // five level arms, one body each + fn emit_default(entry: &AuditEntry, config: &AuditConfig) { + macro_rules! emit { + ($level:expr) => { + tracing::event!( + $level, + timestamp = %entry.timestamp, + caller_id = %entry.caller_id, + target_id = %entry.target_id, + decision = %entry.decision, + reason = %entry.reason, + matched_rule = ?entry.matched_rule, + matched_rule_index = ?entry.matched_rule_index, + identity_type = ?entry.identity_type, + actor_id = ?entry.actor_id, + subject_id = ?entry.subject_id, + delegation_depth = ?entry.delegation_depth, + roles = ?entry.roles, + call_depth = ?entry.call_depth, + trace_id = ?entry.trace_id, + handler_error = ?entry.handler_error, + approval_required = entry.approval_required, + // The literal, because `tracing` requires one for the + // message. `audit_event_name_matches_the_constant` pins it + // against AUDIT_EVENT_NAME so the two cannot drift. + "apcore.acl.audit" + ) + }; + } + match config.log_level.as_str() { + "trace" | "debug" => emit!(tracing::Level::DEBUG), + "warn" => emit!(tracing::Level::WARN), + "error" => emit!(tracing::Level::ERROR), + _ => emit!(tracing::Level::INFO), + } + } + + fn report_failure(&self) { + if self.failed.swap(true, Ordering::Relaxed) { + return; + } + tracing::warn!( + "ACL audit delivery failed (the callback panicked). The access decision is \ + unaffected (PROTOCOL_SPEC §6.3.2 requirement 3) — auditing is a side channel \ + and does not hold a veto over access. Further failures from this sink are not \ + reported; replacing the sink or reloading the ACL starts a new report." + ); + } +} + +/// §6.3.2 requirement 1 — name EVERY field the callback overrides. +/// +/// Not only the most visible one: an operator who set `include_denied` and +/// `log_level` and hears about one of them has been told the smaller half of +/// what happened. +pub(super) fn warn_audit_block_overridden( + callback: Option<&Arc>, + config: Option<&AuditConfig>, +) { + if callback.is_none() || config.is_none() { + return; + } + tracing::warn!( + fields = %AUDIT_FIELDS + .iter() + .map(|f| format!("audit.{f}")) + .collect::>() + .join(", "), + "An audit logger was supplied to this ACL, so it is the effective sink and the ACL \ + file's 'audit:' block does not apply. The callback receives EVERY entry, allow and \ + deny alike. The listed declared settings have no effect (PROTOCOL_SPEC §6.3.2 \ + requirement 1)." + ); +} diff --git a/rust/src/cancel.rs b/rust/src/cancel.rs index 93b3095d..d7e577de 100644 --- a/rust/src/cancel.rs +++ b/rust/src/cancel.rs @@ -363,7 +363,7 @@ impl CancelToken { let registration = self.register_execution(); let id = registration.id; let scopes = registration.scopes.clone(); - let invocation = tokio::task::spawn_blocking(move || { + let invocation = crate::runtime::spawn_blocking(move || { let _registration = registration; task() }); diff --git a/rust/src/executor.rs b/rust/src/executor.rs index 897c5fc5..d0117c6e 100644 --- a/rust/src/executor.rs +++ b/rust/src/executor.rs @@ -523,7 +523,7 @@ pub(crate) async fn open_stream( }; let opening = match token.as_ref() { Some(token) => token.spawn_blocking_tracked(open), - None => tokio::task::spawn_blocking(open), + None => crate::runtime::spawn_blocking(open), }; tokio::select! { biased; diff --git a/rust/src/lib.rs b/rust/src/lib.rs index 138610b1..4998596a 100644 --- a/rust/src/lib.rs +++ b/rust/src/lib.rs @@ -186,9 +186,9 @@ pub use policy::{ PolicyRule, PolicyVerdict, }; pub use registry::registry::{ - is_ephemeral_module_id, module_id_pattern, registry_events, Registry, RegistryEvents, - DEFAULT_MODULE_VERSION, EPHEMERAL_NAMESPACE_PREFIX, MAX_MODULE_ID_LENGTH, MODULE_ID_PATTERN, - REGISTRY_EVENTS, RESERVED_WORDS, + is_ephemeral_module_id, module_id_pattern, registry_events, OutputDeclaration, Registry, + RegistryEvents, DEFAULT_MODULE_VERSION, EPHEMERAL_NAMESPACE_PREFIX, MAX_MODULE_ID_LENGTH, + MODULE_ID_PATTERN, REGISTRY_EVENTS, RESERVED_WORDS, }; pub use registry::{ class_name_to_segment, compute_base_id, derive_module_ids, detect_id_conflicts, ConflictResult, diff --git a/rust/src/observability/exporters.rs b/rust/src/observability/exporters.rs index 8d480550..fc329371 100644 --- a/rust/src/observability/exporters.rs +++ b/rust/src/observability/exporters.rs @@ -117,7 +117,7 @@ impl OTLPExporter { } /// Convert a Span to OTLP JSON format. -#[cfg(feature = "events")] +#[cfg(feature = "observability")] fn span_to_otlp(span: &Span) -> serde_json::Value { #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] // intentional: nanosecond timestamps fit in u64 for dates post-1970 @@ -152,7 +152,7 @@ fn span_to_otlp(span: &Span) -> serde_json::Value { } /// Returns whether the endpoint uses a loopback host. -#[cfg(feature = "events")] +#[cfg(feature = "observability")] fn is_loopback_endpoint(endpoint: &str) -> bool { let Ok(url) = reqwest::Url::parse(endpoint) else { return false; @@ -169,7 +169,7 @@ fn is_loopback_endpoint(endpoint: &str) -> bool { .is_ok_and(|address| address.to_canonical().is_loopback()) } -#[cfg(feature = "events")] +#[cfg(feature = "observability")] #[async_trait] impl SpanExporter for OTLPExporter { async fn export(&self, span: &Span) -> Result<(), ModuleError> { @@ -212,14 +212,14 @@ impl SpanExporter for OTLPExporter { } } -#[cfg(not(feature = "events"))] +#[cfg(not(feature = "observability"))] #[async_trait] impl SpanExporter for OTLPExporter { async fn export(&self, _span: &Span) -> Result<(), ModuleError> { - // Without the `events` feature, export is a silent no-op. + // Without the `observability` feature, export is a silent no-op. // No network call is made; spans are discarded. tracing::warn!( - "OTLPExporter::export called but the `events` feature is not enabled; span discarded" + "OTLPExporter::export called but the `observability` feature is not enabled; span discarded" ); Ok(()) } @@ -308,7 +308,7 @@ impl SpanExporter for CompositeExporter { } } -#[cfg(all(test, feature = "events"))] +#[cfg(all(test, feature = "observability"))] mod tests { use super::is_loopback_endpoint; diff --git a/rust/src/observability/tracing_config.rs b/rust/src/observability/tracing_config.rs index 5c0fb08d..b75d6e06 100644 --- a/rust/src/observability/tracing_config.rs +++ b/rust/src/observability/tracing_config.rs @@ -105,15 +105,15 @@ fn build_exporter(name: &str, endpoint: Option<&str>) -> Option Some(Box::new(StdoutExporter)), "otlp" => { - // Without the `events` feature this crate's OTLPExporter is a + // Without the `observability` feature this crate's OTLPExporter is a // silent no-op that discards every span, so installing a middleware // around it is exactly the "enabled and no traces" state // requirement 4 refuses. - if cfg!(not(feature = "events")) { + if cfg!(not(feature = "observability")) { tracing::warn!( "observability.tracing.exporter is 'otlp' but this build of apcore does not \ - have the `events` feature, so the OTLP exporter would discard every span. \ - No tracing middleware was installed. Rebuild with `--features events`, or \ + have the `observability` feature, so the OTLP exporter would discard every span. \ + No tracing middleware was installed. Rebuild with `--features observability`, or \ set exporter to 'stdout'." ); return None; diff --git a/rust/src/registry/async_lifecycle.rs b/rust/src/registry/async_lifecycle.rs index 703053b4..6d928630 100644 --- a/rust/src/registry/async_lifecycle.rs +++ b/rust/src/registry/async_lifecycle.rs @@ -57,7 +57,7 @@ impl HookScope { hook: impl FnOnce() -> Result + Send + 'static, ) -> Result { let scope = self.clone(); - tokio::task::spawn_blocking(move || { + crate::runtime::spawn_blocking(move || { let hook = || REGISTRY_CALLBACK.sync_scope(scope.registry, hook); match scope.operation { Some(id) => LIFECYCLE_CALLBACK.sync_scope(id, hook), @@ -433,8 +433,7 @@ impl Registry { ); core.lowercase_map .insert(name.to_lowercase(), name.to_owned()); - core.modules.insert(name.to_owned(), Arc::clone(module)); - core.descriptors.insert(name.to_owned(), descriptor); + core.publish_active_module(name, Arc::clone(module), descriptor); if let Some(runtime) = async_runtime { core.ref_counts.insert( name.to_owned(), diff --git a/rust/src/registry/registry.rs b/rust/src/registry/registry.rs index 5a266916..b47be209 100644 --- a/rust/src/registry/registry.rs +++ b/rust/src/registry/registry.rs @@ -21,7 +21,6 @@ use crate::module::{ use crate::registry::conflicts::{detect_id_conflicts, ConflictSeverity, ConflictType}; use crate::registry::metadata::parse_dependencies; use crate::registry::types::DepInfo; -use crate::registry::version::try_matches_version_hint; #[path = "async_lifecycle.rs"] mod async_lifecycle; @@ -30,6 +29,8 @@ mod async_lifecycle; mod filesystem_watch; #[path = "managed_lifecycle.rs"] mod managed_lifecycle; +#[path = "registry_discovery.rs"] +mod registry_discovery; /// Join the `message` field of each validation error detail into a single /// comma-separated string for human-readable error reporting. @@ -462,6 +463,7 @@ fn validate_module_id(name: &str, allow_reserved: bool) -> Result<(), ModuleErro struct RegistryCore { modules: HashMap>, descriptors: HashMap, + output_generations: HashMap>, /// Reference counts for safe hot-reload — prevents unloading while in use. ref_counts: HashMap>, // The explicit acquire/release API identifies leases by name only. Retain @@ -597,7 +599,7 @@ impl ModuleReferences { return; } let references = Arc::clone(self); - let _ = tokio::task::spawn_blocking(move || references.finish_removal(true)).await; + let _ = crate::runtime::spawn_blocking(move || references.finish_removal(true)).await; // An already-running cleanup hook must settle under its owner. if self.state.lock().completed { return; @@ -851,6 +853,7 @@ impl RegistryCore { Self { modules: HashMap::new(), descriptors: HashMap::new(), + output_generations: HashMap::new(), ref_counts: HashMap::new(), manual_leases: HashMap::new(), pending_removals: HashMap::new(), @@ -881,8 +884,21 @@ impl RegistryCore { } } + fn publish_active_module( + &mut self, + name: &str, + module: Arc, + descriptor: ModuleDescriptor, + ) { + self.modules.insert(name.to_owned(), module); + self.descriptors.insert(name.to_owned(), descriptor); + self.output_generations + .insert(name.to_owned(), Arc::new(())); + } + fn remove_module(&mut self, name: &str) -> Option { let primary = self.modules.remove(name)?; + self.output_generations.remove(name); // INVARIANT: publication installs the module and its descriptor under the same lock. let descriptor = self .descriptors @@ -911,6 +927,73 @@ impl RegistryCore { } } +/// Published output schema bound to one active module registration. +/// +/// A detached declaration lets a host verify that a projection still belongs +/// to the registration it observed before execution. Core still decides call +/// access and validates outputs in the execution pipeline. +pub struct OutputDeclaration { + registry: Weak>, + name: String, + generation: Arc<()>, + schema: serde_json::Value, + streaming: bool, +} + +impl OutputDeclaration { + /// The registered output schema. + #[must_use] + pub fn schema(&self) -> &serde_json::Value { + &self.schema + } + + /// Whether the registration declares native streaming. + #[must_use] + pub fn is_streaming(&self) -> bool { + self.streaming + || self.registry.upgrade().is_some_and(|registry| { + let module = self.current_module(®istry); + module.is_some_and(|module| { + module.as_streaming().is_some() || module.annotations().streaming + }) + }) + } + + /// Whether the declaration still belongs to the active, available module. + #[must_use] + pub fn is_current(&self) -> bool { + let Some(registry) = self.registry.upgrade() else { + return false; + }; + self.current_module(®istry).is_some_and(|module| { + // The executor validates Module::output_schema, including when an + // explicitly registered descriptor supplies different metadata. + // Host methods run outside the lock and may change the registry. + module.output_schema() == self.schema && self.matches(®istry.read()) + }) + } + + fn current_module(&self, registry: &RwLock) -> Option> { + let core = registry.read(); + self.matches(&core) + .then(|| Arc::clone(&core.modules[&self.name])) + } + + fn matches(&self, core: &RegistryCore) -> bool { + !core.closed + && !core.draining.contains(&self.name) + && !core.unavailable.contains(&self.name) + && core + .descriptors + .get(&self.name) + .is_some_and(|descriptor| descriptor.enabled) + && core + .output_generations + .get(&self.name) + .is_some_and(|current| Arc::ptr_eq(current, &self.generation)) + } +} + /// Central registry of modules. /// /// The `Registry` uses interior mutability via `parking_lot::RwLock` so that @@ -968,32 +1051,6 @@ pub struct Registry { event_emitter: Arc>>>, } -/// RAII guard that restores a taken-out `Discoverer` back into the registry's -/// slot when dropped — including during panic unwind from `discover().await`. -/// -/// Without this, a panic inside a custom `Discoverer::discover` future would -/// permanently lose the discoverer because the manual "put it back" block -/// below the `.await` would be unreachable. -/// -/// If a concurrent `set_discoverer` swapped in a new instance during the -/// `.await`, that new one wins — the guard only restores when the slot is -/// still `None`. -struct DiscovererRestoreGuard<'a> { - slot: &'a RwLock>>, - discoverer: Option>, -} - -impl Drop for DiscovererRestoreGuard<'_> { - fn drop(&mut self) { - if let Some(d) = self.discoverer.take() { - let mut slot = self.slot.write(); - if slot.is_none() { - *slot = Some(d); - } - } - } -} - impl std::fmt::Debug for Registry { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let core = self.core.read(); @@ -1461,8 +1518,7 @@ impl Registry { "output": latest_descriptor.output_schema, }), ); - core.modules.insert(name.to_string(), latest_module); - core.descriptors.insert(name.to_string(), latest_descriptor); + core.publish_active_module(name, latest_module, latest_descriptor); } } @@ -1566,6 +1622,28 @@ impl Registry { Ok(self.core.read().modules.get(name).cloned()) } + /// Read the output schema and registration identity in one snapshot. + /// + /// Returns `None` for an unavailable module. This metadata accessor does + /// not perform authorization or invoke host code. Verify the runtime + /// schema with [`OutputDeclaration::is_current`] before use. + #[must_use] + pub fn capture_output_declaration(&self, name: &str) -> Option { + let core = self.core.read(); + let descriptor = core.descriptors.get(name)?; + let declaration = OutputDeclaration { + registry: Arc::downgrade(&self.core), + name: name.to_owned(), + generation: Arc::clone(core.output_generations.get(name)?), + schema: descriptor.output_schema.clone(), + streaming: descriptor + .annotations + .as_ref() + .is_some_and(|ann| ann.streaming), + }; + declaration.matches(&core).then_some(declaration) + } + /// Read the governance annotation union without triggering descriptor access warnings. pub(crate) fn governance_annotations(&self, name: &str) -> Option { let (module, declared) = { @@ -1724,30 +1802,6 @@ impl Registry { self.core.read().modules.contains_key(name) } - /// Discover and register modules from a discoverer. - /// - /// Returns the count of entries that were actually registered — - /// entries whose `name` fails `PROTOCOL_SPEC` §2.7 validation, whose - /// `name` duplicates an already-discovered descriptor, or whose - /// instance is rejected by the custom validator are skipped with a - /// `tracing::warn!` and excluded from the count. - /// - /// Aligned with `apcore-python.Registry._discover_custom` and - /// `apcore-typescript.Registry._discoverCustom` — same skip-and-warn - /// semantics for malformed entries, and the same roots: the registry's - /// [`extension_roots`](Self::extension_roots), which a filesystem - /// discoverer such as [`DefaultDiscoverer`](crate::DefaultDiscoverer) - /// scans and nothing else. - #[allow(clippy::similar_names)] // `discoverer` (param) and `discovered` (result) are semantically distinct - pub async fn discover(&self, discoverer: &dyn Discoverer) -> Result { - if self.core.read().closed { - return Err(Self::closed_error()); - } - let roots = self.extension_roots.read().clone(); - let discovered = discoverer.discover(&roots).await?; - Ok(self.register_discovered(discovered).await) - } - /// Register a sys/internal module that bypasses **only** the reserved /// word check. All other `PROTOCOL_SPEC` §2.7 validations (empty, EBNF /// pattern, length, duplicate) still apply. @@ -2088,9 +2142,7 @@ impl Registry { core.schema_cache.insert(name.to_string(), schema); core.lowercase_map .insert(name.to_lowercase(), name.to_string()); - core.modules - .insert(name.to_string(), Arc::clone(&module_arc)); - core.descriptors.insert(name.to_string(), descriptor); + core.publish_active_module(name, Arc::clone(&module_arc), descriptor); true } }; @@ -2651,428 +2703,6 @@ impl Registry { false } - /// Re-run module discovery and update the registry. - /// - /// Equivalent to calling [`discover_internal`](Self::discover_internal). - /// Returns the number of newly registered modules. - pub async fn reload(&self) -> Result { - self.discover_internal().await - } - - /// Discover modules using the internally-set discoverer. - /// - /// Returns the number of newly registered modules. - pub async fn discover_internal(&self) -> Result { - if self.core.read().closed { - return Err(Self::closed_error()); - } - let discovered = self.run_discoverer().await?; - Ok(self.register_discovered(discovered).await) - } - - pub(crate) async fn discover_with_resume( - self: &Arc, - states: &HashMap, - ) -> Result { - if self.core.read().closed { - return Err(Self::closed_error()); - } - let discovered = self.run_discoverer().await?; - self.register_discovered_owned(discovered, states.clone()) - .await - } - - /// Run the internally-set discoverer over the extension roots, without - /// registering what it returns. - async fn run_discoverer(&self) -> Result, ModuleError> { - // Run discovery outside of any lock, but we need to briefly check - // that a discoverer is set. We can't hold the discoverer lock across - // `.await`, so we invoke it through a short-lived critical section - // instead — we need the discoverer to survive across the await, so - // the call itself happens while we still hold a read lock but that - // is a `parking_lot::RwLockReadGuard` which is `Send`. However, we - // must NOT hold it across `.await`. Workaround: require the - // discoverer's `discover()` future to be pollable independently. - // - // We achieve this by extracting nothing from the discoverer guard — - // instead we do discovery on a separate dedicated path: the - // discoverer must provide its own internal sync. In practice we - // simply call discoverer.discover().await inside the block, but we - // cannot hold a parking_lot guard across await. - // - // Since Box can't be moved out of the Option under - // a read lock, we accept a subtle limitation: discovery and - // set_discoverer are mutually exclusive in time. We hold the - // discoverer write lock briefly, replace it with None, perform the - // discovery, then put it back via an RAII guard so the discoverer - // is restored even if `discover().await` panics during unwind. - let discoverer_opt = self.discoverer.write().take(); - let guard = DiscovererRestoreGuard { - slot: &self.discoverer, - discoverer: discoverer_opt, - }; - let Some(active_discoverer) = guard.discoverer.as_ref() else { - return Err(ModuleError::new( - crate::errors::ErrorCode::NoDiscovererConfigured, - "No discoverer configured".to_string(), - )); - }; - - let roots = self.extension_roots.read().clone(); - let discover_result = active_discoverer.discover(&roots).await; - // Explicit drop restores the discoverer via Drop impl (also runs on - // panic unwind from the .await above). `active_discoverer` borrow - // ends here, so the drop is reachable. - drop(guard); - - discover_result - } - - /// Return true if a descriptor's schema fields have an acceptable shape (object or null). - /// - /// Custom discoverers may return non-object JSON for `input_schema` / `output_schema` - /// (e.g., a string or number). Calling this before insertion prevents invalid values from - /// flowing into `schema_cache` and later breaking `export_schema()`. - fn descriptor_schema_shape_is_valid(descriptor: &ModuleDescriptor) -> bool { - let input_ok = descriptor.input_schema.is_object() || descriptor.input_schema.is_null(); - let output_ok = descriptor.output_schema.is_object() || descriptor.output_schema.is_null(); - input_ok && output_ok - } - - fn check_discovered_dependencies( - core: &RegistryCore, - module: &DiscoveredModule, - ) -> Result<(), ModuleError> { - for dependency in module - .descriptor - .dependencies - .iter() - .filter(|dep| !dep.optional) - { - let Some(provider) = core.descriptors.get(&dependency.module_id) else { - return Err(ModuleError::new( - crate::errors::ErrorCode::ModuleLoadError, - format!( - "Required dependency '{}' did not load for '{}'", - dependency.module_id, module.name - ), - )); - }; - let constraint = &dependency.version_constraint; - if !constraint.is_empty() && !try_matches_version_hint(&provider.version, constraint)? { - return Err(ModuleError::dependency_version_mismatch( - &module.name, - &dependency.module_id, - constraint, - &provider.version, - )); - } - } - Ok(()) - } - - fn notify_discovered_load_failed(&self, name: &str, error: &ModuleError) { - let callbacks = self.load_failed_callbacks.read().clone(); - for callback in callbacks { - callback(name, error); - } - self.emit_module_load_failed(name, error); - } - - /// Shared discovery post-processing for `discover()` and `discover_internal()`. - /// - /// For each entry: validate the name per `PROTOCOL_SPEC` §2.7, reject - /// duplicates, run the custom validator, invoke `on_load`, then register - /// the instance. Returns the count of entries that successfully registered. - /// Failed entries are logged at `warn`/`error` and skipped; one bad entry - /// never aborts the batch. - /// - /// Uses the same **deferred-publish** pattern as `register_core` (Issue #65): - /// a module is NOT visible in `core.modules` until its `on_load` succeeds. - async fn register_discovered(&self, discovered: Vec) -> usize { - let batch_ids = discovered.iter().map(|entry| entry.name.clone()).collect(); - self.register_discovered_batch(discovered, &batch_ids, &HashMap::new(), false) - .await - } - - #[allow(clippy::too_many_lines)] // sequential per-entry validation gates in a batch loop; splitting further requires passing state and reduces clarity - async fn register_discovered_batch( - &self, - discovered: impl IntoIterator, - batch_ids: &HashSet, - states: &HashMap, - async_hooks: bool, - ) -> usize { - let mut registered_count = 0usize; - for dm in discovered { - // 1. Validate module_id. - if let Err(e) = validate_module_id(&dm.name, false) { - tracing::warn!( - module_id = %dm.name, - error = %e.message, - "Discovered module rejected: invalid module_id" - ); - continue; - } - - // 1b. Reject the reserved `ephemeral.*` namespace. - // - // PROTOCOL_SPEC:424 names "Standard Registry.register() only" as - // the registration mechanism for `ephemeral.*`. A Discoverer - // reaching this sink would bypass `warn_if_missing_approval` and - // the namespace's audit-provenance contract entirely. apcore-python - // (`registry.py` `_register_discovered`) and apcore-typescript - // (`registry.ts`) both reject here. - if is_ephemeral_module_id(&dm.name) { - tracing::warn!( - module_id = %dm.name, - "Discovered module rejected: the reserved ephemeral.* namespace \ - may only be populated via Registry::register()" - ); - continue; - } - - // 2. Run custom validator (outside any lock). - let validator_snapshot = self.validator.read().as_ref().map(Arc::clone); - if let Some(validator) = validator_snapshot { - let result = validator.validate(dm.module.as_ref(), Some(&dm.descriptor)); - if !result.valid { - tracing::warn!( - module_id = %dm.name, - errors = ?result.errors, - "Custom validator rejected discovered module" - ); - continue; - } - } - - // 3. Validate descriptor schema shapes before insertion. - if !Self::descriptor_schema_shape_is_valid(&dm.descriptor) { - tracing::warn!( - module_id = %dm.name, - "Discovered module descriptor has non-object schema shape — skipping" - ); - continue; - } - - if dm.module.as_async_lifecycle().is_some() { - let name = dm.name.clone(); - let result = if async_hooks { - self.load_discovered_with_hooks(dm, states.get(&name).cloned(), None) - .await - } else { - Err(async_lifecycle::requires_async_registration(&name)) - }; - match result { - Ok(()) => registered_count += 1, - Err(error) => { - tracing::warn!(module_id = name, code = %error.wire_code(), "Discovered module could not load with async hooks"); - } - } - continue; - } - - // Reserve the ID against the same published state used for - // conflict and dependency checks. Lock order is core before in_flight. - let reservation = { - let core = self.core.read(); - if core.closed { - break; - } - if core.check_reload_owner(&dm.name, None).is_err() { - continue; - } - let existing_ids: HashSet = core.modules.keys().cloned().collect(); - match detect_id_conflicts( - &dm.name, - &existing_ids, - RESERVED_WORDS, - Some(&core.lowercase_map), - ) { - Some(c) if c.severity == ConflictSeverity::Error => { - tracing::warn!( - module_id = %dm.name, - conflict = %c.message, - "Discovered module rejected: id conflict" - ); - continue; - } - Some(c) => { - tracing::warn!( - module_id = %dm.name, - conflict = %c.message, - "Discovered module registered despite warning-level ID conflict" - ); - } - None => {} - } - if let Err(error) = Self::check_discovered_dependencies(&core, &dm) { - drop(core); - self.notify_discovered_load_failed(&dm.name, &error); - continue; - } - let Some(reservation) = self.in_flight.reserve(&dm.name) else { - tracing::warn!( - module_id = %dm.name, - "Discovered module rejected: concurrent registration in progress" - ); - continue; - }; - for dep in &dm.descriptor.dependencies { - if dep.optional - && batch_ids.contains(&dep.module_id) - && !core.modules.contains_key(&dep.module_id) - { - tracing::warn!(module_id = %dm.name, dependency_id = %dep.module_id, "Optional dependency did not load"); - } - } - reservation - }; - - // 6. Run on_load WITHOUT any lock held (module NOT yet in core.modules). - match self.with_callback_scope(|| dm.module.on_load()) { - Ok(()) => { - if let Some(state) = states.get(&dm.name) { - self.with_callback_scope(|| { - resume_reloaded_module(&dm.name, dm.module.as_ref(), state.clone()); - }); - } - // Commit: insert into visible maps, remove from in_flight. - let published = { - let mut core = self.core.write(); - let published = if core.closed { - Err(Self::closed_error()) - } else { - Self::check_discovered_dependencies(&core, &dm) - }; - if published.is_ok() { - let schema = serde_json::json!({ - "input": dm.descriptor.input_schema.clone(), - "output": dm.descriptor.output_schema.clone(), - }); - core.schema_cache.insert(dm.name.clone(), schema); - core.lowercase_map - .insert(dm.name.to_lowercase(), dm.name.clone()); - core.modules.insert(dm.name.clone(), Arc::clone(&dm.module)); - core.descriptors - .insert(dm.name.clone(), dm.descriptor.clone()); - core.sources.insert(dm.name.clone(), dm.source.clone()); - } - published - }; - if let Err(error) = published { - self.with_callback_scope(|| run_on_unload(&dm.name, dm.module.as_ref())); - drop(reservation); - self.notify_discovered_load_failed(&dm.name, &error); - continue; - } - - drop(reservation); - self.notify_callbacks("register", &dm.name, dm.module.as_ref()); - registered_count += 1; - } - Err(e) => { - tracing::error!( - module_id = %dm.name, - error = %e.message, - "Discovered module on_load failed; skipping registration" - ); - drop(reservation); - // The same two signals `register_core` fires on this branch. - // Only the tracing line and the in_flight release were here, - // so an on_load failure on the DISCOVERY path was invisible - // to both `on_load_failed` callbacks and to subscribers of - // `apcore.registry.module_load_failed` — while the identical - // failure through the manual `register()` path notified both. - // registry-system.md names "discovery-driven paths - // (discover(), register_discovered, hot-reload, etc.)" - // explicitly (sync finding A-D-005). - self.notify_discovered_load_failed(&dm.name, &e); - } - } - } - - registered_count - } - - /// Set the discoverer. - pub fn set_discoverer(&self, discoverer: Box) { - self.set_discoverer_shared(Arc::from(discoverer)); - } - - /// Install an already-shared discoverer handle. - /// - /// The counterpart to [`Self::set_discoverer`] for callers that keep their - /// own reference — [`ExtensionManager::apply`](crate::extensions::ExtensionManager::apply) - /// retains its registrations (D-78), so it wires a clone rather than the - /// only copy. - pub fn set_discoverer_shared(&self, discoverer: Arc) { - *self.discoverer.write() = Some(discoverer); - } - - /// Set the extension roots passed to `Discoverer::discover()`. - /// - /// Aligned with `apcore-python.Registry` (`_extension_roots`) and - /// `apcore-typescript.Registry` (`_extensionRoots`). Each string is a - /// filesystem path (or logical namespace) the discoverer should search. - pub fn set_extension_roots(&self, roots: Vec) { - *self.extension_roots.write() = roots; - } - - /// Return a snapshot of the configured extension roots. - pub fn extension_roots(&self) -> Vec { - self.extension_roots.read().clone() - } - - /// Populate the extension roots from a [`Config`], unless they are already set. - /// - /// This is the config tier of the precedence apcore-python and - /// apcore-typescript implement in their `Registry` constructors — - /// **explicit > config > default**: - /// - /// 1. Roots already set by [`Self::set_extension_roots`] win and are left - /// alone. That is the explicit tier; an embedder who wired roots by hand - /// must never have them overwritten by a config file. - /// 2. Otherwise `extensions.roots` (multi-root mode) is read, accepting both - /// element forms — a bare path string and a `{ root, namespace }` object. - /// 3. Otherwise `extensions.root` is read, with `./extensions` as default. - /// - /// Configured paths are resolved against the project root (§9.2.2). - /// - /// Before this existed, `extension_roots` initialised empty and was written - /// only by `set_extension_roots`, so a client built from a `Config` that set - /// `extensions.root` handed an empty slice to the discoverer and - /// `APCore::discover()` returned `Ok(0)` — a silent no-op indistinguishable - /// from an empty directory. - pub fn set_extension_roots_from_config(&self, config: &crate::config::Config) { - if !self.extension_roots.read().is_empty() { - return; - } - - if let Some(serde_json::Value::Array(items)) = config.get("extensions.roots") { - let roots: Vec = items - .iter() - .filter_map(|item| match item { - serde_json::Value::String(s) => Some(s.as_str()), - serde_json::Value::Object(o) => { - o.get("root").and_then(serde_json::Value::as_str) - } - _ => None, - }) - .filter(|root| !root.is_empty()) - .map(|root| config.resolve_path(root).to_string_lossy().into_owned()) - .collect(); - if !roots.is_empty() { - *self.extension_roots.write() = roots; - return; - } - } - - if let Some(root) = config.get_path("extensions.root") { - *self.extension_roots.write() = vec![root.to_string_lossy().into_owned()]; - } - } - /// Set the validator. pub fn set_validator(&self, validator: Box) { self.set_validator_shared(validator.into()); @@ -3224,323 +2854,5 @@ impl Default for Registry { } #[cfg(test)] -mod extension_roots_from_config_tests { - use super::Registry; - use crate::config::Config; - - fn config_from(json: serde_json::Value) -> Config { - serde_json::from_value(json).expect("config fixture must deserialize") - } - - fn resolved_roots(config: &Config, names: &[&str]) -> Vec { - let root = config.project_root(); - names - .iter() - .map(|name| root.join(name).to_string_lossy().into_owned()) - .collect() - } - - #[test] - fn config_extensions_root_reaches_the_registry() { - // The #39 case. Before `set_extension_roots_from_config` existed this - // registry kept an empty root list and `discover()` returned Ok(0). - let registry = Registry::new(); - assert_eq!(registry.extension_roots(), Vec::::new()); - - let config = config_from(serde_json::json!({ - "version": "1.0.0", - "project": { "name": "demo" }, - "extensions": { "root": "./my-modules" } - })); - registry.set_extension_roots_from_config(&config); - - assert_eq!( - registry.extension_roots(), - resolved_roots(&config, &["./my-modules"]) - ); - } - - #[test] - fn default_applies_when_config_declares_nothing() { - // Consequence 2 of #39: the canonical `./extensions` default never - // reached Rust, because an empty vec has no fallback. `Config::get` - // resolves the default tier, so reading through it is enough. - let registry = Registry::new(); - let config = config_from(serde_json::json!({ - "version": "1.0.0", - "project": { "name": "demo" } - })); - registry.set_extension_roots_from_config(&config); - - assert_eq!( - registry.extension_roots(), - resolved_roots(&config, &["./extensions"]) - ); - } - - #[test] - fn explicit_roots_are_never_overwritten_by_config() { - // The explicit tier. An embedder who wired roots by hand must keep them. - let registry = Registry::new(); - registry.set_extension_roots(vec!["./hand-wired".to_string()]); - - let config = config_from(serde_json::json!({ - "version": "1.0.0", - "project": { "name": "demo" }, - "extensions": { "root": "./from-config" } - })); - registry.set_extension_roots_from_config(&config); - - assert_eq!(registry.extension_roots(), vec!["./hand-wired".to_string()]); - } - - #[test] - fn multi_root_mode_accepts_both_element_forms() { - // `extensions.roots` elements are a bare string OR a {root, namespace} - // object; an implementation that models only one form drops roots. - let registry = Registry::new(); - let config = config_from(serde_json::json!({ - "version": "1.0.0", - "project": { "name": "demo" }, - "extensions": { "roots": [ - "./extensions", - { "root": "./plugins", "namespace": "plugins" } - ]} - })); - registry.set_extension_roots_from_config(&config); - - assert_eq!( - registry.extension_roots(), - resolved_roots(&config, &["./extensions", "./plugins"]) - ); - } - - #[test] - fn multi_root_takes_precedence_over_single_root() { - let registry = Registry::new(); - let config = config_from(serde_json::json!({ - "version": "1.0.0", - "project": { "name": "demo" }, - "extensions": { "roots": ["./a", "./b"] } - })); - registry.set_extension_roots_from_config(&config); - - assert_eq!( - registry.extension_roots(), - resolved_roots(&config, &["./a", "./b"]) - ); - } -} - -#[cfg(test)] -mod deprecation_metadata_tests { - use super::Registry; - use crate::context::Context; - use crate::errors::ModuleError; - use crate::module::Module; - use async_trait::async_trait; - use serde_json::{json, Value}; - use std::collections::HashMap; - - struct Noop; - - #[async_trait] - impl Module for Noop { - fn input_schema(&self) -> Value { - json!({}) - } - fn output_schema(&self) -> Value { - json!({}) - } - fn description(&self) -> &'static str { - "noop" - } - async fn execute( - &self, - _inputs: Value, - _ctx: &Context, - ) -> Result { - Ok(json!({})) - } - } - - fn deprecation_metadata() -> HashMap { - let mut metadata = HashMap::new(); - metadata.insert( - "x-deprecation".to_string(), - json!({ - "deprecated_since": "0.9.0", - "sunset_version": "1.0.0", - "sunset_date": "2027-01-31", - "migration_guide": "Use executor.email.send_email_v2", - }), - ); - metadata - } - - #[test] - fn sunset_date_is_derived_from_x_deprecation() { - // apcore-python reads `sunset_date` out of the `x-deprecation` block; - // every Rust descriptor builder used to hard-code `None`, so a - // deprecated module reported no sunset date at all. - let registry = Registry::new(); - registry - .register_versioned( - "executor.email.send_email", - Box::new(Noop), - Some("0.9.0"), - Some(deprecation_metadata()), - ) - .expect("register"); - - let desc = registry - .get_definition("executor.email.send_email") - .expect("get_definition") - .expect("descriptor"); - assert_eq!(desc.sunset_date.as_deref(), Some("2027-01-31")); - } - - #[test] - fn sunset_date_stays_none_without_x_deprecation() { - let registry = Registry::new(); - registry - .register_versioned("executor.email.send", Box::new(Noop), None, None) - .expect("register"); - - let desc = registry - .get_definition("executor.email.send") - .expect("get_definition") - .expect("descriptor"); - assert!(desc.sunset_date.is_none()); - } - - #[test] - fn an_explicit_sunset_date_is_not_overwritten() { - let registry = Registry::new(); - let descriptor = crate::registry::registry::ModuleDescriptor { - module_id: "executor.email.legacy".to_string(), - name: None, - description: "noop".to_string(), - documentation: None, - input_schema: json!({}), - output_schema: json!({}), - version: "0.9.0".to_string(), - tags: vec![], - annotations: None, - examples: vec![], - metadata: deprecation_metadata(), - display: None, - sunset_date: Some("2026-12-01".to_string()), - dependencies: vec![], - enabled: true, - }; - registry - .register("executor.email.legacy", Box::new(Noop), descriptor) - .expect("register"); - - let desc = registry - .get_definition("executor.email.legacy") - .expect("get_definition") - .expect("descriptor"); - assert_eq!(desc.sunset_date.as_deref(), Some("2026-12-01")); - } - - #[test] - fn deprecation_warning_fires_on_the_read_not_on_registration() { - // D-89 / spec v1.59.0. This crate used to record the marker (and emit) - // from the shared REGISTRATION core, and its reads never warned at all - // — which loses the notice outright for a host that registers before - // installing a `tracing` subscriber, because the marker is written - // whether or not anything was listening and no later read can re-emit. - // - // This test reads the private marker set, so it proves WHERE the entry - // is recorded, not that a subscriber received anything. The emitted - // warning is counted in tests/test_deprecation_warning_cadence.rs, - // which is the assertion that survives deleting the `tracing::warn!`. - let registry = Registry::new(); - - registry - .register_versioned( - "executor.email.send_email", - Box::new(Noop), - Some("0.9.0"), - Some(deprecation_metadata()), - ) - .expect("register"); - assert!( - registry.deprecation_warned.lock().is_empty(), - "registration must not consume the once-per-notice budget" - ); - - // The first read records it; further reads do not. - for _ in 0..5 { - let _ = registry.get_definition("executor.email.send_email"); - } - assert_eq!(registry.deprecation_warned.lock().len(), 1); - } - - #[test] - fn the_deprecation_dedupe_key_carries_the_notice_and_survives_unregister() { - // D-89 / spec v1.59.0. A re-registration carrying the SAME notice is - // silent — `watch()` re-runs discovery as an unregister + re-register, - // so clearing the key there re-warns for every deprecated module on - // every hot reload. A re-registration carrying a CHANGED notice warns, - // which is what keying on the block buys and what this crate used to - // swallow. - let registry = Registry::new(); - - let register = |version: &str, metadata: HashMap| { - registry - .register_versioned( - "executor.email.send_email", - Box::new(Noop), - Some(version), - Some(metadata), - ) - .expect("register"); - let _ = registry.get_definition("executor.email.send_email"); - }; - - register("0.9.0", deprecation_metadata()); - assert_eq!(registry.deprecation_warned.lock().len(), 1); - - // Same notice, same version: no new entry. - registry - .unregister("executor.email.send_email") - .expect("unregister"); - register("0.9.0", deprecation_metadata()); - assert_eq!( - registry.deprecation_warned.lock().len(), - 1, - "an unchanged notice must not be recorded twice" - ); - - // Changed notice, same version: a new entry. - registry - .unregister("executor.email.send_email") - .expect("unregister"); - let mut changed = HashMap::new(); - changed.insert( - "x-deprecation".to_string(), - json!({ - "deprecated_since": "0.9.0", - "sunset_version": "0.10.0", - "sunset_date": "2026-06-30", - "migration_guide": "Use executor.email.send_email_v2", - }), - ); - register("0.9.0", changed); - assert_eq!( - registry.deprecation_warned.lock().len(), - 2, - "a CHANGED notice on a re-registered module must warn" - ); - - // A different VERSION is still a different notice. - registry - .unregister("executor.email.send_email") - .expect("unregister"); - register("0.10.0", deprecation_metadata()); - assert_eq!(registry.deprecation_warned.lock().len(), 3); - } -} +#[path = "registry_tests.rs"] +mod tests; diff --git a/rust/src/registry/registry_discovery.rs b/rust/src/registry/registry_discovery.rs new file mode 100644 index 00000000..990781dc --- /dev/null +++ b/rust/src/registry/registry_discovery.rs @@ -0,0 +1,599 @@ +//! Registry discovery, deferred publication of discovered modules and extension roots. + +use parking_lot::RwLock; +use std::collections::{HashMap, HashSet}; +use std::sync::Arc; + +use super::{ + async_lifecycle, is_ephemeral_module_id, resume_reloaded_module, run_on_unload, + validate_module_id, DiscoveredModule, Discoverer, ModuleDescriptor, Registry, RegistryCore, + RESERVED_WORDS, +}; +use crate::errors::ModuleError; +use crate::registry::conflicts::{detect_id_conflicts, ConflictSeverity}; +use crate::registry::version::try_matches_version_hint; + +/// RAII guard that restores a taken-out `Discoverer` back into the registry's +/// slot when dropped — including during panic unwind from `discover().await`. +/// +/// Without this, a panic inside a custom `Discoverer::discover` future would +/// permanently lose the discoverer because the manual "put it back" block +/// below the `.await` would be unreachable. +/// +/// If a concurrent `set_discoverer` swapped in a new instance during the +/// `.await`, that new one wins — the guard only restores when the slot is +/// still `None`. +struct DiscovererRestoreGuard<'a> { + slot: &'a RwLock>>, + discoverer: Option>, +} + +impl Drop for DiscovererRestoreGuard<'_> { + fn drop(&mut self) { + if let Some(d) = self.discoverer.take() { + let mut slot = self.slot.write(); + if slot.is_none() { + *slot = Some(d); + } + } + } +} + +impl Registry { + /// Discover and register modules from a discoverer. + /// + /// Returns the count of entries that were actually registered — + /// entries whose `name` fails `PROTOCOL_SPEC` §2.7 validation, whose + /// `name` duplicates an already-discovered descriptor, or whose + /// instance is rejected by the custom validator are skipped with a + /// `tracing::warn!` and excluded from the count. + /// + /// Aligned with `apcore-python.Registry._discover_custom` and + /// `apcore-typescript.Registry._discoverCustom` — same skip-and-warn + /// semantics for malformed entries, and the same roots: the registry's + /// [`extension_roots`](Self::extension_roots), which a filesystem + /// discoverer such as [`DefaultDiscoverer`](crate::DefaultDiscoverer) + /// scans and nothing else. + #[allow(clippy::similar_names)] // `discoverer` (param) and `discovered` (result) are semantically distinct + pub async fn discover(&self, discoverer: &dyn Discoverer) -> Result { + if self.core.read().closed { + return Err(Self::closed_error()); + } + let roots = self.extension_roots.read().clone(); + let discovered = discoverer.discover(&roots).await?; + Ok(self.register_discovered(discovered).await) + } + + /// Re-run module discovery and update the registry. + /// + /// Equivalent to calling [`discover_internal`](Self::discover_internal). + /// Returns the number of newly registered modules. + pub async fn reload(&self) -> Result { + self.discover_internal().await + } + + /// Discover modules using the internally-set discoverer. + /// + /// Returns the number of newly registered modules. + pub async fn discover_internal(&self) -> Result { + if self.core.read().closed { + return Err(Self::closed_error()); + } + let discovered = self.run_discoverer().await?; + Ok(self.register_discovered(discovered).await) + } + + pub(crate) async fn discover_with_resume( + self: &Arc, + states: &HashMap, + ) -> Result { + if self.core.read().closed { + return Err(Self::closed_error()); + } + let discovered = self.run_discoverer().await?; + self.register_discovered_owned(discovered, states.clone()) + .await + } + + /// Run the internally-set discoverer over the extension roots, without + /// registering what it returns. + pub(super) async fn run_discoverer(&self) -> Result, ModuleError> { + // Run discovery outside of any lock, but we need to briefly check + // that a discoverer is set. We can't hold the discoverer lock across + // `.await`, so we invoke it through a short-lived critical section + // instead — we need the discoverer to survive across the await, so + // the call itself happens while we still hold a read lock but that + // is a `parking_lot::RwLockReadGuard` which is `Send`. However, we + // must NOT hold it across `.await`. Workaround: require the + // discoverer's `discover()` future to be pollable independently. + // + // We achieve this by extracting nothing from the discoverer guard — + // instead we do discovery on a separate dedicated path: the + // discoverer must provide its own internal sync. In practice we + // simply call discoverer.discover().await inside the block, but we + // cannot hold a parking_lot guard across await. + // + // Since Box can't be moved out of the Option under + // a read lock, we accept a subtle limitation: discovery and + // set_discoverer are mutually exclusive in time. We hold the + // discoverer write lock briefly, replace it with None, perform the + // discovery, then put it back via an RAII guard so the discoverer + // is restored even if `discover().await` panics during unwind. + let discoverer_opt = self.discoverer.write().take(); + let guard = DiscovererRestoreGuard { + slot: &self.discoverer, + discoverer: discoverer_opt, + }; + let Some(active_discoverer) = guard.discoverer.as_ref() else { + return Err(ModuleError::new( + crate::errors::ErrorCode::NoDiscovererConfigured, + "No discoverer configured".to_string(), + )); + }; + + let roots = self.extension_roots.read().clone(); + let discover_result = active_discoverer.discover(&roots).await; + // Explicit drop restores the discoverer via Drop impl (also runs on + // panic unwind from the .await above). `active_discoverer` borrow + // ends here, so the drop is reachable. + drop(guard); + + discover_result + } + + /// Return true if a descriptor's schema fields have an acceptable shape (object or null). + /// + /// Custom discoverers may return non-object JSON for `input_schema` / `output_schema` + /// (e.g., a string or number). Calling this before insertion prevents invalid values from + /// flowing into `schema_cache` and later breaking `export_schema()`. + pub(super) fn descriptor_schema_shape_is_valid(descriptor: &ModuleDescriptor) -> bool { + let input_ok = descriptor.input_schema.is_object() || descriptor.input_schema.is_null(); + let output_ok = descriptor.output_schema.is_object() || descriptor.output_schema.is_null(); + input_ok && output_ok + } + + pub(super) fn check_discovered_dependencies( + core: &RegistryCore, + module: &DiscoveredModule, + ) -> Result<(), ModuleError> { + for dependency in module + .descriptor + .dependencies + .iter() + .filter(|dep| !dep.optional) + { + let Some(provider) = core.descriptors.get(&dependency.module_id) else { + return Err(ModuleError::new( + crate::errors::ErrorCode::ModuleLoadError, + format!( + "Required dependency '{}' did not load for '{}'", + dependency.module_id, module.name + ), + )); + }; + let constraint = &dependency.version_constraint; + if !constraint.is_empty() && !try_matches_version_hint(&provider.version, constraint)? { + return Err(ModuleError::dependency_version_mismatch( + &module.name, + &dependency.module_id, + constraint, + &provider.version, + )); + } + } + Ok(()) + } + + pub(super) fn notify_discovered_load_failed(&self, name: &str, error: &ModuleError) { + let callbacks = self.load_failed_callbacks.read().clone(); + for callback in callbacks { + callback(name, error); + } + self.emit_module_load_failed(name, error); + } + + /// Shared discovery post-processing for `discover()` and `discover_internal()`. + /// + /// For each entry: validate the name per `PROTOCOL_SPEC` §2.7, reject + /// duplicates, run the custom validator, invoke `on_load`, then register + /// the instance. Returns the count of entries that successfully registered. + /// Failed entries are logged at `warn`/`error` and skipped; one bad entry + /// never aborts the batch. + /// + /// Uses the same **deferred-publish** pattern as `register_core` (Issue #65): + /// a module is NOT visible in `core.modules` until its `on_load` succeeds. + async fn register_discovered(&self, discovered: Vec) -> usize { + let batch_ids = discovered.iter().map(|entry| entry.name.clone()).collect(); + self.register_discovered_batch(discovered, &batch_ids, &HashMap::new(), false) + .await + } + + #[allow(clippy::too_many_lines)] // sequential per-entry validation gates in a batch loop; splitting further requires passing state and reduces clarity + pub(super) async fn register_discovered_batch( + &self, + discovered: impl IntoIterator, + batch_ids: &HashSet, + states: &HashMap, + async_hooks: bool, + ) -> usize { + let mut registered_count = 0usize; + for dm in discovered { + // 1. Validate module_id. + if let Err(e) = validate_module_id(&dm.name, false) { + tracing::warn!( + module_id = %dm.name, + error = %e.message, + "Discovered module rejected: invalid module_id" + ); + continue; + } + + // 1b. Reject the reserved `ephemeral.*` namespace. + // + // PROTOCOL_SPEC:424 names "Standard Registry.register() only" as + // the registration mechanism for `ephemeral.*`. A Discoverer + // reaching this sink would bypass `warn_if_missing_approval` and + // the namespace's audit-provenance contract entirely. apcore-python + // (`registry.py` `_register_discovered`) and apcore-typescript + // (`registry.ts`) both reject here. + if is_ephemeral_module_id(&dm.name) { + tracing::warn!( + module_id = %dm.name, + "Discovered module rejected: the reserved ephemeral.* namespace \ + may only be populated via Registry::register()" + ); + continue; + } + + // 2. Run custom validator (outside any lock). + let validator_snapshot = self.validator.read().as_ref().map(Arc::clone); + if let Some(validator) = validator_snapshot { + let result = validator.validate(dm.module.as_ref(), Some(&dm.descriptor)); + if !result.valid { + tracing::warn!( + module_id = %dm.name, + errors = ?result.errors, + "Custom validator rejected discovered module" + ); + continue; + } + } + + // 3. Validate descriptor schema shapes before insertion. + if !Self::descriptor_schema_shape_is_valid(&dm.descriptor) { + tracing::warn!( + module_id = %dm.name, + "Discovered module descriptor has non-object schema shape — skipping" + ); + continue; + } + + if dm.module.as_async_lifecycle().is_some() { + let name = dm.name.clone(); + let result = if async_hooks { + self.load_discovered_with_hooks(dm, states.get(&name).cloned(), None) + .await + } else { + Err(async_lifecycle::requires_async_registration(&name)) + }; + match result { + Ok(()) => registered_count += 1, + Err(error) => { + tracing::warn!(module_id = name, code = %error.wire_code(), "Discovered module could not load with async hooks"); + } + } + continue; + } + + // Reserve the ID against the same published state used for + // conflict and dependency checks. Lock order is core before in_flight. + let reservation = { + let core = self.core.read(); + if core.closed { + break; + } + if core.check_reload_owner(&dm.name, None).is_err() { + continue; + } + let existing_ids: HashSet = core.modules.keys().cloned().collect(); + match detect_id_conflicts( + &dm.name, + &existing_ids, + RESERVED_WORDS, + Some(&core.lowercase_map), + ) { + Some(c) if c.severity == ConflictSeverity::Error => { + tracing::warn!( + module_id = %dm.name, + conflict = %c.message, + "Discovered module rejected: id conflict" + ); + continue; + } + Some(c) => { + tracing::warn!( + module_id = %dm.name, + conflict = %c.message, + "Discovered module registered despite warning-level ID conflict" + ); + } + None => {} + } + if let Err(error) = Self::check_discovered_dependencies(&core, &dm) { + drop(core); + self.notify_discovered_load_failed(&dm.name, &error); + continue; + } + let Some(reservation) = self.in_flight.reserve(&dm.name) else { + tracing::warn!( + module_id = %dm.name, + "Discovered module rejected: concurrent registration in progress" + ); + continue; + }; + for dep in &dm.descriptor.dependencies { + if dep.optional + && batch_ids.contains(&dep.module_id) + && !core.modules.contains_key(&dep.module_id) + { + tracing::warn!(module_id = %dm.name, dependency_id = %dep.module_id, "Optional dependency did not load"); + } + } + reservation + }; + + // 6. Run on_load WITHOUT any lock held (module NOT yet in core.modules). + match self.with_callback_scope(|| dm.module.on_load()) { + Ok(()) => { + if let Some(state) = states.get(&dm.name) { + self.with_callback_scope(|| { + resume_reloaded_module(&dm.name, dm.module.as_ref(), state.clone()); + }); + } + // Commit: insert into visible maps, remove from in_flight. + let published = { + let mut core = self.core.write(); + let published = if core.closed { + Err(Self::closed_error()) + } else { + Self::check_discovered_dependencies(&core, &dm) + }; + if published.is_ok() { + let schema = serde_json::json!({ + "input": dm.descriptor.input_schema.clone(), + "output": dm.descriptor.output_schema.clone(), + }); + core.schema_cache.insert(dm.name.clone(), schema); + core.lowercase_map + .insert(dm.name.to_lowercase(), dm.name.clone()); + core.publish_active_module( + &dm.name, + Arc::clone(&dm.module), + dm.descriptor.clone(), + ); + core.sources.insert(dm.name.clone(), dm.source.clone()); + } + published + }; + if let Err(error) = published { + self.with_callback_scope(|| run_on_unload(&dm.name, dm.module.as_ref())); + drop(reservation); + self.notify_discovered_load_failed(&dm.name, &error); + continue; + } + + drop(reservation); + self.notify_callbacks("register", &dm.name, dm.module.as_ref()); + registered_count += 1; + } + Err(e) => { + tracing::error!( + module_id = %dm.name, + error = %e.message, + "Discovered module on_load failed; skipping registration" + ); + drop(reservation); + // The same two signals `register_core` fires on this branch. + // Only the tracing line and the in_flight release were here, + // so an on_load failure on the DISCOVERY path was invisible + // to both `on_load_failed` callbacks and to subscribers of + // `apcore.registry.module_load_failed` — while the identical + // failure through the manual `register()` path notified both. + // registry-system.md names "discovery-driven paths + // (discover(), register_discovered, hot-reload, etc.)" + // explicitly (sync finding A-D-005). + self.notify_discovered_load_failed(&dm.name, &e); + } + } + } + + registered_count + } + + /// Set the discoverer. + pub fn set_discoverer(&self, discoverer: Box) { + self.set_discoverer_shared(Arc::from(discoverer)); + } + + /// Install an already-shared discoverer handle. + /// + /// The counterpart to [`Self::set_discoverer`] for callers that keep their + /// own reference — [`ExtensionManager::apply`](crate::extensions::ExtensionManager::apply) + /// retains its registrations (D-78), so it wires a clone rather than the + /// only copy. + pub fn set_discoverer_shared(&self, discoverer: Arc) { + *self.discoverer.write() = Some(discoverer); + } + + /// Set the extension roots passed to `Discoverer::discover()`. + /// + /// Aligned with `apcore-python.Registry` (`_extension_roots`) and + /// `apcore-typescript.Registry` (`_extensionRoots`). Each string is a + /// filesystem path (or logical namespace) the discoverer should search. + pub fn set_extension_roots(&self, roots: Vec) { + *self.extension_roots.write() = roots; + } + + /// Return a snapshot of the configured extension roots. + pub fn extension_roots(&self) -> Vec { + self.extension_roots.read().clone() + } + + /// Populate the extension roots from a [`Config`], unless they are already set. + /// + /// This is the config tier of the precedence apcore-python and + /// apcore-typescript implement in their `Registry` constructors — + /// **explicit > config > default**: + /// + /// 1. Roots already set by [`Self::set_extension_roots`] win and are left + /// alone. That is the explicit tier; an embedder who wired roots by hand + /// must never have them overwritten by a config file. + /// 2. Otherwise `extensions.roots` (multi-root mode) is read, accepting both + /// element forms — a bare path string and a `{ root, namespace }` object. + /// 3. Otherwise `extensions.root` is read, with `./extensions` as default. + /// + /// Configured paths are resolved against the project root (§9.2.2). + /// + /// Before this existed, `extension_roots` initialised empty and was written + /// only by `set_extension_roots`, so a client built from a `Config` that set + /// `extensions.root` handed an empty slice to the discoverer and + /// `APCore::discover()` returned `Ok(0)` — a silent no-op indistinguishable + /// from an empty directory. + pub fn set_extension_roots_from_config(&self, config: &crate::config::Config) { + if !self.extension_roots.read().is_empty() { + return; + } + + if let Some(serde_json::Value::Array(items)) = config.get("extensions.roots") { + let roots: Vec = items + .iter() + .filter_map(|item| match item { + serde_json::Value::String(s) => Some(s.as_str()), + serde_json::Value::Object(o) => { + o.get("root").and_then(serde_json::Value::as_str) + } + _ => None, + }) + .filter(|root| !root.is_empty()) + .map(|root| config.resolve_path(root).to_string_lossy().into_owned()) + .collect(); + if !roots.is_empty() { + *self.extension_roots.write() = roots; + return; + } + } + + if let Some(root) = config.get_path("extensions.root") { + *self.extension_roots.write() = vec![root.to_string_lossy().into_owned()]; + } + } +} + +#[cfg(test)] +mod extension_roots_from_config_tests { + use super::Registry; + use crate::config::Config; + + fn config_from(json: serde_json::Value) -> Config { + serde_json::from_value(json).expect("config fixture must deserialize") + } + + fn resolved_roots(config: &Config, names: &[&str]) -> Vec { + let root = config.project_root(); + names + .iter() + .map(|name| root.join(name).to_string_lossy().into_owned()) + .collect() + } + + #[test] + fn config_extensions_root_reaches_the_registry() { + // The #39 case. Before `set_extension_roots_from_config` existed this + // registry kept an empty root list and `discover()` returned Ok(0). + let registry = Registry::new(); + assert_eq!(registry.extension_roots(), Vec::::new()); + + let config = config_from(serde_json::json!({ + "version": "1.0.0", + "project": { "name": "demo" }, + "extensions": { "root": "./my-modules" } + })); + registry.set_extension_roots_from_config(&config); + + assert_eq!( + registry.extension_roots(), + resolved_roots(&config, &["./my-modules"]) + ); + } + + #[test] + fn default_applies_when_config_declares_nothing() { + // Consequence 2 of #39: the canonical `./extensions` default never + // reached Rust, because an empty vec has no fallback. `Config::get` + // resolves the default tier, so reading through it is enough. + let registry = Registry::new(); + let config = config_from(serde_json::json!({ + "version": "1.0.0", + "project": { "name": "demo" } + })); + registry.set_extension_roots_from_config(&config); + + assert_eq!( + registry.extension_roots(), + resolved_roots(&config, &["./extensions"]) + ); + } + + #[test] + fn explicit_roots_are_never_overwritten_by_config() { + // The explicit tier. An embedder who wired roots by hand must keep them. + let registry = Registry::new(); + registry.set_extension_roots(vec!["./hand-wired".to_string()]); + + let config = config_from(serde_json::json!({ + "version": "1.0.0", + "project": { "name": "demo" }, + "extensions": { "root": "./from-config" } + })); + registry.set_extension_roots_from_config(&config); + + assert_eq!(registry.extension_roots(), vec!["./hand-wired".to_string()]); + } + + #[test] + fn multi_root_mode_accepts_both_element_forms() { + // `extensions.roots` elements are a bare string OR a {root, namespace} + // object; an implementation that models only one form drops roots. + let registry = Registry::new(); + let config = config_from(serde_json::json!({ + "version": "1.0.0", + "project": { "name": "demo" }, + "extensions": { "roots": [ + "./extensions", + { "root": "./plugins", "namespace": "plugins" } + ]} + })); + registry.set_extension_roots_from_config(&config); + + assert_eq!( + registry.extension_roots(), + resolved_roots(&config, &["./extensions", "./plugins"]) + ); + } + + #[test] + fn multi_root_takes_precedence_over_single_root() { + let registry = Registry::new(); + let config = config_from(serde_json::json!({ + "version": "1.0.0", + "project": { "name": "demo" }, + "extensions": { "roots": ["./a", "./b"] } + })); + registry.set_extension_roots_from_config(&config); + + assert_eq!( + registry.extension_roots(), + resolved_roots(&config, &["./a", "./b"]) + ); + } +} diff --git a/rust/src/registry/registry_tests.rs b/rust/src/registry/registry_tests.rs new file mode 100644 index 00000000..8483ada8 --- /dev/null +++ b/rust/src/registry/registry_tests.rs @@ -0,0 +1,253 @@ +use super::Registry; +use crate::context::Context; +use crate::errors::ModuleError; +use crate::module::Module; +use async_trait::async_trait; +use serde_json::{json, Value}; +use std::collections::HashMap; + +struct Noop; + +#[async_trait] +impl Module for Noop { + fn input_schema(&self) -> Value { + json!({}) + } + fn output_schema(&self) -> Value { + json!({}) + } + fn description(&self) -> &'static str { + "noop" + } + async fn execute(&self, _inputs: Value, _ctx: &Context) -> Result { + Ok(json!({})) + } +} + +#[test] +fn output_declaration_does_not_follow_the_same_module_arc_across_registration() { + let registry = Registry::new(); + let name = "test.declaration"; + registry.register_module(name, Box::new(Noop)).unwrap(); + let original = registry.capture_output_declaration(name).unwrap(); + assert_eq!(original.schema(), &json!({})); + assert!(!original.is_streaming()); + assert!(original.is_current()); + + let module = registry.get(name).unwrap().unwrap(); + let descriptor = registry.get_definition(name).unwrap().unwrap(); + assert!(registry.unregister(name).unwrap()); + registry + .reinstate_internal(name, module, descriptor) + .unwrap(); + assert!(!original.is_current()); + assert!(registry + .capture_output_declaration(name) + .unwrap() + .is_current()); +} + +#[test] +fn output_declaration_rejects_schema_mismatch_and_version_promotion() { + let registry = Registry::new(); + let name = "test.declaration"; + registry.register_module(name, Box::new(Noop)).unwrap(); + let original = registry.capture_output_declaration(name).unwrap(); + registry + .register_versioned(name, Box::new(Noop), Some("2.0.0"), None) + .unwrap(); + assert!(!original.is_current()); + assert!(registry + .capture_output_declaration(name) + .unwrap() + .is_current()); + + let mut descriptor = registry.get_definition(name).unwrap().unwrap(); + descriptor.output_schema = json!({"type": "object"}); + assert!(registry.unregister(name).unwrap()); + registry.register(name, Box::new(Noop), descriptor).unwrap(); + assert!(!registry + .capture_output_declaration(name) + .unwrap() + .is_current()); +} + +fn deprecation_metadata() -> HashMap { + let mut metadata = HashMap::new(); + metadata.insert( + "x-deprecation".to_string(), + json!({ + "deprecated_since": "0.9.0", + "sunset_version": "1.0.0", + "sunset_date": "2027-01-31", + "migration_guide": "Use executor.email.send_email_v2", + }), + ); + metadata +} + +#[test] +fn sunset_date_is_derived_from_x_deprecation() { + // apcore-python reads `sunset_date` out of the `x-deprecation` block; + // every Rust descriptor builder used to hard-code `None`, so a + // deprecated module reported no sunset date at all. + let registry = Registry::new(); + registry + .register_versioned( + "executor.email.send_email", + Box::new(Noop), + Some("0.9.0"), + Some(deprecation_metadata()), + ) + .expect("register"); + + let desc = registry + .get_definition("executor.email.send_email") + .expect("get_definition") + .expect("descriptor"); + assert_eq!(desc.sunset_date.as_deref(), Some("2027-01-31")); +} + +#[test] +fn sunset_date_stays_none_without_x_deprecation() { + let registry = Registry::new(); + registry + .register_versioned("executor.email.send", Box::new(Noop), None, None) + .expect("register"); + + let desc = registry + .get_definition("executor.email.send") + .expect("get_definition") + .expect("descriptor"); + assert!(desc.sunset_date.is_none()); +} + +#[test] +fn an_explicit_sunset_date_is_not_overwritten() { + let registry = Registry::new(); + let descriptor = crate::registry::registry::ModuleDescriptor { + module_id: "executor.email.legacy".to_string(), + name: None, + description: "noop".to_string(), + documentation: None, + input_schema: json!({}), + output_schema: json!({}), + version: "0.9.0".to_string(), + tags: vec![], + annotations: None, + examples: vec![], + metadata: deprecation_metadata(), + display: None, + sunset_date: Some("2026-12-01".to_string()), + dependencies: vec![], + enabled: true, + }; + registry + .register("executor.email.legacy", Box::new(Noop), descriptor) + .expect("register"); + + let desc = registry + .get_definition("executor.email.legacy") + .expect("get_definition") + .expect("descriptor"); + assert_eq!(desc.sunset_date.as_deref(), Some("2026-12-01")); +} + +#[test] +fn deprecation_warning_fires_on_the_read_not_on_registration() { + // D-89 / spec v1.59.0. This crate used to record the marker (and emit) + // from the shared REGISTRATION core, and its reads never warned at all + // — which loses the notice outright for a host that registers before + // installing a `tracing` subscriber, because the marker is written + // whether or not anything was listening and no later read can re-emit. + // + // This test reads the private marker set, so it proves WHERE the entry + // is recorded, not that a subscriber received anything. The emitted + // warning is counted in tests/test_deprecation_warning_cadence.rs, + // which is the assertion that survives deleting the `tracing::warn!`. + let registry = Registry::new(); + + registry + .register_versioned( + "executor.email.send_email", + Box::new(Noop), + Some("0.9.0"), + Some(deprecation_metadata()), + ) + .expect("register"); + assert!( + registry.deprecation_warned.lock().is_empty(), + "registration must not consume the once-per-notice budget" + ); + + // The first read records it; further reads do not. + for _ in 0..5 { + let _ = registry.get_definition("executor.email.send_email"); + } + assert_eq!(registry.deprecation_warned.lock().len(), 1); +} + +#[test] +fn the_deprecation_dedupe_key_carries_the_notice_and_survives_unregister() { + // D-89 / spec v1.59.0. A re-registration carrying the SAME notice is + // silent — `watch()` re-runs discovery as an unregister + re-register, + // so clearing the key there re-warns for every deprecated module on + // every hot reload. A re-registration carrying a CHANGED notice warns, + // which is what keying on the block buys and what this crate used to + // swallow. + let registry = Registry::new(); + + let register = |version: &str, metadata: HashMap| { + registry + .register_versioned( + "executor.email.send_email", + Box::new(Noop), + Some(version), + Some(metadata), + ) + .expect("register"); + let _ = registry.get_definition("executor.email.send_email"); + }; + + register("0.9.0", deprecation_metadata()); + assert_eq!(registry.deprecation_warned.lock().len(), 1); + + // Same notice, same version: no new entry. + registry + .unregister("executor.email.send_email") + .expect("unregister"); + register("0.9.0", deprecation_metadata()); + assert_eq!( + registry.deprecation_warned.lock().len(), + 1, + "an unchanged notice must not be recorded twice" + ); + + // Changed notice, same version: a new entry. + registry + .unregister("executor.email.send_email") + .expect("unregister"); + let mut changed = HashMap::new(); + changed.insert( + "x-deprecation".to_string(), + json!({ + "deprecated_since": "0.9.0", + "sunset_version": "0.10.0", + "sunset_date": "2026-06-30", + "migration_guide": "Use executor.email.send_email_v2", + }), + ); + register("0.9.0", changed); + assert_eq!( + registry.deprecation_warned.lock().len(), + 2, + "a CHANGED notice on a re-registered module must warn" + ); + + // A different VERSION is still a different notice. + registry + .unregister("executor.email.send_email") + .expect("unregister"); + register("0.10.0", deprecation_metadata()); + assert_eq!(registry.deprecation_warned.lock().len(), 3); +} diff --git a/rust/src/runtime.rs b/rust/src/runtime.rs index bf52f839..7770a15e 100644 --- a/rust/src/runtime.rs +++ b/rust/src/runtime.rs @@ -1,8 +1,12 @@ use std::sync::OnceLock; -use tokio::runtime::{Handle, Runtime}; +use tokio::runtime::Handle; + +#[cfg(not(target_family = "wasm"))] +use tokio::runtime::Runtime; /// Process-owned scheduler for work that outlives the host's current task or runtime. +#[cfg(not(target_family = "wasm"))] pub(crate) fn background_runtime() -> Result { static RUNTIME: OnceLock> = OnceLock::new(); RUNTIME @@ -16,3 +20,31 @@ pub(crate) fn background_runtime() -> Result { .as_ref() .map(|runtime| runtime.handle().clone()) } + +/// WASI hosts drive background work on their current single-threaded runtime. +#[cfg(target_family = "wasm")] +pub(crate) fn background_runtime() -> Result { + static NO_RUNTIME: OnceLock = OnceLock::new(); + Handle::try_current().map_err(|_| { + NO_RUNTIME.get_or_init(|| { + std::io::Error::other("APCore requires an active Tokio runtime on WASM") + }) + }) +} + +/// Dispatch synchronous hooks on a worker thread where the host supports it. +/// WASI executes such callbacks cooperatively on the current runtime. +pub(crate) fn spawn_blocking(task: F) -> tokio::task::JoinHandle +where + F: FnOnce() -> T + Send + 'static, + T: Send + 'static, +{ + #[cfg(not(target_family = "wasm"))] + { + tokio::task::spawn_blocking(task) + } + #[cfg(target_family = "wasm")] + { + tokio::spawn(async move { task() }) + } +} diff --git a/rust/tests/run-wasi.mjs b/rust/tests/run-wasi.mjs new file mode 100644 index 00000000..a4a9977e --- /dev/null +++ b/rust/tests/run-wasi.mjs @@ -0,0 +1,8 @@ +import { readFile } from 'node:fs/promises'; +import { WASI } from 'node:wasi'; + +const [file, ...args] = process.argv.slice(2); +const wasi = new WASI({ version: 'preview1', args: [file, ...args], env: {}, preopens: {} }); +const module = await WebAssembly.compile(await readFile(file)); +const instance = await WebAssembly.instantiate(module, wasi.getImportObject()); +process.exitCode = wasi.start(instance); diff --git a/typescript/src/browser/index.ts b/typescript/src/browser/index.ts index 383ac2bf..691ab2a3 100644 --- a/typescript/src/browser/index.ts +++ b/typescript/src/browser/index.ts @@ -198,7 +198,7 @@ export { // ---- Registry helpers (pure) --------------------------------------------- export { detectIdConflicts } from '../registry/conflicts.js'; export type { ConflictResult, ConflictType, ConflictSeverity } from '../registry/conflicts.js'; -export type { ModuleDescriptor, DiscoveredModule, DependencyInfo } from '../registry/types.js'; +export type { ModuleDescriptor, DiscoveredModule, DependencyInfo, OutputDeclaration } from '../registry/types.js'; export { classNameToSegment, discoverMultiClass } from '../registry/multi-class.js'; export type { ClassDescriptor, MultiClassEntry } from '../registry/multi-class.js'; diff --git a/typescript/src/node-api.ts b/typescript/src/node-api.ts index 5c9d65ab..b0925c8c 100644 --- a/typescript/src/node-api.ts +++ b/typescript/src/node-api.ts @@ -315,7 +315,7 @@ export { export type { AssertOpenAiStrictOptions } from './schema/openai-strict.js'; // Registry types -export type { ModuleDescriptor, DiscoveredModule, DependencyInfo } from './registry/types.js'; +export type { ModuleDescriptor, DiscoveredModule, DependencyInfo, OutputDeclaration } from './registry/types.js'; // Registry conflicts export { detectIdConflicts } from './registry/conflicts.js'; diff --git a/typescript/src/registry/registry.ts b/typescript/src/registry/registry.ts index d07c6e53..d96ad2e4 100644 --- a/typescript/src/registry/registry.ts +++ b/typescript/src/registry/registry.ts @@ -2,6 +2,7 @@ * Central module registry for discovering, registering, and querying modules. */ +import { Kind } from '@sinclair/typebox'; import type { Config } from '../config.js'; import { getDefault } from '../config-defaults.js'; import type { Context } from '../context.js'; @@ -38,14 +39,35 @@ import { resolveDependencies } from './dependencies.js'; import { resolveEntryPoint } from './entry-point.js'; import { mergeModuleMetadata, parseDependencies, snapshotRegistryData } from './metadata-pure.js'; import { governanceUnion } from '../schema/annotations.js'; +import { jsonSchemaToTypeBox, sortedKeysStringify, sourceSchemaFor } from '../schema/loader-pure.js'; import { _discoverMultiClass } from './multi-class.js'; import { getSchema } from './schema-query.js'; import { toStrictSchema } from '../schema/strict.js'; -import type { DependencyInfo, DiscoveredModule, ModuleDescriptor } from './types.js'; +import type { DependencyInfo, DiscoveredModule, ModuleDescriptor, OutputDeclaration } from './types.js'; import { validateModule } from './validation.js'; import { matchesVersionHint } from './version.js'; import { type ManagedDrainPolicy, runManagedDrain } from './managed-drain.js'; +/** Include only JSON data in a declaration and reject hidden or computed annotations. */ +function outputSchemaJSON(schema: Record): string { + return JSON.stringify(schema, (_key, value: unknown) => { + if (value !== null && typeof value === 'object' && !Array.isArray(value) && + Object.values(Object.getOwnPropertyDescriptors(value)).some(property => + !property.enumerable || !Object.hasOwn(property, 'value'))) { + throw new TypeError('Expected output schema data properties'); + } + if (typeof value === 'undefined' || typeof value === 'function' || typeof value === 'symbol' || + (typeof value === 'number' && !Number.isFinite(value))) { + throw new TypeError('Expected an output schema JSON value'); + } + return value; + }); +} + +function outputSchemaDigest(schema: Record): string { + return sortedKeysStringify(JSON.parse(outputSchemaJSON(schema))); +} + /** @internal Registration state used to compensate for a failed reload. */ export interface RegistrationSnapshot { readonly moduleId: string; @@ -1536,6 +1558,54 @@ export class Registry { return this._executionGenerations.get(moduleId)?.discoveryToken ?? null; } + /** Capture an output schema bound to its current published registration. */ + captureOutputDeclaration(moduleId: string): OutputDeclaration | null { + const generation = this.publicGeneration(moduleId); + const module = this._modules.get(moduleId) as Record | undefined; + if (generation === null || !module) return null; + + const read = () => { + if (this.publicGeneration(moduleId) !== generation) return null; + const schema = module['outputSchema'] as Record | undefined; + if (schema == null || typeof schema !== 'object' || Array.isArray(schema)) return null; + const annotations = module['annotations'] as ModuleAnnotations | null | undefined; + return { + schema, + source: sourceSchemaFor(schema), + streaming: typeof module['stream'] === 'function' || annotations?.streaming === true || + this.getDeclaredAnnotations(moduleId)?.streaming === true, + }; + }; + try { + const captured = read(); + if (captured === null || this.publicGeneration(moduleId) !== generation) return null; + const schema = JSON.parse(outputSchemaJSON(captured.source)) as Record; + const sourceDigest = sortedKeysStringify(schema); + // Core may lazily compile a JSON declaration during its first call. + // Accept that exact representation, including its preserved annotations. + const expectedCompiled = outputSchemaDigest(Kind in captured.source + ? captured.source : jsonSchemaToTypeBox(captured.source)); + if (Kind in captured.schema && outputSchemaDigest(captured.schema) !== expectedCompiled) return null; + return { + schema, + streaming: captured.streaming, + isCurrent: () => { + try { + const current = read(); + return current !== null && current.streaming === captured.streaming && + outputSchemaDigest(current.source) === sourceDigest && + (!(Kind in current.schema) || outputSchemaDigest(current.schema) === expectedCompiled) && + this.publicGeneration(moduleId) === generation; + } catch { + return false; + } + }, + }; + } catch { + return null; + } + } + /** Return the module descriptor with detached schemas and metadata records. */ getDefinition(moduleId: string, versionHint?: string | null): ModuleDescriptor | null { // Keep the same invalid-ID error as the instance lookup. diff --git a/typescript/src/registry/types.ts b/typescript/src/registry/types.ts index d669492e..3f816a6d 100644 --- a/typescript/src/registry/types.ts +++ b/typescript/src/registry/types.ts @@ -4,6 +4,14 @@ import type { ModuleAnnotations, ModuleExample } from '../module.js'; +/** Detached output metadata that can be checked against its published registration. */ +export interface OutputDeclaration { + readonly schema: Record; + readonly streaming: boolean; + /** True while the registration, output schema, and streaming status match. */ + isCurrent(): boolean; +} + export interface ModuleDescriptor { moduleId: string; name: string | null; diff --git a/typescript/tests/registry/test-output-declaration.test.ts b/typescript/tests/registry/test-output-declaration.test.ts new file mode 100644 index 00000000..d5948aed --- /dev/null +++ b/typescript/tests/registry/test-output-declaration.test.ts @@ -0,0 +1,79 @@ +import { Executor, Registry, STREAMING_MARKER } from '../../src/index.js'; +import { describe, expect, it } from 'vitest'; + +const skill = 'reports.download'; + +function download() { + return { + description: 'Download an archived report', + inputSchema: { type: 'object' }, + outputSchema: { + type: 'object', + properties: { report: { type: 'string', enum: ['opaque'], 'x-a2a-artifact': true } }, + required: ['report'], + }, + async execute() { return { report: 'opaque' }; }, + }; +} + +describe('Registry.captureOutputDeclaration', () => { + it('preserves the detached authored schema after Core compiles it for a call', async () => { + const registry = new Registry(); + const module = download(); + const schema = structuredClone(module.outputSchema); + await registry.register(skill, module); + const declaration = registry.captureOutputDeclaration(skill); + expect(declaration?.streaming).toBe(false); + expect(declaration?.schema).toEqual(schema); + expect(await new Executor({ registry }).call(skill, {})).toEqual({ report: 'opaque' }); + expect(declaration?.isCurrent()).toBe(true); + expect(registry.captureOutputDeclaration(skill)?.schema).toEqual(schema); + if (declaration) declaration.schema.properties = {}; + expect(registry.captureOutputDeclaration(skill)?.schema).toEqual(schema); + expect(declaration?.isCurrent()).toBe(true); + }); + + it('rejects schema drift and a new registration of the same module instance', async () => { + const registry = new Registry(); + const module = download(); + await registry.register(skill, module); + const declaration = registry.captureOutputDeclaration(skill); + module.outputSchema.properties.report['x-a2a-artifact'] = false; + expect(declaration?.isCurrent()).toBe(false); + module.outputSchema.properties.report['x-a2a-artifact'] = true; + await registry.unregister(skill); + expect(registry.captureOutputDeclaration(skill)).toBeNull(); + await registry.register(skill, module); + expect(declaration?.isCurrent()).toBe(false); + expect(registry.captureOutputDeclaration(skill)?.isCurrent()).toBe(true); + }); + + it('rejects drift in the compiled representation before and after capture', async () => { + const registry = new Registry(); + const module = download(); + await registry.register(skill, module); + const declaration = registry.captureOutputDeclaration(skill); + await new Executor({ registry }).call(skill, {}); + const compiled = module.outputSchema.properties.report as Record; + compiled['x-sensitive'] = true; + expect(declaration?.isCurrent()).toBe(false); + expect(registry.captureOutputDeclaration(skill)).toBeNull(); + }); + + it('rejects a declaration with a hidden sensitivity annotation', async () => { + const registry = new Registry(); + const module = download(); + Object.defineProperty(module.outputSchema.properties.report, 'x-sensitive', { value: true }); + await registry.register(skill, module); + expect(registry.captureOutputDeclaration(skill)).toBeNull(); + }); + + it('identifies native streaming modules', async () => { + const registry = new Registry(); + await registry.register(skill, { + ...download(), [STREAMING_MARKER]: true, + async *stream() { yield { report: 'opaque' }; }, + }); + expect(registry.captureOutputDeclaration(skill)?.streaming).toBe(true); + }); +}); From 2a28c2cfeed08d8b803c6b5ee033221badc8f016 Mon Sep 17 00:00:00 2001 From: tercel Date: Sun, 29 Nov 2026 18:28:43 +0800 Subject: [PATCH 2/6] Implement the opt-in artifact reference contract across SDKs Signed-off-by: tercel --- conformance/README.md | 1 + conformance/fixtures/artifact_reference.json | 542 ++++++++++++++++++ planning/atlas-artifact-reference/contract.md | 56 ++ python/src/apcore/__init__.py | 5 + python/src/apcore/_artifact_projection.py | 61 ++ python/src/apcore/artifacts.py | 98 ++++ .../src/apcore/schema/_artifact_assertions.py | 140 +++++ python/src/apcore/schema/hardening.py | 29 +- python/src/apcore/schema/loader.py | 52 +- python/src/apcore/schema/validator.py | 56 +- python/tests/test_artifact_reference.py | 178 ++++++ python/tests/test_public_api.py | 4 + rust/src/artifacts.rs | 164 ++++++ rust/src/lib.rs | 5 + rust/src/schema/artifact_reference.rs | 185 ++++++ rust/src/schema/hardening.rs | 10 +- rust/src/schema/mod.rs | 1 + rust/src/schema/validator.rs | 41 +- rust/tests/artifact_reference_spec.rs | 346 +++++++++++ rust/tests/it.rs | 2 + schemas/artifact-ref.schema.json | 29 + typescript/src/artifact.ts | 97 ++++ typescript/src/browser/index.ts | 3 + typescript/src/node-api.ts | 3 + typescript/src/schema/artifact-reference.ts | 99 ++++ typescript/src/schema/loader-pure.ts | 34 +- typescript/src/schema/validator.ts | 81 ++- .../conformance-artifact-reference.test.ts | 155 +++++ 28 files changed, 2408 insertions(+), 69 deletions(-) create mode 100644 conformance/fixtures/artifact_reference.json create mode 100644 planning/atlas-artifact-reference/contract.md create mode 100644 python/src/apcore/_artifact_projection.py create mode 100644 python/src/apcore/artifacts.py create mode 100644 python/src/apcore/schema/_artifact_assertions.py create mode 100644 python/tests/test_artifact_reference.py create mode 100644 rust/src/artifacts.rs create mode 100644 rust/src/schema/artifact_reference.rs create mode 100644 rust/tests/artifact_reference_spec.rs create mode 100644 schemas/artifact-ref.schema.json create mode 100644 typescript/src/artifact.ts create mode 100644 typescript/src/schema/artifact-reference.ts create mode 100644 typescript/tests/conformance-artifact-reference.test.ts diff --git a/conformance/README.md b/conformance/README.md index 70937179..d1d8a5a7 100644 --- a/conformance/README.md +++ b/conformance/README.md @@ -48,6 +48,7 @@ declared extension. Adapter wire projections are verified in Surfaces. | `extension_point_lookup.json` | D-108 | `get`/`get_all`/`unregister` reject an UNREGISTERED extension point with `GENERAL_INVALID_INPUT`, and do not raise for a registered point holding nothing (spec v1.51.0) | | `config_env.json` | — | Configuration environment variable override | | `context_serialization.json` | — | Cross-language Context serialize/deserialize round-trip | +| `artifact_reference.json` | [Opt-in artifact reference contract](../planning/atlas-artifact-reference/contract.md) | Closed wire shape, media and byte assertions, local references and schema dialect checks. | | `schema_validation.json` | §4.15 | Schema validation edge cases, plus the **opt-in library-level** coercing mode. Cases carrying `expected_valid_strict` / `expected_valid_coerce` document BOTH modes and SHOULD be asserted against both, naming the mode explicitly rather than relying on a constructor default. The coercing mode is a knob on the standalone validator API only — it never reaches the module-invocation boundary, which is covered by `schema_keyword_parity.json` (TYPE_MAPPING §17.3). | | `schema_hardening_union.json` | §4.15 Hardening | anyOf/oneOf union evaluation: all-branches, exactly-one, ambiguous-error | | `schema_hardening_recursive.json` | §4.15 Hardening | Recursive schema support: TreeNode pattern, depth 1-5 | diff --git a/conformance/fixtures/artifact_reference.json b/conformance/fixtures/artifact_reference.json new file mode 100644 index 00000000..953a0405 --- /dev/null +++ b/conformance/fixtures/artifact_reference.json @@ -0,0 +1,542 @@ +{ + "description": "Opt-in 2020-12 artifact references and media/size assertions", + "test_cases": [ + { + "id": "bounded_reference", + "schema": { + "type": "object", + "properties": { + "payload": { + "x-media-types": [ + "application/json" + ], + "x-max-bytes": 7 + } + }, + "required": [ + "payload" + ] + }, + "data": { + "payload": { + "id": "id_0", + "media_type": "application/json", + "size_bytes": 7 + } + }, + "expected": "valid" + }, + { + "id": "zero_bytes", + "schema": { + "x-artifact-ref": true + }, + "data": { + "id": "id_0", + "media_type": "application/json", + "size_bytes": 0 + }, + "expected": "valid" + }, + { + "id": "unsafe_id", + "schema": { + "x-artifact-ref": true + }, + "data": { + "id": "https://host.test/asset", + "media_type": "application/json", + "size_bytes": 7 + }, + "expected": "invalid_instance" + }, + { + "id": "newline_in_id", + "schema": { + "x-artifact-ref": true + }, + "data": { + "id": "id_0\n", + "media_type": "application/json", + "size_bytes": 7 + }, + "expected": "invalid_instance" + }, + { + "id": "media_parameter", + "schema": { + "x-artifact-ref": true + }, + "data": { + "id": "id_0", + "media_type": "text/plain;charset=utf-8", + "size_bytes": 7 + }, + "expected": "invalid_instance" + }, + { + "id": "media_lowercase", + "schema": { + "x-artifact-ref": true + }, + "data": { + "id": "id_0", + "media_type": "Text/plain", + "size_bytes": 7 + }, + "expected": "invalid_instance" + }, + { + "id": "media_wildcard", + "schema": { + "x-artifact-ref": true + }, + "data": { + "id": "id_0", + "media_type": "text/*", + "size_bytes": 7 + }, + "expected": "invalid_instance" + }, + { + "id": "size_bool", + "schema": { + "x-artifact-ref": true + }, + "data": { + "id": "id_0", + "media_type": "application/json", + "size_bytes": true + }, + "expected": "invalid_instance" + }, + { + "id": "size_fraction", + "schema": { + "x-artifact-ref": true + }, + "data": { + "id": "id_0", + "media_type": "application/json", + "size_bytes": 1.5 + }, + "expected": "invalid_instance" + }, + { + "id": "size_safe_limit", + "schema": { + "x-artifact-ref": true + }, + "data": { + "id": "id_0", + "media_type": "application/json", + "size_bytes": 9007199254740991 + }, + "expected": "valid" + }, + { + "id": "size_outside_safe_limit", + "schema": { + "x-artifact-ref": true + }, + "data": { + "id": "id_0", + "media_type": "application/json", + "size_bytes": 9007199254740992 + }, + "expected": "invalid_instance" + }, + { + "id": "unexpected_location", + "schema": { + "x-artifact-ref": true + }, + "data": { + "id": "id_0", + "media_type": "application/json", + "size_bytes": 7, + "url": "https://host.test/" + }, + "expected": "invalid_instance" + }, + { + "id": "over_bound", + "schema": { + "type": "object", + "properties": { + "payload": { + "x-media-types": [ + "application/json" + ], + "x-max-bytes": 7 + } + }, + "required": [ + "payload" + ] + }, + "data": { + "payload": { + "id": "id_0", + "media_type": "application/json", + "size_bytes": 8 + } + }, + "expected": "invalid_instance" + }, + { + "id": "wrong_type", + "schema": { + "type": "object", + "properties": { + "payload": { + "x-media-types": [ + "application/json" + ], + "x-max-bytes": 7 + } + }, + "required": [ + "payload" + ] + }, + "data": { + "payload": { + "id": "id_0", + "media_type": "text/plain", + "size_bytes": 7 + } + }, + "expected": "invalid_instance" + }, + { + "id": "optional_missing", + "schema": { + "type": "object", + "properties": { + "payload": { + "x-media-types": [ + "application/json" + ], + "x-max-bytes": 7 + } + } + }, + "data": {}, + "expected": "valid" + }, + { + "id": "homogeneous_items", + "schema": { + "type": "object", + "properties": { + "payload": { + "type": "array", + "items": { + "x-artifact-ref": true + } + } + }, + "required": [ + "payload" + ] + }, + "data": { + "payload": [ + { + "id": "id_0", + "media_type": "application/json", + "size_bytes": 7 + }, + { + "id": "id_0", + "media_type": "application/json", + "size_bytes": 7 + } + ] + }, + "expected": "valid" + }, + { + "id": "homogeneous_items_invalid", + "schema": { + "type": "object", + "properties": { + "payload": { + "type": "array", + "items": { + "x-artifact-ref": true + } + } + }, + "required": [ + "payload" + ] + }, + "data": { + "payload": [ + { + "id": "id_0", + "media_type": "application/json", + "size_bytes": 7 + }, + { + "id": "..", + "media_type": "application/json", + "size_bytes": 7 + } + ] + }, + "expected": "invalid_instance" + }, + { + "id": "local_definition_and_sibling", + "schema": { + "type": "object", + "$defs": { + "media": { + "x-artifact-ref": true + } + }, + "properties": { + "payload": { + "$ref": "#/$defs/media", + "x-max-bytes": 7 + } + }, + "required": [ + "payload" + ] + }, + "data": { + "payload": { + "id": "id_0", + "media_type": "application/json", + "size_bytes": 7 + } + }, + "expected": "valid" + }, + { + "id": "local_definition_sibling_rejected", + "schema": { + "type": "object", + "$defs": { + "media": { + "x-artifact-ref": true + } + }, + "properties": { + "payload": { + "$ref": "#/$defs/media", + "x-max-bytes": 7 + } + }, + "required": [ + "payload" + ] + }, + "data": { + "payload": { + "id": "id_0", + "media_type": "application/json", + "size_bytes": 8 + } + }, + "expected": "invalid_instance" + }, + { + "id": "nullable_branched", + "schema": { + "anyOf": [ + { + "type": "null" + }, + { + "x-artifact-ref": true + } + ] + }, + "data": null, + "expected": "valid" + }, + { + "id": "tagged_null", + "schema": { + "x-artifact-ref": true + }, + "data": null, + "expected": "invalid_instance" + }, + { + "id": "bad_tag", + "schema": { + "x-artifact-ref": false + }, + "data": { + "id": "id_0", + "media_type": "application/json", + "size_bytes": 7 + }, + "expected": "invalid_schema" + }, + { + "id": "bad_bound", + "schema": { + "x-max-bytes": true + }, + "data": { + "id": "id_0", + "media_type": "application/json", + "size_bytes": 7 + }, + "expected": "invalid_schema" + }, + { + "id": "empty_media_list", + "schema": { + "x-media-types": [] + }, + "data": { + "id": "id_0", + "media_type": "application/json", + "size_bytes": 7 + }, + "expected": "invalid_schema" + }, + { + "id": "wildcard_declaration", + "schema": { + "x-media-types": [ + "image/*" + ] + }, + "data": { + "id": "id_0", + "media_type": "application/json", + "size_bytes": 7 + }, + "expected": "invalid_schema" + }, + { + "id": "duplicate_declaration", + "schema": { + "x-media-types": [ + "image/png", + "image/png" + ] + }, + "data": { + "id": "id_0", + "media_type": "application/json", + "size_bytes": 7 + }, + "expected": "invalid_schema" + }, + { + "id": "invalid_unused_definition", + "schema": { + "type": "object", + "$defs": { + "unused": { + "x-max-bytes": -1 + } + } + }, + "data": {}, + "expected": "invalid_schema" + }, + { + "id": "tagged_legacy_dialect", + "schema": { + "$schema": "http://json-schema.org/draft-07/schema#", + "x-artifact-ref": true + }, + "data": { + "id": "id_0", + "media_type": "application/json", + "size_bytes": 7 + }, + "expected": "invalid_schema" + }, + { + "id": "annotation_like_instance_values", + "schema": { + "type": "object", + "examples": [ + { + "x-max-bytes": -1 + } + ] + }, + "data": { + "x-artifact-ref": false + }, + "expected": "valid" + }, + { + "id": "unannotated_string", + "schema": { + "type": "string" + }, + "data": "opaque-a2a-id", + "expected": "valid" + }, + { + "id": "nested_tagged_legacy_dialect", + "schema": { + "type": "object", + "$defs": { + "legacy": { + "$id": "https://example.test/legacy-artifact", + "$schema": "http://json-schema.org/draft-07/schema#", + "x-artifact-ref": true + } + } + }, + "data": {}, + "expected": "invalid_schema" + }, + { + "id": "draft_2020_uri_fragment", + "schema": { + "$schema": "https://json-schema.org/draft/2020-12/schema#", + "x-artifact-ref": true + }, + "data": { + "id": "id_0", + "media_type": "application/json", + "size_bytes": 7 + }, + "expected": "valid" + }, + { + "id": "tag_under_legacy_ancestor", + "schema": { + "$schema": "http://json-schema.org/draft-07/schema#", + "definitions": { + "new": { + "$id": "https://example.test/new", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "x-artifact-ref": true + } + } + }, + "data": {}, + "expected": "invalid_schema" + }, + { + "id": "invalid_empty_all_of", + "schema": { + "allOf": [], + "x-artifact-ref": true + }, + "data": { + "id": "id_0", + "media_type": "application/json", + "size_bytes": 7 + }, + "expected": "invalid_schema" + } + ] +} diff --git a/planning/atlas-artifact-reference/contract.md b/planning/atlas-artifact-reference/contract.md new file mode 100644 index 00000000..b62df986 --- /dev/null +++ b/planning/atlas-artifact-reference/contract.md @@ -0,0 +1,56 @@ +# Atlas artifact reference contract review + +Status: implementation contract for an opt-in candidate. Protocol 2.0.0 draft revision 5 remains authoritative. The review uses the MCP byte store and A2A hosted-link pilots and the existing validation and durability boundaries. + +## Decisions + +| Review question | Decision | +| --- | --- | +| What crossed both adapters in the pilot? | An opaque ID scoped by authenticated authority. MCP serves bytes, while A2A projects a host-issued link. `ArtifactRef` carries only ID, media type, and byte count. | +| Can a registry or schema validator prove the content exists? | Schema validation checks a declaration and the declared metadata synchronously. The host store proves existence, authorization, liveness, and immutable content at read time. | +| Where is the transport boundary? | Core never downloads a URL or loads a path for an artifact. URI construction, HTTP signing, caching, and transport error mapping belong to Surfaces and the host. | +| How is an existing module affected? | A declaration opts in through a reserved keyword. Untagged schemas and both existing opaque-string pilots keep their current behavior. No changes to the evaluator, ACL, approval, or execution order. | + +## Wire shape + +The [JSON Schema](../../schemas/artifact-ref.schema.json) defines a closed object with exactly `id`, `media_type`, and `size_bytes`. + +- `id` is 1–128 ASCII characters from letters, digits, `_`, and `-`. It is opaque, scoped to the selected host store, and carries no authority. +- `media_type` is a canonical lowercase `type/subtype`. Each component starts with an ASCII letter or digit and has at most 127 characters. Remaining characters use the restricted name alphabet in [RFC 6838 §4.2](https://www.rfc-editor.org/rfc/rfc6838.html#section-4.2). Parameters, ranges, whitespace, and signed URLs are excluded from the wire shape. +- `size_bytes` is an integer between 0 and 9,007,199,254,740,991 inclusive. The range round-trips through JSON number APIs in all three SDKs. Boolean values are invalid. + +## Schema assertions + +The profile uses Draft 2020-12, also the default when `$schema` is omitted. All explicitly declared dialects along an assertion’s schema path must be Draft 2020-12. Both spellings of its meta-schema URI, with or without the empty fragment, are accepted. A legacy resource without assertions retains its native behavior. A malformed declaration fails as `SCHEMA_PARSE_ERROR`. Any of `x-artifact-ref`, `x-media-types`, or `x-max-bytes` applies the closed reference shape at that schema node. `x-artifact-ref` has the literal value `true`. `x-media-types` is a nonempty array of unique canonical media types and performs exact matching. `x-max-bytes` is an inclusive nonnegative safe-integer bound. The assertions compose with existing constraints. Optional fields use the existing JSON Schema optional-property behavior. To allow `null`, the constraint belongs in the object branch of the union. Declarations at ordinary schema positions, including properties, homogeneous items, and local definitions, retain the native JSON Schema branch and reference behavior. + +Prefer lowering to standard assertions in a validation-only schema. Preserve raw keywords in exported declarations. Skip data-valued keywords such as `examples`, `const`, `enum`, and `default` when looking for declarations. Reject malformed declarations as `SCHEMA_PARSE_ERROR`, including in unused definitions of opted-in schemas. An invalid instance uses the existing schema validation path and error model. Validation diagnostics for opted-in schemas never echo instance values. External schema retrieval remains disabled. Validation never asks a store or uses a URL. Start with JSON-compatible runtime values. Enforcement occurs at built-in input and output validation and the public validation entry points. Approval and policy ordering remain as specified by Core. + +An output field can declare a reference to a PNG thumbnail with a 64 KiB limit. + +```json +{ + "type": "object", + "properties": { + "thumbnail": { + "type": "object", + "x-artifact-ref": true, + "x-media-types": ["image/png"], + "x-max-bytes": 65536 + } + }, + "required": ["thumbnail"] +} +``` + +## Host store + +The SDK offers an async `ArtifactStore` interface. Its `read` method receives an opaque ID, the current trusted `Identity`, and `max_bytes`. Return the authorized immutable bytes and the authoritative `ArtifactRef`, or an absent result for unavailable, expired, unauthorized, or over-budget reads. Backend failures remain errors. Implementations enforce authorization and expiry for each call and bound reads before materializing bytes. Hosts can use separate stores for separate ID namespaces. + +The SDK's `read_artifact` helper receives a validated reference, the current identity and a read limit (default 8 MiB). It rejects invalid or over-budget input before opening the store. It passes `min(limit, size_bytes)` to `read`, verifies metadata exactly equals the reference and verifies actual byte length. Missing or inconsistent objects return absent. Callers must pass identities derived from trusted authentication. An artifact ID never replaces authentication or the call's governance gates. Store implementations and all writes remain host-owned. + +## Acceptance checks + +1. All SDKs agree on the shared wire fixture, including zero bytes, excessive size, unsafe IDs, mixed-case types and wildcard/parameter rejection. +2. Built-in invocation rejects media/size violations before entering module code and rejects mismatched module output. Untagged behavior stays stable. Valid and invalid declaration positions agree across SDKs. +3. An unauthorized, expired, unavailable or mismatched read returns no bytes. Over-budget reads make no store request. The store receives the correct identity and byte bound. +4. A pilot sends one governed reference through the MCP and A2A wire entries and resolves it against one host-owned store. Existing deployments retain the opaque-string pilot and existing transport guardrails. diff --git a/python/src/apcore/__init__.py b/python/src/apcore/__init__.py index 143a717f..f2e00359 100644 --- a/python/src/apcore/__init__.py +++ b/python/src/apcore/__init__.py @@ -21,6 +21,7 @@ CallbackApprovalHandler, ScopedApprovalHandler, ) +from apcore.artifacts import ArtifactContent, ArtifactRef, ArtifactStore, read_artifact from apcore.cancel import CancelToken, ExecutionCancelledError from apcore.call_budget import CallBudget, CallBudgetSnapshot from apcore.capabilities import AccessHint, CallableDefinition, CapabilityPage, CapabilitySearchProvider, ModuleSummary @@ -601,8 +602,12 @@ def enable(module_id: str, reason: str = "Enabled via APCore client") -> dict[st "ApprovalPendingError", "ApprovalRequest", "ApprovalResult", + "ArtifactContent", + "ArtifactRef", + "ArtifactStore", "AutoApproveHandler", "BoundModule", + "read_artifact", "CallBudget", "CallBudgetExceededError", "CallBudgetSnapshot", diff --git a/python/src/apcore/_artifact_projection.py b/python/src/apcore/_artifact_projection.py new file mode 100644 index 00000000..78df6a90 --- /dev/null +++ b/python/src/apcore/_artifact_projection.py @@ -0,0 +1,61 @@ +"""Safe projection of direct output fields that declare a Core ArtifactRef.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, Any + +from pydantic import ValidationError + +if TYPE_CHECKING: + from apcore.artifacts import ArtifactRef + +_ASSERTIONS = frozenset({"x-artifact-ref", "x-media-types", "x-max-bytes"}) +_DIRECT_FIELD_KEYS = _ASSERTIONS | { + "type", + "title", + "description", + "x-sensitive", +} +_ROOT_APPLICATORS = frozenset( + { + "$ref", + "$dynamicRef", + "$recursiveRef", + "allOf", + "anyOf", + "oneOf", + "if", + "then", + "else", + "dependentSchemas", + "dependencies", + "patternProperties", + } +) + + +def is_direct_artifact_reference(root: dict[str, Any], field: dict[str, Any]) -> bool: + """Reject ambiguous declarations before exposing a host-issued link.""" + return ( + root.get("type") == "object" + and not root.get("x-sensitive") + and _ROOT_APPLICATORS.isdisjoint(root) + and not field.get("x-sensitive") + and field.get("type") in (None, "object") + and not _ASSERTIONS.isdisjoint(field) + and all(key in _DIRECT_FIELD_KEYS or key.startswith("x-") for key in field) + ) + + +def parse_artifact_reference(value: Any, field: dict[str, Any]) -> ArtifactRef | None: + """Validate the final field value against its declared media limits.""" + from apcore.artifacts import ArtifactRef + + from apcore.schema.hardening import validate_schema_dict + + try: + if validate_schema_dict(value, field).valid: + return ArtifactRef.model_validate(value) + except ValidationError: + pass + return None diff --git a/python/src/apcore/artifacts.py b/python/src/apcore/artifacts.py new file mode 100644 index 00000000..b7d99693 --- /dev/null +++ b/python/src/apcore/artifacts.py @@ -0,0 +1,98 @@ +"""Opaque artifact references and bounded, host-owned reads.""" + +from __future__ import annotations + +import re +from dataclasses import dataclass +from typing import Any, Protocol + +from pydantic import BaseModel, ConfigDict, Field, ValidationError, field_validator + +from apcore.context import Identity + +__all__ = ["ArtifactContent", "ArtifactRef", "ArtifactStore", "read_artifact"] + +_MAX_SIZE = 9_007_199_254_740_991 +_ID_PATTERN = r"^[A-Za-z0-9_-]{1,128}$" +_MEDIA_NAME = r"[a-z0-9][a-z0-9!#$&^_.+-]{0,126}" +_MEDIA_PATTERN = rf"^{_MEDIA_NAME}/{_MEDIA_NAME}$" +_MEDIA_RE = re.compile(_MEDIA_PATTERN) + + +def _is_canonical_media_type(value: Any) -> bool: + return isinstance(value, str) and _MEDIA_RE.fullmatch(value) is not None + + +def _json_integer(value: Any) -> Any: + return int(value) if isinstance(value, float) and value.is_integer() else value + + +class ArtifactRef(BaseModel): + """Closed JSON metadata for an artifact in the selected host store.""" + + model_config = ConfigDict( + extra="forbid", + frozen=True, + strict=True, + revalidate_instances="always", + hide_input_in_errors=True, + json_schema_extra={"x-artifact-ref": True}, + ) + + id: str = Field(pattern=_ID_PATTERN) + media_type: str = Field(pattern=_MEDIA_PATTERN) + size_bytes: int = Field(ge=0, le=_MAX_SIZE) + + @field_validator("size_bytes", mode="before") + @classmethod + def _normalize_json_integer(cls, value: Any) -> Any: + return _json_integer(value) + + +@dataclass(frozen=True, slots=True) +class ArtifactContent: + """The host's authoritative metadata and immutable bytes.""" + + ref: ArtifactRef + content: bytes + + +class ArtifactStore(Protocol): + """A host store enforcing identity, liveness, and byte limits on each read.""" + + async def read(self, artifact_id: str, identity: Identity, max_bytes: int) -> ArtifactContent | None: + """Return an authorized live artifact within the bound, or no result.""" + ... + + +async def read_artifact( + reference: ArtifactRef, + identity: Identity, + store: ArtifactStore, + *, + max_bytes: int = 8 * 1024 * 1024, +) -> ArtifactContent | None: + """Resolve a reference with a trusted identity and verify the returned bytes.""" + if type(max_bytes) is not int or not 0 <= max_bytes <= _MAX_SIZE: + raise ValueError("The artifact read limit must be a nonnegative safe integer") + if not isinstance(identity, Identity) or not isinstance(identity.id, str) or not identity.id: + raise ValueError("An authenticated identity is required for artifact reads") + if not isinstance(reference, ArtifactRef): + raise ValueError("Invalid artifact reference") + try: + validated = ArtifactRef.model_validate(reference) + except ValidationError: + raise ValueError("Invalid artifact reference") from None + if validated.size_bytes > max_bytes: + return None + + artifact = await store.read(validated.id, identity, validated.size_bytes) + if not isinstance(artifact, ArtifactContent) or type(artifact.content) is not bytes: + return None + if not isinstance(artifact.ref, ArtifactRef) or len(artifact.content) != validated.size_bytes: + return None + try: + actual = ArtifactRef.model_validate(artifact.ref) + except ValidationError: + return None + return artifact if actual == validated else None diff --git a/python/src/apcore/schema/_artifact_assertions.py b/python/src/apcore/schema/_artifact_assertions.py new file mode 100644 index 00000000..237bce10 --- /dev/null +++ b/python/src/apcore/schema/_artifact_assertions.py @@ -0,0 +1,140 @@ +"""Lower opt-in artifact keywords to standard JSON Schema assertions.""" + +from __future__ import annotations + +from collections.abc import Iterator +from copy import copy +from typing import Any + +from apcore.artifacts import _ID_PATTERN, _MAX_SIZE, _MEDIA_PATTERN, _is_canonical_media_type, _json_integer +from apcore.errors import SchemaParseError + +_KEYWORDS = {"x-artifact-ref", "x-media-types", "x-max-bytes"} +_DIALECT = "https://json-schema.org/draft/2020-12/schema" +_SINGLE = ( + "items", + "additionalItems", + "contains", + "additionalProperties", + "unevaluatedProperties", + "unevaluatedItems", + "propertyNames", + "not", + "if", + "then", + "else", + "contentSchema", +) +_MAP = ("properties", "patternProperties", "$defs", "definitions", "dependentSchemas", "dependencies") +_ARRAY = ("allOf", "anyOf", "oneOf", "prefixItems") + + +def _children(node: dict[str, Any]) -> Iterator[tuple[str, str | int | None, dict[str, Any]]]: + for key in _SINGLE: + child = node.get(key) + if isinstance(child, dict): + yield key, None, child + for key in _MAP: + children = node.get(key) + if isinstance(children, dict): + for name, child in children.items(): + if isinstance(child, dict): + yield key, name, child + for key in (*_ARRAY, "items"): + children = node.get(key) + if isinstance(children, list): + for index, child in enumerate(children): + if isinstance(child, dict): + yield key, index, child + + +def _schema_nodes(schema: dict[str, Any]) -> Iterator[tuple[dict[str, Any], bool]]: + """Visit schema positions only, including unreferenced local definitions.""" + pending = [(schema, True)] + visited: set[tuple[int, bool]] = set() + while pending: + node, current = pending.pop() + if "$schema" in node: + dialect = node["$schema"] + current = current and dialect in (_DIALECT, _DIALECT + "#") + key = (id(node), current) + if key in visited: + continue + visited.add(key) + yield node, current + pending.extend((child, current) for _, _, child in _children(node)) + + +def _copy_schema_nodes(nodes: list[dict[str, Any]]) -> dict[int, dict[str, Any]]: + # A dict can be shared between a schema position and a data keyword in a + # YAML anchor or Python literal. Clone schema positions independently. + copies = {id(node): dict(node) for node in nodes} + for node in nodes: + replacement = copies[id(node)] + for key, location, child in _children(node): + if location is None: + replacement[key] = copies[id(child)] + else: + if replacement[key] is node[key]: + replacement[key] = copy(node[key]) + replacement[key][location] = copies[id(child)] + return copies + + +def _assertion(node: dict[str, Any]) -> dict[str, Any]: + if node.get("x-artifact-ref", True) is not True: + raise SchemaParseError("The x-artifact-ref declaration must be true") + media_type: dict[str, Any] = { + "type": "string", + "pattern": _MEDIA_PATTERN, + # ECMAScript's `$` can also match before a trailing line terminator. + "not": {"pattern": r"[^a-z0-9!#$&^_.+/-]"}, + } + if "x-media-types" in node: + types = node["x-media-types"] + if ( + not isinstance(types, list) + or not types + or not all(_is_canonical_media_type(item) for item in types) + or len(types) != len(set(types)) + ): + raise SchemaParseError("The x-media-types declaration requires unique canonical media types") + media_type["enum"] = list(types) + limit = _json_integer(node.get("x-max-bytes", _MAX_SIZE)) + if type(limit) is not int or not 0 <= limit <= _MAX_SIZE: + raise SchemaParseError("The x-max-bytes declaration requires a nonnegative safe integer") + return { + "type": "object", + "required": ["id", "media_type", "size_bytes"], + "additionalProperties": False, + "properties": { + "id": {"type": "string", "pattern": _ID_PATTERN, "not": {"pattern": r"[^A-Za-z0-9_-]"}}, + "media_type": media_type, + "size_bytes": {"type": "integer", "minimum": 0, "maximum": limit}, + }, + } + + +def lower_artifact_assertions(schema: dict[str, Any]) -> dict[str, Any] | None: + """Return a validation-only copy for an opted-in schema, or no replacement.""" + if not isinstance(schema, dict): + return None + tagged = [] + nodes = [] + for node, current in _schema_nodes(schema): + nodes.append(node) + if not _KEYWORDS.isdisjoint(node): + if not current: + raise SchemaParseError("Artifact assertions require JSON Schema Draft 2020-12") + tagged.append(node) + if not tagged: + return None + + copies = _copy_schema_nodes(nodes) + for node in tagged: + replacement = copies[id(node)] + conjuncts = replacement.get("allOf", []) + if not isinstance(conjuncts, list) or ("allOf" in replacement and not conjuncts): + raise SchemaParseError("Artifact assertions require allOf to contain schema objects") + replacement["allOf"] = [*conjuncts, _assertion(node)] + return copies[id(schema)] diff --git a/python/src/apcore/schema/hardening.py b/python/src/apcore/schema/hardening.py index bbae8e36..8ba4f562 100644 --- a/python/src/apcore/schema/hardening.py +++ b/python/src/apcore/schema/hardening.py @@ -33,6 +33,8 @@ from referencing.exceptions import Unresolvable from referencing.jsonschema import DRAFT202012 +from apcore.errors import SchemaParseError +from apcore.schema._artifact_assertions import lower_artifact_assertions from apcore.schema.types import SchemaValidationErrorDetail, SchemaValidationResult, _validation_failure_message __all__ = ["content_hash", "validate_schema_dict", "warn_format_violations"] @@ -185,16 +187,29 @@ def validate_schema_dict(data: Any, schema: dict[str, Any]) -> SchemaValidationR Format violations (date-time, email, uri, …) emit a logger.warning but do NOT fail validation (SHOULD-level enforcement per PROTOCOL_SPEC §4.15.4). """ + lowered = lower_artifact_assertions(schema) + return _validate_schema(data, schema if lowered is None else lowered, artifact=lowered is not None) + + +def _validate_schema( + data: Any, schema: dict[str, Any], *, artifact: bool = False, warn_formats: bool = True +) -> SchemaValidationResult: validation_schema = _inherit_decimal_dialect(schema) validator = _Draft202012DecimalValidator(validation_schema, registry=Registry()) - raw_errors = list(validator.iter_errors(data)) + try: + raw_errors = list(validator.iter_errors(data)) + except Unresolvable: + if not artifact: + raise + raise SchemaParseError("Unable to resolve a schema reference in the artifact declaration") from None if raw_errors: error_code = _map_error_code(raw_errors) - details = [_error_to_detail(e) for e in raw_errors] + details = [_error_to_detail(e, hide_instance=artifact) for e in raw_errors] return SchemaValidationResult(valid=False, errors=details, error_code=error_code) - _check_formats_and_warn(data, validation_schema) + if warn_formats: + _check_formats_and_warn(data, validation_schema) return SchemaValidationResult(valid=True, errors=[]) @@ -228,7 +243,9 @@ def warn_format_violations(data: Any, model: Any) -> None: if isinstance(data, BaseModel): data = data.model_dump(mode="json") - _check_formats_and_warn(data, _inherit_decimal_dialect(source_schema)) + lowered = getattr(model, "__apcore_artifact_validation_schema__", None) + validation_schema = lowered if isinstance(lowered, dict) else source_schema + _check_formats_and_warn(data, _inherit_decimal_dialect(validation_schema)) # Sub-schema keywords whose value is itself a schema (or a collection of them). @@ -272,7 +289,7 @@ def _map_error_code(errors: list[JsonschemaError]) -> str: return "SCHEMA_VALIDATION_ERROR" -def _error_to_detail(error: JsonschemaError) -> SchemaValidationErrorDetail: +def _error_to_detail(error: JsonschemaError, *, hide_instance: bool = False) -> SchemaValidationErrorDetail: path_parts = list(error.absolute_path) path = "".join("/" + str(part).replace("~", "~0").replace("/", "~1") for part in path_parts) raw_validator = error.validator @@ -282,7 +299,7 @@ def _error_to_detail(error: JsonschemaError) -> SchemaValidationErrorDetail: message=_validation_failure_message(constraint or "type"), constraint=constraint, expected=None, - actual=error.instance, + actual=None if hide_instance else error.instance, ) diff --git a/python/src/apcore/schema/loader.py b/python/src/apcore/schema/loader.py index e7d1aa7b..49fd3fdf 100644 --- a/python/src/apcore/schema/loader.py +++ b/python/src/apcore/schema/loader.py @@ -17,13 +17,15 @@ from pydantic.functional_validators import AfterValidator, BeforeValidator from pydantic_core import PydanticCustomError, PydanticUndefined from referencing import Registry, Resource +from referencing.exceptions import Unresolvable from referencing.jsonschema import DRAFT202012 from apcore.config import Config from apcore.errors import SchemaNotFoundError, SchemaParseError +from apcore.schema._artifact_assertions import lower_artifact_assertions from apcore.schema.hardening import _Draft202012DecimalValidator, _inherit_decimal_dialect, content_hash from apcore.schema.ref_resolver import RefResolver -from apcore.schema.types import ResolvedSchema, SchemaDefinition, SchemaStrategy +from apcore.schema.types import ResolvedSchema, SchemaDefinition, SchemaStrategy, _validation_failure_message from apcore.version import _negotiate_document_version __all__ = ["SchemaLoader"] @@ -327,14 +329,14 @@ def _scalar_annotation(type_name: str) -> Any: return base -def _to_jsonable(value: Any) -> Any: +def _to_jsonable(value: Any, *, by_alias: bool = False) -> Any: """Convert a validated Pydantic value back to plain JSON data for a jsonschema check.""" if isinstance(value, BaseModel): - return value.model_dump(mode="json") + return value.model_dump(mode="json", by_alias=True) if by_alias else value.model_dump(mode="json") if isinstance(value, dict): - return {k: _to_jsonable(v) for k, v in value.items()} + return {k: _to_jsonable(v, by_alias=by_alias) for k, v in value.items()} if isinstance(value, (list, tuple)): - return [_to_jsonable(v) for v in value] + return [_to_jsonable(v, by_alias=by_alias) for v in value] return value @@ -343,6 +345,7 @@ def _make_schema_assertion( *, plain_data: bool = False, registry: Registry | None = None, + artifact: bool = False, ) -> Callable[[Any], Any]: """Build an AfterValidator asserting *sub_schema* on an already-typed value. @@ -370,14 +373,21 @@ def _make_schema_assertion( def assert_sub_schema(value: Any) -> Any: data = value if plain_data else _to_jsonable(value) - for error in validator.iter_errors(data): + try: + error = next(validator.iter_errors(data), None) + except Unresolvable: + if not artifact: + raise + raise SchemaParseError("Unable to resolve a schema reference in the artifact declaration") from None + if error is not None: # `validator` is the failing keyword name (`enum`, `const`, `not`, …). # Passing it through as the error type keeps the reported `constraint` # specific instead of collapsing every combinator to "value". + keyword = str(error.validator or "value") raise PydanticCustomError( - cast(Any, str(error.validator or "value")), - error.message, - {"expected": error.validator_value}, + cast(Any, keyword), + _validation_failure_message(keyword) if artifact else error.message, + None if artifact else {"expected": error.validator_value}, ) return value @@ -395,11 +405,22 @@ def model_json_schema(cls, *args: Any, **kwargs: Any) -> dict[str, Any]: return deepcopy(cls.__apcore_source_schema__) -def _generate_source_model(schema: dict[str, Any], model_name: str) -> type[BaseModel]: +class _ArtifactSourceSchemaModel(_SourceSchemaModel): + model_config = ConfigDict(hide_input_in_errors=True) + + +def _generate_source_model( + schema: dict[str, Any], model_name: str, *, lowered_artifacts: dict[str, Any] | None = None +) -> type[BaseModel]: # Binding payloads already use JSON values. The original contract can # validate directly, without narrowing a type or transforming values in # a generated annotation. Expose declared fields for native introspection. - validate = _as_model_before_validator(_make_schema_assertion(schema, plain_data=True)) + artifact = lowered_artifacts is not None + validate = _as_model_before_validator( + _make_schema_assertion( + schema if lowered_artifacts is None else lowered_artifacts, plain_data=True, artifact=artifact + ) + ) required = set(schema.get("required", ())) fields: dict[str, Any] = { name: (Any, ... if name in required else None) @@ -408,12 +429,14 @@ def _generate_source_model(schema: dict[str, Any], model_name: str) -> type[Base } model = create_model( # type: ignore[call-overload] model_name, - __base__=_SourceSchemaModel, + __base__=_ArtifactSourceSchemaModel if artifact else _SourceSchemaModel, __validators__={"_apcore_source_contract": validate}, **fields, ) model.__apcore_source_schema__ = schema # type: ignore[attr-defined] model.__apcore_has_assertions__ = True # type: ignore[attr-defined] + if artifact: + model.__apcore_artifact_validation_schema__ = lowered_artifacts # type: ignore[attr-defined] return model @@ -656,8 +679,9 @@ def generate_model( down unchanged through every nested model, so a ``$ref`` buried in ``properties`` still finds ``$defs`` at the top of the document. """ - if validate_source: - return _generate_source_model(json_schema, model_name) + lowered = lower_artifact_assertions(json_schema) if root is None or validate_source else None + if validate_source or lowered is not None: + return _generate_source_model(json_schema, model_name, lowered_artifacts=lowered) if root is None: root = json_schema properties = json_schema.get("properties", {}) diff --git a/python/src/apcore/schema/validator.py b/python/src/apcore/schema/validator.py index 88823de4..cddb87b4 100644 --- a/python/src/apcore/schema/validator.py +++ b/python/src/apcore/schema/validator.py @@ -2,13 +2,15 @@ from __future__ import annotations +import json from functools import lru_cache from inspect import signature from typing import Any, NamedTuple, cast -from pydantic import BaseModel, ValidationError as PydanticValidationError +from pydantic import BaseModel, PydanticUserError, ValidationError as PydanticValidationError from pydantic_core import SchemaValidator as CoreSchemaValidator, core_schema +from apcore.schema._artifact_assertions import lower_artifact_assertions from apcore.schema.types import SchemaValidationErrorDetail, SchemaValidationResult, _validation_failure_message __all__ = ["SchemaValidator", "coerce_value"] @@ -167,12 +169,41 @@ def adapt(node: Any) -> Any: return _NativeIntegerValidator(CoreSchemaValidator(adapted, **options), has_union) +@lru_cache(maxsize=128) +def _native_artifact_schema(model: type[BaseModel], _revision: object) -> dict[str, Any] | None: + if isinstance(getattr(model, "__apcore_source_schema__", None), dict): + return None # Generated models already compile their artifact assertions. + try: + schema = model.model_json_schema() + except PydanticUserError: + # Native-only models can support calls without having a JSON contract. + return None + return lower_artifact_assertions(schema) + + +def _check_native_artifacts( + model: type[BaseModel], data: Any, *, json_mode: bool = False +) -> SchemaValidationResult | None: + lowered = _native_artifact_schema(model, model.__pydantic_validator__) + if lowered is None: + return None + from apcore.schema.hardening import _validate_schema + from apcore.schema.loader import _to_jsonable + + payload = json.loads(data) if json_mode else _to_jsonable(data, by_alias=True) + return _validate_schema(payload, lowered, artifact=True, warn_formats=False) + + def _validate_strict_model(model: type[BaseModel], data: Any, *, json_mode: bool) -> Any: """Validate in the caller's mode without general type coercion.""" original = model.model_validate_json if json_mode else model.model_validate if not isinstance(model, type) or not issubclass(model, BaseModel): return original(data, strict=True) + artifact_result = _check_native_artifacts(model, data, json_mode=json_mode) + if artifact_result is not None and not artifact_result.valid: + raise artifact_result.to_error() + default = BaseModel.model_validate_json if json_mode else BaseModel.model_validate revision = model.__pydantic_validator__ if getattr(original, "__func__", None) is not getattr(default, "__func__", None) or not isinstance( @@ -254,6 +285,15 @@ def validate(self, data: Any, model: type[BaseModel]) -> SchemaValidationResult: """ data = self._coerce(data, model) + lowered = getattr(model, "__apcore_artifact_validation_schema__", None) + if isinstance(lowered, dict): + from apcore.schema.hardening import _validate_schema + + return _validate_schema(data, lowered, artifact=True) + artifact_result = _check_native_artifacts(model, data) + if artifact_result is not None and not artifact_result.valid: + return artifact_result + union_result = self._validate_top_level_union(data, model) if union_result is not None: return union_result @@ -277,7 +317,7 @@ def validate(self, data: Any, model: type[BaseModel]) -> SchemaValidationResult: # SCHEMA_VALIDATION_ERROR (spec §8.2) rather than None. return SchemaValidationResult( valid=False, - errors=self._pydantic_error_to_details(e), + errors=self._pydantic_error_to_details(e, hide_instance=artifact_result is not None), error_code="SCHEMA_VALIDATION_ERROR", ) @@ -329,18 +369,24 @@ def validate_output(self, data: dict[str, Any], model: type[BaseModel]) -> dict[ def _validate_and_dump(self, data: dict[str, Any], model: type[BaseModel]) -> dict[str, Any]: """Validate data and return model_dump(). Raises SchemaValidationError on failure.""" + data = self._coerce(data, model) + artifact_result = _check_native_artifacts(model, data) + if artifact_result is not None and not artifact_result.valid: + raise artifact_result.to_error() try: - instance = model.model_validate(self._coerce(data, model), strict=not self._coerce_types) + instance = model.model_validate(data, strict=not self._coerce_types) generated = isinstance(getattr(model, "__apcore_source_schema__", None), dict) return instance.model_dump(exclude_unset=generated) except PydanticValidationError as e: result = SchemaValidationResult(valid=False, errors=self._pydantic_error_to_details(e)) raise result.to_error() - def _pydantic_error_to_details(self, error: PydanticValidationError) -> list[SchemaValidationErrorDetail]: + def _pydantic_error_to_details( + self, error: PydanticValidationError, *, hide_instance: bool = False + ) -> list[SchemaValidationErrorDetail]: """Convert Pydantic v2 ValidationError to apcore error details.""" details: list[SchemaValidationErrorDetail] = [] - for err in error.errors(): + for err in error.errors(include_input=not hide_instance, include_context=not hide_instance): loc = err.get("loc", ()) pydantic_type = err.get("type", "") if pydantic_type in {"missing", "extra_forbidden"}: diff --git a/python/tests/test_artifact_reference.py b/python/tests/test_artifact_reference.py new file mode 100644 index 00000000..13844384 --- /dev/null +++ b/python/tests/test_artifact_reference.py @@ -0,0 +1,178 @@ +"""Artifact reference validation and host reads.""" + +import json +from pathlib import Path +from typing import Annotated + +import pytest +from pydantic import BaseModel, Field, ValidationError + +from apcore import APCore, ArtifactContent, ArtifactRef, Identity, read_artifact +from apcore.config import Config +from apcore.errors import SchemaParseError, SchemaValidationError +from apcore.schema.hardening import validate_schema_dict +from apcore.schema.loader import SchemaLoader +from apcore.schema.validator import SchemaValidator + +_FIXTURE = Path(__file__).resolve().parents[2] / "conformance" / "fixtures" / "artifact_reference.json" +_CASES = json.loads(_FIXTURE.read_text())["test_cases"] +_GOOD = {"id": "preview_1", "media_type": "text/plain", "size_bytes": 3} +_BAD = {**_GOOD, "id": "private://payload-value", "media_type": "secret/invalid", "size_bytes": 42} +_NATIVE_FIELD = Annotated[ + dict[str, object], Field(json_schema_extra={"x-media-types": ["text/plain"], "x-max-bytes": 3}) +] + + +@pytest.mark.parametrize("case", _CASES, ids=[case["id"] for case in _CASES]) +def test_shared_raw_schemas(case: dict) -> None: + schema, data, expected = case["schema"], case["data"], case["expected"] + original = json.dumps(schema) + if expected == "invalid_schema": + with pytest.raises(SchemaParseError): + validate_schema_dict(data, schema) + else: + assert validate_schema_dict(data, schema).valid is (expected == "valid") + assert json.dumps(schema) == original + + +def test_public_validator_checks_generated_models_and_preserves_declaration() -> None: + source = {"type": "object", "properties": {"ref": {"x-artifact-ref": True}}, "required": ["ref"]} + model = SchemaLoader(Config()).generate_model(source, "ArtifactInput") + validator = SchemaValidator() + assert model.model_json_schema() == source + assert validator.validate_input({"ref": _GOOD}, model) == {"ref": _GOOD} + result = validator.validate({"ref": _BAD}, model) + assert not result.valid + assert "payload-value" not in repr(result) and "secret/invalid" not in repr(result) + with pytest.raises(SchemaValidationError): + validator.validate_output({"ref": _BAD}, model) + + +def test_schema_assertions_ignore_aliased_data_and_hide_wire_values(caplog: pytest.LogCaptureFixture) -> None: + constraint = {"x-artifact-ref": True, "properties": {"id": {"format": "email"}}} + schema = { + "type": "object", + "properties": {"ref": constraint, "literal": {"const": constraint}}, + } + assert validate_schema_dict({"ref": _GOOD, "literal": constraint}, schema).valid + assert _GOOD["id"] not in caplog.text + bad = validate_schema_dict({"ref": _BAD, "literal": constraint}, schema) + assert not bad.valid and _BAD["id"] not in repr(bad) + assert "allOf" not in constraint + + +def test_artifact_schema_cannot_retrieve_external_references() -> None: + schema = {"x-artifact-ref": True, "$ref": "https://schema.invalid/artifact.json"} + with pytest.raises(SchemaParseError, match="Unable to resolve"): + validate_schema_dict(_GOOD, schema) + + +def test_untagged_legacy_resource_remains_valid_next_to_an_artifact_declaration() -> None: + schema = { + "type": "object", + "properties": { + "ref": {"x-artifact-ref": True}, + "legacy": {"$schema": "http://json-schema.org/draft-07/schema#", "type": "string"}, + }, + } + assert validate_schema_dict({"ref": _GOOD, "legacy": "old"}, schema).valid + assert not validate_schema_dict({"ref": _GOOD, "legacy": 99}, schema).valid + + +class _NativeInput(BaseModel): + ref: _NATIVE_FIELD + + +def test_public_validator_checks_native_annotations() -> None: + validator = SchemaValidator() + assert validator.validate({"ref": _GOOD}, _NativeInput).valid + assert not validator.validate({"ref": _BAD}, _NativeInput).valid + with pytest.raises(SchemaValidationError): + validator.validate_input({"ref": _BAD}, _NativeInput) + + +async def test_pipeline_checks_annotated_inputs_and_outputs() -> None: + core = APCore() + calls = [] + + @core.module("artifact.checked") + def checked(ref: _NATIVE_FIELD, break_output: bool = False) -> _NativeInput: + calls.append(ref) + return _NativeInput(ref=_BAD if break_output else ref) + + try: + with pytest.raises(SchemaValidationError, match="Input validation failed") as invalid_input: + await core.call_async("artifact.checked", {"ref": _BAD}) + assert "payload-value" not in repr(invalid_input.value.details) + assert not calls + assert await core.call_async("artifact.checked", {"ref": _GOOD}) == {"ref": _GOOD} + with pytest.raises(SchemaValidationError, match="Output validation failed"): + await core.call_async("artifact.checked", {"ref": _GOOD, "break_output": True}) + assert len(calls) == 2 + finally: + await core.shutdown() + + +async def test_native_artifact_values_remain_typed_at_module_entry() -> None: + core = APCore() + + @core.module("artifact.typed") + def accept(reference: ArtifactRef) -> ArtifactRef: + assert isinstance(reference, ArtifactRef) + return reference + + reference = ArtifactRef.model_validate(_GOOD) + try: + assert await accept.invoke_async(reference) == reference + assert await core.call_async("artifact.typed", {"reference": _GOOD}) == _GOOD + finally: + await core.shutdown() + + +async def test_artifact_model_and_host_reads() -> None: + reference = ArtifactRef.model_validate(_GOOD) + assert reference.model_dump() == _GOOD + for invalid in (_BAD, {**_GOOD, "id": "id\n"}, {**_GOOD, "size_bytes": True}, {**_GOOD, "extra": 0}): + with pytest.raises(ValidationError): + ArtifactRef.model_validate(invalid) + + owner = Identity(id="owner", issuer="test") + visitor = Identity(id="owner", issuer="foreign") + + class Store: + response: ArtifactContent | None = ArtifactContent(ref=reference, content=b"xyz") + requests: list[tuple[str, Identity, int]] = [] + + async def read(self, artifact_id: str, identity: Identity, max_bytes: int) -> ArtifactContent | None: + self.requests.append((artifact_id, identity, max_bytes)) + return self.response if identity == owner else None + + store = Store() + assert await read_artifact(reference, owner, store, max_bytes=2) is None + assert not store.requests + with pytest.raises(ValueError): + await read_artifact(reference, owner, store, max_bytes=True) + with pytest.raises(ValueError): + await read_artifact(ArtifactRef.model_construct(**_BAD), owner, store) + assert not store.requests + assert await read_artifact(reference, owner, store, max_bytes=8) == store.response + assert store.requests[-1] == (reference.id, owner, reference.size_bytes) + assert await read_artifact(reference, visitor, store) is None + store.response = ArtifactContent(ref=reference, content=b"wrong length") + assert await read_artifact(reference, owner, store) is None + wrong = ArtifactRef.model_validate({**_GOOD, "id": "different"}) + store.response = ArtifactContent(ref=wrong, content=b"xyz") + assert await read_artifact(reference, owner, store) is None + store.response = None + assert await read_artifact(reference, owner, store) is None + empty = ArtifactRef.model_validate({**_GOOD, "size_bytes": 0}) + store.response = ArtifactContent(ref=empty, content=b"") + assert await read_artifact(empty, owner, store, max_bytes=0) == store.response + assert store.requests[-1] == (empty.id, owner, 0) + + class Unavailable: + async def read(self, artifact_id: str, identity: Identity, max_bytes: int) -> ArtifactContent | None: + raise OSError("backend failure") + + with pytest.raises(OSError, match="backend failure"): + await read_artifact(reference, owner, Unavailable()) diff --git a/python/tests/test_public_api.py b/python/tests/test_public_api.py index c478d742..a3e6a277 100644 --- a/python/tests/test_public_api.py +++ b/python/tests/test_public_api.py @@ -454,6 +454,9 @@ class TestPublicAPIAll: "ApprovalPendingError", "ApprovalRequest", "ApprovalResult", + "ArtifactContent", + "ArtifactRef", + "ArtifactStore", "AutoApproveHandler", "BoundModule", "CallBudget", @@ -502,6 +505,7 @@ class TestPublicAPIAll: "call_async", "close", "module", + "read_artifact", "redact_sensitive", "register", "stream", diff --git a/rust/src/artifacts.rs b/rust/src/artifacts.rs new file mode 100644 index 00000000..63a54c4c --- /dev/null +++ b/rust/src/artifacts.rs @@ -0,0 +1,164 @@ +//! Opt-in artifact reference metadata and authorized host storage reads. + +use async_trait::async_trait; +use serde::{Deserialize, Deserializer, Serialize}; +use serde_json::Value; + +use crate::{Identity, ModuleError}; + +/// Largest artifact size that round-trips in all SDKs' JSON number APIs. +pub const MAX_ARTIFACT_BYTES: u64 = 9_007_199_254_740_991; +/// Default per-read budget in bytes. +pub const DEFAULT_ARTIFACT_READ_LIMIT: u64 = 8 * 1024 * 1024; + +/// Wire-safe metadata for an immutable object in a host-selected store. +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] +pub struct ArtifactRef { + /// Opaque identifier scoped to the store. It carries no authority. + pub id: String, + /// Canonical lowercase media type without parameters. + pub media_type: String, + /// Exact byte count of the artifact content. + pub size_bytes: u64, +} + +impl ArtifactRef { + /// Construct and validate an artifact reference. + pub fn new( + id: impl Into, + media_type: impl Into, + size_bytes: u64, + ) -> Result { + let reference = Self { + id: id.into(), + media_type: media_type.into(), + size_bytes, + }; + reference.validate()?; + Ok(reference) + } + + /// Validate the metadata without consulting a store. + pub fn validate(&self) -> Result<(), ModuleError> { + if (1..=128).contains(&self.id.len()) + && self + .id + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-')) + && is_media_type(&self.media_type) + && self.size_bytes <= MAX_ARTIFACT_BYTES + { + Ok(()) + } else { + Err(ModuleError::invalid_input("Invalid artifact reference")) + } + } +} + +impl<'de> Deserialize<'de> for ArtifactRef { + fn deserialize>(deserializer: D) -> Result { + let raw = Value::deserialize(deserializer)?; + let Some(fields) = raw.as_object().filter(|fields| fields.len() == 3) else { + return Err(serde::de::Error::custom("Invalid artifact reference")); + }; + let parts = || { + Some(( + fields.get("id")?.as_str()?, + fields.get("media_type")?.as_str()?, + safe_byte_count(fields.get("size_bytes")?)?, + )) + }; + let (id, media_type, size_bytes) = + parts().ok_or_else(|| serde::de::Error::custom("Invalid artifact reference"))?; + Self::new(id, media_type, size_bytes) + .map_err(|_| serde::de::Error::custom("Invalid artifact reference")) + } +} + +pub(crate) fn safe_byte_count(value: &Value) -> Option { + if let Some(bytes) = value.as_u64() { + return (bytes <= MAX_ARTIFACT_BYTES).then_some(bytes); + } + let bytes = value.as_f64()?; + // JSON Schema treats integral JSON numbers as integers even with a decimal + // point. Within the safe-number range the conversion is exact. + if (0.0..=9_007_199_254_740_991.0).contains(&bytes) && bytes.fract() == 0.0 { + #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] + Some(bytes as u64) + } else { + None + } +} + +pub(crate) fn is_media_type(media_type: &str) -> bool { + fn component(value: &str) -> bool { + fn alphanumeric(byte: u8) -> bool { + byte.is_ascii_lowercase() || byte.is_ascii_digit() + } + let mut bytes = value.bytes(); + value.len() <= 127 + && bytes.next().is_some_and(alphanumeric) + && bytes.all(|byte| alphanumeric(byte) || b"!#$&^_.+-".contains(&byte)) + } + + media_type + .split_once('/') + .is_some_and(|(kind, subtype)| component(kind) && component(subtype)) +} + +/// Authorized bytes and the authoritative metadata returned by a host store. +#[derive(Clone, Eq, PartialEq)] +pub struct ArtifactContent { + /// The metadata actually associated with the stored bytes. + pub r#ref: ArtifactRef, + /// A copy of the immutable content held by the store. + pub content: Vec, +} + +/// A trusted host's artifact read boundary. +#[async_trait] +pub trait ArtifactStore: Send + Sync { + /// Read the current artifact under the caller's authority and byte budget. + /// + /// Implementations check authorization and expiry on each call and bound + /// reads before materializing content. Missing, expired, unauthorized, and + /// over-budget objects return `None`. + async fn read( + &self, + id: &str, + identity: &Identity, + max_bytes: u64, + ) -> Result, ModuleError>; +} + +/// Check a reference, fetch bounded bytes, and verify the returned metadata. +/// +/// The identity must come from trusted authentication. `None` uses the +/// default limit. A budget outside the safe-integer range is invalid. +pub async fn read_artifact( + store: &dyn ArtifactStore, + reference: &ArtifactRef, + identity: &Identity, + limit: Option, +) -> Result, ModuleError> { + reference.validate()?; + if identity.id().is_empty() { + return Err(ModuleError::invalid_input( + "Artifact reads require an authenticated identity", + )); + } + let limit = limit.unwrap_or(DEFAULT_ARTIFACT_READ_LIMIT); + if limit > MAX_ARTIFACT_BYTES { + return Err(ModuleError::invalid_input("Invalid artifact read limit")); + } + if reference.size_bytes > limit { + return Ok(None); + } + let content = store + .read(&reference.id, identity, reference.size_bytes) + .await?; + Ok(content.filter(|stored| { + &stored.r#ref == reference + && u64::try_from(stored.content.len()) == Ok(reference.size_bytes) + })) +} diff --git a/rust/src/lib.rs b/rust/src/lib.rs index 4998596a..34fba3a3 100644 --- a/rust/src/lib.rs +++ b/rust/src/lib.rs @@ -14,6 +14,7 @@ pub const VERSION: &str = env!("CARGO_PKG_VERSION"); pub mod acl; pub mod acl_handlers; pub mod approval; +pub mod artifacts; pub mod async_task; pub mod bindings; pub mod builtin_steps; @@ -62,6 +63,10 @@ pub use approval::{ AlwaysDenyHandler, ApprovalHandler, ApprovalRequest, ApprovalResult, AutoApproveHandler, CallbackApprovalHandler, }; +pub use artifacts::{ + read_artifact, ArtifactContent, ArtifactRef, ArtifactStore, DEFAULT_ARTIFACT_READ_LIMIT, + MAX_ARTIFACT_BYTES, +}; pub use capability::{ AccessHint, CallableDefinition, CapabilityPage, CapabilityQuery, CapabilitySearchProvider, ModuleSummary, diff --git a/rust/src/schema/artifact_reference.rs b/rust/src/schema/artifact_reference.rs new file mode 100644 index 00000000..d2c40971 --- /dev/null +++ b/rust/src/schema/artifact_reference.rs @@ -0,0 +1,185 @@ +//! Validation-only lowering of the Draft 2020-12 artifact profile. + +use serde_json::{json, Map, Value}; +use std::collections::HashSet; + +use crate::artifacts::{is_media_type, safe_byte_count, MAX_ARTIFACT_BYTES}; + +const MEDIA_PATTERN: &str = + r"^[a-z0-9][a-z0-9!#$&^_.+-]{0,126}/[a-z0-9][a-z0-9!#$&^_.+-]{0,126}(?![\s\S])"; +const TAG: &str = "x-artifact-ref"; +const MEDIA: &str = "x-media-types"; +const MAX_BYTES: &str = "x-max-bytes"; + +enum SchemaChildren { + Map, + Array, + TupleOrSchema, + Single, +} + +fn child_kind(keyword: &str) -> Option { + match keyword { + "properties" | "patternProperties" | "definitions" | "$defs" | "dependentSchemas" + | "dependencies" => Some(SchemaChildren::Map), + "allOf" | "anyOf" | "oneOf" | "prefixItems" => Some(SchemaChildren::Array), + "items" => Some(SchemaChildren::TupleOrSchema), + "additionalProperties" + | "propertyNames" + | "additionalItems" + | "contains" + | "not" + | "if" + | "then" + | "else" + | "unevaluatedItems" + | "unevaluatedProperties" + | "contentSchema" => Some(SchemaChildren::Single), + // Data and annotation keywords such as examples, enum and default + // are not schema positions. + _ => None, + } +} + +fn has_local_declaration(fields: &Map) -> bool { + [TAG, MEDIA, MAX_BYTES] + .iter() + .any(|keyword| fields.contains_key(*keyword)) +} + +pub(super) fn has_artifact_declaration(schema: &Value) -> bool { + schema.as_object().is_some_and(|fields| { + has_local_declaration(fields) + || fields + .iter() + .any(|(keyword, child)| match child_kind(keyword) { + Some(SchemaChildren::Map) => child + .as_object() + .is_some_and(|entries| entries.values().any(has_artifact_declaration)), + Some(SchemaChildren::Array) => child + .as_array() + .is_some_and(|entries| entries.iter().any(has_artifact_declaration)), + Some(SchemaChildren::TupleOrSchema) => child.as_array().map_or_else( + || has_artifact_declaration(child), + |entries| entries.iter().any(has_artifact_declaration), + ), + Some(SchemaChildren::Single) => has_artifact_declaration(child), + None => false, + }) + }) +} + +/// Add standard assertions only to actual schema positions. The supplied tree +/// is for validation, while descriptors and schema exports keep the original. +pub(super) fn lower_artifact_references(schema: &mut Value) -> Result { + lower_node(schema, true) +} + +fn lower_node(schema: &mut Value, inherited_2020: bool) -> Result { + let Some(fields) = schema.as_object_mut() else { + return Ok(false); + }; + // A tagged declaration belongs to its resource's dialect. Inspect the + // original dialect scopes before Core removes nested declarations from + // the validation-only tree. + let supported = inherited_2020 + && fields.get("$schema").is_none_or(|uri| { + matches!( + uri.as_str(), + Some( + "https://json-schema.org/draft/2020-12/schema" + | "https://json-schema.org/draft/2020-12/schema#" + ) + ) + }); + let mut tagged = false; + for (keyword, child) in &mut *fields { + match child_kind(keyword) { + Some(SchemaChildren::Map) => { + if let Some(entries) = child.as_object_mut() { + for node in entries.values_mut() { + tagged |= lower_node(node, supported)?; + } + } + } + Some(SchemaChildren::Array) => { + if let Some(entries) = child.as_array_mut() { + for node in entries { + tagged |= lower_node(node, supported)?; + } + } + } + Some(SchemaChildren::TupleOrSchema) => { + if let Some(entries) = child.as_array_mut() { + for node in entries { + tagged |= lower_node(node, supported)?; + } + } else { + tagged |= lower_node(child, supported)?; + } + } + Some(SchemaChildren::Single) => tagged |= lower_node(child, supported)?, + None => {} + } + } + if !has_local_declaration(fields) { + return Ok(tagged); + } + if !supported { + return Err("Artifact reference assertions require Draft 2020-12".to_owned()); + } + let assertion = artifact_assertion(fields)?; + match fields.get_mut("allOf") { + None => { + fields.insert("allOf".to_owned(), Value::Array(vec![assertion])); + } + // Preserve the original schema's draft validity. The meta-schema + // rejects allOf arrays that are empty or malformed. + Some(Value::Array(clauses)) if !clauses.is_empty() => clauses.push(assertion), + Some(_) => return Err("Artifact reference schema has an invalid allOf".to_owned()), + } + Ok(true) +} + +fn artifact_assertion(fields: &Map) -> Result { + if fields + .get(TAG) + .is_some_and(|value| value != &Value::Bool(true)) + { + return Err("x-artifact-ref must be true".to_owned()); + } + let max_bytes = fields + .get(MAX_BYTES) + .map_or(Ok(MAX_ARTIFACT_BYTES), |value| { + safe_byte_count(value) + .ok_or_else(|| "x-max-bytes must be a nonnegative safe integer".to_owned()) + })?; + let mut media = json!({"type": "string", "pattern": MEDIA_PATTERN}); + if let Some(value) = fields.get(MEDIA) { + let mut distinct = HashSet::new(); + if !value.as_array().is_some_and(|items| { + !items.is_empty() + && items.iter().all(|item| { + item.as_str() + .is_some_and(|name| is_media_type(name) && distinct.insert(name)) + }) + }) { + return Err( + "x-media-types must be a nonempty array of unique canonical media types".to_owned(), + ); + } + media["enum"] = value.clone(); + } + Ok(json!({ + "type": "object", + "required": ["id", "media_type", "size_bytes"], + // The three required names and size cap close the object without + // echoing unknown names in additionalProperties errors. + "maxProperties": 3, + "properties": { + "id": {"type": "string", "minLength": 1, "maxLength": 128, "not": {"pattern": "[^A-Za-z0-9_-]"}}, + "media_type": media, + "size_bytes": {"type": "integer", "minimum": 0, "maximum": max_bytes}, + } + })) +} diff --git a/rust/src/schema/hardening.rs b/rust/src/schema/hardening.rs index 4c872dc8..a308a16e 100644 --- a/rust/src/schema/hardening.rs +++ b/rust/src/schema/hardening.rs @@ -86,7 +86,7 @@ pub struct FormatWarning { pub path: String, /// The declared format, e.g. `date-time`. pub format: String, - /// The string value that did not parse as the declared format. + /// The string that did not parse, redacted for artifact-reference schemas. pub value: String, } @@ -105,6 +105,14 @@ pub fn format_warnings(data: &Value, schema: &Value) -> Vec { let mut warnings = Vec::new(); let mut cache = WalkCache::default(); walk_format(data, schema, "", &mut warnings, &mut cache); + // An opted-in document can apply the shape through a local reference or + // combinator. Preserve the warning locations and formats without carrying + // any artifact instance values in diagnostics. + if !warnings.is_empty() && super::artifact_reference::has_artifact_declaration(schema) { + for warning in &mut warnings { + "[REDACTED]".clone_into(&mut warning.value); + } + } // Order-preserving de-duplication. An array of N offending elements yields // N warnings, so the membership test has to be O(1), not a linear rescan. let mut seen: HashSet = HashSet::with_capacity(warnings.len()); diff --git a/rust/src/schema/mod.rs b/rust/src/schema/mod.rs index 1513ab37..4beb4df5 100644 --- a/rust/src/schema/mod.rs +++ b/rust/src/schema/mod.rs @@ -1,6 +1,7 @@ // APCore Protocol — Schema module // Spec reference: Schema loading, validation, export, and reference resolution +mod artifact_reference; pub mod exporter; pub mod hardening; #[cfg(feature = "config")] diff --git a/rust/src/schema/validator.rs b/rust/src/schema/validator.rs index a40b9df6..9ab09f77 100644 --- a/rust/src/schema/validator.rs +++ b/rust/src/schema/validator.rs @@ -300,7 +300,9 @@ impl SchemaValidator { /// meaningful while normalisation 2 removes the only cross-draft divergence /// apcore cares about. pub(crate) fn build_validator(schema: &Value) -> Result { - let normalised = strip_nested_schema(schema, true); + let mut normalised = schema.clone(); + let artifact_profile = super::artifact_reference::lower_artifact_references(&mut normalised)?; + strip_nested_schema(&mut normalised, true); jsonschema::options() // SchemaLoader owns the only filesystem-reference boundary. A host // enabling jsonschema's default Cargo features cannot add I/O here. @@ -308,7 +310,13 @@ pub(crate) fn build_validator(schema: &Value) -> Result { .with_keyword("multipleOf", DecimalMultipleOf::compile) .should_validate_formats(false) .build(&normalised) - .map_err(|e| e.to_string()) + .map_err(|e| { + if artifact_profile { + e.masked().to_string() + } else { + e.to_string() + } + }) } struct DecimalNumber { @@ -434,30 +442,27 @@ impl Retrieve for LocalSchemaOnly { } } -/// Deep-copy `value`, removing every nested `"$schema": ""` entry. +/// Remove nested `"$schema": ""` entries from the validation-only tree. /// /// `top` marks the root object, whose declaration is preserved so the document's /// own draft is still detected. Non-string `$schema` values are kept: they can /// only be a property *named* `$schema`, never a meta-schema declaration. -fn strip_nested_schema(value: &Value, top: bool) -> Value { +fn strip_nested_schema(value: &mut Value, top: bool) { match value { Value::Object(map) => { - let mut out = serde_json::Map::with_capacity(map.len()); - for (key, child) in map { - if key == "$schema" && !top && child.is_string() { - continue; - } - out.insert(key.clone(), strip_nested_schema(child, false)); + if !top && map.get("$schema").is_some_and(Value::is_string) { + map.remove("$schema"); + } + for child in map.values_mut() { + strip_nested_schema(child, false); } - Value::Object(out) } - Value::Array(items) => Value::Array( - items - .iter() - .map(|item| strip_nested_schema(item, false)) - .collect(), - ), - other => other.clone(), + Value::Array(items) => { + for item in items { + strip_nested_schema(item, false); + } + } + _ => {} } } diff --git a/rust/tests/artifact_reference_spec.rs b/rust/tests/artifact_reference_spec.rs new file mode 100644 index 00000000..bcb97b4c --- /dev/null +++ b/rust/tests/artifact_reference_spec.rs @@ -0,0 +1,346 @@ +//! Core ArtifactRef conformance, invocation and trusted store reads. + +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex}; + +use apcore::executor::validate_against_schema; +use apcore::{ + read_artifact, ArtifactContent, ArtifactRef, ArtifactStore, Config, Context, ErrorCode, + Executor, Identity, Module, ModuleError, Registry, SchemaValidator, + DEFAULT_ARTIFACT_READ_LIMIT, MAX_ARTIFACT_BYTES, +}; +use async_trait::async_trait; +use serde_json::{json, Value}; + +#[test] +fn shared_wire_cases_validate_through_both_entry_points() { + let path = crate::conformance_env::find_fixtures_root().join("artifact_reference.json"); + let fixture: Value = serde_json::from_reader(std::fs::File::open(path).unwrap()).unwrap(); + let validator = SchemaValidator::new(); + for test in fixture["test_cases"].as_array().unwrap() { + let name = test["id"].as_str().unwrap(); + let schema = &test["schema"]; + let output = &test["data"]; + let direct = validator.validate_detailed(output, schema); + let invocation = validate_against_schema(output, schema, "Input"); + match test["expected"].as_str().unwrap() { + "valid" => { + assert!(direct.valid, "{name}: {:?}", direct.errors); + assert!(invocation.is_ok(), "{name}: {invocation:?}"); + } + "invalid_instance" => { + assert!(!direct.valid, "{name}"); + assert_ne!( + direct.error_code, + Some(ErrorCode::SchemaParseError), + "{name}: {:?}", + direct.errors + ); + assert_eq!( + invocation.unwrap_err().code, + ErrorCode::SchemaValidationError, + "{name}" + ); + } + "invalid_schema" => { + assert!(!direct.valid, "{name}"); + assert_eq!( + direct.error_code, + Some(ErrorCode::SchemaParseError), + "{name}" + ); + assert_eq!( + invocation.unwrap_err().code, + ErrorCode::SchemaParseError, + "{name}" + ); + } + unexpected => panic!("unexpected case outcome: {unexpected}"), + } + } +} + +fn reference() -> ArtifactRef { + ArtifactRef::new("report_0", "text/plain", 4).unwrap() +} + +fn artifact_schema() -> Value { + json!({ + "type": "object", + "properties": {"payload": {"x-artifact-ref": true, "x-media-types": ["text/plain"], "x-max-bytes": 4}}, + "required": ["payload"] + }) +} + +struct ArtifactModule { + output: Value, + entered: Arc, +} + +#[async_trait] +impl Module for ArtifactModule { + fn input_schema(&self) -> Value { + artifact_schema() + } + + fn output_schema(&self) -> Value { + artifact_schema() + } + + fn description(&self) -> &'static str { + "Artifact reference fixture" + } + + async fn execute(&self, _inputs: Value, _ctx: &Context) -> Result { + self.entered.fetch_add(1, Ordering::Relaxed); + Ok(self.output.clone()) + } +} + +#[tokio::test] +async fn pipeline_validates_input_and_output_and_exports_original_declarations() { + let registry = Arc::new(Registry::new()); + let valid = json!({"payload": reference()}); + let entered = Arc::new(AtomicUsize::new(0)); + registry + .register_module( + "test.artifact", + Box::new(ArtifactModule { + output: valid.clone(), + entered: entered.clone(), + }), + ) + .unwrap(); + + let malformed_output = json!({"payload": {"id":"output-secret", "media_type": "application/json", "size_bytes":5}}); + registry + .register_module( + "test.invalid_artifact", + Box::new(ArtifactModule { + output: malformed_output, + entered: entered.clone(), + }), + ) + .unwrap(); + assert_eq!( + registry + .get_definition("test.artifact") + .unwrap() + .unwrap() + .output_schema, + artifact_schema() + ); + assert_eq!( + registry.export_schema("test.artifact", false).unwrap()["output_schema"], + artifact_schema() + ); + let executor = Executor::new(registry, Config::default()); + + let bad_input = + json!({"payload": {"id":"input-secret", "media_type":"text/plain", "size_bytes":5}}); + let denied = executor + .call("test.artifact", bad_input, None, None) + .await + .unwrap_err(); + assert_eq!(denied.code, ErrorCode::SchemaValidationError); + assert!(!serde_json::to_string(&denied.to_dict()) + .unwrap() + .contains("input-secret")); + assert_eq!(entered.load(Ordering::Relaxed), 0); + assert_eq!( + executor + .call("test.artifact", valid.clone(), None, None) + .await + .unwrap(), + valid + ); + + let invalid_output = executor + .call("test.invalid_artifact", valid, None, None) + .await + .unwrap_err(); + assert_eq!(invalid_output.code, ErrorCode::SchemaValidationError); + assert!(!serde_json::to_string(&invalid_output.to_dict()) + .unwrap() + .contains("output-secret")); + assert_eq!(entered.load(Ordering::Relaxed), 2); +} + +#[test] +fn reference_wire_decode_and_schema_errors_do_not_echo_artifact_values() { + let valid = json!({"id": "report_0", "media_type": "text/plain", "size_bytes": 4}); + assert_eq!( + serde_json::from_value::(valid.clone()).unwrap(), + reference() + ); + assert_eq!(serde_json::to_value(reference()).unwrap(), valid); + let invalid = json!({"id": "https://no-echo.test/private-data", "media_type": "text/plain", "size_bytes": 4, "credential-no-echo": "value-no-echo"}); + let schema = json!({"x-artifact-ref": true}); + let serde_error = serde_json::from_value::(invalid.clone()).unwrap_err(); + let direct = SchemaValidator::new().validate_detailed(&invalid, &schema); + let pipeline = validate_against_schema(&invalid, &schema, "Input").unwrap_err(); + assert!(!direct.valid); + assert!(!serde_error.to_string().contains("no-echo")); + assert!(!format!("{:?}", direct.errors).contains("no-echo")); + assert!(!serde_json::to_string(&pipeline.to_dict()) + .unwrap() + .contains("no-echo")); +} + +#[test] +fn opted_in_format_warnings_preserve_location_without_values() { + let schema = json!({ + "$defs": {"artifact": {"x-artifact-ref": true}}, + "$ref": "#/$defs/artifact", + "properties": {"id": {"format": "uuid"}} + }); + let input = serde_json::to_value(reference()).unwrap(); + let detailed = SchemaValidator::new().validate_detailed(&input, &schema); + assert!(detailed.valid); + assert_eq!( + detailed.warnings, + apcore::schema::format_warnings(&input, &schema) + ); + assert_eq!(detailed.warnings.len(), 1); + assert_eq!(detailed.warnings[0].path, "/id"); + assert_eq!(detailed.warnings[0].format, "uuid"); + assert_eq!(detailed.warnings[0].value, "[REDACTED]"); + + let untagged = json!({ + "properties": {"id": {"format": "uuid"}}, + "examples": [{"x-artifact-ref": true}] + }); + assert_eq!( + apcore::schema::format_warnings(&input, &untagged)[0].value, + "report_0" + ); +} + +struct ReadStore { + calls: Mutex>, + result: Result, ModuleError>, +} + +#[async_trait] +impl ArtifactStore for ReadStore { + async fn read( + &self, + id: &str, + identity: &Identity, + max_bytes: u64, + ) -> Result, ModuleError> { + self.calls + .lock() + .unwrap() + .push((id.to_owned(), identity.clone(), max_bytes)); + if identity.id() == "authorized" { + self.result.clone() + } else { + Ok(None) + } + } +} + +#[tokio::test] +async fn reads_verify_trusted_identity_limit_current_metadata_and_exact_byte_count() { + let reference = reference(); + let principal = Identity::new( + "authorized".to_owned(), + "user".to_owned(), + vec![], + Default::default(), + ); + let untrusted = Identity::new( + "stranger".to_owned(), + "user".to_owned(), + vec![], + Default::default(), + ); + let store = ReadStore { + calls: Mutex::default(), + result: Ok(Some(ArtifactContent { + r#ref: reference.clone(), + content: b"data".to_vec(), + })), + }; + + assert!(read_artifact(&store, &reference, &principal, Some(3)) + .await + .unwrap() + .is_none()); + let too_large = ArtifactRef { + size_bytes: DEFAULT_ARTIFACT_READ_LIMIT + 1, + ..reference.clone() + }; + assert!(read_artifact(&store, &too_large, &principal, None) + .await + .unwrap() + .is_none()); + let malformed = ArtifactRef { + id: "not/a/path".to_owned(), + ..reference.clone() + }; + assert!(read_artifact(&store, &malformed, &principal, None) + .await + .is_err()); + assert!( + read_artifact(&store, &reference, &principal, Some(MAX_ARTIFACT_BYTES + 1)) + .await + .is_err() + ); + let no_identity = Identity::new(String::new(), "user".to_owned(), vec![], Default::default()); + let Err(error) = read_artifact(&store, &reference, &no_identity, None).await else { + panic!("expected an invalid identity error") + }; + assert_eq!(error.code, ErrorCode::GeneralInvalidInput); + assert!(store.calls.lock().unwrap().is_empty()); + + assert!(read_artifact(&store, &reference, &untrusted, None) + .await + .unwrap() + .is_none()); + let content = read_artifact(&store, &reference, &principal, None) + .await + .unwrap() + .unwrap(); + assert_eq!(content.content, b"data"); + assert_eq!( + store.calls.lock().unwrap()[1], + (reference.id.clone(), principal.clone(), 4) + ); + + for result in [ + None, + Some(ArtifactContent { + r#ref: ArtifactRef { + media_type: "image/png".to_owned(), + ..reference.clone() + }, + content: b"data".to_vec(), + }), + Some(ArtifactContent { + r#ref: reference.clone(), + content: b"short".to_vec(), + }), + ] { + let store = ReadStore { + calls: Mutex::default(), + result: Ok(result), + }; + assert!(read_artifact(&store, &reference, &principal, Some(4)) + .await + .unwrap() + .is_none()); + } + let error_store = ReadStore { + calls: Mutex::default(), + result: Err(ModuleError::new( + ErrorCode::ModuleTimeout, + "store unavailable", + )), + }; + let Err(error) = read_artifact(&error_store, &reference, &principal, None).await else { + panic!("expected store error") + }; + assert_eq!(error.code, ErrorCode::ModuleTimeout); +} diff --git a/rust/tests/it.rs b/rust/tests/it.rs index 7e1dee91..7401ab86 100644 --- a/rust/tests/it.rs +++ b/rust/tests/it.rs @@ -26,6 +26,8 @@ mod acl_system_spec; mod apcore_client_spec; #[path = "approval_system_spec.rs"] mod approval_system_spec; +#[path = "artifact_reference_spec.rs"] +mod artifact_reference_spec; #[path = "async_tasks_spec.rs"] mod async_tasks_spec; #[path = "call_chain_guard_spec.rs"] diff --git a/schemas/artifact-ref.schema.json b/schemas/artifact-ref.schema.json new file mode 100644 index 00000000..c8ab9c0a --- /dev/null +++ b/schemas/artifact-ref.schema.json @@ -0,0 +1,29 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://apcore.dev/schemas/artifact-ref.schema.json", + "title": "APCore artifact reference", + "description": "Opaque metadata for an immutable artifact in a trusted host store.", + "type": "object", + "required": ["id", "media_type", "size_bytes"], + "additionalProperties": false, + "properties": { + "id": { + "description": "Opaque identifier scoped to the selected host store.", + "type": "string", + "minLength": 1, + "maxLength": 128, + "not": {"pattern": "[^A-Za-z0-9_-]"} + }, + "media_type": { + "description": "Canonical lowercase media type without parameters.", + "type": "string", + "pattern": "^[a-z0-9][a-z0-9!#$&^_.+-]{0,126}/[a-z0-9][a-z0-9!#$&^_.+-]{0,126}(?![\\s\\S])" + }, + "size_bytes": { + "description": "Exact byte count within the interoperable JSON safe-integer range.", + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + } + } +} diff --git a/typescript/src/artifact.ts b/typescript/src/artifact.ts new file mode 100644 index 00000000..35f165f7 --- /dev/null +++ b/typescript/src/artifact.ts @@ -0,0 +1,97 @@ +/** Host-owned artifact metadata and bounded reads. */ +import { InvalidInputError } from './errors.js'; +import { Identity } from './identity.js'; + +/** @internal The ASCII opaque identifier shared by the parser and schema profile. */ +export const ARTIFACT_ID_PATTERN = '^[A-Za-z0-9_-]{1,128}$(?![\\s\\S])'; +/** @internal RFC 6838 restricted-name alphabet in normalized lowercase. */ +export const ARTIFACT_MEDIA_TYPE_PATTERN = '^[a-z0-9][a-z0-9!#$&^_.+\\-]{0,126}/[a-z0-9][a-z0-9!#$&^_.+\\-]{0,126}$(?![\\s\\S])'; +const opaqueId = new RegExp(ARTIFACT_ID_PATTERN); +const mediaType = new RegExp(ARTIFACT_MEDIA_TYPE_PATTERN); +const DEFAULT_READ_LIMIT = 8_388_608; +const byteLength = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype), 'byteLength')!.get!; + +/** An opaque JSON reference scoped to the host's selected artifact store. */ +export interface ArtifactRef { + readonly id: string; + readonly media_type: string; + readonly size_bytes: number; +} + +export interface ArtifactContent { + readonly ref: ArtifactRef; + readonly content: Uint8Array; +} + +/** Authorize each read for the current identity and enforce the limit before allocating bytes. */ +export interface ArtifactStore { + read(id: string, identity: Identity, maxBytes: number): Promise; +} + +/** @internal */ +export function isCanonicalArtifactMediaType(value: unknown): value is string { + return typeof value === 'string' && mediaType.test(value); +} + +/** @internal */ +export function isArtifactByteCount(value: unknown): value is number { + return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0; +} + +/** Parse and detach a closed reference without revealing its contents in diagnostics. */ +export function parseArtifactRef(value: unknown): ArtifactRef { + try { + const parsed = artifactReference(value); + if (parsed !== null) return parsed; + } catch { + // Reflecting a hostile object must not disclose contents in the diagnostic. + } + throw new InvalidInputError('Invalid artifact reference'); +} + +function artifactReference(value: unknown): ArtifactRef | null { + if (value === null || typeof value !== 'object' || Array.isArray(value)) return null; + const prototype = Object.getPrototypeOf(value); + if (prototype !== Object.prototype && prototype !== null) return null; + const descriptors = Object.getOwnPropertyDescriptors(value); + if (Reflect.ownKeys(descriptors).length !== 3) return null; + const id = ownValue(descriptors['id']); + const media = ownValue(descriptors['media_type']); + const size = ownValue(descriptors['size_bytes']); + if (typeof id !== 'string' || !opaqueId.test(id) || !isCanonicalArtifactMediaType(media) || !isArtifactByteCount(size)) { + return null; + } + return Object.freeze({ id, media_type: media, size_bytes: size === 0 ? 0 : size }); +} + +function ownValue(descriptor: PropertyDescriptor | undefined): unknown { + return descriptor?.enumerable && Object.hasOwn(descriptor, 'value') ? descriptor.value : undefined; +} + +/** Read authorized bytes for a reference using an identity supplied by the trusted host. */ +export async function readArtifact( + store: ArtifactStore, + reference: ArtifactRef, + identity: Identity, + maxBytes = DEFAULT_READ_LIMIT, +): Promise { + const ref = parseArtifactRef(reference); + if (!isArtifactByteCount(maxBytes)) throw new InvalidInputError('Invalid artifact read limit'); + if (!(identity instanceof Identity) || typeof identity.id !== 'string' || identity.id.length === 0) { + throw new InvalidInputError('Artifact reads require a trusted identity'); + } + if (ref.size_bytes > maxBytes) return null; + const result = await store.read(ref.id, identity, Math.min(maxBytes, ref.size_bytes)); + if (result == null) return null; + try { + const stored = artifactReference(result.ref); + const content = result.content; + if (!stored || stored.id !== ref.id || stored.media_type !== ref.media_type || stored.size_bytes !== ref.size_bytes || + !(content instanceof Uint8Array) || byteLength.call(content) !== ref.size_bytes) return null; + const snapshot = new Uint8Array(ref.size_bytes); + snapshot.set(content); + return { ref: stored, content: snapshot }; + } catch { + return null; + } +} diff --git a/typescript/src/browser/index.ts b/typescript/src/browser/index.ts index 691ab2a3..c96289a6 100644 --- a/typescript/src/browser/index.ts +++ b/typescript/src/browser/index.ts @@ -170,6 +170,9 @@ export { jsonSchemaToTypeBox, contentHashAsync, } from '../schema/loader-pure.js'; +export { parseArtifactRef, readArtifact } from '../artifact.js'; +export type { ArtifactRef, ArtifactContent, ArtifactStore } from '../artifact.js'; + export { SchemaValidator } from '../schema/validator.js'; export { SchemaStrategy, ExportProfile } from '../schema/types.js'; export type { diff --git a/typescript/src/node-api.ts b/typescript/src/node-api.ts index b0925c8c..c5b33c43 100644 --- a/typescript/src/node-api.ts +++ b/typescript/src/node-api.ts @@ -290,6 +290,9 @@ export { // Version export { negotiateVersion, VersionIncompatibleError } from './version.js'; +export { parseArtifactRef, readArtifact } from './artifact.js'; +export type { ArtifactRef, ArtifactContent, ArtifactStore } from './artifact.js'; + // Schema export { SchemaLoader, diff --git a/typescript/src/schema/artifact-reference.ts b/typescript/src/schema/artifact-reference.ts new file mode 100644 index 00000000..36313ad9 --- /dev/null +++ b/typescript/src/schema/artifact-reference.ts @@ -0,0 +1,99 @@ +/** Lower the artifact profile to JSON Schema assertions for validation only. */ +import { + ARTIFACT_ID_PATTERN, ARTIFACT_MEDIA_TYPE_PATTERN, isArtifactByteCount, isCanonicalArtifactMediaType, +} from '../artifact.js'; +import { SchemaParseError } from '../errors.js'; + +type Schema = Record; +const schemaMaps = ['$defs', 'definitions', 'properties', 'patternProperties', 'dependentSchemas', 'dependencies']; +const schemaLists = ['allOf', 'anyOf', 'oneOf', 'prefixItems', 'items']; +const schemaValues = [ + 'additionalItems', 'additionalProperties', 'contains', 'contentSchema', 'else', 'if', 'items', 'not', + 'propertyNames', 'then', 'unevaluatedItems', 'unevaluatedProperties', +]; +const draft202012 = 'https://json-schema.org/draft/2020-12/schema'; +const keywords = ['x-artifact-ref', 'x-media-types', 'x-max-bytes']; + +function isSchema(value: unknown): value is Schema { + return value !== null && typeof value === 'object' && !Array.isArray(value); +} + +function referenceAssertion(node: Schema): Schema { + if (Object.hasOwn(node, 'x-artifact-ref') && node['x-artifact-ref'] !== true) { + throw new SchemaParseError('x-artifact-ref must be true'); + } + const type = { type: 'string', pattern: ARTIFACT_MEDIA_TYPE_PATTERN } as Schema; + if (Object.hasOwn(node, 'x-media-types')) { + const mediaTypes = node['x-media-types']; + if (!Array.isArray(mediaTypes) || mediaTypes.length === 0 || !Array.from(mediaTypes).every(isCanonicalArtifactMediaType) || + new Set(mediaTypes).size !== mediaTypes.length) { + throw new SchemaParseError('x-media-types must contain unique canonical media types'); + } + type['enum'] = mediaTypes; + } + const limit = Object.hasOwn(node, 'x-max-bytes') ? node['x-max-bytes'] : Number.MAX_SAFE_INTEGER; + if (!isArtifactByteCount(limit)) throw new SchemaParseError('x-max-bytes must be a nonnegative safe integer'); + return { + type: 'object', + properties: { + id: { type: 'string', pattern: ARTIFACT_ID_PATTERN }, + media_type: type, + size_bytes: { type: 'integer', minimum: 0, maximum: limit }, + }, + required: ['id', 'media_type', 'size_bytes'], + additionalProperties: false, + }; +} + +/** @internal A copy-on-write transform that visits schema positions and leaves data-valued keywords alone. */ +export function lowerArtifactReferences(schema: Schema, root = schema): { schema: Schema; root: Schema } { + const visited = new WeakMap(); + function walk(input: unknown): unknown { + if (!isSchema(input)) return input; + const value = input; + const known = visited.get(value); + if (known !== undefined) return known; + visited.set(value, value); + let result = value; + function assign(key: string, next: unknown): void { + if (next === value[key]) return; + if (result === value) result = { ...value }; + result[key] = next; + } + for (const key of schemaValues) assign(key, walk(value[key])); + for (const key of schemaLists) { + const list = value[key]; + if (!Array.isArray(list)) continue; + const next = list.map(walk); + if (next.some((child, index) => child !== list[index])) assign(key, next); + } + for (const key of schemaMaps) { + const map = value[key]; + if (!isSchema(map)) continue; + const entries = Object.entries(map); + const next = entries.map(([name, child]) => [name, walk(child)]); + if (next.some(([, child], index) => child !== entries[index][1])) assign(key, Object.fromEntries(next)); + } + if (keywords.some((keyword) => Object.hasOwn(value, keyword))) { + const assertion = referenceAssertion(value); + const allOf = result['allOf']; + if (allOf !== undefined && (!Array.isArray(allOf) || allOf.length === 0)) throw new SchemaParseError('allOf must contain schemas'); + assign('allOf', [...(allOf ?? []), assertion]); + for (const keyword of keywords) delete result[keyword]; + } + if (result !== value) assertDialect(value); + visited.set(value, result); + return result; + } + const document = walk(root) as Schema; + const selected = walk(schema) as Schema; + if (selected !== schema || document !== root) assertDialect(root); + return { schema: selected, root: document }; +} + +function assertDialect(schema: Schema): void { + const dialect = schema['$schema']; + if (Object.hasOwn(schema, '$schema') && dialect !== draft202012 && dialect !== `${draft202012}#`) { + throw new SchemaParseError('Artifact references require Draft 2020-12'); + } +} diff --git a/typescript/src/schema/loader-pure.ts b/typescript/src/schema/loader-pure.ts index 6955aced..63f9693e 100644 --- a/typescript/src/schema/loader-pure.ts +++ b/typescript/src/schema/loader-pure.ts @@ -21,8 +21,11 @@ import { type RedactionReferenceContext, } from '../utils/redaction-references.js'; import { KEYWORD_MARKER } from './constants.js'; +import { lowerArtifactReferences } from './artifact-reference.js'; const sourceSchemas = new WeakMap>(); +const artifactValidationSchemas = new WeakMap(); +const artifactValidation = new WeakSet(); const referenceContexts = new WeakMap, RedactionReferenceContext>(); /** @internal Return the original schema document for schema-aware capture. */ @@ -71,11 +74,38 @@ export function jsonSchemaToTypeBox( schema: Record, root?: Record, ): TSchema { - const converted = _convert(schema, root ?? schema); + const document = root ?? schema; + const lowered = lowerArtifactReferences(schema, document); + const converted = _convert(schema, document); sourceSchemas.set(converted, schema); + if (lowered.schema !== schema || lowered.root !== document) { + artifactValidationSchemas.set(converted, _compileArtifactValidation(lowered)); + } return converted; } +/** @internal Compile opted-in assertions without modifying the exported declaration. */ +export function withArtifactReferences(schema: TSchema): TSchema { + const validated = artifactValidationSchemas.get(schema); + if (validated !== undefined) return validated; + if (sourceSchemas.has(schema)) return schema; + const source = sourceSchemaFor(schema); + const lowered = lowerArtifactReferences(source); + return lowered.schema === source ? schema : _compileArtifactValidation(lowered); +} + +/** @internal Artifact validation avoids diagnostics derived from runtime data. */ +export function isArtifactValidationSchema(schema: TSchema): boolean { + return artifactValidation.has(schema); +} + +function _compileArtifactValidation(lowered: ReturnType): TSchema { + const compiled = _convert(lowered.schema, lowered.root); + sourceSchemas.set(compiled, lowered.schema); + artifactValidation.add(compiled); + return compiled; +} + function _convert(schema: Record | boolean, root: Record): TSchema { if (typeof schema === 'boolean') return schema ? Type.Unknown() : Type.Never(); const ref = typeof schema['$ref'] === 'string' ? _convertRef(schema['$ref'], schema, root) : null; @@ -524,7 +554,7 @@ function _checkRef( } let converted = byRoot.get(root); if (converted === undefined) { - converted = jsonSchemaToTypeBox(target, root); + converted = _convert(target, root); byRoot.set(root, converted); } return Value.Check(converted, value); diff --git a/typescript/src/schema/validator.ts b/typescript/src/schema/validator.ts index 466113d0..c5b2148a 100644 --- a/typescript/src/schema/validator.ts +++ b/typescript/src/schema/validator.ts @@ -2,14 +2,32 @@ * SchemaValidator — validates runtime data against TypeBox schemas. */ -import type { TSchema } from '@sinclair/typebox'; +import { Kind, type TSchema } from '@sinclair/typebox'; import { Value, type ValueError } from '@sinclair/typebox/value'; import { ValueErrorType } from '@sinclair/typebox/errors'; import type { SchemaValidationErrorDetail, SchemaValidationResult } from './types.js'; import { validationResultToError } from './types.js'; import { KEYWORD_MARKER } from './constants.js'; import { FORMAT_VALIDATORS, withFormatsAsAnnotations } from './formats.js'; -import { convertedApplicatorFailure, withExactTypeBoxMultipleOf } from './loader-pure.js'; +import { + convertedApplicatorFailure, isArtifactValidationSchema, sourceSchemaFor, withArtifactReferences, withExactTypeBoxMultipleOf, +} from './loader-pure.js'; + +function artifactValidationFailure(errorCode = 'SCHEMA_VALIDATION_ERROR'): SchemaValidationResult { + return { + valid: false, + errorCode, + errors: [{ path: '', keyword: 'x-artifact-ref', message: 'Value does not satisfy the artifact-enabled schema' }], + }; +} + +function nativeArtifactContract(schema: TSchema, lowered: TSchema): TSchema | undefined { + // Keep TypeBox's host-defined refinements alongside the JSON Schema assertions. + if (schema !== lowered && Kind in schema && sourceSchemaFor(schema) === schema) { + return withExactTypeBoxMultipleOf(schema); + } + return undefined; +} /** * The branch list of a union node, or `null` when the schema is not one. @@ -207,9 +225,11 @@ export class SchemaValidator { * formats are enforced at SHOULD level by `_checkFormats`, never here. */ validate(data: Record, schema: TSchema): SchemaValidationResult { - const validationSchema = withExactTypeBoxMultipleOf(schema); - return withFormatsAsAnnotations(schema, () => - this._validate(this._coerce(data, validationSchema), validationSchema)); + const declaredSchema = withArtifactReferences(schema); + const validationSchema = withExactTypeBoxMultipleOf(declaredSchema); + const nativeSchema = nativeArtifactContract(schema, declaredSchema); + return withFormatsAsAnnotations(declaredSchema, () => + this._validate(this._coerce(data, validationSchema), validationSchema, nativeSchema)); } /** @@ -225,7 +245,17 @@ export class SchemaValidator { return coerceValue(data, schema) as Record; } - private _validate(data: Record, schema: TSchema): SchemaValidationResult { + private _validate(data: Record, schema: TSchema, nativeSchema?: TSchema): SchemaValidationResult { + if (nativeSchema && !withFormatsAsAnnotations(nativeSchema, () => this._passesStructural(data, nativeSchema))) { + return artifactValidationFailure(); + } + const result = this._validateSchema(data, schema); + return result.valid || !isArtifactValidationSchema(schema) + ? result + : artifactValidationFailure(result.errorCode ?? undefined); + } + + private _validateSchema(data: Record, schema: TSchema): SchemaValidationResult { const s = schema as Record; // oneOf: exhaustive counting — exactly one branch must match @@ -256,21 +286,19 @@ export class SchemaValidator { return this._validateStructural(data, schema); } - /** The plain TypeBox check, decoding first when type coercion is enabled. */ - private _validateStructural(data: unknown, schema: TSchema): SchemaValidationResult { - let passed: boolean; - if (this._coerceTypes) { - try { - Value.Decode(schema, data); - passed = true; - } catch { - passed = false; - } - } else { - passed = Value.Check(schema, data); + private _passesStructural(data: unknown, schema: TSchema): boolean { + if (!this._coerceTypes) return Value.Check(schema, data); + try { + Value.Decode(schema, data); + return true; + } catch { + return false; } + } - if (!passed) { + /** The plain TypeBox check, decoding first when type coercion is enabled. */ + private _validateStructural(data: unknown, schema: TSchema): SchemaValidationResult { + if (!this._passesStructural(data, schema)) { // Errors are collected only on the failing path — `Value.Errors` walks // the whole schema. return { @@ -380,19 +408,22 @@ export class SchemaValidator { } private _validateAndReturn(data: Record, schema: TSchema): Record { - const validationSchema = withExactTypeBoxMultipleOf(schema); - return withFormatsAsAnnotations(schema, () => { + const declaredSchema = withArtifactReferences(schema); + const validationSchema = withExactTypeBoxMultipleOf(declaredSchema); + const nativeSchema = nativeArtifactContract(schema, declaredSchema); + return withFormatsAsAnnotations(declaredSchema, () => { // Route through _validate() so union schemas surface their specific error // code (SCHEMA_UNION_NO_MATCH / SCHEMA_UNION_AMBIGUOUS) and plain failures // surface SCHEMA_VALIDATION_ERROR — all preserved through the thrown error. const value = this._coerce(data, validationSchema); - const result = this._validate(value, validationSchema); + const result = this._validate(value, validationSchema, nativeSchema); if (!result.valid) { throw validationResultToError(result); } if (this._coerceTypes) { - return Value.Decode(validationSchema, value) as Record; + return withFormatsAsAnnotations(nativeSchema ?? declaredSchema, () => + Value.Decode(nativeSchema ?? validationSchema, value) as Record); } return value; }); @@ -408,6 +439,10 @@ export class SchemaValidator { this._walkFormats(data, schema as Record, '/', warnings); // The same annotation can be reached through more than one union branch. const unique = [...new Set(warnings)]; + if (unique.length > 0 && isArtifactValidationSchema(schema)) { + console.warn('[apcore:schema] Format validation failed in an artifact-enabled schema'); + return true; + } for (const w of unique) { console.warn(`[apcore:schema] ${w}`); } diff --git a/typescript/tests/conformance-artifact-reference.test.ts b/typescript/tests/conformance-artifact-reference.test.ts new file mode 100644 index 00000000..450f72ab --- /dev/null +++ b/typescript/tests/conformance-artifact-reference.test.ts @@ -0,0 +1,155 @@ +import { readFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { Kind, Type, TypeRegistry } from '@sinclair/typebox'; +import { describe, expect, it, vi } from 'vitest'; +import { + Executor, Identity, Registry, SchemaValidator, jsonSchemaToTypeBox, + parseArtifactRef, readArtifact, type ArtifactStore, +} from '../src/index.js'; +import { findFixturesRoot } from './spec-repo.js'; + +interface Case { + id: string; + schema: Record; + data: Record; + expected: 'valid' | 'invalid_instance' | 'invalid_schema'; +} + +const fixture: { test_cases: Case[] } = JSON.parse( + readFileSync(join(findFixturesRoot(), 'artifact_reference.json'), 'utf-8'), +); +const ref = { id: 'art_1', media_type: 'application/octet-stream', size_bytes: 2 }; +const identity = new Identity('alice'); +const artifact = { 'x-artifact-ref': true, 'x-max-bytes': 2 }; +const objectWith = (property: string, declaration: Record) => ({ + type: 'object', properties: { [property]: declaration }, required: [property], +}); + +for (const trial of fixture.test_cases) { + it(`conformance artifact reference: ${trial.id}`, () => { + const validator = new SchemaValidator(); + const run = () => validator.validate(trial.data, jsonSchemaToTypeBox(trial.schema)); + if (trial.expected === 'invalid_schema') { + expect(run).toThrow(expect.objectContaining({ code: 'SCHEMA_PARSE_ERROR' })); + } else { + const result = run(); + expect(result.valid).toBe(trial.expected === 'valid'); + if (trial.schema['x-artifact-ref'] && trial.data !== null && typeof trial.data === 'object') { + if (trial.expected === 'valid') expect(parseArtifactRef(trial.data)).toEqual(trial.data); + else expect(() => parseArtifactRef(trial.data)).toThrow(expect.objectContaining({ code: 'GENERAL_INVALID_INPUT' })); + } + } + }); +} + +describe('artifact reference invocation', () => { + it('validates input before entering the module, validates output and preserves the raw declaration', async () => { + const registry = new Registry(); + const execute = vi.fn(({ arg }: Record) => ({ result: arg })); + await registry.register('test.artifact', { + description: 'Read an artifact', inputSchema: objectWith('arg', artifact), + outputSchema: objectWith('result', { 'x-media-types': ['application/octet-stream'], 'x-max-bytes': 1 }), + execute, + }); + const executor = new Executor({ registry }); + await expect(executor.call('test.artifact', { arg: { ...ref, size_bytes: 3 } })).rejects.toMatchObject({ code: 'SCHEMA_VALIDATION_ERROR' }); + expect(execute).not.toHaveBeenCalled(); + await expect(executor.call('test.artifact', { arg: ref })).rejects.toMatchObject({ code: 'SCHEMA_VALIDATION_ERROR' }); + expect(execute).toHaveBeenCalledOnce(); + await expect(executor.call('test.artifact', { arg: { ...ref, size_bytes: 1 } })).resolves.toEqual({ result: { ...ref, size_bytes: 1 } }); + expect(registry.captureOutputDeclaration('test.artifact')?.schema).toEqual(objectWith('result', { + 'x-media-types': ['application/octet-stream'], 'x-max-bytes': 1, + })); + }); + + it('keeps dynamic data paths out of artifact diagnostics', () => { + const logger = vi.spyOn(console, 'warn').mockImplementation(() => {}); + try { + const fields = { type: 'object', additionalProperties: { type: 'string', format: 'uuid' } }; + const tagged = jsonSchemaToTypeBox({ ...fields, properties: { payload: artifact } }); + const validator = new SchemaValidator(); + expect(validator.validate({ payload: ref, 'secret-user-key': 'bad uuid' }, tagged)).toMatchObject({ valid: true, warnLogged: true }); + expect(JSON.stringify(logger.mock.calls)).not.toContain('secret-user-key'); + expect(JSON.stringify(logger.mock.calls)).not.toContain('bad uuid'); + expect(JSON.stringify(validator.validate({ payload: ref, 'secret-user-key': false }, tagged))).not.toContain('secret-user-key'); + logger.mockClear(); + expect(validator.validate({ 'ordinary-key': 'bad uuid' }, jsonSchemaToTypeBox(fields)).valid).toBe(true); + expect(JSON.stringify(logger.mock.calls)).toContain('ordinary-key'); + } finally { + logger.mockRestore(); + } + }); + + it('checks references resolved against an explicit source document', () => { + const source = { $defs: { payload: { 'x-artifact-ref': true } } }; + const schema = jsonSchemaToTypeBox({ $ref: '#/$defs/payload', 'x-max-bytes': 2 }, source); + const validator = new SchemaValidator(); + expect(validator.validate(ref, schema).valid).toBe(true); + expect(validator.validate({ ...ref, size_bytes: 3 }, schema).valid).toBe(false); + expect(validator.validate({ ...ref, media_type: '*/*' }, schema).valid).toBe(false); + expect(() => jsonSchemaToTypeBox({ $ref: '#/$defs/payload' }, { + ...source, $schema: 'http://json-schema.org/draft-07/schema#', + })).toThrow(expect.objectContaining({ code: 'SCHEMA_PARSE_ERROR' })); + }); + + it('keeps native TypeBox refinements when adding artifact assertions', () => { + const name = 'TestArtifactRefinement'; + TypeRegistry.Set(name, (_schema, value) => value === 'approved'); + try { + const schema = Type.Object({ + payload: Type.Object({}, { 'x-artifact-ref': true }), + custom: Type.Unsafe({ [Kind]: name, type: 'string' }), + }); + const validator = new SchemaValidator(); + expect(validator.validate({ payload: ref, custom: 'approved' }, schema).valid).toBe(true); + expect(validator.validate({ payload: ref, custom: 'rejected' }, schema).valid).toBe(false); + } finally { + TypeRegistry.Delete(name); + } + }); + + it('applies the extension in native TypeBox and public validation methods', () => { + const schema = Type.Object({ payload: Type.Object({}, { 'x-artifact-ref': true }) }); + const validator = new SchemaValidator(); + expect(validator.validateInput({ payload: ref }, schema)).toEqual({ payload: ref }); + expect(() => validator.validateOutput({ payload: { ...ref, url: 'secret-url' } }, schema)).toThrow( + expect.objectContaining({ code: 'SCHEMA_VALIDATION_ERROR' }), + ); + expect(JSON.stringify(validator.validate({ payload: { ...ref, id: 'secret ref' } }, schema))).not.toContain('secret ref'); + }); +}); + +describe('artifact store', () => { + it('passes identity and the exact byte bound and returns a detached byte snapshot', async () => { + const content = Uint8Array.of(0, 1); + const read = vi.fn(async () => ({ ref, content })); + const result = await readArtifact({ read }, ref, identity); + expect(read).toHaveBeenCalledExactlyOnceWith(ref.id, identity, ref.size_bytes); + content[0] = 100; + expect(result).toEqual({ ref, content: Uint8Array.of(0, 1) }); + }); + + it('rejects bad reads without opening the store and omits absent or inconsistent bytes', async () => { + const read = vi.fn(); + const store = { read }; + await expect(readArtifact(store, { ...ref, id: '../bad' }, identity)).rejects.toMatchObject({ code: 'GENERAL_INVALID_INPUT' }); + await expect(readArtifact(store, ref, identity, 1)).resolves.toBeNull(); + await expect(readArtifact(store, ref, identity, -1)).rejects.toMatchObject({ code: 'GENERAL_INVALID_INPUT' }); + await expect(readArtifact(store, ref, new Identity(''))).rejects.toMatchObject({ code: 'GENERAL_INVALID_INPUT' }); + expect(read).not.toHaveBeenCalled(); + + const validBytes = Uint8Array.of(0, 1); + const spoofedBytes = Uint8Array.of(0, 1, 2); + Object.defineProperty(spoofedBytes, 'byteLength', { value: 2 }); + for (const absent of [null, { ref: { ...ref, id: 'art_2' }, content: validBytes }, + { ref: { ...ref, media_type: 'image/png' }, content: validBytes }, + { ref, content: Uint8Array.of(0) }, { ref, content: Uint8Array.of(0, 1, 2) }, { ref, content: spoofedBytes }, + ]) { + read.mockResolvedValueOnce(absent); + await expect(readArtifact(store, ref, identity)).resolves.toBeNull(); + } + const failure = new Error('store unavailable'); + read.mockRejectedValueOnce(failure); + await expect(readArtifact(store, ref, identity)).rejects.toBe(failure); + }); +}); From 01611914b44c0b39618156fa825d35d8e2d0cac2 Mon Sep 17 00:00:00 2001 From: tercel Date: Sun, 29 Nov 2026 19:25:58 +0800 Subject: [PATCH 3/6] Add host-owned durable input recovery across Core SDKs Signed-off-by: tercel --- conformance/README.md | 1 + conformance/fixtures/durable_input.json | 789 ++++++++++++++++++ planning/atlas-durable-input/contract.md | 34 + python/src/apcore/__init__.py | 5 + python/src/apcore/durable_input.py | 134 +++ python/src/apcore/errors.py | 28 +- python/tests/test_durable_input.py | 221 +++++ python/tests/test_public_api.py | 3 + rust/src/durable_input.rs | 238 ++++++ rust/src/lib.rs | 2 + rust/tests/durable_input_spec.rs | 380 +++++++++ rust/tests/it.rs | 2 + typescript/src/browser/index.ts | 3 + typescript/src/durable-input.ts | 119 +++ typescript/src/node-api.ts | 3 + .../tests/conformance-durable-input.test.ts | 201 +++++ 16 files changed, 2162 insertions(+), 1 deletion(-) create mode 100644 conformance/fixtures/durable_input.json create mode 100644 planning/atlas-durable-input/contract.md create mode 100644 python/src/apcore/durable_input.py create mode 100644 python/tests/test_durable_input.py create mode 100644 rust/src/durable_input.rs create mode 100644 rust/tests/durable_input_spec.rs create mode 100644 typescript/src/durable-input.ts create mode 100644 typescript/tests/conformance-durable-input.test.ts diff --git a/conformance/README.md b/conformance/README.md index d1d8a5a7..03c9da0a 100644 --- a/conformance/README.md +++ b/conformance/README.md @@ -48,6 +48,7 @@ declared extension. Adapter wire projections are verified in Surfaces. | `extension_point_lookup.json` | D-108 | `get`/`get_all`/`unregister` reject an UNREGISTERED extension point with `GENERAL_INVALID_INPUT`, and do not raise for a registered point holding nothing (spec v1.51.0) | | `config_env.json` | — | Configuration environment variable override | | `context_serialization.json` | — | Cross-language Context serialize/deserialize round-trip | +| `durable_input.json` | [Opt-in durable input contract](../planning/atlas-durable-input/contract.md) | Cross-process request shape and owner, caller, deadline, and answer validation. | | `artifact_reference.json` | [Opt-in artifact reference contract](../planning/atlas-artifact-reference/contract.md) | Closed wire shape, media and byte assertions, local references and schema dialect checks. | | `schema_validation.json` | §4.15 | Schema validation edge cases, plus the **opt-in library-level** coercing mode. Cases carrying `expected_valid_strict` / `expected_valid_coerce` document BOTH modes and SHOULD be asserted against both, naming the mode explicitly rather than relying on a constructor default. The coercing mode is a knob on the standalone validator API only — it never reaches the module-invocation boundary, which is covered by `schema_keyword_parity.json` (TYPE_MAPPING §17.3). | | `schema_hardening_union.json` | §4.15 Hardening | anyOf/oneOf union evaluation: all-branches, exactly-one, ambiguous-error | diff --git a/conformance/fixtures/durable_input.json b/conformance/fixtures/durable_input.json new file mode 100644 index 00000000..4ceed406 --- /dev/null +++ b/conformance/fixtures/durable_input.json @@ -0,0 +1,789 @@ +{ + "description": "Host-level durable input prepare and strict owner/deadline binding", + "test_cases": [ + { + "id": "direct_fresh_resume", + "record": { + "request_id": "9b0b9d7134364bd4a37e55a137f094c3", + "expires_at_ms": 2000, + "module_id": "delivery.confirm", + "module_version": "1.2.3", + "caller_id": null, + "owner": { + "issuer": "fixture", + "type": "user", + "id": "alice" + }, + "arguments": { + "job": "job-1", + "options": { + "priority": true + } + } + }, + "identity": { + "issuer": "fixture", + "type": "user", + "id": "alice", + "roles": [ + "dispatcher" + ] + }, + "caller_id": null, + "answer": "north", + "now_ms": 1999, + "expected": "ready", + "arguments": { + "job": "job-1", + "options": { + "priority": true + }, + "input_request_id": "9b0b9d7134364bd4a37e55a137f094c3", + "answer": "north" + } + }, + { + "id": "answer_may_be_null", + "record": { + "request_id": "9b0b9d7134364bd4a37e55a137f094c3", + "expires_at_ms": 2000, + "module_id": "delivery.confirm", + "module_version": "1.2.3", + "caller_id": null, + "owner": { + "issuer": "fixture", + "type": "user", + "id": "alice" + }, + "arguments": { + "job": "job-1", + "options": { + "priority": true + } + } + }, + "identity": { + "issuer": "fixture", + "type": "user", + "id": "alice", + "roles": [ + "dispatcher" + ] + }, + "caller_id": null, + "answer": null, + "now_ms": 1999, + "expected": "ready", + "arguments": { + "job": "job-1", + "options": { + "priority": true + }, + "input_request_id": "9b0b9d7134364bd4a37e55a137f094c3", + "answer": null + } + }, + { + "id": "nested_answer", + "record": { + "request_id": "9b0b9d7134364bd4a37e55a137f094c3", + "expires_at_ms": 2000, + "module_id": "delivery.confirm", + "module_version": "1.2.3", + "caller_id": null, + "owner": { + "issuer": "fixture", + "type": "user", + "id": "alice" + }, + "arguments": { + "job": "job-1", + "options": { + "priority": true + } + } + }, + "identity": { + "issuer": "fixture", + "type": "user", + "id": "alice", + "roles": [ + "dispatcher" + ] + }, + "caller_id": null, + "answer": { + "destination": [ + "north", + 1, + false + ] + }, + "now_ms": 1999, + "expected": "ready", + "arguments": { + "job": "job-1", + "options": { + "priority": true + }, + "input_request_id": "9b0b9d7134364bd4a37e55a137f094c3", + "answer": { + "destination": [ + "north", + 1, + false + ] + } + } + }, + { + "id": "fresh_roles_used", + "record": { + "request_id": "9b0b9d7134364bd4a37e55a137f094c3", + "expires_at_ms": 2000, + "module_id": "delivery.confirm", + "module_version": "1.2.3", + "caller_id": null, + "owner": { + "issuer": "fixture", + "type": "user", + "id": "alice" + }, + "arguments": { + "job": "job-1", + "options": { + "priority": true + } + } + }, + "identity": { + "issuer": "fixture", + "type": "user", + "id": "alice", + "roles": [] + }, + "caller_id": null, + "answer": "north", + "now_ms": 1999, + "expected": "ready", + "arguments": { + "job": "job-1", + "options": { + "priority": true + }, + "input_request_id": "9b0b9d7134364bd4a37e55a137f094c3", + "answer": "north" + } + }, + { + "id": "exact_expiry", + "record": { + "request_id": "9b0b9d7134364bd4a37e55a137f094c3", + "expires_at_ms": 2000, + "module_id": "delivery.confirm", + "module_version": "1.2.3", + "caller_id": null, + "owner": { + "issuer": "fixture", + "type": "user", + "id": "alice" + }, + "arguments": { + "job": "job-1", + "options": { + "priority": true + } + } + }, + "identity": { + "issuer": "fixture", + "type": "user", + "id": "alice", + "roles": [ + "dispatcher" + ] + }, + "caller_id": null, + "answer": "north", + "now_ms": 2000, + "expected": "unavailable" + }, + { + "id": "expired", + "record": { + "request_id": "9b0b9d7134364bd4a37e55a137f094c3", + "expires_at_ms": 2000, + "module_id": "delivery.confirm", + "module_version": "1.2.3", + "caller_id": null, + "owner": { + "issuer": "fixture", + "type": "user", + "id": "alice" + }, + "arguments": { + "job": "job-1", + "options": { + "priority": true + } + } + }, + "identity": { + "issuer": "fixture", + "type": "user", + "id": "alice", + "roles": [ + "dispatcher" + ] + }, + "caller_id": null, + "answer": "north", + "now_ms": 2001, + "expected": "unavailable" + }, + { + "id": "different_issuer", + "record": { + "request_id": "9b0b9d7134364bd4a37e55a137f094c3", + "expires_at_ms": 2000, + "module_id": "delivery.confirm", + "module_version": "1.2.3", + "caller_id": null, + "owner": { + "issuer": "fixture", + "type": "user", + "id": "alice" + }, + "arguments": { + "job": "job-1", + "options": { + "priority": true + } + } + }, + "identity": { + "issuer": "different", + "type": "user", + "id": "alice", + "roles": [ + "dispatcher" + ] + }, + "caller_id": null, + "answer": "north", + "now_ms": 1999, + "expected": "unavailable" + }, + { + "id": "different_subject", + "record": { + "request_id": "9b0b9d7134364bd4a37e55a137f094c3", + "expires_at_ms": 2000, + "module_id": "delivery.confirm", + "module_version": "1.2.3", + "caller_id": null, + "owner": { + "issuer": "fixture", + "type": "user", + "id": "alice" + }, + "arguments": { + "job": "job-1", + "options": { + "priority": true + } + } + }, + "identity": { + "issuer": "fixture", + "type": "user", + "id": "bob", + "roles": [ + "dispatcher" + ] + }, + "caller_id": null, + "answer": "north", + "now_ms": 1999, + "expected": "unavailable" + }, + { + "id": "different_type", + "record": { + "request_id": "9b0b9d7134364bd4a37e55a137f094c3", + "expires_at_ms": 2000, + "module_id": "delivery.confirm", + "module_version": "1.2.3", + "caller_id": null, + "owner": { + "issuer": "fixture", + "type": "user", + "id": "alice" + }, + "arguments": { + "job": "job-1", + "options": { + "priority": true + } + } + }, + "identity": { + "issuer": "fixture", + "type": "agent", + "id": "alice", + "roles": [ + "dispatcher" + ] + }, + "caller_id": null, + "answer": "north", + "now_ms": 1999, + "expected": "unavailable" + }, + { + "id": "missing_issuer", + "record": { + "request_id": "9b0b9d7134364bd4a37e55a137f094c3", + "expires_at_ms": 2000, + "module_id": "delivery.confirm", + "module_version": "1.2.3", + "caller_id": null, + "owner": { + "issuer": "fixture", + "type": "user", + "id": "alice" + }, + "arguments": { + "job": "job-1", + "options": { + "priority": true + } + } + }, + "identity": { + "type": "user", + "id": "alice", + "roles": [ + "dispatcher" + ] + }, + "caller_id": null, + "answer": "north", + "now_ms": 1999, + "expected": "unavailable" + }, + { + "id": "different_caller", + "record": { + "request_id": "9b0b9d7134364bd4a37e55a137f094c3", + "expires_at_ms": 2000, + "module_id": "delivery.confirm", + "module_version": "1.2.3", + "caller_id": null, + "owner": { + "issuer": "fixture", + "type": "user", + "id": "alice" + }, + "arguments": { + "job": "job-1", + "options": { + "priority": true + } + } + }, + "identity": { + "issuer": "fixture", + "type": "user", + "id": "alice", + "roles": [ + "dispatcher" + ] + }, + "caller_id": "worker.dispatch", + "answer": "north", + "now_ms": 1999, + "expected": "unavailable" + }, + { + "id": "scoped_caller", + "record": { + "request_id": "9b0b9d7134364bd4a37e55a137f094c3", + "expires_at_ms": 2000, + "module_id": "delivery.confirm", + "module_version": "1.2.3", + "caller_id": "worker.dispatch", + "owner": { + "issuer": "fixture", + "type": "user", + "id": "alice" + }, + "arguments": { + "job": "job-1", + "options": { + "priority": true + } + } + }, + "identity": { + "issuer": "fixture", + "type": "user", + "id": "alice", + "roles": [ + "dispatcher" + ] + }, + "caller_id": "worker.dispatch", + "answer": "north", + "now_ms": 1999, + "expected": "ready", + "arguments": { + "job": "job-1", + "options": { + "priority": true + }, + "input_request_id": "9b0b9d7134364bd4a37e55a137f094c3", + "answer": "north" + } + }, + { + "id": "absent_record", + "record": null, + "identity": { + "issuer": "fixture", + "type": "user", + "id": "alice", + "roles": [ + "dispatcher" + ] + }, + "caller_id": null, + "answer": "north", + "now_ms": 1999, + "expected": "unavailable" + }, + { + "id": "wrong_request_shape", + "record": { + "request_id": "missing", + "expires_at_ms": 2000, + "module_id": "delivery.confirm", + "module_version": "1.2.3", + "caller_id": null, + "owner": { + "issuer": "fixture", + "type": "user", + "id": "alice" + }, + "arguments": { + "job": "job-1", + "options": { + "priority": true + } + } + }, + "identity": { + "issuer": "fixture", + "type": "user", + "id": "alice", + "roles": [ + "dispatcher" + ] + }, + "caller_id": null, + "answer": "north", + "now_ms": 1999, + "expected": "unavailable" + }, + { + "id": "nonpositive_expiry", + "record": { + "request_id": "9b0b9d7134364bd4a37e55a137f094c3", + "expires_at_ms": 0, + "module_id": "delivery.confirm", + "module_version": "1.2.3", + "caller_id": null, + "owner": { + "issuer": "fixture", + "type": "user", + "id": "alice" + }, + "arguments": { + "job": "job-1", + "options": { + "priority": true + } + } + }, + "identity": { + "issuer": "fixture", + "type": "user", + "id": "alice", + "roles": [ + "dispatcher" + ] + }, + "caller_id": null, + "answer": "north", + "now_ms": 1999, + "expected": "unavailable" + }, + { + "id": "missing_version", + "record": { + "request_id": "9b0b9d7134364bd4a37e55a137f094c3", + "expires_at_ms": 2000, + "module_id": "delivery.confirm", + "module_version": "", + "caller_id": null, + "owner": { + "issuer": "fixture", + "type": "user", + "id": "alice" + }, + "arguments": { + "job": "job-1", + "options": { + "priority": true + } + } + }, + "identity": { + "issuer": "fixture", + "type": "user", + "id": "alice", + "roles": [ + "dispatcher" + ] + }, + "caller_id": null, + "answer": "north", + "now_ms": 1999, + "expected": "unavailable" + }, + { + "id": "unexpected_record_key", + "record": { + "request_id": "9b0b9d7134364bd4a37e55a137f094c3", + "expires_at_ms": 2000, + "module_id": "delivery.confirm", + "module_version": "1.2.3", + "caller_id": null, + "owner": { + "issuer": "fixture", + "type": "user", + "id": "alice" + }, + "arguments": { + "job": "job-1", + "options": { + "priority": true + } + }, + "private": "extra" + }, + "identity": { + "issuer": "fixture", + "type": "user", + "id": "alice", + "roles": [ + "dispatcher" + ] + }, + "caller_id": null, + "answer": "north", + "now_ms": 1999, + "expected": "unavailable" + }, + { + "id": "unexpected_owner_key", + "record": { + "request_id": "9b0b9d7134364bd4a37e55a137f094c3", + "expires_at_ms": 2000, + "module_id": "delivery.confirm", + "module_version": "1.2.3", + "caller_id": null, + "owner": { + "issuer": "fixture", + "type": "user", + "id": "alice", + "extra": "field" + }, + "arguments": { + "job": "job-1", + "options": { + "priority": true + } + } + }, + "identity": { + "issuer": "fixture", + "type": "user", + "id": "alice", + "roles": [ + "dispatcher" + ] + }, + "caller_id": null, + "answer": "north", + "now_ms": 1999, + "expected": "unavailable" + }, + { + "id": "approval_token_in_business_args", + "record": { + "request_id": "9b0b9d7134364bd4a37e55a137f094c3", + "expires_at_ms": 2000, + "module_id": "delivery.confirm", + "module_version": "1.2.3", + "caller_id": null, + "owner": { + "issuer": "fixture", + "type": "user", + "id": "alice" + }, + "arguments": { + "_approval_token": "value" + } + }, + "identity": { + "issuer": "fixture", + "type": "user", + "id": "alice", + "roles": [ + "dispatcher" + ] + }, + "caller_id": null, + "answer": "north", + "now_ms": 1999, + "expected": "unavailable" + }, + { + "id": "answer_in_business_args", + "record": { + "request_id": "9b0b9d7134364bd4a37e55a137f094c3", + "expires_at_ms": 2000, + "module_id": "delivery.confirm", + "module_version": "1.2.3", + "caller_id": null, + "owner": { + "issuer": "fixture", + "type": "user", + "id": "alice" + }, + "arguments": { + "answer": "north" + } + }, + "identity": { + "issuer": "fixture", + "type": "user", + "id": "alice", + "roles": [ + "dispatcher" + ] + }, + "caller_id": null, + "answer": "north", + "now_ms": 1999, + "expected": "unavailable" + }, + { + "id": "request_in_business_args", + "record": { + "request_id": "9b0b9d7134364bd4a37e55a137f094c3", + "expires_at_ms": 2000, + "module_id": "delivery.confirm", + "module_version": "1.2.3", + "caller_id": null, + "owner": { + "issuer": "fixture", + "type": "user", + "id": "alice" + }, + "arguments": { + "input_request_id": "existing" + } + }, + "identity": { + "issuer": "fixture", + "type": "user", + "id": "alice", + "roles": [ + "dispatcher" + ] + }, + "caller_id": null, + "answer": "north", + "now_ms": 1999, + "expected": "unavailable" + }, + { + "id": "unsafe_clock", + "record": { + "request_id": "9b0b9d7134364bd4a37e55a137f094c3", + "expires_at_ms": 2000, + "module_id": "delivery.confirm", + "module_version": "1.2.3", + "caller_id": null, + "owner": { + "issuer": "fixture", + "type": "user", + "id": "alice" + }, + "arguments": { + "job": "job-1", + "options": { + "priority": true + } + } + }, + "identity": { + "issuer": "fixture", + "type": "user", + "id": "alice", + "roles": [ + "dispatcher" + ] + }, + "caller_id": null, + "answer": "north", + "now_ms": -1, + "expected": "invalid" + }, + { + "id": "unsafe_number_answer", + "record": { + "request_id": "9b0b9d7134364bd4a37e55a137f094c3", + "expires_at_ms": 2000, + "module_id": "delivery.confirm", + "module_version": "1.2.3", + "caller_id": null, + "owner": { + "issuer": "fixture", + "type": "user", + "id": "alice" + }, + "arguments": { + "job": "job-1", + "options": { + "priority": true + } + } + }, + "identity": { + "issuer": "fixture", + "type": "user", + "id": "alice", + "roles": [ + "dispatcher" + ] + }, + "caller_id": null, + "answer": 9007199254740992, + "now_ms": 1999, + "expected": "invalid" + } + ] +} diff --git a/planning/atlas-durable-input/contract.md b/planning/atlas-durable-input/contract.md new file mode 100644 index 00000000..63980fe5 --- /dev/null +++ b/planning/atlas-durable-input/contract.md @@ -0,0 +1,34 @@ +# Durable input recovery contract + +## Review decisions + +An application opens an input request before admitting the effectful call. It persists the request first and then returns the host-level `InputRequiredError`. Reissuing the same business intent must reuse the request or a stable business operation key. A distinct request ID only deduplicates retries of that request. The SDK contract is opt-in. It leaves protocol draft revision 5, in-call Elicitation, and Phase B approval intact. It never snapshots a running pipeline, resumes a program counter, restores an authenticated identity from disk, or replays an arbitrary interrupted call. + +A host uses `prepare_input_resume` (`prepareInputResume` in TypeScript) on a persisted record. It supplies the newly authenticated identity, the current caller ID and a trusted UTC clock. The helper reconstructs detached arguments and returns an `InputResume`. The host starts a fresh, ordinary Core call with those arguments. The host composes `InputResume.matches` into its post-validation policy for the protected module. The final policy verifies the selected module version and exact validated business arguments. ACL, current approval configuration, token scope, and all other policy decisions still apply. No path returns a stored effect result before the current invocation has satisfied those gates. + +## Persisted and public data + +| Record field | Rule | +| --- | --- | +| `request_id` | Exactly 32 lowercase ASCII hexadecimal characters. The host supplies an unpredictable ID and inserts it uniquely. IDs are correlators, not credentials. | +| `expires_at_ms` | Positive JSON safe integer, UTC Unix milliseconds. At `now_ms >= expires_at_ms`, an expired request is unavailable, including retry after completion. | +| `module_id`, `module_version` | Nonempty strings. The version is a specific, immutable effect contract, never a default or a range. The host changes the version when effect or approval-relevant behavior changes. | +| `caller_id` | Nonempty string or JSON null. Freeze this alongside the effective actor. | +| `owner` | Exactly `issuer`, `type`, and `id`, each a nonempty string identifying a direct authenticated principal. Delegated identities are outside this initial profile. Roles, scopes, and attributes come from current authentication. | +| `arguments` | JSON object accepted by Core's existing policy argument canonicalization. Must not contain top-level `input_request_id`, `answer`, or `_approval_token`. | + +The persisted record is a closed object. The public error uses code `INPUT_REQUIRED`, message `Additional input is required`, and details `request_id` and `expires_at_ms` only. The host supplies UI prompts and answer schema separately. The error is not automatically retryable. Do not publish business arguments, identities, or approval tokens in this error. + +Prepare takes `(record, answer, identity, caller_id, now_ms)` and adds `input_request_id` and `answer` to its detached business arguments. The answer may be any canonical JSON value, including null. The module's input schema checks the expected answer type. The helper reports `INPUT_RESUME_UNAVAILABLE` for unknown, malformed, expired or unauthorized records, and rejects invalid clock or unencodable submitted data before dispatch. The `InputResume` exposes an argument copy and the target module ID. `matches(policy_request, now_ms)` fails closed if the direct principal, caller, module, version, deadline or canonical validated arguments differ. Current roles, scopes, and attributes continue through the live governance checks. This comparison uses the existing post-validation canonical argument contract. The same check is safe to run in preflight. The host adds an optional fresh `_approval_token` only to a separate call argument copy when retrying the same approval after a pending response. Core binds it to the live call, never to an input request ID. + +## Side-effect boundary + +Persisting an input request does not start business work. A host runs any business mutation inside a transaction that checks the live request and expiry and uses `request_id` as a unique operation key. The mutation and completion record commit atomically. The completion records the canonical answer and result. An identical retry goes through current Core governance, then returns that result. A different answer for a completed request conflicts. If the process crashes before commit, the transaction rolls back; a crash after commit recovers the existing result. When an effect is external, the host needs a durable outbox and an independently deduplicating consumer or the destination's idempotency contract. Core supplies no general exactly-once guarantee for remote mutations. + +The host installs the final guard on every execution entry for the protected module and composes it with existing policy. It does not enable a strategy that can skip actual ACL, approval or validation. Preparation and before-execution middleware must not perform the protected business effect. The transaction rechecks expiry immediately before its write to cover waiting and races after policy. Database permissions, retention, clock discipline, and handler durability belong to the host. + +## Acceptance + +The shared contract checks pending error serialization, authorization binding, exact version and arguments, expiry boundary, changed permissions, answer validation, fresh and scoped pending approval, crash/retry, and competing answers. Core tests cover three compatible SDK APIs and actual governed calls. The dual-repository acceptance uses real protocol dispatch plus a host-owned durable SQLite effect and early negative cases. Retain existing in-call interaction and approval behavior. + +Run `python scripts/verify-durable-input.py` in Surfaces with matching local Core and MCP inputs. Its child processes cover repeated issuance, approval and ACL after restart, changes to the answer or module version, expiry in policy or at the write, process termination before commit, and concurrent identical and competing answers. diff --git a/python/src/apcore/__init__.py b/python/src/apcore/__init__.py index f2e00359..1536eb80 100644 --- a/python/src/apcore/__init__.py +++ b/python/src/apcore/__init__.py @@ -77,6 +77,7 @@ from apcore.registry.types import DependencyInfo, DiscoveredModule, ModuleDescriptor from apcore.events.emitter import EventSubscriber from apcore.executor import Executor +from apcore.durable_input import InputResume, prepare_input_resume from apcore.utils.redaction import REDACTED_VALUE, redact_sensitive # Module types @@ -148,6 +149,7 @@ IdTooLongError, InternalError, InvalidInputError, + InputRequiredError, InvalidParentIdError, InvalidSegmentError, ModuleDisabledError, @@ -631,6 +633,8 @@ def enable(module_id: str, reason: str = "Enabled via APCore client") -> dict[st "ExecutionStrategy", "Executor", "Identity", + "InputRequiredError", + "InputResume", "Middleware", "Module", "ModuleAnnotations", @@ -655,6 +659,7 @@ def enable(module_id: str, reason: str = "Enabled via APCore client") -> dict[st "close", "module", "redact_sensitive", + "prepare_input_resume", "register", "stream", "to_strict_schema", diff --git a/python/src/apcore/durable_input.py b/python/src/apcore/durable_input.py new file mode 100644 index 00000000..b1301f1e --- /dev/null +++ b/python/src/apcore/durable_input.py @@ -0,0 +1,134 @@ +"""Prepare and bind a host-owned durable input request to a fresh Core call.""" + +from __future__ import annotations + +from copy import deepcopy +from dataclasses import dataclass, field +from typing import Any, TypeGuard + +from apcore._post_validation_policy import _argument_digest +from apcore.context import Identity, _APPROVAL_TOKEN_KEY +from apcore.errors import ( + InvalidInputError, + ModuleError, + PolicyEvaluationError, + _valid_input_milliseconds, + _valid_input_request_id, +) +from apcore.policy import PolicyEvaluationRequest + +__all__ = ["InputResume", "prepare_input_resume"] + +_RECORD_FIELDS = {"request_id", "expires_at_ms", "module_id", "module_version", "caller_id", "owner", "arguments"} +_OWNER_FIELDS = {"issuer", "type", "id"} +_RESERVED_ARGUMENTS = {"input_request_id", "answer", _APPROVAL_TOKEN_KEY} + + +def _nonempty_string(value: object) -> TypeGuard[str]: + return type(value) is str and bool(value) + + +def _direct_principal(identity: Identity | None) -> tuple[str, str, str] | None: + if not isinstance(identity, Identity) or identity.on_behalf_of is not None: + return None + issuer, kind, principal = identity.issuer, identity.type, identity.id + if not (_nonempty_string(issuer) and _nonempty_string(kind) and _nonempty_string(principal)): + return None + return issuer, kind, principal + + +def _matches_owner(owner: Any, principal: tuple[str, str, str]) -> bool: + return ( + type(owner) is dict + and owner.keys() == _OWNER_FIELDS + and all(_nonempty_string(value) for value in owner.values()) + and (owner["issuer"], owner["type"], owner["id"]) == principal + ) + + +def _unavailable() -> ModuleError: + return ModuleError("INPUT_RESUME_UNAVAILABLE", "Input request is unavailable", retryable=False) + + +@dataclass(frozen=True, slots=True) +class InputResume: + """A prepared invocation that the host checks again at final policy.""" + + module_id: str + _module_version: str = field(repr=False) + _caller_id: str | None = field(repr=False) + _owner: tuple[str, str, str] = field(repr=False) + _expires_at_ms: int = field(repr=False) + _arguments: dict[str, Any] = field(repr=False) + _digest: str = field(repr=False) + + @property + def arguments(self) -> dict[str, Any]: + """Return an independent copy of the prepared call arguments.""" + return deepcopy(self._arguments) + + def matches(self, policy_request: PolicyEvaluationRequest, now_ms: int) -> bool: + """Compare a preflight or final policy snapshot against this invocation.""" + if ( + not isinstance(policy_request, PolicyEvaluationRequest) + or not _valid_input_milliseconds(now_ms, minimum=0) + or now_ms >= self._expires_at_ms + or policy_request.module_id != self.module_id + or policy_request.module_version != self._module_version + or policy_request.caller_id != self._caller_id + or _direct_principal(policy_request.identity) != self._owner + or type(policy_request.arguments) is not dict + ): + return False + try: + return _argument_digest(policy_request.arguments) == self._digest + except PolicyEvaluationError: + return False + + +def prepare_input_resume( + record: dict[str, Any] | None, + answer: Any, + identity: Identity | None, + caller_id: str | None, + now_ms: int, +) -> InputResume: + """Bind a closed persisted record and input to the current caller and clock.""" + if not _valid_input_milliseconds(now_ms, minimum=0): + raise InvalidInputError("Invalid input resume clock") + try: + _argument_digest({"answer": answer}) + answer = deepcopy(answer) + except (PolicyEvaluationError, RecursionError): + raise InvalidInputError("The submitted answer must be a canonical JSON value") from None + + if type(record) is not dict or record.keys() != _RECORD_FIELDS: + raise _unavailable() + request_id, expires_at_ms = record["request_id"], record["expires_at_ms"] + module_id, module_version = record["module_id"], record["module_version"] + owner, arguments, stored_caller = record["owner"], record["arguments"], record["caller_id"] + principal = _direct_principal(identity) + if ( + not _valid_input_request_id(request_id) + or not _valid_input_milliseconds(expires_at_ms) + or now_ms >= expires_at_ms + or not _nonempty_string(module_id) + or not _nonempty_string(module_version) + or (caller_id is not None and not _nonempty_string(caller_id)) + or (stored_caller is not None and not _nonempty_string(stored_caller)) + or stored_caller != caller_id + or principal is None + or not _matches_owner(owner, principal) + or type(arguments) is not dict + or not _RESERVED_ARGUMENTS.isdisjoint(arguments) + ): + raise _unavailable() + + expanded = {**arguments, "input_request_id": request_id, "answer": answer} + try: + _argument_digest(expanded) + snapshot = deepcopy(expanded) + digest = _argument_digest(snapshot) + except (PolicyEvaluationError, RecursionError): + raise _unavailable() from None + return InputResume(module_id, module_version, caller_id, principal, expires_at_ms, snapshot, digest) diff --git a/python/src/apcore/errors.py b/python/src/apcore/errors.py index 730cf90d..450fe761 100644 --- a/python/src/apcore/errors.py +++ b/python/src/apcore/errors.py @@ -10,7 +10,7 @@ import threading from datetime import datetime, timezone -from typing import Any, Literal +from typing import Any, Literal, TypeGuard __all__ = [ "ModuleError", @@ -44,6 +44,7 @@ "CircularCallError", "CallFrequencyExceededError", "InvalidInputError", + "InputRequiredError", "InvalidParentIdError", "ContextBindingError", "FuncMissingTypeHintError", @@ -771,6 +772,31 @@ def __init__( super().__init__(code=code, message=message, **kwargs) +def _valid_input_request_id(value: object) -> TypeGuard[str]: + return type(value) is str and len(value) == 32 and all(char in "0123456789abcdef" for char in value) + + +def _valid_input_milliseconds(value: object, *, minimum: int = 1) -> TypeGuard[int]: + return type(value) is int and minimum <= value <= (1 << 53) - 1 + + +class InputRequiredError(ModuleError): + """An application persisted a request for input before admitting a call.""" + + _default_retryable: bool | None = False + + def __init__(self, request_id: str, expires_at_ms: int) -> None: + if not _valid_input_request_id(request_id) or not _valid_input_milliseconds(expires_at_ms): + raise InvalidInputError("Invalid input request metadata") + super().__init__( + code="INPUT_REQUIRED", + message="Additional input is required", + details={"request_id": request_id, "expires_at_ms": expires_at_ms}, + ) + self.request_id = request_id + self.expires_at_ms = expires_at_ms + + class InvalidParentIdError(ModuleError, ValueError): """Raised when ``TraceContext.inject`` gets a ``parent_id`` override that is not 16 lowercase hex characters (``^[0-9a-f]{16}$``). diff --git a/python/tests/test_durable_input.py b/python/tests/test_durable_input.py new file mode 100644 index 00000000..a0273791 --- /dev/null +++ b/python/tests/test_durable_input.py @@ -0,0 +1,221 @@ +"""Verify host-owned durable input and the fresh Core dispatch boundary.""" + +import json +from dataclasses import replace +from pathlib import Path +from typing import Any + +import pytest + +from apcore import ( + ACL, + ACLRule, + ApprovalPendingError, + ApprovalRequest, + ApprovalResult, + Context, + Executor, + Identity, + InputRequiredError, + InputResume, + ModuleError, + PolicyEvaluationRequest, + PolicyVerdict, + Registry, + prepare_input_resume, +) + +_REQUEST_ID = "a" * 32 +_MODULE = "delivery.confirm" +_OWNER = Identity("owner", issuer="issuer.example", roles=("dispatcher",)) +_FIXTURE = Path(__file__).resolve().parents[2] / "conformance" / "fixtures" / "durable_input.json" +_CASES = json.loads(_FIXTURE.read_text())["test_cases"] + + +def _record() -> dict[str, Any]: + return { + "request_id": _REQUEST_ID, + "expires_at_ms": 200, + "module_id": _MODULE, + "module_version": "1.0.0", + "caller_id": None, + "owner": {"id": _OWNER.id, "type": _OWNER.type, "issuer": _OWNER.issuer}, + "arguments": {"job": {"id": "delivery-1"}}, + } + + +def _request(resume: InputResume) -> PolicyEvaluationRequest: + return PolicyEvaluationRequest(_MODULE, "1.0.0", None, _OWNER, resume.arguments, ()) + + +def test_input_required_public_error_contains_only_the_pending_reference() -> None: + error = InputRequiredError(_REQUEST_ID, 200) + assert error.code == "INPUT_REQUIRED" and error.message == "Additional input is required" + assert error.request_id == _REQUEST_ID and error.expires_at_ms == 200 + assert error.to_dict()["details"] == {"request_id": _REQUEST_ID, "expires_at_ms": 200} + assert error.retryable is False + + +@pytest.mark.parametrize(("request_id", "expires_at_ms"), [("A" * 32, 1), (_REQUEST_ID, True), (_REQUEST_ID, 0)]) +def test_input_required_rejects_malformed_metadata(request_id: str, expires_at_ms: int) -> None: + with pytest.raises(ModuleError) as error: + InputRequiredError(request_id, expires_at_ms) + assert error.value.code == "GENERAL_INVALID_INPUT" + + +@pytest.mark.parametrize("case", _CASES, ids=[case["id"] for case in _CASES]) +def test_shared_durable_input_fixture(case: dict[str, Any]) -> None: + identity = Identity(**case["identity"]) if case["identity"] is not None else None + args = (case["record"], case["answer"], identity, case["caller_id"], case["now_ms"]) + if case["expected"] == "ready": + resume = prepare_input_resume(*args) + assert resume.arguments == case["arguments"] + record = case["record"] + policy = PolicyEvaluationRequest( + record["module_id"], + record["module_version"], + case["caller_id"], + identity, + case["arguments"], + (), + ) + assert resume.matches(policy, case["now_ms"]) + assert not resume.matches(policy, record["expires_at_ms"]) + else: + with pytest.raises(ModuleError) as error: + prepare_input_resume(*args) + expected_code = "INPUT_RESUME_UNAVAILABLE" if case["expected"] == "unavailable" else "GENERAL_INVALID_INPUT" + assert error.value.code == expected_code + assert not error.value.details + + +def test_preparation_detaches_nested_values_and_binds_exact_validated_arguments() -> None: + record = _record() + answer = {"destination": ["north"]} + resume = prepare_input_resume(record, answer, _OWNER, None, 100) + record["arguments"]["job"]["id"] = "changed" + answer["destination"].append("south") + copy = resume.arguments + copy["answer"]["destination"].append("secret") + assert resume.module_id == _MODULE + assert resume.arguments == { + "job": {"id": "delivery-1"}, + "input_request_id": _REQUEST_ID, + "answer": {"destination": ["north"]}, + } + request = _request(resume) + assert resume.matches(request, 199) + assert not resume.matches(request, 200) + assert not resume.matches(request, True) + assert not resume.matches(replace(request, module_id="delivery.other"), 100) + assert not resume.matches(replace(request, module_version="2.0.0"), 100) + assert not resume.matches(replace(request, caller_id="app.caller"), 100) + assert not resume.matches(replace(request, identity=Identity("owner", issuer="foreign.example")), 100) + assert resume.matches(replace(request, identity=replace(_OWNER, roles=("current-role",))), 100) + override = {**request.arguments, "answer": {"destination": ["elsewhere"]}} + assert not resume.matches(replace(request, arguments=override), 100) + assert not resume.matches(replace(request, arguments={**request.arguments, "_approval_token": "token"}), 100) + + +def test_delegated_identity_is_ineligible_even_with_same_effective_id() -> None: + parent = Identity("parent", issuer="issuer.example", scopes=("delivery",)) + delegate = replace(_OWNER, scopes=("delivery",), on_behalf_of=parent) + with pytest.raises(ModuleError) as unavailable: + prepare_input_resume(_record(), "north", delegate, None, 100) + assert unavailable.value.code == "INPUT_RESUME_UNAVAILABLE" + resume = prepare_input_resume(_record(), "north", _OWNER, None, 100) + assert not resume.matches(replace(_request(resume), identity=delegate), 100) + + +class _Work: + description = "Confirm a delivery once the answer is accepted" + input_schema = { + "type": "object", + "properties": { + "input_request_id": {"type": "string"}, + "job": {"type": "object"}, + "answer": {"type": "string", "enum": ["north", "south"]}, + }, + "required": ["input_request_id", "job", "answer"], + "additionalProperties": False, + } + output_schema = {"type": "object"} + + def __init__(self) -> None: + self.effects = 0 + + async def execute(self, inputs: dict[str, Any], context: Context) -> dict[str, Any]: + self.effects += 1 + return {"route": inputs["answer"]} + + +class _Review: + supports_final_scope = True + + def __init__(self) -> None: + self.pending: tuple[str | None, str | None] | None = None + + async def request_approval(self, request: ApprovalRequest) -> ApprovalResult: + self.pending = request.module_version, request.canonical_args_digest + return ApprovalResult("pending", approval_id="private-test-token") + + async def check_approval(self, approval_id: str) -> ApprovalResult: + pytest.fail("Checking status must not authorize the effect") + + async def check_approval_for_call(self, approval_id: str, request: ApprovalRequest) -> ApprovalResult: + if approval_id != "private-test-token" or self.pending != ( + request.module_version, + request.canonical_args_digest, + ): + return ApprovalResult("rejected") + self.pending = None + return ApprovalResult("approved") + + +async def test_resume_uses_current_pipeline_validation_acl_policy_and_scoped_approval() -> None: + now = 100 + prepared = prepare_input_resume(_record(), "north", _OWNER, None, now) + + class Guard: + async def evaluate(self, request: PolicyEvaluationRequest) -> PolicyVerdict: + return PolicyVerdict("require_approval" if prepared.matches(request, now) else "deny") + + registry = Registry() + original, latest = _Work(), _Work() + await registry.register_async(_MODULE, original, version="1.0.0") + await registry.register_async(_MODULE, latest, version="2.0.0") + acl = ACL([ACLRule(["@external"], [_MODULE], "allow", conditions={"roles": ["dispatcher"]})], default_effect="deny") + with Executor(registry, acl=acl, policy_evaluator=Guard(), approval_handler=_Review()) as executor: + revoked = replace(_OWNER, roles=()) + for arguments, actor, version, error in ( + (prepared.arguments, revoked, "1.0.0", "ACL_DENIED"), + (dict(prepared.arguments, answer=True), _OWNER, "1.0.0", "SCHEMA_VALIDATION_ERROR"), + (dict(prepared.arguments, answer="south"), _OWNER, "1.0.0", "POLICY_DENIED"), + (prepared.arguments, _OWNER, "2.0.0", "POLICY_DENIED"), + ): + with pytest.raises(ModuleError) as denied: + await executor.call_async(_MODULE, arguments, Context.create(actor), version_hint=version) + assert denied.value.code == error + + with pytest.raises(ApprovalPendingError) as waiting: + await executor.call_async(_MODULE, prepared.arguments, Context.create(_OWNER), version_hint="1.0.0") + assert original.effects == latest.effects == 0 + with pytest.raises(ModuleError) as wrong_token: + await executor.call_async( + _MODULE, + dict(prepared.arguments, _approval_token="unrelated"), + Context.create(_OWNER), + version_hint="1.0.0", + ) + assert wrong_token.value.code == "APPROVAL_DENIED" + retry = dict(prepared.arguments, _approval_token=waiting.value.approval_id) + assert "_approval_token" not in prepared.arguments + assert await executor.call_async(_MODULE, retry, Context.create(_OWNER), version_hint="1.0.0") == { + "route": "north" + } + + now = 200 + with pytest.raises(ModuleError) as expired: + await executor.call_async(_MODULE, prepared.arguments, Context.create(_OWNER), version_hint="1.0.0") + assert expired.value.code == "POLICY_DENIED" + assert original.effects == 1 and latest.effects == 0 diff --git a/python/tests/test_public_api.py b/python/tests/test_public_api.py index a3e6a277..5c1766ae 100644 --- a/python/tests/test_public_api.py +++ b/python/tests/test_public_api.py @@ -482,6 +482,8 @@ class TestPublicAPIAll: "ExecutionStrategy", "Executor", "Identity", + "InputRequiredError", + "InputResume", "Middleware", "Module", "ModuleAnnotations", @@ -507,6 +509,7 @@ class TestPublicAPIAll: "module", "read_artifact", "redact_sensitive", + "prepare_input_resume", "register", "stream", "to_strict_schema", diff --git a/rust/src/durable_input.rs b/rust/src/durable_input.rs new file mode 100644 index 00000000..fb940a46 --- /dev/null +++ b/rust/src/durable_input.rs @@ -0,0 +1,238 @@ +//! Opt-in preparation of fresh Core calls from host-owned input requests. + +use std::fmt; + +use serde::Deserialize; +use serde_json::{json, Map, Value}; + +use crate::policy::{final_arguments_digest, PolicyEvaluationRequest, APPROVAL_TOKEN_KEY}; +use crate::{Identity, ModuleError}; + +const MAX_TIME_MS: u64 = (1 << 53) - 1; +const REQUEST_ID_KEY: &str = "input_request_id"; +const ANSWER_KEY: &str = "answer"; +const INPUT_REQUIRED_CODE: &str = "INPUT_REQUIRED"; +const INPUT_UNAVAILABLE_CODE: &str = "INPUT_RESUME_UNAVAILABLE"; +const INPUT_REQUIRED_MESSAGE: &str = "Additional input is required"; + +/// Public response for a request that the host already persisted. +/// +/// This response carries no UI prompt, business arguments, principal or +/// approval credential. Its request ID is a correlator. +#[derive(Debug, Clone, Eq, PartialEq, thiserror::Error)] +#[error("Additional input is required")] +pub struct InputRequiredError { + request_id: String, + expires_at_ms: u64, +} + +impl InputRequiredError { + /// Build the public error from the persisted request's ID and expiry. + pub fn new(request_id: impl Into, expires_at_ms: u64) -> Result { + let request_id = request_id.into(); + if !valid_request_id(&request_id) || !valid_expiry(expires_at_ms) { + return Err(ModuleError::invalid_input("Invalid input request metadata")); + } + Ok(Self { + request_id, + expires_at_ms, + }) + } + + /// Opaque request correlator supplied by the host. + #[must_use] + pub fn request_id(&self) -> &str { + &self.request_id + } + + /// Expiration in UTC Unix milliseconds. + #[must_use] + pub fn expires_at_ms(&self) -> u64 { + self.expires_at_ms + } +} + +impl From for ModuleError { + fn from(error: InputRequiredError) -> Self { + Self::new_custom(INPUT_REQUIRED_CODE, INPUT_REQUIRED_MESSAGE) + .expect("the durable input error code is reserved by this extension") + .with_details( + [ + ("request_id".to_owned(), Value::String(error.request_id)), + ("expires_at_ms".to_owned(), json!(error.expires_at_ms)), + ] + .into(), + ) + .with_retryable(false) + } +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct DirectOwner { + issuer: String, + #[serde(rename = "type")] + identity_type: String, + id: String, +} + +impl DirectOwner { + fn matches(&self, identity: &Identity) -> bool { + !self.issuer.is_empty() + && !self.identity_type.is_empty() + && !self.id.is_empty() + && identity.on_behalf_of().is_none() + && identity.issuer() == Some(self.issuer.as_str()) + && identity.identity_type() == self.identity_type + && identity.id() == self.id + } +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct InputRecord { + request_id: String, + expires_at_ms: u64, + module_id: String, + module_version: String, + caller_id: Option, + owner: DirectOwner, + arguments: Map, +} + +impl InputRecord { + fn parse(value: &Value) -> Option { + // The stored record is closed and requires an explicit caller_id, + // whose value may be null. Serde would otherwise default a missing + // Option field to None. + value.as_object()?.get("caller_id")?; + let record = Self::deserialize(value).ok()?; + (valid_request_id(&record.request_id) + && valid_expiry(record.expires_at_ms) + && !record.module_id.is_empty() + && !record.module_version.is_empty() + && record + .caller_id + .as_ref() + .is_none_or(|caller| !caller.is_empty()) + && [REQUEST_ID_KEY, ANSWER_KEY, APPROVAL_TOKEN_KEY] + .iter() + .all(|key| !record.arguments.contains_key(*key))) + .then_some(record) + } +} + +fn valid_request_id(id: &str) -> bool { + id.len() == 32 + && id + .bytes() + .all(|byte| matches!(byte, b'0'..=b'9' | b'a'..=b'f')) +} + +fn valid_expiry(expires_at_ms: u64) -> bool { + (1..=MAX_TIME_MS).contains(&expires_at_ms) +} + +fn unavailable() -> ModuleError { + ModuleError::new_custom(INPUT_UNAVAILABLE_CODE, "The input request is unavailable") + .expect("the durable input error code is reserved by this extension") + .with_retryable(false) +} + +/// Detached arguments and binding for a fresh, ordinarily governed Core call. +/// +/// The host composes [`Self::matches`] into its post-validation policy for the +/// target module and rechecks the live request in its effect transaction. +pub struct InputResume { + module_id: String, + module_version: String, + caller_id: Option, + expires_at_ms: u64, + owner: DirectOwner, + arguments: Value, + arguments_digest: String, +} + +impl fmt::Debug for InputResume { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter + .debug_struct("InputResume") + .finish_non_exhaustive() + } +} + +impl InputResume { + /// ID of the module that the host should call afresh. + #[must_use] + pub fn module_id(&self) -> &str { + &self.module_id + } + + /// A detached argument copy. Add a fresh approval token, if needed, only + /// to this copy before sending the normal call. + #[must_use] + pub fn arguments(&self) -> Value { + self.arguments.clone() + } + + /// Check the live final policy input and expiration without I/O. + /// + /// Current ACL and approval still determine what the direct actor may do. + /// The comparison binds the actor's issuer, type and ID. + #[must_use] + pub fn matches(&self, policy_request: &PolicyEvaluationRequest, now_ms: i64) -> bool { + u64::try_from(now_ms).is_ok_and(|now| now < self.expires_at_ms) + && policy_request.module_id == self.module_id + && policy_request.module_version.as_deref() == Some(self.module_version.as_str()) + && policy_request.caller_id == self.caller_id + && policy_request + .identity + .as_ref() + .is_some_and(|identity| self.owner.matches(identity)) + && final_arguments_digest(&policy_request.arguments) + .is_ok_and(|digest| digest == self.arguments_digest) + } +} + +/// Prepare a fresh call from a host-owned persisted input record. +/// +/// `Value::Null` represents a missing record. The identity must come from the +/// current trusted authentication, and `caller_id` must be the effective caller +/// the final policy will see. No credentials are restored from the record. +pub fn prepare_input_resume( + record: &Value, + answer: &Value, + identity: &Identity, + caller_id: Option<&str>, + now_ms: i64, +) -> Result { + let now_ms = u64::try_from(now_ms) + .ok() + .filter(|now| *now <= MAX_TIME_MS) + .ok_or_else(|| ModuleError::invalid_input("Invalid input request clock"))?; + final_arguments_digest(answer) + .map_err(|_| ModuleError::invalid_input("Input answer is not canonical JSON"))?; + let record = InputRecord::parse(record).ok_or_else(unavailable)?; + if now_ms >= record.expires_at_ms + || record.caller_id.as_deref() != caller_id + || !record.owner.matches(identity) + { + return Err(unavailable()); + } + let mut arguments = record.arguments; + arguments.insert(REQUEST_ID_KEY.to_owned(), Value::String(record.request_id)); + arguments.insert(ANSWER_KEY.to_owned(), answer.clone()); + let arguments = Value::Object(arguments); + // The answer already passed canonicalization, so any failure here was + // introduced by the persisted business arguments. + let arguments_digest = final_arguments_digest(&arguments).map_err(|_| unavailable())?; + Ok(InputResume { + module_id: record.module_id, + module_version: record.module_version, + caller_id: record.caller_id, + expires_at_ms: record.expires_at_ms, + owner: record.owner, + arguments, + arguments_digest, + }) +} diff --git a/rust/src/lib.rs b/rust/src/lib.rs index 34fba3a3..579afabe 100644 --- a/rust/src/lib.rs +++ b/rust/src/lib.rs @@ -27,6 +27,7 @@ pub mod context; pub mod context_key; pub mod context_keys; pub mod decorator; +pub mod durable_input; pub mod error_formatter; pub mod errors; pub mod events; @@ -109,6 +110,7 @@ pub use context_keys::{ TRACING_SPANS, }; pub use decorator::FunctionModule; +pub use durable_input::{prepare_input_resume, InputRequiredError, InputResume}; pub use error_formatter::{ErrorFormatter, ErrorFormatterRegistry}; pub use errors::{ ErrorCode, ErrorCodeRegistry, ModuleError, VersionIncompatibleError, diff --git a/rust/tests/durable_input_spec.rs b/rust/tests/durable_input_spec.rs new file mode 100644 index 00000000..513ba509 --- /dev/null +++ b/rust/tests/durable_input_spec.rs @@ -0,0 +1,380 @@ +//! Opt-in durable input contract at preparation and actual Core policy entry. + +use std::sync::atomic::{AtomicI64, AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex}; + +use apcore::{ + prepare_input_resume, ApprovalHandler, ApprovalRequest, ApprovalResult, Config, Context, + ErrorCode, Executor, Identity, InputRequiredError, InputResume, Module, ModuleError, + PolicyEffect, PolicyEvaluationRequest, PolicyEvaluator, PolicyVerdict, Registry, ACL, +}; +use async_trait::async_trait; +use serde_json::{json, Value}; + +const REQUEST_ID: &str = "9b0b9d7134364bd4a37e55a137f094c3"; +const MODULE_ID: &str = "delivery.confirm"; +const VERSION: &str = "1.2.3"; +const EXPIRES_AT: u64 = 2000; +const CREDENTIAL: &str = "fixture-approval-credential"; + +#[test] +fn public_required_error_exposes_only_request_metadata() { + let public = InputRequiredError::new(REQUEST_ID, EXPIRES_AT).unwrap(); + assert_eq!(public.expires_at_ms(), EXPIRES_AT); + assert_eq!(public.request_id(), REQUEST_ID); + assert_eq!(public.to_string(), "Additional input is required"); + let wire = ModuleError::from(public).to_dict(); + assert_eq!(wire["code"], "INPUT_REQUIRED"); + assert_eq!(wire["message"], "Additional input is required"); + assert_eq!(wire["retryable"], false); + assert_eq!( + wire["details"], + json!({"request_id": REQUEST_ID, "expires_at_ms": EXPIRES_AT}) + ); + assert!(InputRequiredError::new("private-metadata", EXPIRES_AT).is_err()); + assert!(InputRequiredError::new(REQUEST_ID, 0).is_err()); +} + +#[test] +fn shared_cases_prepare_and_compare_detached_arguments() { + let path = crate::conformance_env::find_fixtures_root().join("durable_input.json"); + let fixture: Value = serde_json::from_reader(std::fs::File::open(path).unwrap()).unwrap(); + for test in fixture["test_cases"].as_array().unwrap() { + let name = test["id"].as_str().unwrap(); + let record = &test["record"]; + let identity: Identity = serde_json::from_value(test["identity"].clone()).unwrap(); + let caller = test["caller_id"].as_str(); + let now = test["now_ms"].as_i64().unwrap(); + let result = prepare_input_resume(record, &test["answer"], &identity, caller, now); + match test["expected"].as_str().unwrap() { + "ready" => { + let resume = result.unwrap_or_else(|error| panic!("{name}: {error}")); + assert_eq!( + resume.module_id(), + record["module_id"].as_str().unwrap(), + "{name}" + ); + assert_eq!(resume.arguments(), test["arguments"], "{name}"); + let mut altered = resume.arguments(); + altered["answer"] = json!("replacement"); + assert_ne!(resume.arguments(), altered); + let request = PolicyEvaluationRequest { + module_id: resume.module_id().to_owned(), + module_version: record["module_version"].as_str().map(str::to_owned), + caller_id: caller.map(str::to_owned), + identity: Some(identity.clone()), + arguments: resume.arguments(), + sensitive_fields: vec![], + }; + assert!(resume.matches(&request, now), "{name}"); + for mismatch in [ + PolicyEvaluationRequest { + arguments: altered, + ..request.clone() + }, + PolicyEvaluationRequest { + module_version: Some("different".into()), + ..request.clone() + }, + PolicyEvaluationRequest { + module_version: None, + ..request.clone() + }, + PolicyEvaluationRequest { + module_id: "different.module".into(), + ..request.clone() + }, + PolicyEvaluationRequest { + identity: None, + ..request.clone() + }, + PolicyEvaluationRequest { + caller_id: Some("different.caller".into()), + ..request.clone() + }, + ] { + assert!(!resume.matches(&mismatch, now), "{name}"); + } + assert!( + !resume.matches(&request, record["expires_at_ms"].as_i64().unwrap()), + "{name}" + ); + assert!(!resume.matches(&request, -1), "{name}"); + } + "unavailable" => { + let error = result.unwrap_err(); + assert_eq!(error.wire_code(), "INPUT_RESUME_UNAVAILABLE", "{name}"); + assert!(error.to_dict().get("details").is_none(), "{name}"); + } + "invalid" => assert_eq!( + result.unwrap_err().code, + ErrorCode::GeneralInvalidInput, + "{name}" + ), + other => panic!("unknown expectation {other}"), + } + } +} + +fn persisted_record() -> Value { + json!({ + "request_id": REQUEST_ID, "expires_at_ms": EXPIRES_AT, + "module_id": MODULE_ID, "module_version": VERSION, "caller_id": null, + "owner": {"issuer": "fixture", "type": "user", "id": "alice"}, + "arguments": {"job": "job-1"} + }) +} + +fn identity(scopes: &[&str]) -> Identity { + Identity::new( + "alice".into(), + "user".into(), + vec!["dispatcher".into()], + Default::default(), + ) + .with_authority( + Some(scopes.iter().map(|s| (*s).to_owned()).collect()), + Some("fixture".into()), + ) + .unwrap() +} + +#[test] +fn preparation_rejects_delegation_missing_caller_and_unsafe_stored_arguments() { + let actor = identity(&["dispatch"]); + let delegate = actor + .delegate(actor.clone(), vec!["dispatch".into()]) + .unwrap(); + let inaccessible = + prepare_input_resume(&persisted_record(), &Value::Null, &delegate, None, 200); + assert_eq!( + inaccessible.unwrap_err().wire_code(), + "INPUT_RESUME_UNAVAILABLE" + ); + + let mut bad_record = persisted_record(); + bad_record.as_object_mut().unwrap().remove("caller_id"); + let inaccessible = prepare_input_resume(&bad_record, &Value::Null, &actor, None, 200); + assert_eq!( + inaccessible.unwrap_err().wire_code(), + "INPUT_RESUME_UNAVAILABLE" + ); + + let mut bad_record = persisted_record(); + bad_record["arguments"]["unsafe"] = json!(9_007_199_254_740_992_i64); + let inaccessible = prepare_input_resume(&bad_record, &Value::Null, &actor, None, 200); + assert_eq!( + inaccessible.unwrap_err().wire_code(), + "INPUT_RESUME_UNAVAILABLE" + ); +} + +struct ProtectedModule(AtomicUsize); + +#[async_trait] +impl Module for ProtectedModule { + fn input_schema(&self) -> Value { + json!({ + "type":"object", + "properties":{"input_request_id":{"type":"string"},"answer":{"type":"string"},"job":{"type":"string"}}, + "required":["input_request_id","answer","job"],"additionalProperties":false + }) + } + + fn output_schema(&self) -> Value { + json!({"type":"object"}) + } + + fn description(&self) -> &'static str { + "Protected input fixture" + } + + fn version(&self) -> Option<&str> { + Some(VERSION) + } + + async fn execute(&self, args: Value, _: &Context) -> Result { + Ok(json!({"calls": self.0.fetch_add(1, Ordering::Relaxed) + 1, "received": args})) + } +} + +struct Guard { + resume: InputResume, + now: AtomicI64, +} + +#[async_trait] +impl PolicyEvaluator for Guard { + async fn evaluate( + &self, + request: &PolicyEvaluationRequest, + ) -> Result { + let decision = if self + .resume + .matches(request, self.now.load(Ordering::Relaxed)) + { + PolicyEffect::RequireApproval + } else { + PolicyEffect::Deny + }; + Ok(PolicyVerdict { + decision, + rule_id: None, + }) + } +} + +fn approval_scope(request: &ApprovalRequest) -> Value { + json!([ + request.authority_key(), + request.module_id, + request.module_version, + request.caller_id, + request.canonical_args_digest, + ]) +} + +#[derive(Debug, Default)] +struct Approver { + pending: Mutex>, + checks: AtomicUsize, +} + +#[async_trait] +impl ApprovalHandler for Approver { + fn supports_final_scope(&self) -> bool { + true + } + + fn supports_authority_scope(&self) -> bool { + true + } + + async fn request_approval( + &self, + request: &ApprovalRequest, + ) -> Result { + *self.pending.lock().unwrap() = Some(approval_scope(request)); + let mut result = ApprovalResult::default(); + result.status = "pending".into(); + result.approval_id = Some(CREDENTIAL.into()); + Ok(result) + } + + async fn check_approval(&self, _: &str) -> Result { + panic!("unscoped approval status must not authorize execution") + } + + async fn check_approval_for_call( + &self, + token: &str, + request: &ApprovalRequest, + ) -> Result { + self.checks.fetch_add(1, Ordering::Relaxed); + let mut pending = self.pending.lock().unwrap(); + if token != CREDENTIAL || pending.as_ref() != Some(&approval_scope(request)) { + return Ok(ApprovalResult::rejected("scope did not match")); + } + pending.take(); + Ok(ApprovalResult::approved("reviewer")) + } +} + +#[tokio::test] +async fn real_pipeline_rechecks_current_acl_validation_policy_and_scoped_approval() { + let actor = identity(&["dispatch"]); + let context = Context::new(actor.clone()); + let record = persisted_record(); + let resume = prepare_input_resume(&record, &json!("north"), &actor, None, 1000).unwrap(); + let inputs = resume.arguments(); + let guard = Arc::new(Guard { + resume, + now: AtomicI64::new(1000), + }); + let approver = Arc::new(Approver::default()); + let registry = Registry::new(); + registry + .register_module(MODULE_ID, Box::new(ProtectedModule(AtomicUsize::new(0)))) + .unwrap(); + let mut executor = Executor::new(registry, Config::default()); + executor.set_acl(ACL::new( + serde_json::from_value(json!([{ + "effect": "allow", "callers": ["@external"], "targets": [MODULE_ID], + "conditions": {"scopes": ["dispatch"]} + }])) + .unwrap(), + "deny", + None, + )); + executor.set_policy_evaluator(Some(guard.clone())).unwrap(); + executor.set_approval_handler_shared(approver.clone()); + + let preflight = executor + .validate(MODULE_ID, &inputs, Some(&context)) + .await + .unwrap(); + assert!(preflight.requires_approval, "{preflight:?}"); + assert!(approver.pending.lock().unwrap().is_none()); + let mut invalid = inputs.clone(); + invalid["answer"] = json!(7); + let error = executor + .call(MODULE_ID, invalid, Some(&context), None) + .await + .unwrap_err(); + assert_eq!(error.code, ErrorCode::SchemaValidationError); + + let reduced = identity(&[]); + assert!(prepare_input_resume(&record, &json!("north"), &reduced, None, 1000).is_ok()); + let reduced = Context::new(reduced); + let denied = executor + .call(MODULE_ID, inputs.clone(), Some(&reduced), None) + .await + .unwrap_err(); + assert_eq!(denied.code, ErrorCode::ACLDenied); + + let pending = executor + .call(MODULE_ID, inputs.clone(), Some(&context), None) + .await + .unwrap_err(); + assert_eq!(pending.code, ErrorCode::ApprovalPending); + assert_eq!(pending.details["approval_id"], CREDENTIAL); + let mut changed = inputs.clone(); + changed["answer"] = json!("south"); + changed["_approval_token"] = pending.details["approval_id"].clone(); + let denied = executor + .call(MODULE_ID, changed, Some(&context), None) + .await + .unwrap_err(); + assert_eq!(denied.code, ErrorCode::PolicyDenied); + assert_eq!(approver.checks.load(Ordering::Relaxed), 0); + + let mut mismatched_token = inputs.clone(); + mismatched_token["_approval_token"] = json!(REQUEST_ID); + let denied = executor + .call(MODULE_ID, mismatched_token, Some(&context), None) + .await + .unwrap_err(); + assert_eq!(denied.code, ErrorCode::ApprovalDenied); + let mut approved = inputs.clone(); + approved["_approval_token"] = pending.details["approval_id"].clone(); + let output = executor + .call(MODULE_ID, approved.clone(), Some(&context), None) + .await + .unwrap(); + assert_eq!(output, json!({"calls": 1, "received": inputs})); + assert_eq!(approver.checks.load(Ordering::Relaxed), 2); + let denied = executor + .call(MODULE_ID, approved, Some(&context), None) + .await + .unwrap_err(); + assert_eq!(denied.code, ErrorCode::ApprovalDenied); + + guard + .now + .store(i64::try_from(EXPIRES_AT).unwrap(), Ordering::Relaxed); + let expired = executor + .call(MODULE_ID, inputs, Some(&context), None) + .await + .unwrap_err(); + assert_eq!(expired.code, ErrorCode::PolicyDenied); +} diff --git a/rust/tests/it.rs b/rust/tests/it.rs index 7401ab86..d146f630 100644 --- a/rust/tests/it.rs +++ b/rust/tests/it.rs @@ -48,6 +48,8 @@ mod core_executor_spec; mod decorator_bindings_spec; #[path = "deep_chain_v150_spec.rs"] mod deep_chain_v150_spec; +#[path = "durable_input_spec.rs"] +mod durable_input_spec; #[path = "error_formatter_registry.rs"] mod error_formatter_registry; #[path = "error_system_spec.rs"] diff --git a/typescript/src/browser/index.ts b/typescript/src/browser/index.ts index c96289a6..48388e2a 100644 --- a/typescript/src/browser/index.ts +++ b/typescript/src/browser/index.ts @@ -170,6 +170,9 @@ export { jsonSchemaToTypeBox, contentHashAsync, } from '../schema/loader-pure.js'; +export { InputRequiredError, prepareInputResume } from '../durable-input.js'; +export type { InputResume } from '../durable-input.js'; + export { parseArtifactRef, readArtifact } from '../artifact.js'; export type { ArtifactRef, ArtifactContent, ArtifactStore } from '../artifact.js'; diff --git a/typescript/src/durable-input.ts b/typescript/src/durable-input.ts new file mode 100644 index 00000000..5163f7ba --- /dev/null +++ b/typescript/src/durable-input.ts @@ -0,0 +1,119 @@ +/** Prepare a fresh governed call from a host-owned input request. */ +import { InvalidInputError, ModuleError } from './errors.js'; +import { isTrustedIdentity, type Identity } from './identity.js'; +import { snapshotJsonObject, type PolicyEvaluationRequest } from './policy-evaluation.js'; + +const REQUEST_ID = /^[a-f0-9]{32}$/; +const RECORD_FIELDS = ['request_id', 'expires_at_ms', 'module_id', 'module_version', 'caller_id', 'owner', 'arguments']; +const OWNER_FIELDS = ['issuer', 'type', 'id']; +const RESERVED_ARGUMENTS = ['input_request_id', 'answer', '_approval_token']; + +/** A request for additional input, persisted by the host before reporting it. */ +export class InputRequiredError extends ModuleError { + static override readonly DEFAULT_RETRYABLE = false; + + constructor(requestId: string, expiresAtMs: number) { + if (!validRequestId(requestId) || !validClock(expiresAtMs) || expiresAtMs === 0) { + throw new InvalidInputError('Invalid input request metadata'); + } + super('INPUT_REQUIRED', 'Additional input is required', + Object.freeze({ request_id: requestId, expires_at_ms: expiresAtMs })); + this.name = 'InputRequiredError'; + } +} + +/** A detached argument snapshot and its final post-validation policy guard. */ +export interface InputResume { + readonly moduleId: string; + /** Each access returns a separate copy for a fresh invocation. */ + readonly arguments: Record; + matches(request: PolicyEvaluationRequest, nowMs: number): boolean; +} + +function validRequestId(value: unknown): value is string { + return typeof value === 'string' && value.length === 32 && REQUEST_ID.test(value); +} + +function validClock(value: unknown): value is number { + return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0; +} + +function hasText(value: unknown): value is string { + return typeof value === 'string' && value.length > 0; +} + +function isRecord(value: unknown): value is Record { + return value !== null && typeof value === 'object' && !Array.isArray(value); +} + +function hasExactly(record: Record, keys: readonly string[]): boolean { + return Object.keys(record).length === keys.length && keys.every((key) => Object.hasOwn(record, key)); +} + +function matchesOwner(identity: Identity | null, owner: Record): boolean { + return isTrustedIdentity(identity) && identity.onBehalfOf === undefined && + identity.issuer === owner['issuer'] && identity.type === owner['type'] && identity.id === owner['id']; +} + +function unavailable(): ModuleError { + return new ModuleError('INPUT_RESUME_UNAVAILABLE', 'The input request is unavailable', + undefined, undefined, undefined, false); +} + +function parseRecord(value: unknown) { + let record: Record; + try { + record = snapshotJsonObject(value).arguments; + } catch { + throw unavailable(); + } + const { + request_id: requestId, expires_at_ms: expiresAtMs, module_id: moduleId, + module_version: moduleVersion, caller_id: callerId, owner, arguments: businessArgs, + } = record; + if (!hasExactly(record, RECORD_FIELDS) || !validRequestId(requestId) || !validClock(expiresAtMs) || expiresAtMs === 0 || + !hasText(moduleId) || !hasText(moduleVersion) || (callerId !== null && !hasText(callerId)) || + !isRecord(owner) || !hasExactly(owner, OWNER_FIELDS) || !OWNER_FIELDS.every((key) => hasText(owner[key])) || + !isRecord(businessArgs) || RESERVED_ARGUMENTS.some((key) => Object.hasOwn(businessArgs, key))) { + throw unavailable(); + } + return { requestId, expiresAtMs, moduleId, moduleVersion, callerId, owner, businessArgs }; +} + +/** Bind a submitted answer to current authentication and a fresh Core invocation. */ +export function prepareInputResume( + record: unknown, + answer: unknown, + identity: Identity | null, + callerId: string | null, + nowMs: number, +): InputResume { + if (!validClock(nowMs)) throw new InvalidInputError('Invalid input resume clock'); + const { requestId, expiresAtMs, moduleId, moduleVersion, callerId: expectedCaller, owner, businessArgs } = parseRecord(record); + if (nowMs >= expiresAtMs || callerId !== expectedCaller || !matchesOwner(identity, owner)) throw unavailable(); + + let snapshot: ReturnType; + try { + snapshot = snapshotJsonObject({ ...businessArgs, input_request_id: requestId, answer }); + } catch { + throw new InvalidInputError('The submitted answer is not a canonical JSON value'); + } + const canonical = snapshot.canonical.join(''); + const argumentsSnapshot = snapshot.arguments; + const resume: InputResume = { + moduleId, + get arguments() { return structuredClone(argumentsSnapshot); }, + matches(request: PolicyEvaluationRequest, nowMs: number): boolean { + if (!validClock(nowMs) || nowMs >= expiresAtMs) return false; + try { + return request.moduleId === moduleId && request.moduleVersion === moduleVersion && + request.callerId === expectedCaller && matchesOwner(request.identity, owner) && !request.signal.aborted && + snapshotJsonObject(request.arguments).canonical.join('') === canonical; + } catch { + return false; + } + }, + }; + Object.defineProperty(resume, 'arguments', { enumerable: false }); + return Object.freeze(resume); +} diff --git a/typescript/src/node-api.ts b/typescript/src/node-api.ts index c5b33c43..794f5332 100644 --- a/typescript/src/node-api.ts +++ b/typescript/src/node-api.ts @@ -290,6 +290,9 @@ export { // Version export { negotiateVersion, VersionIncompatibleError } from './version.js'; +export { InputRequiredError, prepareInputResume } from './durable-input.js'; +export type { InputResume } from './durable-input.js'; + export { parseArtifactRef, readArtifact } from './artifact.js'; export type { ArtifactRef, ArtifactContent, ArtifactStore } from './artifact.js'; diff --git a/typescript/tests/conformance-durable-input.test.ts b/typescript/tests/conformance-durable-input.test.ts new file mode 100644 index 00000000..db428b3c --- /dev/null +++ b/typescript/tests/conformance-durable-input.test.ts @@ -0,0 +1,201 @@ +import { readFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { Type } from '@sinclair/typebox'; +import { describe, expect, it, vi } from 'vitest'; +import { + ACL, Context, createAnnotations, createApprovalResult, Executor, Identity, InputRequiredError, + prepareInputResume, Registry, type ApprovalHandler, type ApprovalRequest, type PolicyEvaluationRequest, +} from '../src/index.js'; +import { findFixturesRoot } from './spec-repo.js'; + +interface IdentityFixture { id: string; type: string; roles?: string[]; issuer?: string } +interface Case { + id: string; + record: unknown; + identity: IdentityFixture | null; + caller_id: string | null; + answer: unknown; + now_ms: number; + expected: 'ready' | 'unavailable' | 'invalid'; + arguments?: Record; +} +const fixture = JSON.parse(readFileSync(join(findFixturesRoot(), 'durable_input.json'), 'utf8')) as { test_cases: Case[] }; +const requestId = '9b0b9d7134364bd4a37e55a137f094c3'; +const moduleId = 'delivery.confirm'; +const version = '1.2.3'; +const expiry = 2000; +const now = 1999; +const principal = (roles = ['dispatcher']) => new Identity('alice', 'user', roles, {}, { issuer: 'fixture' }); +const durableRecord = () => ({ + request_id: requestId, expires_at_ms: expiry, module_id: moduleId, module_version: version, + caller_id: null, owner: { issuer: 'fixture', type: 'user', id: 'alice' }, + arguments: { job: 'job-1', options: { priority: true, optionsVersion: 0 } }, +}); + +function policyRequest(args: Record): PolicyEvaluationRequest { + return { + moduleId, moduleVersion: version, callerId: null, identity: principal(), arguments: args, + sensitiveFields: [], signal: new AbortController().signal, + }; +} + +describe('durable_input.json', () => { + for (const trial of fixture.test_cases) { + it(trial.id, () => { + const identity = trial.identity && new Identity( + trial.identity.id, trial.identity.type, trial.identity.roles, {}, { issuer: trial.identity.issuer }, + ); + const prepare = () => prepareInputResume(trial.record, trial.answer, identity, trial.caller_id, trial.now_ms); + if (trial.expected === 'ready') { + const resume = prepare(); + expect(resume.moduleId).toBe(moduleId); + expect(resume.arguments).toEqual(trial.arguments); + expect(resume.matches({ ...policyRequest(resume.arguments), identity, callerId: trial.caller_id }, trial.now_ms)).toBe(true); + } else { + expect(prepare).toThrow(expect.objectContaining({ + code: trial.expected === 'unavailable' ? 'INPUT_RESUME_UNAVAILABLE' : 'GENERAL_INVALID_INPUT', + })); + } + }); + } +}); + +describe('durable input bindings', () => { + it('serializes the pending error with correlator and expiry only', () => { + const error = new InputRequiredError(requestId, expiry); + const wire = error.toJSON(); + expect(wire).toEqual({ code: 'INPUT_REQUIRED', message: 'Additional input is required', + details: { request_id: requestId, expires_at_ms: expiry }, timestamp: expect.any(String), retryable: false }); + expect(Object.isFrozen(error.details)).toBe(true); + expect(() => new InputRequiredError('secret-invalid-id', expiry)).toThrow(expect.objectContaining({ code: 'GENERAL_INVALID_INPUT' })); + expect(() => new InputRequiredError(requestId, 0)).toThrow(expect.objectContaining({ code: 'GENERAL_INVALID_INPUT' })); + }); + + it('keeps detached arguments bound by exact canonical equality', () => { + const record = durableRecord(); + const answer = { values: ['north', false] }; + const resume = prepareInputResume(record, answer, principal(), null, now); + const pristine = resume.arguments; + expect(JSON.stringify(resume)).not.toContain('job-1'); + record.arguments.options.priority = false; + answer.values[0] = 'east'; + (resume.arguments.options as typeof record.arguments.options).priority = false; + expect(resume.arguments).toEqual(pristine); + const reordered = { answer: { values: ['north', false] }, job: 'job-1', input_request_id: requestId, + options: { optionsVersion: 0, priority: true } }; + const request = policyRequest(reordered); + expect(resume.matches(request, now)).toBe(true); + expect(resume.matches({ ...request, arguments: { ...reordered, options: { ...reordered.options, optionsVersion: -0 } } }, now)).toBe(false); + expect(resume.matches({ ...request, arguments: { ...reordered, _approval_token: 'approval' } }, now)).toBe(false); + expect(resume.matches({ ...request, moduleId: 'other.module' }, now)).toBe(false); + expect(resume.matches({ ...request, moduleVersion: '1.2.4' }, now)).toBe(false); + expect(resume.matches({ ...request, moduleVersion: null }, now)).toBe(false); + expect(resume.matches({ ...request, callerId: 'other.caller' }, now)).toBe(false); + expect(resume.matches({ ...request, identity: null }, now)).toBe(false); + expect(resume.matches(request, expiry)).toBe(false); + expect(resume.matches(request, NaN)).toBe(false); + const terminal = new AbortController(); + terminal.abort(); + expect(resume.matches({ ...request, signal: terminal.signal }, now)).toBe(false); + }); + + it('rejects delegated or fabricated principals and keeps rejected record data out of errors', () => { + const actor = new Identity('alice', 'user', [], {}, { issuer: 'fixture', scopes: ['delivery.confirm'] }); + const subject = new Identity('other', 'user', [], {}, { issuer: 'fixture', scopes: ['delivery.confirm'] }); + const delegated = subject.delegate(actor, ['delivery.confirm']); + const record = durableRecord(); + for (const identity of [delegated, null, { id: 'alice', type: 'user', issuer: 'fixture' } as Identity]) { + expect(() => prepareInputResume(record, 'north', identity, null, now)).toThrow( + expect.objectContaining({ code: 'INPUT_RESUME_UNAVAILABLE', details: {} }), + ); + } + const unread = vi.fn(() => record.owner); + const computed = Object.defineProperty({ ...record }, 'owner', { get: unread, enumerable: true }); + expect(() => prepareInputResume(computed, 'north', actor, null, now)).toThrow( + expect.objectContaining({ code: 'INPUT_RESUME_UNAVAILABLE', details: {} }), + ); + expect(unread).not.toHaveBeenCalled(); + const resume = prepareInputResume(record, 'north', actor, null, now); + expect(resume.matches({ ...policyRequest(resume.arguments), identity: delegated }, now)).toBe(false); + expect(() => prepareInputResume(record, BigInt(10), principal(), null, now)).toThrow( + expect.objectContaining({ code: 'GENERAL_INVALID_INPUT', details: {} }), + ); + }); +}); + +const inputSchema = Type.Object({ + job: Type.String(), options: Type.Object({ priority: Type.Boolean(), optionsVersion: Type.Integer() }), + input_request_id: Type.String(), answer: Type.String({ minLength: 1 }), +}, { additionalProperties: false }); +async function registered(requiresApproval = false) { + const registry = new Registry(); + const execute = vi.fn((args: Record) => ({ receipt: args['answer'] })); + await registry.register(moduleId, { description: 'Confirm a delivery', inputSchema, + outputSchema: Type.Object({ receipt: Type.String() }), annotations: createAnnotations({ requiresApproval }), execute }, version); + return { registry, execute }; +} + +describe('durable input on the governed pipeline', () => { + it('enforces ACL, schema, selected version, validated arguments and live expiry before the effect', async () => { + const { registry, execute } = await registered(); + const actor = principal(); + let resume = prepareInputResume(durableRecord(), 'north', actor, null, now); + let clock = now; + const evaluate = vi.fn(async (request: PolicyEvaluationRequest) => ({ decision: resume.matches(request, clock) ? 'allow' : 'deny' } as const)); + const acl = new ACL([{ callers: ['*'], targets: [moduleId], effect: 'allow', description: '', conditions: { roles: ['dispatcher'] } }], 'deny'); + const executor = new Executor({ registry, acl, policyEvaluator: { evaluate } }); + expect((await executor.validate(moduleId, resume.arguments, Context.create(actor))).valid).toBe(true); + expect(execute).not.toHaveBeenCalled(); + await expect(executor.call(moduleId, resume.arguments, Context.create(actor))).resolves.toEqual({ receipt: 'north' }); + await expect(executor.call(moduleId, resume.arguments, Context.create(principal([])))).rejects.toMatchObject({ code: 'ACL_DENIED' }); + expect(evaluate).toHaveBeenCalledTimes(2); + const invalid = prepareInputResume(durableRecord(), [], actor, null, now); + await expect(executor.call(moduleId, invalid.arguments, Context.create(actor))).rejects.toMatchObject({ code: 'SCHEMA_VALIDATION_ERROR' }); + await expect(executor.call(moduleId, { ...resume.arguments, answer: 'east' }, Context.create(actor))).rejects.toMatchObject({ code: 'POLICY_DENIED' }); + resume = prepareInputResume({ ...durableRecord(), module_version: '1.4.0' }, 'north', actor, null, now); + await expect(executor.call(moduleId, resume.arguments, Context.create(actor))).rejects.toMatchObject({ code: 'POLICY_DENIED' }); + resume = prepareInputResume(durableRecord(), 'north', actor, null, now); + clock = expiry; + await expect(executor.call(moduleId, resume.arguments, Context.create(actor))).rejects.toMatchObject({ code: 'POLICY_DENIED' }); + clock = now; + const rewritten = new Executor({ registry, acl, policyEvaluator: { evaluate } }); + rewritten.useBefore((_id, args) => ({ ...args, answer: 'east' })); + await expect(rewritten.call(moduleId, resume.arguments, Context.create(actor))).rejects.toMatchObject({ code: 'POLICY_DENIED' }); + expect(evaluate.mock.lastCall?.[0].arguments['answer']).toBe('east'); + expect(execute).toHaveBeenCalledOnce(); + }); + + it('requires a fresh scoped approval and never treats the input ID as a credential', async () => { + const { registry, execute } = await registered(true); + const actor = principal(); + let resume = prepareInputResume(durableRecord(), 'north', actor, null, now); + let pending: ApprovalRequest | undefined; + const token = 'new-approval'; + const checkApprovalForCall = vi.fn>(async (credential, attempt) => + createApprovalResult({ status: credential === token && attempt.moduleId === pending?.moduleId && + attempt.moduleVersion === pending?.moduleVersion && attempt.callerId === pending?.callerId && + attempt.context.identity?.id === pending?.context.identity?.id && + attempt.context.identity?.issuer === pending?.context.identity?.issuer && + attempt.canonicalArgsDigest === pending?.canonicalArgsDigest ? 'approved' : 'rejected' })); + const approvalHandler: ApprovalHandler = { + supportsFinalScope: true, + async requestApproval(request) { pending = request; return createApprovalResult({ status: 'pending', approvalId: token }); }, + async checkApproval() { throw new Error('Status-only approval cannot authorize the call'); }, + checkApprovalForCall, + }; + const executor = new Executor({ registry, approvalHandler, policyEvaluator: { + async evaluate(request) { return { decision: resume.matches(request, now) ? 'allow' : 'deny' }; }, + } }); + await expect(executor.call(moduleId, resume.arguments, Context.create(actor))).rejects.toMatchObject({ code: 'APPROVAL_PENDING' }); + await expect(executor.call(moduleId, { ...resume.arguments, _approval_token: requestId }, Context.create(actor))).rejects.toMatchObject({ code: 'APPROVAL_DENIED' }); + await expect(executor.call(moduleId, { ...resume.arguments, answer: 'east', _approval_token: token }, Context.create(actor))).rejects.toMatchObject({ code: 'POLICY_DENIED' }); + expect(execute).not.toHaveBeenCalled(); + await expect(executor.call(moduleId, { ...resume.arguments, _approval_token: token }, Context.create(actor))).resolves.toEqual({ receipt: 'north' }); + expect(execute).toHaveBeenCalledOnce(); + expect(resume.arguments).not.toHaveProperty('_approval_token'); + resume = prepareInputResume({ ...durableRecord(), request_id: 'a'.repeat(32) }, 'north', actor, null, now); + await expect(executor.call(moduleId, { ...resume.arguments, _approval_token: token }, Context.create(actor))).rejects.toMatchObject({ code: 'APPROVAL_DENIED' }); + expect(checkApprovalForCall).toHaveBeenCalledTimes(3); + expect(execute).toHaveBeenCalledOnce(); + }); +}); From 8ee0fc5c7a1767d8ea958668cc79598fe1679229 Mon Sep 17 00:00:00 2001 From: tercel Date: Sun, 29 Nov 2026 19:36:45 +0800 Subject: [PATCH 4/6] Close Atlas schema validation and CI review gaps Signed-off-by: tercel --- .github/workflows/sdk-rust.yml | 2 +- docs/spec/conformance.md | 6 ++- examples/python/durable-input/README.md | 12 +++--- .../python/durable-input/durable_input.py | 2 +- examples/python/durable-input/verify.py | 2 +- planning/atlas-artifact-reference/contract.md | 2 + python/src/apcore/schema/loader.py | 8 ++-- python/src/apcore/schema/validator.py | 27 ++++++++++++- python/tests/test_artifact_reference.py | 19 ++++++++- rust/tests/artifact_reference_spec.rs | 2 +- rust/tests/durable_input_spec.rs | 2 +- typescript/src/registry/registry.ts | 39 ++++++++++++------- typescript/src/schema/artifact-reference.ts | 5 +++ typescript/src/schema/loader-pure.ts | 3 +- .../conformance-artifact-reference.test.ts | 9 +++++ .../registry/test-output-declaration.test.ts | 13 ++++++- 16 files changed, 119 insertions(+), 34 deletions(-) diff --git a/.github/workflows/sdk-rust.yml b/.github/workflows/sdk-rust.yml index 3f1e121b..bfb01316 100644 --- a/.github/workflows/sdk-rust.yml +++ b/.github/workflows/sdk-rust.yml @@ -73,7 +73,7 @@ jobs: env: CONFORMANCE_SPEC_REPO: ${{ github.workspace }} - - uses: actions/setup-node@v4 + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4 if: matrix.rust == 'stable' with: node-version: '22' diff --git a/docs/spec/conformance.md b/docs/spec/conformance.md index 80aafe28..4aefd476 100644 --- a/docs/spec/conformance.md +++ b/docs/spec/conformance.md @@ -326,7 +326,7 @@ The following requirements are not met by the SDK implementations in this reposi ## 8. Conformance Test Fixtures -The repository ships **102 cross-language fixture files** under `conformance/fixtures/` covering **1272 test cases**. `conformance-integrity` checks these two numbers, §8.1's per-fixture counts and its Total row against the fixtures themselves. Each fixture is consumed by all three SDK test runners (§5.2). An SDK declaring a conformance level **MUST** pass every fixture whose tested feature is required at that level (§5.3). +The repository ships **104 cross-language fixture files** under `conformance/fixtures/` covering **1329 test cases**. `conformance-integrity` checks these two numbers, §8.1's per-fixture counts and its Total row against the fixtures themselves. Each fixture is consumed by all three SDK test runners (§5.2). An SDK declaring a conformance level **MUST** pass every fixture whose tested feature is required at that level (§5.3). ### 8.1 Fixture Inventory @@ -434,7 +434,9 @@ The repository ships **102 cross-language fixture files** under `conformance/fix | [`usage_contract`](https://github.com/aiperceivable/apcore/blob/main/conformance/fixtures/usage_contract.json) | 11 | `system.usage.*` value semantics no schema can assert (spec §6.7.1) | | [`usage_exporter`](https://github.com/aiperceivable/apcore/blob/main/conformance/fixtures/usage_exporter.json) | 3 | `UsageExporter` push interface (D-55) | | [`version_negotiation`](https://github.com/aiperceivable/apcore/blob/main/conformance/fixtures/version_negotiation.json) | 12 | Version negotiation (Algorithm A14) | -| **Total** | **1272** | **102 fixtures** | +| [`artifact_reference`](https://github.com/aiperceivable/apcore/blob/main/conformance/fixtures/artifact_reference.json) | 34 | Opt-in artifact reference wire shape, media and byte assertions, and schema validation | +| [`durable_input`](https://github.com/aiperceivable/apcore/blob/main/conformance/fixtures/durable_input.json) | 23 | Durable input request shape and resume binding to identity, caller, deadline, and answer | +| **Total** | **1329** | **104 fixtures** | ### 8.2 Loading Fixtures from a Test Runner diff --git a/examples/python/durable-input/README.md b/examples/python/durable-input/README.md index 89ae74bc..88362e4b 100644 --- a/examples/python/durable-input/README.md +++ b/examples/python/durable-input/README.md @@ -27,10 +27,9 @@ and independently requires approval for the answer, including retries. The prompt exposes a request ID, allowed choices and a UTC Unix expiry in seconds. A repeated request with the same principal and job key returns the original prompt and expiry. Use a new job key to start a new attempt after -expiry. A pending request expires at `now >= expires_at`, including when the -approval check finishes after the deadline. After completion, the same answer -can recover the existing result past the prompt expiry while its row is retained, -subject to the current ACL and approval. A different answer conflicts with the +expiry. A request expires at `now >= expires_at`, including when the +approval check finishes after the deadline. Before expiry, the same +answer can recover the existing result subject to the current ACL and approval. A different answer conflicts with the recorded choice. The delivery row is both the business effect and the durable completion record. @@ -46,9 +45,8 @@ A separate pending approval flow would use APCore's approval token contract and a durable approval handler in addition to this input store. This prompt-and-answer flow uses existing APCore ACL and approval interfaces. -Its request and error names are local to the example. See the -[Durability Boundary](../../../docs/spec/design-durability-boundary.md) for -the invocation contract. +Its request and error names are local to the example. Hosts implementing the +SDK contract can use [InputRequiredError and prepare_input_resume](../../../planning/atlas-durable-input/contract.md). ## Verify diff --git a/examples/python/durable-input/durable_input.py b/examples/python/durable-input/durable_input.py index 71dfa277..80d5a049 100644 --- a/examples/python/durable-input/durable_input.py +++ b/examples/python/durable-input/durable_input.py @@ -124,7 +124,7 @@ def _load_request(self, db: sqlite3.Connection, request_id: str, owner: str) -> if row is None: raise PermissionError("The request is unavailable for this principal") job_id, expires_at, destination = row - if destination is None and self._clock() >= expires_at: + if self._clock() >= expires_at: raise ModuleError("INPUT_REQUEST_EXPIRED", "The input request expired before an answer was recorded") return job_id, destination diff --git a/examples/python/durable-input/verify.py b/examples/python/durable-input/verify.py index 0848f0c3..d5795d23 100644 --- a/examples/python/durable-input/verify.py +++ b/examples/python/durable-input/verify.py @@ -111,7 +111,7 @@ def effects() -> list[tuple[str, str]]: completed = {"request_id": request_id, "job_id": "job-1", "destination": "north"} assert [reply.result() for reply in replies] == [completed, completed] assert effects() == [(request_id, "north")] - assert run("alice", "approve", 200, "answer", request_id, "north") == completed + assert run("alice", "approve", 200, "answer", request_id, "north") == {"error": "INPUT_REQUEST_EXPIRED"} assert run("alice", "approve", 102, "answer", request_id, "south") == {"error": "INPUT_ANSWER_CONFLICT"} assert run("revoked", "approve", 103, "answer", request_id, "north") == {"error": "ACL_DENIED"} assert run("alice", "deny", 103, "answer", request_id, "north") == {"error": "APPROVAL_DENIED"} diff --git a/planning/atlas-artifact-reference/contract.md b/planning/atlas-artifact-reference/contract.md index b62df986..2dceeb48 100644 --- a/planning/atlas-artifact-reference/contract.md +++ b/planning/atlas-artifact-reference/contract.md @@ -23,6 +23,8 @@ The [JSON Schema](../../schemas/artifact-ref.schema.json) defines a closed objec The profile uses Draft 2020-12, also the default when `$schema` is omitted. All explicitly declared dialects along an assertion’s schema path must be Draft 2020-12. Both spellings of its meta-schema URI, with or without the empty fragment, are accepted. A legacy resource without assertions retains its native behavior. A malformed declaration fails as `SCHEMA_PARSE_ERROR`. Any of `x-artifact-ref`, `x-media-types`, or `x-max-bytes` applies the closed reference shape at that schema node. `x-artifact-ref` has the literal value `true`. `x-media-types` is a nonempty array of unique canonical media types and performs exact matching. `x-max-bytes` is an inclusive nonnegative safe-integer bound. The assertions compose with existing constraints. Optional fields use the existing JSON Schema optional-property behavior. To allow `null`, the constraint belongs in the object branch of the union. Declarations at ordinary schema positions, including properties, homogeneous items, and local definitions, retain the native JSON Schema branch and reference behavior. +In TypeScript, compose JSON Schema documents before calling `jsonSchemaToTypeBox`. An already converted artifact document is a complete validator with its own reference context. Embedding it as a native TypeBox child is rejected. Native TypeBox declarations can use artifact assertions directly without that conversion. + Prefer lowering to standard assertions in a validation-only schema. Preserve raw keywords in exported declarations. Skip data-valued keywords such as `examples`, `const`, `enum`, and `default` when looking for declarations. Reject malformed declarations as `SCHEMA_PARSE_ERROR`, including in unused definitions of opted-in schemas. An invalid instance uses the existing schema validation path and error model. Validation diagnostics for opted-in schemas never echo instance values. External schema retrieval remains disabled. Validation never asks a store or uses a URL. Start with JSON-compatible runtime values. Enforcement occurs at built-in input and output validation and the public validation entry points. Approval and policy ordering remain as specified by Core. An output field can declare a reference to a PNG thumbnail with a 64 KiB limit. diff --git a/python/src/apcore/schema/loader.py b/python/src/apcore/schema/loader.py index 49fd3fdf..740d262b 100644 --- a/python/src/apcore/schema/loader.py +++ b/python/src/apcore/schema/loader.py @@ -384,10 +384,12 @@ def assert_sub_schema(value: Any) -> Any: # Passing it through as the error type keeps the reported `constraint` # specific instead of collapsing every combinator to "value". keyword = str(error.validator or "value") + if artifact: + raise PydanticCustomError( + cast(Any, keyword), "{message}", {"message": _validation_failure_message(keyword)} + ) raise PydanticCustomError( - cast(Any, keyword), - _validation_failure_message(keyword) if artifact else error.message, - None if artifact else {"expected": error.validator_value}, + cast(Any, keyword), "{message}", {"expected": error.validator_value, "message": error.message} ) return value diff --git a/python/src/apcore/schema/validator.py b/python/src/apcore/schema/validator.py index cddb87b4..597b0e20 100644 --- a/python/src/apcore/schema/validator.py +++ b/python/src/apcore/schema/validator.py @@ -10,7 +10,8 @@ from pydantic import BaseModel, PydanticUserError, ValidationError as PydanticValidationError from pydantic_core import SchemaValidator as CoreSchemaValidator, core_schema -from apcore.schema._artifact_assertions import lower_artifact_assertions +from apcore.errors import SchemaParseError +from apcore.schema._artifact_assertions import _KEYWORDS as _ARTIFACT_KEYWORDS, lower_artifact_assertions from apcore.schema.types import SchemaValidationErrorDetail, SchemaValidationResult, _validation_failure_message __all__ = ["SchemaValidator", "coerce_value"] @@ -169,6 +170,28 @@ def adapt(node: Any) -> Any: return _NativeIntegerValidator(CoreSchemaValidator(adapted, **options), has_union) +def _native_artifact_metadata(model: type[BaseModel]) -> bool: + """Find explicit Pydantic extension metadata when JSON Schema export fails.""" + pending: list[Any] = [model.__pydantic_core_schema__] + visited: set[int] = set() + while pending: + node = pending.pop() + if not isinstance(node, (dict, list, tuple)) or id(node) in visited: + continue + visited.add(id(node)) + if isinstance(node, dict): + metadata = node.get("metadata") + extra = metadata.get("pydantic_js_extra") if isinstance(metadata, dict) else None + declared = node.get("cls") if node.get("type") == "model" else None + config_extra = declared.model_config.get("json_schema_extra") if isinstance(declared, type) and issubclass(declared, BaseModel) else None + if any(isinstance(item, dict) and not _ARTIFACT_KEYWORDS.isdisjoint(item) for item in (extra, config_extra)): + return True + pending.extend(child for key, child in node.items() if key not in _CORE_SCHEMA_PAYLOAD_KEYS) + else: + pending.extend(node) + return False + + @lru_cache(maxsize=128) def _native_artifact_schema(model: type[BaseModel], _revision: object) -> dict[str, Any] | None: if isinstance(getattr(model, "__apcore_source_schema__", None), dict): @@ -176,6 +199,8 @@ def _native_artifact_schema(model: type[BaseModel], _revision: object) -> dict[s try: schema = model.model_json_schema() except PydanticUserError: + if _native_artifact_metadata(model): + raise SchemaParseError("Unable to generate the artifact-enabled model schema") from None # Native-only models can support calls without having a JSON contract. return None return lower_artifact_assertions(schema) diff --git a/python/tests/test_artifact_reference.py b/python/tests/test_artifact_reference.py index 13844384..aaf1c797 100644 --- a/python/tests/test_artifact_reference.py +++ b/python/tests/test_artifact_reference.py @@ -5,7 +5,7 @@ from typing import Annotated import pytest -from pydantic import BaseModel, Field, ValidationError +from pydantic import BaseModel, ConfigDict, Field, ValidationError from apcore import APCore, ArtifactContent, ArtifactRef, Identity, read_artifact from apcore.config import Config @@ -91,6 +91,23 @@ def test_public_validator_checks_native_annotations() -> None: validator.validate_input({"ref": _BAD}, _NativeInput) +def test_unexportable_model_rejects_explicit_artifact_annotations() -> None: + class NativeObject: + pass + + class NativeOnly(BaseModel): + model_config = ConfigDict(arbitrary_types_allowed=True) + native: NativeObject = Field(default_factory=NativeObject) + + class ArtifactModel(NativeOnly): + ref: _NATIVE_FIELD + + validator = SchemaValidator() + assert validator.validate({}, NativeOnly).valid + with pytest.raises(SchemaParseError, match="Unable to generate the artifact-enabled model schema"): + validator.validate({"ref": _BAD}, ArtifactModel) + + async def test_pipeline_checks_annotated_inputs_and_outputs() -> None: core = APCore() calls = [] diff --git a/rust/tests/artifact_reference_spec.rs b/rust/tests/artifact_reference_spec.rs index bcb97b4c..653ba1bc 100644 --- a/rust/tests/artifact_reference_spec.rs +++ b/rust/tests/artifact_reference_spec.rs @@ -15,7 +15,7 @@ use serde_json::{json, Value}; #[test] fn shared_wire_cases_validate_through_both_entry_points() { let path = crate::conformance_env::find_fixtures_root().join("artifact_reference.json"); - let fixture: Value = serde_json::from_reader(std::fs::File::open(path).unwrap()).unwrap(); + let fixture: Value = serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap(); let validator = SchemaValidator::new(); for test in fixture["test_cases"].as_array().unwrap() { let name = test["id"].as_str().unwrap(); diff --git a/rust/tests/durable_input_spec.rs b/rust/tests/durable_input_spec.rs index 513ba509..a05cb8af 100644 --- a/rust/tests/durable_input_spec.rs +++ b/rust/tests/durable_input_spec.rs @@ -38,7 +38,7 @@ fn public_required_error_exposes_only_request_metadata() { #[test] fn shared_cases_prepare_and_compare_detached_arguments() { let path = crate::conformance_env::find_fixtures_root().join("durable_input.json"); - let fixture: Value = serde_json::from_reader(std::fs::File::open(path).unwrap()).unwrap(); + let fixture: Value = serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap(); for test in fixture["test_cases"].as_array().unwrap() { let name = test["id"].as_str().unwrap(); let record = &test["record"]; diff --git a/typescript/src/registry/registry.ts b/typescript/src/registry/registry.ts index d96ad2e4..b44df96b 100644 --- a/typescript/src/registry/registry.ts +++ b/typescript/src/registry/registry.ts @@ -48,24 +48,37 @@ import { validateModule } from './validation.js'; import { matchesVersionHint } from './version.js'; import { type ManagedDrainPolicy, runManagedDrain } from './managed-drain.js'; -/** Include only JSON data in a declaration and reject hidden or computed annotations. */ -function outputSchemaJSON(schema: Record): string { - return JSON.stringify(schema, (_key, value: unknown) => { - if (value !== null && typeof value === 'object' && !Array.isArray(value) && - Object.values(Object.getOwnPropertyDescriptors(value)).some(property => - !property.enumerable || !Object.hasOwn(property, 'value'))) { +/** Capture data properties without invoking getters or serialization hooks. */ +function snapshotOutputSchema(value: unknown, visiting = new Set()): unknown { + if (value === null || typeof value === 'string' || typeof value === 'boolean' || + (typeof value === 'number' && Number.isFinite(value))) return value; + if (typeof value !== 'object' || visiting.has(value)) { + throw new TypeError('Expected an acyclic output schema JSON value'); + } + visiting.add(value); + const prototype: unknown = Object.getPrototypeOf(value); + const array = Array.isArray(value); + if (array ? prototype !== Array.prototype : prototype !== Object.prototype && prototype !== null) { + throw new TypeError('Expected plain output schema data'); + } + const descriptors = Object.getOwnPropertyDescriptors(value); + const entries = Object.entries(descriptors).filter(([name]) => !array || name !== 'length'); + if (array && (entries.length !== descriptors['length']?.value || + entries.some(([name], index) => name !== String(index)))) { + throw new TypeError('Expected a dense output schema array'); + } + const fields = entries.map(([key, descriptor]) => { + if (!descriptor.enumerable || !Object.hasOwn(descriptor, 'value')) { throw new TypeError('Expected output schema data properties'); } - if (typeof value === 'undefined' || typeof value === 'function' || typeof value === 'symbol' || - (typeof value === 'number' && !Number.isFinite(value))) { - throw new TypeError('Expected an output schema JSON value'); - } - return value; + return [key, snapshotOutputSchema(descriptor.value, visiting)] as const; }); + visiting.delete(value); + return array ? fields.map(([, item]) => item) : Object.fromEntries(fields); } function outputSchemaDigest(schema: Record): string { - return sortedKeysStringify(JSON.parse(outputSchemaJSON(schema))); + return sortedKeysStringify(snapshotOutputSchema(schema)); } /** @internal Registration state used to compensate for a failed reload. */ @@ -1579,7 +1592,7 @@ export class Registry { try { const captured = read(); if (captured === null || this.publicGeneration(moduleId) !== generation) return null; - const schema = JSON.parse(outputSchemaJSON(captured.source)) as Record; + const schema = snapshotOutputSchema(captured.source) as Record; const sourceDigest = sortedKeysStringify(schema); // Core may lazily compile a JSON declaration during its first call. // Accept that exact representation, including its preserved annotations. diff --git a/typescript/src/schema/artifact-reference.ts b/typescript/src/schema/artifact-reference.ts index 36313ad9..b9db1a84 100644 --- a/typescript/src/schema/artifact-reference.ts +++ b/typescript/src/schema/artifact-reference.ts @@ -12,6 +12,8 @@ const schemaValues = [ 'propertyNames', 'then', 'unevaluatedItems', 'unevaluatedProperties', ]; const draft202012 = 'https://json-schema.org/draft/2020-12/schema'; +// TypeBox preserves the symbol through its native copies and optional wrappers. +export const CONVERTED_ARTIFACT_DOCUMENT = Symbol('apcore:ArtifactDocument'); const keywords = ['x-artifact-ref', 'x-media-types', 'x-max-bytes']; function isSchema(value: unknown): value is Schema { @@ -51,6 +53,9 @@ export function lowerArtifactReferences(schema: Schema, root = schema): { schema function walk(input: unknown): unknown { if (!isSchema(input)) return input; const value = input; + if (Object.hasOwn(value, CONVERTED_ARTIFACT_DOCUMENT)) { + throw new SchemaParseError('Compose artifact schema documents before converting them to TypeBox'); + } const known = visited.get(value); if (known !== undefined) return known; visited.set(value, value); diff --git a/typescript/src/schema/loader-pure.ts b/typescript/src/schema/loader-pure.ts index 63f9693e..90d8eeaf 100644 --- a/typescript/src/schema/loader-pure.ts +++ b/typescript/src/schema/loader-pure.ts @@ -21,7 +21,7 @@ import { type RedactionReferenceContext, } from '../utils/redaction-references.js'; import { KEYWORD_MARKER } from './constants.js'; -import { lowerArtifactReferences } from './artifact-reference.js'; +import { CONVERTED_ARTIFACT_DOCUMENT, lowerArtifactReferences } from './artifact-reference.js'; const sourceSchemas = new WeakMap>(); const artifactValidationSchemas = new WeakMap(); @@ -79,6 +79,7 @@ export function jsonSchemaToTypeBox( const converted = _convert(schema, document); sourceSchemas.set(converted, schema); if (lowered.schema !== schema || lowered.root !== document) { + Object.defineProperty(converted, CONVERTED_ARTIFACT_DOCUMENT, { value: true, enumerable: true }); artifactValidationSchemas.set(converted, _compileArtifactValidation(lowered)); } return converted; diff --git a/typescript/tests/conformance-artifact-reference.test.ts b/typescript/tests/conformance-artifact-reference.test.ts index 450f72ab..bebde1a8 100644 --- a/typescript/tests/conformance-artifact-reference.test.ts +++ b/typescript/tests/conformance-artifact-reference.test.ts @@ -92,6 +92,15 @@ describe('artifact reference invocation', () => { })).toThrow(expect.objectContaining({ code: 'SCHEMA_PARSE_ERROR' })); }); + it('requires artifact subdocuments to be composed before conversion', () => { + const child = jsonSchemaToTypeBox({ $ref: '#/$defs/payload', $defs: { payload: artifact } }); + const validator = new SchemaValidator(); + expect(validator.validate(ref, child).valid).toBe(true); + expect(() => validator.validate({ payload: { ...ref, media_type: '*/*' } }, Type.Object({ + payload: Type.Optional(child), + }))).toThrow(expect.objectContaining({ code: 'SCHEMA_PARSE_ERROR' })); + }); + it('keeps native TypeBox refinements when adding artifact assertions', () => { const name = 'TestArtifactRefinement'; TypeRegistry.Set(name, (_schema, value) => value === 'approved'); diff --git a/typescript/tests/registry/test-output-declaration.test.ts b/typescript/tests/registry/test-output-declaration.test.ts index d5948aed..24a6fb97 100644 --- a/typescript/tests/registry/test-output-declaration.test.ts +++ b/typescript/tests/registry/test-output-declaration.test.ts @@ -1,5 +1,5 @@ import { Executor, Registry, STREAMING_MARKER } from '../../src/index.js'; -import { describe, expect, it } from 'vitest'; +import { describe, expect, it, vi } from 'vitest'; const skill = 'reports.download'; @@ -68,6 +68,17 @@ describe('Registry.captureOutputDeclaration', () => { expect(registry.captureOutputDeclaration(skill)).toBeNull(); }); + it('rejects serialization hooks without invoking them', async () => { + const registry = new Registry(); + const module = download(); + const report = module.outputSchema.properties.report; + const toJSON = vi.fn(() => ({ type: 'string', 'x-a2a-artifact': true })); + Object.defineProperty(report, 'toJSON', { value: toJSON }); + await registry.register(skill, module); + expect(registry.captureOutputDeclaration(skill)).toBeNull(); + expect(toJSON).not.toHaveBeenCalled(); + }); + it('identifies native streaming modules', async () => { const registry = new Registry(); await registry.register(skill, { From fcbd92f351f4182b28a5374b4ea2f07141968ae8 Mon Sep 17 00:00:00 2001 From: tercel Date: Sun, 29 Nov 2026 19:39:02 +0800 Subject: [PATCH 5/6] Follow split Rust registry tests in decision coverage Signed-off-by: tercel --- conformance/decision_coverage.json | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/conformance/decision_coverage.json b/conformance/decision_coverage.json index 17445d29..cde92bff 100644 --- a/conformance/decision_coverage.json +++ b/conformance/decision_coverage.json @@ -267,7 +267,8 @@ ], "rust": [ "tests/test_deprecation_warning_cadence.rs", - "src/registry/registry.rs::deprecation_metadata_tests" + "src/registry/registry_tests.rs::deprecation_warning_fires_on_the_read_not_on_registration", + "src/registry/registry_tests.rs::the_deprecation_dedupe_key_carries_the_notice_and_survives_unregister" ] }, "discriminates": "Six dimensions, each isolated by its own mutation: the dedupe guard itself (ten reads must warn once), the version in the key (a newly registered version is a new notice), per-INSTANCE scope (a process-global set silences a second registry's advisory for a module its operator has never been told about), the EMISSION POINT, the NOTICE in the key, and a control — a module with no `x-deprecation` block must never warn, without which 'exactly one warning' also holds for an SDK that warns once for any module at all.\n\nEvery test counts the warning THE OPERATOR RECEIVES. apcore-rust's original unit test asserted the size of the private `deprecation_warned` set instead, and measured: with the `log_deprecation_warning` call deleted, that test still PASSES while four of the five original tests fail. The set is the artifact that records the decision; the emitted warning is the mechanism it exists for.\n\n**The two dimensions v1.49.0 left open were adjudicated at v1.59.0 and are now asserted.** (a) EMISSION POINT — the read, never registration. `the_warning_fires_on_the_read_not_on_registration` asserts zero warnings from `register` and exactly one from the first `get_definition`. Mutation: emitting at registration as apcore-rust did reddens it, and reddens every other read-counting case with it — not noise, but the failure itself: the marker is written whether or not a subscriber was listening, so the read is then deduped and the notice is lost outright. (b) DEDUPE KEY — `(module_id, version, x-deprecation block)`, never cleared on `unregister`. Two cases, each the other's control: the SAME notice on a re-registration must be silent (mutation: clearing on unregister reddens it, which is the hot-reload spam apcore-python shipped), and a CHANGED notice must warn (mutation: dropping the block from the key reddens exactly this one, which is the new notice apcore-typescript and apcore-rust swallowed). Both mutations were measured on all three SDKs and each reddens exactly its own case." From 403482c27d5f88d3f070a01ecd1cb103ebfc97f9 Mon Sep 17 00:00:00 2001 From: tercel Date: Sun, 29 Nov 2026 19:58:09 +0800 Subject: [PATCH 6/6] Align durable input expiry validation across SDKs Signed-off-by: tercel --- conformance/fixtures/durable_input.json | 173 ++++++++++++++++++ docs/spec/conformance.md | 6 +- planning/atlas-durable-input/contract.md | 2 +- python/src/apcore/durable_input.py | 3 + python/tests/test_durable_input.py | 2 +- rust/src/artifacts.rs | 20 +- rust/src/durable_input.rs | 14 +- rust/src/schema/artifact_reference.rs | 5 +- rust/src/utils/helpers.rs | 20 ++ rust/tests/durable_input_spec.rs | 9 +- .../tests/conformance-durable-input.test.ts | 4 +- 11 files changed, 225 insertions(+), 33 deletions(-) diff --git a/conformance/fixtures/durable_input.json b/conformance/fixtures/durable_input.json index 4ceed406..ab32edf5 100644 --- a/conformance/fixtures/durable_input.json +++ b/conformance/fixtures/durable_input.json @@ -42,6 +42,179 @@ "answer": "north" } }, + { + "id": "integral_exponent_expiry", + "record": { + "request_id": "9b0b9d7134364bd4a37e55a137f094c3", + "expires_at_ms": 2e3, + "module_id": "delivery.confirm", + "module_version": "1.2.3", + "caller_id": null, + "owner": { + "issuer": "fixture", + "type": "user", + "id": "alice" + }, + "arguments": { + "job": "job-1", + "options": { + "priority": true + } + } + }, + "identity": { + "issuer": "fixture", + "type": "user", + "id": "alice", + "roles": [ + "dispatcher" + ] + }, + "caller_id": null, + "answer": "north", + "now_ms": 1999, + "expected": "ready", + "arguments": { + "job": "job-1", + "options": { + "priority": true + }, + "input_request_id": "9b0b9d7134364bd4a37e55a137f094c3", + "answer": "north" + } + }, + { + "id": "fractional_expiry", + "record": { + "request_id": "9b0b9d7134364bd4a37e55a137f094c3", + "expires_at_ms": 2.0005e3, + "module_id": "delivery.confirm", + "module_version": "1.2.3", + "caller_id": null, + "owner": { + "issuer": "fixture", + "type": "user", + "id": "alice" + }, + "arguments": { + "job": "job-1", + "options": { + "priority": true + } + } + }, + "identity": { + "issuer": "fixture", + "type": "user", + "id": "alice", + "roles": [ + "dispatcher" + ] + }, + "caller_id": null, + "answer": "north", + "now_ms": 1999, + "expected": "unavailable" + }, + { + "id": "unsafe_expiry", + "record": { + "request_id": "9b0b9d7134364bd4a37e55a137f094c3", + "expires_at_ms": 9.007199254740992e15, + "module_id": "delivery.confirm", + "module_version": "1.2.3", + "caller_id": null, + "owner": { + "issuer": "fixture", + "type": "user", + "id": "alice" + }, + "arguments": { + "job": "job-1", + "options": { + "priority": true + } + } + }, + "identity": { + "issuer": "fixture", + "type": "user", + "id": "alice", + "roles": [ + "dispatcher" + ] + }, + "caller_id": null, + "answer": "north", + "now_ms": 1999, + "expected": "unavailable" + }, + { + "id": "string_expiry", + "record": { + "request_id": "9b0b9d7134364bd4a37e55a137f094c3", + "expires_at_ms": "2e3", + "module_id": "delivery.confirm", + "module_version": "1.2.3", + "caller_id": null, + "owner": { + "issuer": "fixture", + "type": "user", + "id": "alice" + }, + "arguments": { + "job": "job-1", + "options": { + "priority": true + } + } + }, + "identity": { + "issuer": "fixture", + "type": "user", + "id": "alice", + "roles": [ + "dispatcher" + ] + }, + "caller_id": null, + "answer": "north", + "now_ms": 1999, + "expected": "unavailable" + }, + { + "id": "boolean_expiry", + "record": { + "request_id": "9b0b9d7134364bd4a37e55a137f094c3", + "expires_at_ms": true, + "module_id": "delivery.confirm", + "module_version": "1.2.3", + "caller_id": null, + "owner": { + "issuer": "fixture", + "type": "user", + "id": "alice" + }, + "arguments": { + "job": "job-1", + "options": { + "priority": true + } + } + }, + "identity": { + "issuer": "fixture", + "type": "user", + "id": "alice", + "roles": [ + "dispatcher" + ] + }, + "caller_id": null, + "answer": "north", + "now_ms": 1999, + "expected": "unavailable" + }, { "id": "answer_may_be_null", "record": { diff --git a/docs/spec/conformance.md b/docs/spec/conformance.md index 4aefd476..f6922cc0 100644 --- a/docs/spec/conformance.md +++ b/docs/spec/conformance.md @@ -326,7 +326,7 @@ The following requirements are not met by the SDK implementations in this reposi ## 8. Conformance Test Fixtures -The repository ships **104 cross-language fixture files** under `conformance/fixtures/` covering **1329 test cases**. `conformance-integrity` checks these two numbers, §8.1's per-fixture counts and its Total row against the fixtures themselves. Each fixture is consumed by all three SDK test runners (§5.2). An SDK declaring a conformance level **MUST** pass every fixture whose tested feature is required at that level (§5.3). +The repository ships **104 cross-language fixture files** under `conformance/fixtures/` covering **1334 test cases**. `conformance-integrity` checks these two numbers, §8.1's per-fixture counts and its Total row against the fixtures themselves. Each fixture is consumed by all three SDK test runners (§5.2). An SDK declaring a conformance level **MUST** pass every fixture whose tested feature is required at that level (§5.3). ### 8.1 Fixture Inventory @@ -435,8 +435,8 @@ The repository ships **104 cross-language fixture files** under `conformance/fix | [`usage_exporter`](https://github.com/aiperceivable/apcore/blob/main/conformance/fixtures/usage_exporter.json) | 3 | `UsageExporter` push interface (D-55) | | [`version_negotiation`](https://github.com/aiperceivable/apcore/blob/main/conformance/fixtures/version_negotiation.json) | 12 | Version negotiation (Algorithm A14) | | [`artifact_reference`](https://github.com/aiperceivable/apcore/blob/main/conformance/fixtures/artifact_reference.json) | 34 | Opt-in artifact reference wire shape, media and byte assertions, and schema validation | -| [`durable_input`](https://github.com/aiperceivable/apcore/blob/main/conformance/fixtures/durable_input.json) | 23 | Durable input request shape and resume binding to identity, caller, deadline, and answer | -| **Total** | **1329** | **104 fixtures** | +| [`durable_input`](https://github.com/aiperceivable/apcore/blob/main/conformance/fixtures/durable_input.json) | 28 | Durable input request shape and resume binding to identity, caller, deadline, and answer | +| **Total** | **1334** | **104 fixtures** | ### 8.2 Loading Fixtures from a Test Runner diff --git a/planning/atlas-durable-input/contract.md b/planning/atlas-durable-input/contract.md index 63980fe5..d4d93d78 100644 --- a/planning/atlas-durable-input/contract.md +++ b/planning/atlas-durable-input/contract.md @@ -11,7 +11,7 @@ A host uses `prepare_input_resume` (`prepareInputResume` in TypeScript) on a per | Record field | Rule | | --- | --- | | `request_id` | Exactly 32 lowercase ASCII hexadecimal characters. The host supplies an unpredictable ID and inserts it uniquely. IDs are correlators, not credentials. | -| `expires_at_ms` | Positive JSON safe integer, UTC Unix milliseconds. At `now_ms >= expires_at_ms`, an expired request is unavailable, including retry after completion. | +| `expires_at_ms` | Positive JSON safe integer, UTC Unix milliseconds. Integral decimal and exponent forms such as `2000.0` and `2e3` are valid. At `now_ms >= expires_at_ms`, an expired request is unavailable, including retry after completion. | | `module_id`, `module_version` | Nonempty strings. The version is a specific, immutable effect contract, never a default or a range. The host changes the version when effect or approval-relevant behavior changes. | | `caller_id` | Nonempty string or JSON null. Freeze this alongside the effective actor. | | `owner` | Exactly `issuer`, `type`, and `id`, each a nonempty string identifying a direct authenticated principal. Delegated identities are outside this initial profile. Roles, scopes, and attributes come from current authentication. | diff --git a/python/src/apcore/durable_input.py b/python/src/apcore/durable_input.py index b1301f1e..8a24670d 100644 --- a/python/src/apcore/durable_input.py +++ b/python/src/apcore/durable_input.py @@ -105,6 +105,9 @@ def prepare_input_resume( if type(record) is not dict or record.keys() != _RECORD_FIELDS: raise _unavailable() request_id, expires_at_ms = record["request_id"], record["expires_at_ms"] + # JSON numbers such as 2e3 are decoded as floats even when integral. + if type(expires_at_ms) is float and expires_at_ms.is_integer(): + expires_at_ms = int(expires_at_ms) module_id, module_version = record["module_id"], record["module_version"] owner, arguments, stored_caller = record["owner"], record["arguments"], record["caller_id"] principal = _direct_principal(identity) diff --git a/python/tests/test_durable_input.py b/python/tests/test_durable_input.py index a0273791..f57979ae 100644 --- a/python/tests/test_durable_input.py +++ b/python/tests/test_durable_input.py @@ -80,7 +80,7 @@ def test_shared_durable_input_fixture(case: dict[str, Any]) -> None: (), ) assert resume.matches(policy, case["now_ms"]) - assert not resume.matches(policy, record["expires_at_ms"]) + assert not resume.matches(policy, int(record["expires_at_ms"])) else: with pytest.raises(ModuleError) as error: prepare_input_resume(*args) diff --git a/rust/src/artifacts.rs b/rust/src/artifacts.rs index 63a54c4c..2a1641e4 100644 --- a/rust/src/artifacts.rs +++ b/rust/src/artifacts.rs @@ -4,10 +4,11 @@ use async_trait::async_trait; use serde::{Deserialize, Deserializer, Serialize}; use serde_json::Value; +use crate::utils::helpers::{safe_json_u64, MAX_SAFE_JSON_INTEGER}; use crate::{Identity, ModuleError}; /// Largest artifact size that round-trips in all SDKs' JSON number APIs. -pub const MAX_ARTIFACT_BYTES: u64 = 9_007_199_254_740_991; +pub const MAX_ARTIFACT_BYTES: u64 = MAX_SAFE_JSON_INTEGER; /// Default per-read budget in bytes. pub const DEFAULT_ARTIFACT_READ_LIMIT: u64 = 8 * 1024 * 1024; @@ -65,7 +66,7 @@ impl<'de> Deserialize<'de> for ArtifactRef { Some(( fields.get("id")?.as_str()?, fields.get("media_type")?.as_str()?, - safe_byte_count(fields.get("size_bytes")?)?, + safe_json_u64(fields.get("size_bytes")?)?, )) }; let (id, media_type, size_bytes) = @@ -75,21 +76,6 @@ impl<'de> Deserialize<'de> for ArtifactRef { } } -pub(crate) fn safe_byte_count(value: &Value) -> Option { - if let Some(bytes) = value.as_u64() { - return (bytes <= MAX_ARTIFACT_BYTES).then_some(bytes); - } - let bytes = value.as_f64()?; - // JSON Schema treats integral JSON numbers as integers even with a decimal - // point. Within the safe-number range the conversion is exact. - if (0.0..=9_007_199_254_740_991.0).contains(&bytes) && bytes.fract() == 0.0 { - #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] - Some(bytes as u64) - } else { - None - } -} - pub(crate) fn is_media_type(media_type: &str) -> bool { fn component(value: &str) -> bool { fn alphanumeric(byte: u8) -> bool { diff --git a/rust/src/durable_input.rs b/rust/src/durable_input.rs index fb940a46..60a27867 100644 --- a/rust/src/durable_input.rs +++ b/rust/src/durable_input.rs @@ -2,13 +2,13 @@ use std::fmt; -use serde::Deserialize; +use serde::{Deserialize, Deserializer}; use serde_json::{json, Map, Value}; use crate::policy::{final_arguments_digest, PolicyEvaluationRequest, APPROVAL_TOKEN_KEY}; +use crate::utils::helpers::{safe_json_u64, MAX_SAFE_JSON_INTEGER}; use crate::{Identity, ModuleError}; -const MAX_TIME_MS: u64 = (1 << 53) - 1; const REQUEST_ID_KEY: &str = "input_request_id"; const ANSWER_KEY: &str = "answer"; const INPUT_REQUIRED_CODE: &str = "INPUT_REQUIRED"; @@ -92,6 +92,7 @@ impl DirectOwner { #[serde(deny_unknown_fields)] struct InputRecord { request_id: String, + #[serde(deserialize_with = "deserialize_expiry")] expires_at_ms: u64, module_id: String, module_version: String, @@ -129,8 +130,13 @@ fn valid_request_id(id: &str) -> bool { .all(|byte| matches!(byte, b'0'..=b'9' | b'a'..=b'f')) } +fn deserialize_expiry<'de, D: Deserializer<'de>>(deserializer: D) -> Result { + let value = Value::deserialize(deserializer)?; + safe_json_u64(&value).ok_or_else(|| serde::de::Error::custom("Invalid durable input expiry")) +} + fn valid_expiry(expires_at_ms: u64) -> bool { - (1..=MAX_TIME_MS).contains(&expires_at_ms) + (1..=MAX_SAFE_JSON_INTEGER).contains(&expires_at_ms) } fn unavailable() -> ModuleError { @@ -208,7 +214,7 @@ pub fn prepare_input_resume( ) -> Result { let now_ms = u64::try_from(now_ms) .ok() - .filter(|now| *now <= MAX_TIME_MS) + .filter(|now| *now <= MAX_SAFE_JSON_INTEGER) .ok_or_else(|| ModuleError::invalid_input("Invalid input request clock"))?; final_arguments_digest(answer) .map_err(|_| ModuleError::invalid_input("Input answer is not canonical JSON"))?; diff --git a/rust/src/schema/artifact_reference.rs b/rust/src/schema/artifact_reference.rs index d2c40971..12cc8910 100644 --- a/rust/src/schema/artifact_reference.rs +++ b/rust/src/schema/artifact_reference.rs @@ -3,7 +3,8 @@ use serde_json::{json, Map, Value}; use std::collections::HashSet; -use crate::artifacts::{is_media_type, safe_byte_count, MAX_ARTIFACT_BYTES}; +use crate::artifacts::{is_media_type, MAX_ARTIFACT_BYTES}; +use crate::utils::helpers::safe_json_u64; const MEDIA_PATTERN: &str = r"^[a-z0-9][a-z0-9!#$&^_.+-]{0,126}/[a-z0-9][a-z0-9!#$&^_.+-]{0,126}(?![\s\S])"; @@ -151,7 +152,7 @@ fn artifact_assertion(fields: &Map) -> Result { let max_bytes = fields .get(MAX_BYTES) .map_or(Ok(MAX_ARTIFACT_BYTES), |value| { - safe_byte_count(value) + safe_json_u64(value) .ok_or_else(|| "x-max-bytes must be a nonnegative safe integer".to_owned()) })?; let mut media = json!({"type": "string", "pattern": MEDIA_PATTERN}); diff --git a/rust/src/utils/helpers.rs b/rust/src/utils/helpers.rs index d64294e8..900c0e54 100644 --- a/rust/src/utils/helpers.rs +++ b/rust/src/utils/helpers.rs @@ -1,9 +1,29 @@ // APCore Protocol — Helper utilities // Spec reference: Pattern matching, call chain guards, error propagation +use serde_json::Value; + use crate::context::Context; use crate::errors::{ErrorCode, ModuleError}; +pub(crate) const MAX_SAFE_JSON_INTEGER: u64 = (1 << 53) - 1; + +/// Read a nonnegative integral JSON number within the portable safe range. +pub(crate) fn safe_json_u64(value: &Value) -> Option { + if let Some(number) = value.as_u64() { + return (number <= MAX_SAFE_JSON_INTEGER).then_some(number); + } + let number = value.as_f64()?; + // JSON Schema treats integral JSON numbers as integers even with a decimal + // point or exponent. Within the safe-number range the conversion is exact. + if (0.0..=9_007_199_254_740_991.0).contains(&number) && number.fract() == 0.0 { + #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] + Some(number as u64) + } else { + None + } +} + /// Default maximum call chain depth before `CallDepthExceeded` is returned. pub const DEFAULT_MAX_CALL_DEPTH: usize = 32; /// Default maximum repeat count for a single module in the call chain. diff --git a/rust/tests/durable_input_spec.rs b/rust/tests/durable_input_spec.rs index a05cb8af..cc3742d3 100644 --- a/rust/tests/durable_input_spec.rs +++ b/rust/tests/durable_input_spec.rs @@ -95,10 +95,11 @@ fn shared_cases_prepare_and_compare_detached_arguments() { ] { assert!(!resume.matches(&mismatch, now), "{name}"); } - assert!( - !resume.matches(&request, record["expires_at_ms"].as_i64().unwrap()), - "{name}" - ); + // Ready fixture deadlines are safe integers, even when the JSON + // decoder stores the exponent representation as a float. + #[allow(clippy::cast_possible_truncation)] + let deadline_ms = record["expires_at_ms"].as_f64().unwrap() as i64; + assert!(!resume.matches(&request, deadline_ms), "{name}"); assert!(!resume.matches(&request, -1), "{name}"); } "unavailable" => { diff --git a/typescript/tests/conformance-durable-input.test.ts b/typescript/tests/conformance-durable-input.test.ts index db428b3c..c4b1e84c 100644 --- a/typescript/tests/conformance-durable-input.test.ts +++ b/typescript/tests/conformance-durable-input.test.ts @@ -50,7 +50,9 @@ describe('durable_input.json', () => { const resume = prepare(); expect(resume.moduleId).toBe(moduleId); expect(resume.arguments).toEqual(trial.arguments); - expect(resume.matches({ ...policyRequest(resume.arguments), identity, callerId: trial.caller_id }, trial.now_ms)).toBe(true); + const request = { ...policyRequest(resume.arguments), identity, callerId: trial.caller_id }; + expect(resume.matches(request, trial.now_ms)).toBe(true); + expect(resume.matches(request, (trial.record as { expires_at_ms: number }).expires_at_ms)).toBe(false); } else { expect(prepare).toThrow(expect.objectContaining({ code: trial.expected === 'unavailable' ? 'INPUT_RESUME_UNAVAILABLE' : 'GENERAL_INVALID_INPUT',