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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions python/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ dependencies = [
"pydantic>=2.7,<3",
"jsonschema>=4.21,<5",
"referencing>=0.30,<1",
"typing-extensions>=4.7,<5",
]

[project.urls]
Expand Down
2 changes: 1 addition & 1 deletion python/src/apcore/_post_validation_policy.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
from apcore.pipeline import PipelineContext

_SAFE_INT = (1 << 53) - 1
_RULE_ID = re.compile(r"[A-Za-z0-9_.-]{1,64}\Z")
_RULE_ID = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,63}\Z")
_EVALUATOR_TIMEOUT_SECONDS = 1.0


Expand Down
77 changes: 32 additions & 45 deletions python/src/apcore/bindings.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,7 @@
from pydantic import BaseModel

from apcore.config import Config
from apcore.decorator import (
FunctionModule,
generate_input_model,
generate_output_model,
)
from apcore.decorator import FunctionModule
from apcore.errors import (
BindingCallableNotFoundError,
BindingFileInvalidError,
Expand Down Expand Up @@ -517,15 +513,14 @@ def resolve_target(self, target_string: str) -> Callable:
def _resolve_schema(
self,
binding: dict[str, Any],
func: Callable,
binding_file_dir: pathlib.Path,
schema_loader: SchemaLoader,
config: Config | None,
*,
file_path: str,
module_id: str,
) -> tuple[type[BaseModel], type[BaseModel]]:
"""Resolve input/output schema per protocol-spec §5.12.2."""
) -> tuple[type[BaseModel] | None, type[BaseModel] | None, bool]:
"""Resolve supplied schemas and indicate whether inference requires strict schemas."""
modes = _detect_schema_modes(binding)
if len(modes) > 1:
raise BindingSchemaModeConflictError(
Expand All @@ -543,7 +538,7 @@ def _resolve_schema(
f"binding '{module_id}': explicit schema mode requires both 'input_schema' and 'output_schema'"
),
)
return _binding_models(schema_loader, binding, file_path)
return (*_binding_models(schema_loader, binding, file_path), False)

# Mode 2: external reference
if "schema_ref" in binding:
Expand All @@ -567,7 +562,7 @@ def _resolve_schema(
raise BindingFileInvalidError(
file_path=str(ref_path), reason="Schema reference and its input/output schemas must be mappings"
)
return _binding_models(schema_loader, ref_data, str(ref_path))
return (*_binding_models(schema_loader, ref_data, str(ref_path)), False)

# Mode 3: explicit auto_schema OR mode 4: implicit auto (default)
try:
Expand All @@ -585,25 +580,7 @@ def _resolve_schema(
file_path=file_path,
remediation="auto_schema is explicitly false; provide input_schema/output_schema or schema_ref instead",
)
# Implicit default: auto_schema true (permissive)
if auto_mode is None:
auto_mode = "permissive"

try:
input_schema = generate_input_model(func)
output_schema = generate_output_model(func)
except (FuncMissingTypeHintError, FuncMissingReturnTypeError) as exc:
raise BindingSchemaInferenceFailedError(
target=binding["target"],
module_id=module_id,
file_path=file_path,
) from exc

if auto_mode == "strict":
self._enforce_strict_or_raise(input_schema, "input", module_id=module_id, file_path=file_path)
self._enforce_strict_or_raise(output_schema, "output", module_id=module_id, file_path=file_path)

return input_schema, output_schema
return None, None, auto_mode == "strict"

def _enforce_strict_or_raise(
self,
Expand Down Expand Up @@ -642,27 +619,37 @@ def _create_module_from_binding(
metadata = {**(metadata or {}), "display": display}
func = self.resolve_target(binding["target"])

input_schema, output_schema = self._resolve_schema(
input_schema, output_schema, strict = self._resolve_schema(
binding,
func,
binding_file_dir,
schema_loader,
config,
file_path=file_path,
module_id=module_id,
)

return FunctionModule(
func=func,
module_id=module_id,
description=binding.get("description"),
documentation=binding.get("documentation"),
tags=binding.get("tags"),
version=binding.get("version", "1.0.0"),
annotations=binding.get("annotations"),
metadata=metadata,
display=display,
input_schema=input_schema,
output_schema=output_schema,
resources=binding.get("resources"),
)
try:
module = FunctionModule(
func=func,
module_id=module_id,
description=binding.get("description"),
documentation=binding.get("documentation"),
tags=binding.get("tags"),
version=binding.get("version", "1.0.0"),
annotations=binding.get("annotations"),
metadata=metadata,
display=display,
input_schema=input_schema,
output_schema=output_schema,
resources=binding.get("resources"),
)
except (FuncMissingTypeHintError, FuncMissingReturnTypeError) as exc:
raise BindingSchemaInferenceFailedError(
target=binding["target"],
module_id=module_id,
file_path=file_path,
) from exc
if strict:
self._enforce_strict_or_raise(module.input_schema, "input", module_id=module_id, file_path=file_path)
self._enforce_strict_or_raise(module.output_schema, "output", module_id=module_id, file_path=file_path)
return module
4 changes: 4 additions & 0 deletions python/src/apcore/context.py
Original file line number Diff line number Diff line change
Expand Up @@ -470,12 +470,16 @@ def create(

def with_progress_reporter(self, callback: ProgressReporter | None) -> Context[T]:
"""Return a context with its own progress callback binding."""
if callback is not None and not callable(callback):
raise InvalidInputError("Progress reporter must be a function")
context = self._with_local_binding()
context._progress_reporter = callback
return context

def with_elicitation_handler(self, callback: ElicitationHandler | None) -> Context[T]:
"""Return a context with its own request-for-input callback binding."""
if callback is not None and not callable(callback):
raise InvalidInputError("Elicitation handler must be a function")
context = self._with_local_binding()
context._elicitation_handler = callback
return context
Expand Down
27 changes: 15 additions & 12 deletions python/src/apcore/decorator.py
Original file line number Diff line number Diff line change
Expand Up @@ -132,27 +132,32 @@ def _has_object_output(annotation: Any, *, root: bool = False) -> bool:
return issubclass(cls, BaseModel) or (issubclass(cls, Mapping) if root else cls is dict)


class _TypedDictOutput(RootModel):
class _ObjectRootOutput(RootModel):
@classmethod
def __get_pydantic_json_schema__(cls, schema: CoreSchema, handler: GetJsonSchemaHandler) -> dict[str, Any]:
# Protocol adapters consume an explicit object-shaped root schema.
return handler.resolve_ref_schema(super().__get_pydantic_json_schema__(schema, handler))


def _output_model(return_type: Any) -> type[BaseModel]:
def _infer_output(return_type: Any) -> tuple[type[BaseModel], bool]:
"""Infer the output schema and whether its wire shape needs a result envelope."""
origin = get_origin(return_type) or return_type
if return_type is type(None) or origin is dict:
return create_model("OutputModel", __config__=ConfigDict(extra="allow"))
if is_typeddict(origin):
return typing.cast(type[BaseModel], _TypedDictOutput.__class_getitem__(return_type))
if isinstance(return_type, type) and issubclass(return_type, BaseModel) and _has_object_output(return_type):
return return_type
return create_model("OutputModel", result=(return_type, ...))
return create_model("OutputModel", __config__=ConfigDict(extra="allow")), False
base_type = get_args(return_type)[0] if origin is Annotated else return_type
if is_typeddict(base_type):
return typing.cast(type[BaseModel], _ObjectRootOutput.__class_getitem__(return_type)), False
if isinstance(base_type, type) and issubclass(base_type, BaseModel) and _has_object_output(base_type):
if origin is Annotated:
return typing.cast(type[BaseModel], _ObjectRootOutput.__class_getitem__(return_type)), False
return base_type, False
return create_model("OutputModel", result=(return_type, ...)), True


def generate_output_model(func: Callable) -> type[BaseModel]:
"""Generate an object schema for a function's declared return type."""
return _output_model(_output_annotation(func))
schema, _ = _infer_output(_output_annotation(func))
return schema


def _context_param_name(func: Any) -> str | None:
Expand Down Expand Up @@ -221,9 +226,7 @@ def __init__(
self.input_schema = input_schema if input_schema is not None else generate_input_model(func, param_descs)
wrap_result = False
if output_schema is None:
return_type = _output_annotation(func)
output_schema = _output_model(return_type)
wrap_result = return_type is not type(None) and not _has_object_output(return_type)
output_schema, wrap_result = _infer_output(_output_annotation(func))
self.output_schema = output_schema

context_param_name = _context_param_name(func)
Expand Down
6 changes: 4 additions & 2 deletions python/src/apcore/sys_modules/identity.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,9 @@
)

_IDENTITY_REDACTED_TOKEN: str = "<redacted>"
_IDENTITY_RESERVED_KEYS = frozenset(
{"id", "type", "roles", "actor_id", "subject_id", "delegation_depth", "issuer", "scopes", "on_behalf_of"}
)


def _extract_caller_id(context: Any) -> str:
Expand Down Expand Up @@ -98,8 +101,7 @@ def _identity_snapshot(identity: Any) -> dict[str, Any]:
attrs = getattr(identity, "attrs", None) or {}
if isinstance(attrs, dict):
for key, value in attrs.items():
# Don't shadow the canonical id/type/roles keys.
if key in snapshot:
if key in _IDENTITY_RESERVED_KEYS:
continue
snapshot[key] = _redact_nested(_redact_identity_attr(str(key), value), frozenset())
return snapshot
Expand Down
19 changes: 19 additions & 0 deletions python/tests/sys_modules/test_control.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import os
import time
from pathlib import Path
from types import SimpleNamespace
from typing import Any
from unittest.mock import MagicMock, patch

Expand All @@ -15,6 +16,7 @@
from apcore.approval import AutoApproveHandler
from apcore.client import APCore
from apcore.config import Config
from apcore.context import Identity
from apcore.errors import InvalidInputError, ModuleDisabledError, ModuleError, ModuleNotFoundError, ReloadFailedError
from apcore.events.emitter import ApCoreEvent, EventEmitter
from apcore.module import ModuleAnnotations
Expand All @@ -26,9 +28,26 @@
_default_toggle_state,
check_module_disabled,
)
from apcore.sys_modules.identity import _extract_identity_dict
from apcore.sys_modules.overrides import InMemoryOverridesStore


def test_audit_identity_filters_reserved_attributes():
identity = Identity(
id="sample",
type="user",
attrs=dict.fromkeys(
("id", "type", "roles", "actor_id", "subject_id", "delegation_depth", "issuer", "scopes", "on_behalf_of"),
"attribute",
) | {"display_name": "Sample"},
)
assert _extract_identity_dict(SimpleNamespace(identity=identity)) == {
"id": "sample",
"type": "user",
"display_name": "Sample",
}


# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
Expand Down
40 changes: 39 additions & 1 deletion python/tests/test_bindings.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,13 @@

from __future__ import annotations

import sys
import json
import sys
from typing import Annotated

import pytest
from pydantic import BaseModel, RootModel
from typing_extensions import TypedDict

from apcore.bindings import BindingLoader
from apcore.decorator import FunctionModule
Expand All @@ -22,6 +25,41 @@
from apcore.registry import Registry


class _Response(BaseModel):
name: str


class _ResponseDict(TypedDict):
name: str


_MixedRoot = RootModel[dict[str, str] | list[str]]


@pytest.mark.parametrize(
("annotation", "value", "expected"),
[
(_Response | None, _Response(name="sample"), {"result": {"name": "sample"}}),
(_ResponseDict | None, {"name": "sample"}, {"result": {"name": "sample"}}),
(_Response | None, None, {"result": None}),
(Annotated[_Response, "metadata"], _Response(name="sample"), {"name": "sample"}),
(Annotated[_ResponseDict, "metadata"], {"name": "sample"}, {"name": "sample"}),
(_MixedRoot, _MixedRoot({"name": "sample"}), {"result": {"name": "sample"}}),
],
)
def test_binding_infers_result_envelope(loader, registry, tmp_path, monkeypatch, annotation, value, expected):
def respond():
return value

respond.__annotations__["return"] = annotation
monkeypatch.setattr(loader, "resolve_target", lambda _: respond)
source = tmp_path / "example.binding.yaml"
source.write_text("bindings:\n - module_id: test.response\n target: binding_helpers:respond\n")
loader.load_bindings(str(source), registry)

assert Executor(registry=registry).call("test.response", {}) == expected


@pytest.fixture
def loader() -> BindingLoader:
return BindingLoader()
Expand Down
2 changes: 2 additions & 0 deletions python/uv.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading