From 7573f0de32634e00ba0585d42094613c0add9a76 Mon Sep 17 00:00:00 2001 From: tercel Date: Sat, 28 Nov 2026 20:10:33 +0800 Subject: [PATCH 1/3] feat(runtime): add invocation budgets and realtime interactions Signed-off-by: tercel --- .github/workflows/packages.yml | 9 +- conformance/README.md | 1 + conformance/check_config_key_consumers.py | 12 + conformance/config_key_consumers.json | 4 + conformance/extract_doc_examples.py | 1 + conformance/fixtures/call_budget.json | 101 +++++ .../fixtures/config_key_governance.json | 1 + docs/features/context-object.md | 126 +++++- docs/features/error-system.md | 3 +- docs/features/observability.md | 2 +- docs/features/redaction.md | 3 + docs/index.md | 6 +- planning/beta-closeout/overview.md | 5 + planning/beta-closeout/plan.md | 34 ++ planning/beta-closeout/state.json | 57 +++ planning/beta-closeout/tasks/python.md | 4 + planning/beta-closeout/tasks/rust.md | 4 + planning/beta-closeout/tasks/surfaces.md | 3 + planning/beta-closeout/tasks/typescript.md | 4 + planning/beta-closeout/tasks/verification.md | 4 + python/apcore-conformance.yaml | 2 +- python/pyproject.toml | 2 +- python/src/apcore/__init__.py | 18 +- python/src/apcore/_post_validation_policy.py | 45 +-- python/src/apcore/builtin_steps.py | 65 ++- python/src/apcore/call_budget.py | 124 ++++++ python/src/apcore/cancel.py | 65 ++- python/src/apcore/config.py | 7 + python/src/apcore/context.py | 107 ++++- python/src/apcore/errors.py | 20 +- python/src/apcore/executor.py | 24 +- .../apcore/observability/context_logger.py | 26 +- python/src/apcore/pipeline.py | 16 +- python/src/apcore/utils/redaction.py | 41 +- python/tests/test_call_budget.py | 229 +++++++++++ python/tests/test_public_api.py | 6 + python/tests/test_realtime_context.py | 66 +++ python/tests/test_redaction_regex_cap.py | 57 +++ python/uv.lock | 2 +- rust/Cargo.lock | 4 +- rust/Cargo.toml | 4 +- rust/apcore-conformance.yaml | 2 +- rust/apcore-macros/Cargo.toml | 2 +- rust/src/builtin_steps.rs | 173 +++++--- rust/src/call_budget.rs | 259 ++++++++++++ rust/src/cancel.rs | 15 + rust/src/config.rs | 12 + rust/src/context.rs | 43 +- rust/src/errors.rs | 4 + rust/src/executor.rs | 84 +++- rust/src/interaction.rs | 191 +++++++++ rust/src/lib.rs | 8 + rust/src/observability/redaction.rs | 89 ++++- rust/src/pipeline.rs | 33 ++ rust/src/pipeline_config.rs | 16 + rust/src/sys_modules/audit.rs | 1 + rust/tests/call_budget.rs | 377 ++++++++++++++++++ rust/tests/context_serialization_test.rs | 2 + rust/tests/core_profile.rs | 2 + rust/tests/realtime_context.rs | 130 ++++++ .../test_config_load_framework_sections.rs | 6 +- rust/tests/test_event_naming_canonical.rs | 1 + .../test_reload_order_registration_paths.rs | 1 + ...st_system_modules_hardening_conformance.rs | 1 + rust/tests/test_trace_context_conformance.rs | 1 + schemas/apcore-config.schema.json | 7 + typescript/apcore-conformance.yaml | 2 +- typescript/package.json | 2 +- typescript/src/async-task.ts | 19 +- typescript/src/browser/index.ts | 5 +- typescript/src/builtin-steps.ts | 55 ++- typescript/src/call-budget.ts | 217 ++++++++++ typescript/src/cancel.ts | 26 ++ typescript/src/config-defaults.ts | 8 + typescript/src/config-key-surface.ts | 1 + typescript/src/config.ts | 8 +- typescript/src/context.ts | 125 ++++-- typescript/src/errors.ts | 11 + typescript/src/executor.ts | 82 ++-- typescript/src/node-api.ts | 5 +- .../src/observability/context-logger.ts | 31 ++ typescript/src/pipeline.ts | 3 +- .../tests/conformance-call-budget.test.ts | 61 +++ .../test-redaction-config-keys.test.ts | 32 ++ typescript/tests/test-call-budget.test.ts | 207 ++++++++++ .../tests/test-context-interactions.test.ts | 100 +++++ 86 files changed, 3487 insertions(+), 287 deletions(-) create mode 100644 conformance/fixtures/call_budget.json create mode 100644 planning/beta-closeout/overview.md create mode 100644 planning/beta-closeout/plan.md create mode 100644 planning/beta-closeout/state.json create mode 100644 planning/beta-closeout/tasks/python.md create mode 100644 planning/beta-closeout/tasks/rust.md create mode 100644 planning/beta-closeout/tasks/surfaces.md create mode 100644 planning/beta-closeout/tasks/typescript.md create mode 100644 planning/beta-closeout/tasks/verification.md create mode 100644 python/src/apcore/call_budget.py create mode 100644 python/tests/test_call_budget.py create mode 100644 python/tests/test_realtime_context.py create mode 100644 python/tests/test_redaction_regex_cap.py create mode 100644 rust/src/call_budget.rs create mode 100644 rust/src/interaction.rs create mode 100644 rust/tests/call_budget.rs create mode 100644 rust/tests/realtime_context.rs create mode 100644 typescript/src/call-budget.ts create mode 100644 typescript/tests/conformance-call-budget.test.ts create mode 100644 typescript/tests/test-call-budget.test.ts create mode 100644 typescript/tests/test-context-interactions.test.ts diff --git a/.github/workflows/packages.yml b/.github/workflows/packages.yml index 5cbe88ee..4bb6ab9b 100644 --- a/.github/workflows/packages.yml +++ b/.github/workflows/packages.yml @@ -46,6 +46,7 @@ jobs: python3 "$GITHUB_WORKSPACE/conformance/extract_doc_examples.py" python "$temporary" (cd quick-start && "$temporary/venv/bin/python" -I example.py) (cd typed-module && "$temporary/venv/bin/python" -I example.py) + (cd invocation-budget && "$temporary/venv/bin/python" -I example.py) python -m venv "$temporary/full" "$temporary/full/bin/python" -m pip install "${wheel[0]}[all]" "$temporary/full/bin/python" -m pip check @@ -118,10 +119,15 @@ jobs: [[bin]] name = "typed-module" path = "typed-module/example.rs" + + [[bin]] + name = "invocation-budget" + path = "invocation-budget/example.rs" EOF (cd quick-start && cargo run --quiet --manifest-path ../Cargo.toml --bin quick-start) (cd governed-stream && cargo run --locked --quiet --manifest-path ../Cargo.toml --bin governed-stream) (cd typed-module && cargo run --locked --quiet --manifest-path ../Cargo.toml --bin typed-module) + (cd invocation-budget && cargo run --locked --quiet --manifest-path ../Cargo.toml --bin invocation-budget) - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 with: name: core-rust-distribution @@ -170,10 +176,11 @@ jobs: node --input-type=module -e 'import {APCore} from "apcore-js/full"; import {Config} from "apcore-js/config"; import {createFilesystemDiscoveryPlugin} from "apcore-js/discovery"; if (!new APCore({config: new Config(), plugins: [createFilesystemDiscoveryPlugin()]}).registry) throw new Error("invalid full assembly");' python3 "$GITHUB_WORKSPACE/conformance/extract_doc_examples.py" typescript "$temporary" ./node_modules/.bin/tsc --strict --module NodeNext --target ES2022 --rootDir . --outDir compiled \ - quick-start/example.ts governed-stream/example.ts typed-module/example.ts + quick-start/example.ts governed-stream/example.ts typed-module/example.ts invocation-budget/example.ts (cd quick-start && node ../compiled/quick-start/example.js) (cd governed-stream && node ../compiled/governed-stream/example.js) (cd typed-module && node ../compiled/typed-module/example.js) + (cd invocation-budget && node ../compiled/invocation-budget/example.js) - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 with: name: core-npm-distribution diff --git a/conformance/README.md b/conformance/README.md index 2afcd7c3..70937179 100644 --- a/conformance/README.md +++ b/conformance/README.md @@ -57,6 +57,7 @@ declared extension. Adapter wire projections are verified in Surfaces. | `openai_strict_compat.json` | protocol-spec §5.12.5 | OpenAI structured-outputs strict-mode compatibility detection backing `BindingStrictSchemaIncompatibleError` on the `auto_schema: strict` binding path. Pins the supported/unsupported keyword set (`anyOf` supported except at root; `$ref`/`$defs` recursion supported; `oneOf`/`allOf`/`not`/`if`/`then`/`else`/`minLength`/`maxLength`/`patternProperties`/`uniqueItems`/… unsupported; nine supported `format` values) and the sorted, de-duplicated feature-path list all three SDKs must emit byte-identically. Detection never rewrites — an author-written `oneOf` is reported, not downgraded to `anyOf` — see `driver_contract`. | | `schema_export_envelope.json` | §4.16 / A23 | `Registry.export_schema(module_id, strict)` envelope parity — exactly the four keys `schemas/module-schema-export.schema.json` declares. Descriptor metadata (`name`/`version`/`tags`/`annotations`/`examples`) belongs to `system.manifest.module`, and there is no sibling `definitions` key: `$defs` stay inside `input_schema`. Drivers MUST assert the key set EXACTLY — an extra key is the defect this pins. | | `config_key_governance.json` | §9.1 / §9.3 / §9.15.3 | Governance of the configuration key surface: an SDK default or constraint table MUST stay inside the key set `apcore-config.schema.json` + `defaults.schema.json` + `sys-modules.schema.json` declare, and MUST reproduce every canonical default exactly. `allowed_keys` / `canonical_defaults` are derived from those schemas by `conformance/generate_config_key_governance.py` — never hand-edit them. | +| `call_budget.json` | Call-budget SDK contract | Governed calls reconcile estimated and actual cost, retain overruns, and stop admitting work after the configured count or cost limit. | | `config_path_typed_keys.json` | §9.2.1 | The closed set of path-typed configuration keys, declared by `"x-apcore-path": true` in `apcore-config.schema.json`. Asserts the SDK accessor equals the declared set in BOTH directions, and that `bindings.pattern` (a glob, not a path) stays out. Asserts nothing about resolution bases — that is `config_project_root.json`'s subject (§9.2.2). | | `config_project_root.json` | §9.2.2 / §9.14 | One captured project root across discovery tiers, explicit and symlinked loads, and subsequent working-directory changes. Pins filesystem paths from defaults, mappings, YAML, and environment overrides, including numeric names and trailing directory qualifiers. Drives the ACL and schema loaders against competing directories. | | `schema_strict_conversion.json` | A23 / §4.16 | `to_strict_schema()` output parity: the exact strict-mode schema all three SDKs must emit. Pins the object-detection rule (`properties` alone identifies an object schema — `type` may be absent, `"object"`, or `["object", "null"]`; `properties` beside a non-object `type` is inert), the single nullable spelling (`{anyOf: [, {type: "null"}]}` for a property with no `type` keyword or with `enum`, `const`, references or applicators — an author-written `oneOf`/`anyOf` is wrapped, never appended to), recursion into `prefixItems`/`items`/combinators/`$defs`, `x-*` + `default` stripping, and the sorted-and-complete `required` list. Drivers MUST call A23 directly — see `driver_contract`. | diff --git a/conformance/check_config_key_consumers.py b/conformance/check_config_key_consumers.py index 5172d7ec..b87d0a80 100644 --- a/conformance/check_config_key_consumers.py +++ b/conformance/check_config_key_consumers.py @@ -1387,6 +1387,18 @@ def _sensitive_keys() -> str | None: return None +@probe("obs.redaction.max_regex_scan_length") +def _max_regex_scan_length() -> str | None: + """The executor redacts values above the configured UTF-8 byte limit.""" + out = _capture_point( + {"sensitive_keys": [], "regex_patterns": ["^secret$"], "max_regex_scan_length": 4}, + {"probe_field": "ééé", "other_field": "éé"}, + ) + if out.get("probe_field") != "***REDACTED***" or out.get("other_field") != "éé": + return "executor did not enforce the configured UTF-8 regex scan limit" + return None + + @probe("obs.redaction.regex_patterns") def _regex_patterns() -> str | None: """A VALUE matching the key is redacted at the capture point; one that is not, is not.""" diff --git a/conformance/config_key_consumers.json b/conformance/config_key_consumers.json index 7e05a98e..7d3c39b8 100644 --- a/conformance/config_key_consumers.json +++ b/conformance/config_key_consumers.json @@ -177,6 +177,10 @@ "reason": "No code path reads it.", "tracking": "https://github.com/aiperceivable/apcore/issues/118" }, + "obs.redaction.max_regex_scan_length": { + "status": "live", + "probe": "obs.redaction.max_regex_scan_length" + }, "obs.redaction.regex_patterns": { "status": "live", "probe": "obs.redaction.regex_patterns" diff --git a/conformance/extract_doc_examples.py b/conformance/extract_doc_examples.py index f8b7b625..f95e0377 100644 --- a/conformance/extract_doc_examples.py +++ b/conformance/extract_doc_examples.py @@ -37,6 +37,7 @@ def main() -> None: (STREAM_GUIDE, "stream-config", "yaml", "governed-stream/apcore.yaml"), (STREAM_GUIDE, "stream-acl", "yaml", "governed-stream/acl/global_acl.yaml"), ("docs/features/module-interface.md", "typed-module", args.language, f"typed-module/example.{ext}"), + ("docs/features/context-object.md", "invocation-budget", args.language, f"invocation-budget/example.{ext}"), ) try: files = [(args.destination / target, example(source, label, lang)) for source, label, lang, target in sources] diff --git a/conformance/fixtures/call_budget.json b/conformance/fixtures/call_budget.json new file mode 100644 index 00000000..acd48a8b --- /dev/null +++ b/conformance/fixtures/call_budget.json @@ -0,0 +1,101 @@ +{ + "description": "Shared call-tree accounting through the public governed call entry point.", + "test_cases": [ + { + "id": "settle_actual_cost_and_exhaust_call_count", + "module_id": "budget.fixture", + "max_calls": 2, + "max_cost": 5, + "estimated_cost": 2, + "calls": [ + { + "actual_cost": 3 + }, + { + "actual_cost": 1 + }, + { + "actual_cost": 0 + } + ], + "expected": [ + { + "calls_used": 1, + "calls_reserved": 0, + "cost_used": 3, + "error_code": null + }, + { + "calls_used": 2, + "calls_reserved": 0, + "cost_used": 4, + "error_code": null + }, + { + "calls_used": 2, + "calls_reserved": 0, + "cost_used": 4, + "error_code": "CALL_BUDGET_EXCEEDED" + } + ] + }, + { + "id": "keep_the_charge_for_an_actual_overrun", + "module_id": "budget.fixture", + "max_calls": null, + "max_cost": 3, + "estimated_cost": 1, + "calls": [ + { + "actual_cost": 4 + }, + { + "actual_cost": 0 + } + ], + "expected": [ + { + "calls_used": 1, + "calls_reserved": 0, + "cost_used": 4, + "error_code": "CALL_BUDGET_EXCEEDED" + }, + { + "calls_used": 1, + "calls_reserved": 0, + "cost_used": 4, + "error_code": "CALL_BUDGET_EXCEEDED" + } + ] + }, + { + "id": "keep_the_estimate_if_the_module_does_not_report_cost", + "module_id": "budget.fixture", + "max_calls": 3, + "max_cost": 3, + "estimated_cost": 2, + "calls": [ + { + "actual_cost": null + }, + { + "actual_cost": null + } + ], + "expected": [ + { + "calls_used": 1, + "calls_reserved": 0, + "cost_used": 2, + "error_code": null + }, + { + "calls_used": 1, + "calls_reserved": 0, + "cost_used": 2, + "error_code": "CALL_BUDGET_EXCEEDED" + } + ] + } + ] +} diff --git a/conformance/fixtures/config_key_governance.json b/conformance/fixtures/config_key_governance.json index e8649c51..1563c515 100644 --- a/conformance/fixtures/config_key_governance.json +++ b/conformance/fixtures/config_key_governance.json @@ -44,6 +44,7 @@ "logging.format", "logging.level", "middleware.disabled", + "obs.redaction.max_regex_scan_length", "obs.redaction.regex_patterns", "obs.redaction.replacement", "obs.redaction.sensitive_keys", diff --git a/docs/features/context-object.md b/docs/features/context-object.md index f7da1048..3798079e 100644 --- a/docs/features/context-object.md +++ b/docs/features/context-object.md @@ -34,7 +34,7 @@ For caller-identity semantics see [Identity System](./identity-system.md). For ` | Framework engine dependency | `trace_id`, `caller_id`, `call_chain`, `executor` | Removing any one breaks the framework | | Almost always needed | `identity` | ACL is first-class; it needs a standardized "who" | | Logging safety | `redacted_inputs`, `redacted_output` | Payload copies safe to log | -| Optional extensions | `cancel_token`, `services`, `global_deadline` | Cooperative cancellation, DI, call-tree budget | +| Optional extensions | `cancel_token`, `services`, `global_deadline` | Cooperative cancellation, dependency injection, and an absolute deadline | | Generic bag | `data` | Pipeline state, locale, feature flags | ### Field Constraints @@ -152,11 +152,133 @@ For cross-process transfer (distributed execution, task queues) a Context serial TypeScript's `serialize()` / `deserialize()` remain as deprecated aliases of `toJSON()` / `fromJSON()`. - Serialized: `_context_version: 1`, `trace_id`, `caller_id`, `call_chain`, `identity`, `data` (keys not starting with `_`), and `redacted_inputs` / `redacted_output` when set. -- Not serialized (runtime-only): `executor`, `cancel_token`, `services`, `global_deadline`. +- Not serialized (runtime-only): `executor`, `cancel_token`, `services`, `global_deadline`, and the invocation attachments described below. - A `_context_version` greater than 1 logs a warning and deserialization proceeds best-effort. After deserialization `executor` is null; the receiving Executor binds itself on the first call ([Executor binding to Context](./core-executor.md#contract-executor-binding-to-context)), synthesizes a fresh local `CancelToken`, and recomputes `global_deadline` from its own configuration. `services` is re-injected by the application. +### In-process invocation attachments + +A host can derive a context with a shared call budget, a progress reporter, +or an elicitation handler. Child calls inherit the attachments. Reattach them +locally when reconstructing a context from serialized data. + +A budget counts invocations that start business execution. Pending approval, +input rejection, and cancellation before dispatch release their reservations. +Each dispatched retry consumes a call. A host can assign a cost estimate in +integer units to each module. During execution, `record_cost` or `recordCost` +replaces the estimate once with the actual total for that attempt. A reported +overrun remains charged and returns `CALL_BUDGET_EXCEEDED`. Preflight leaves +the budget unchanged. + +=== "Python" + + + ```python + from apcore import APCore, CallBudget, Context + + client = APCore() + budget = CallBudget(max_calls=8, max_cost=20, estimated_costs={"reports.render": 2}) + context = Context.create().with_budget(budget) + + + @client.module("reports.render", description="Render a report") + def render(context: Context) -> dict[str, bool]: + context.record_cost(3) + return {"rendered": True} + + + assert client.call("reports.render", {}, context) == {"rendered": True} + assert (budget.snapshot().calls_used, budget.snapshot().cost_used) == (1, 3) + client.close() + ``` + + Use `with_progress_reporter` and `with_elicitation_handler` to attach + callbacks. Modules await `context.report_progress(...)` or + `context.elicit(...)` during execution. + +=== "TypeScript" + + + ```typescript + import assert from 'node:assert/strict'; + import { APCore, CallBudget, Context } from 'apcore-js'; + + const client = new APCore(); + const budget = new CallBudget({ maxCalls: 8, maxCost: 20, estimatedCosts: { 'reports.render': 2 } }); + const context = Context.create().withBudget(budget); + await client.register('reports.render', { + description: 'Render a report', + inputSchema: { type: 'object' }, + outputSchema: { type: 'object', properties: { rendered: { type: 'boolean' } } }, + execute(_input: unknown, context: Context) { + context.recordCost(3); + return { rendered: true }; + }, + }); + assert.deepEqual(await client.call('reports.render', {}, context), { rendered: true }); + assert.deepEqual(budget.snapshot(), { callsUsed: 1, callsReserved: 0, costUsed: 3 }); + await client.shutdown(); + ``` + + Use `withProgressReporter` and `withElicitationHandler` to attach + callbacks. Modules await `context.reportProgress(...)` or + `context.elicit(...)` during execution. + +=== "Rust" + + + ```rust + use apcore::{APCore, CallBudget, Context, ModuleError}; + use schemars::JsonSchema; + use serde::{Deserialize, Serialize}; + use serde_json::Value; + use std::{collections::HashMap, sync::Arc}; + + #[derive(Deserialize, JsonSchema, Serialize)] + struct RenderInput {} + + #[derive(Deserialize, JsonSchema, Serialize)] + struct RenderOutput { + rendered: bool, + } + + /// Render a report. + #[apcore::module(id = "reports.render")] + async fn render(_input: RenderInput, context: &Context) -> Result { + context.record_cost(3)?; + Ok(RenderOutput { rendered: true }) + } + + #[tokio::main] + async fn main() -> Result<(), ModuleError> { + let client = APCore::new(); + render::DECLARATION.register(&client)?; + let budget = Arc::new(CallBudget::new( + Some(8), + Some(20), + HashMap::from([("reports.render".into(), 2)]), + )?); + let context = Context::::anonymous().with_budget(Some(Arc::clone(&budget))); + let result = render::HANDLE.invoke(&client, RenderInput {}, Some(&context)).await?; + assert!(result.rendered); + assert_eq!((budget.snapshot().calls_used, budget.snapshot().cost_used), (1, 3)); + Ok(()) + } + ``` + + Use `with_progress_reporter` and `with_elicitation_handler` to attach + callbacks. Modules await `context.report_progress(...)` or + `context.elicit(...)` during execution. + +Progress reporting has no effect when the host supplies no reporter. +Elicitation without a handler returns an empty optional result. With a +handler, the response indicates acceptance, decline, or cancellation. +Execution cancellation and the invocation deadline also apply to the callbacks. + +Rust code that constructs a `Context { ... }` struct literal can migrate to +`Context::create(...)` or `Context::anonymous()` and apply the derivation methods. + ## Edge Cases | Scenario | Behavior | Level | diff --git a/docs/features/error-system.md b/docs/features/error-system.md index 439838d6..ef5e5d31 100644 --- a/docs/features/error-system.md +++ b/docs/features/error-system.md @@ -275,8 +275,9 @@ Class names are the Python / TypeScript names; where the two differ, both are gi | `CALL_DEPTH_EXCEEDED` | `CallDepthExceededError` | Exceeds max nesting depth (`details`: `depth`, `max_depth`, `call_chain`) | | `CIRCULAR_CALL` | `CircularCallError` | Circular call detected (`details`: `module_id`, `call_chain`) | | `CALL_FREQUENCY_EXCEEDED` | `CallFrequencyExceededError` | Module called too many times (`details`: `module_id`, `count`, `max_repeat`, `call_chain`) | +| `CALL_BUDGET_EXCEEDED` | `CallBudgetExceededError` (Python and TypeScript), `ErrorCode::CallBudgetExceeded` (Rust) | The call tree exceeded its call or cost limit. The nonretryable error reports the `dimension` as `calls` or `cost`. | -See [Call Chain Guard](./call-chain-guard.md) for when each is raised. +See [Call Chain Guard](./call-chain-guard.md) and [Call-tree budgets](./context-object.md#in-process-invocation-attachments) for the execution boundaries. #### Binding Errors diff --git a/docs/features/observability.md b/docs/features/observability.md index 22c3769c..249ed896 100644 --- a/docs/features/observability.md +++ b/docs/features/observability.md @@ -27,7 +27,7 @@ Only the keys below touch observability. The authoritative per-key status is `co | `observability.tracing.sampling_rate` | live | Probability used by `proportional` and `error_first` (default `1.0`) | | `observability.tracing.exporter` | live | `stdout` (default) · `otlp` · `jaeger` | | `observability.tracing.otlp_endpoint` | live | OTLP target; only valid with `exporter: otlp` | -| `obs.redaction.sensitive_keys` · `regex_patterns` · `replacement` | live | See [Redaction](./redaction.md#configured-rules-obsredaction) | +| `obs.redaction.sensitive_keys` · `regex_patterns` · `replacement` · `max_regex_scan_length` | live | See [Redaction](./redaction.md#configured-rules-obsredaction) | | `sys_modules.error_history.max_entries_per_module` · `max_total_entries` | live | Limits of the auto-created `ErrorHistory` ([Error History](./error-history.md#configuration)) | | `sys_modules.events.thresholds.error_rate` · `latency_p99_ms` | live | Alert thresholds of `PlatformNotifyMiddleware` ([Metrics and Usage](./metrics-and-usage.md#threshold-alerts)) | | `observability.metrics.enabled` · `observability.metrics.exporter` | **inert** | Read by nothing; deprecated ([§9.2.4](../spec/protocol-spec.md#924-deprecated-configuration-keys)). Metrics come from a `MetricsCollector` you construct. | diff --git a/docs/features/redaction.md b/docs/features/redaction.md index 46ede65a..079be60c 100644 --- a/docs/features/redaction.md +++ b/docs/features/redaction.md @@ -50,6 +50,7 @@ With these inputs, `context.redacted_inputs` holds `{"username": "alice", "passw |---|---|---|---| | `obs.redaction.sensitive_keys` | list of strings | the [default list](#default-sensitive_keys) | Field-name rules | | `obs.redaction.regex_patterns` | list of strings | `[]` | Regular expressions tested against string values | +| `obs.redaction.max_regex_scan_length` | integer | `65536` | UTF-8 byte limit for a value before regex matching | | `obs.redaction.replacement` | string | `***REDACTED***` | The marker written in place of a redacted value | ```yaml @@ -108,6 +109,8 @@ access_key private_key authorization auth credential cookie session beare - Each pattern is searched for anywhere in the value (**unanchored**) and **case-insensitively**; write `^…$` to require a whole-value match. - Only **string** values are tested. Numbers, booleans, `null`, objects and arrays are never converted to strings to be tested; objects and arrays are walked, so a string inside them is still tested at its own position. +- With a regex rule active, a string above the configured byte limit uses the + replacement marker. A string exactly at the limit still goes through matching. - Keep patterns inside the portable subset of [§9.2.3](../spec/protocol-spec.md#923-pattern-valued-values) — no lookaround, no backreferences, no inline flag groups such as `(?i)` — so they mean the same thing in all three SDKs. - A pattern that does not compile is reported when the configuration is read (naming the pattern and the engine's error) and redacts nothing. It is never silently dropped. diff --git a/docs/index.md b/docs/index.md index 840dd81f..4fd469d7 100644 --- a/docs/index.md +++ b/docs/index.md @@ -25,9 +25,9 @@ A schema makes a capability contract machine-readable and validatable. It does n | Component | Package | Stable | In development | |---|---|---|---| | Protocol specification | [protocol-spec.md](spec/protocol-spec.md) | `1.66.0` | `2.0.0` (draft revision 4) | -| Python SDK | `apcore` | `0.33.0` | `1.0.0a6` | -| TypeScript SDK | `apcore-js` | `0.33.0` | `1.0.0-alpha.6` | -| Rust SDK | `apcore` | `0.33.0` | `1.0.0-alpha.6` | +| Python SDK | `apcore` | `0.33.0` | `1.0.0b1` | +| TypeScript SDK | `apcore-js` | `0.33.0` | `1.0.0-beta.1` | +| Rust SDK | `apcore` | `0.33.0` | `1.0.0-beta.1` | The protocol `2.0.0` draft defines the contract for the SDK `1.0.0` release line. The three core SDKs share that release line. Surface adapters (`apcore-mcp`, `apcore-a2a`, `apcore-cli`, `apcore-toolkit`) are versioned independently and declare the core range they support in their package metadata. diff --git a/planning/beta-closeout/overview.md b/planning/beta-closeout/overview.md new file mode 100644 index 00000000..ee552d87 --- /dev/null +++ b/planning/beta-closeout/overview.md @@ -0,0 +1,5 @@ +# Beta Closeout + +Finish the remaining SDK work from the architecture blueprint and verify the +adapter pilot from the same set of installed candidates. Coordinate one PR per +repository. Record public installation and adoption evidence when it exists. diff --git a/planning/beta-closeout/plan.md b/planning/beta-closeout/plan.md new file mode 100644 index 00000000..f3e40d0a --- /dev/null +++ b/planning/beta-closeout/plan.md @@ -0,0 +1,34 @@ +# Beta Closeout Implementation Plan + +## Core acceptance + +- Keep the six-argument Context constructor. Budget and interaction attachments + live in process, follow child contexts, and stay out of serialized context. +- Verify that the stock call-chain guard reserves a slot atomically. Denial, + validation failure, cancellation before dispatch, and a pending approval + release that slot. Business dispatch commits the slot and the estimated cost. + Each dispatched retry is charged separately. Preflight leaves the ledger intact. +- Settle each active invocation's cost once with the observed amount. Charge + amounts even when they exceed the limit and prevent later spending over cap. +- Verify live progress and elicitation with configured callbacks, cancellation, + deadline, and absent handlers. Keep the existing approval lifecycle. +- Bound regular-expression input to 65,536 UTF-8 bytes by default. With an + active regex rule, redact string values above the cap before matching. + +## Surface pilot + +- Start with opt-in artifact links on MCP tool results. Use a top-level output + property marked `x-mcp-artifact` for an opaque artifact ID and retain the + existing text and structured results. Read binary content through a guarded + resource lookup. +- Verify owner and current authority, expiry, size, and an actual MCP client. + The adapter accepts opaque IDs and in-process data from a trusted host. +- Assess the A2A mapping using the same access and expiry guarantees before + proposing a common Core artifact contract. + +## Delivery + +Python, TypeScript, and Rust SDK changes run in parallel. Combine their evidence +with the Surface integration tests, installed package checks, and the existing +candidate workflow. Changes to normative protocol text require maintainer +approval under AGENTS.md. diff --git a/planning/beta-closeout/state.json b/planning/beta-closeout/state.json new file mode 100644 index 00000000..2dc3de9c --- /dev/null +++ b/planning/beta-closeout/state.json @@ -0,0 +1,57 @@ +{ + "feature": "beta-closeout", + "created": "2026-11-28", + "updated": "2026-11-28", + "status": "in_progress", + "execution_order": [ + "python", + "typescript", + "rust", + "surfaces", + "verification" + ], + "progress": { + "total_tasks": 5, + "completed": 3, + "in_progress": 2, + "pending": 0 + }, + "tasks": [ + { + "id": "python", + "file": "tasks/python.md", + "title": "Python Core runtime", + "status": "completed" + }, + { + "id": "typescript", + "file": "tasks/typescript.md", + "title": "TypeScript Core runtime", + "status": "completed" + }, + { + "id": "rust", + "file": "tasks/rust.md", + "title": "Rust Core runtime", + "status": "completed" + }, + { + "id": "surfaces", + "file": "tasks/surfaces.md", + "title": "Guarded media reference pilot", + "status": "in_progress" + }, + { + "id": "verification", + "file": "tasks/verification.md", + "title": "Cross-language and candidate verification", + "status": "in_progress", + "dependencies": [ + "python", + "typescript", + "rust", + "surfaces" + ] + } + ] +} diff --git a/planning/beta-closeout/tasks/python.md b/planning/beta-closeout/tasks/python.md new file mode 100644 index 00000000..336b7ad9 --- /dev/null +++ b/planning/beta-closeout/tasks/python.md @@ -0,0 +1,4 @@ +# Python Core Runtime + +Implement the shared acceptance criteria in [the plan](../plan.md) with the +stock synchronous and asynchronous executor entry points and streaming. diff --git a/planning/beta-closeout/tasks/rust.md b/planning/beta-closeout/tasks/rust.md new file mode 100644 index 00000000..1a93cd7c --- /dev/null +++ b/planning/beta-closeout/tasks/rust.md @@ -0,0 +1,4 @@ +# Rust Core Runtime + +Implement the shared acceptance criteria in [the plan](../plan.md) while +keeping the default feature graph and Rust toolchain floor. diff --git a/planning/beta-closeout/tasks/surfaces.md b/planning/beta-closeout/tasks/surfaces.md new file mode 100644 index 00000000..4fe5aefc --- /dev/null +++ b/planning/beta-closeout/tasks/surfaces.md @@ -0,0 +1,3 @@ +# Guarded Media Reference Pilot + +Implement and test the Surface pilot in [the plan](../plan.md). diff --git a/planning/beta-closeout/tasks/typescript.md b/planning/beta-closeout/tasks/typescript.md new file mode 100644 index 00000000..66e060c7 --- /dev/null +++ b/planning/beta-closeout/tasks/typescript.md @@ -0,0 +1,4 @@ +# TypeScript Core Runtime + +Implement the shared acceptance criteria in [the plan](../plan.md) while +preserving the portable package entry. diff --git a/planning/beta-closeout/tasks/verification.md b/planning/beta-closeout/tasks/verification.md new file mode 100644 index 00000000..eb79fb92 --- /dev/null +++ b/planning/beta-closeout/tasks/verification.md @@ -0,0 +1,4 @@ +# Cross-Language and Candidate Verification + +Check the shared behaviors, existing full suites, typed and protocol +integration tests, and installed candidates listed in [the plan](../plan.md). diff --git a/python/apcore-conformance.yaml b/python/apcore-conformance.yaml index 9b613b7b..cda1b0fd 100644 --- a/python/apcore-conformance.yaml +++ b/python/apcore-conformance.yaml @@ -1,6 +1,6 @@ implementation: name: apcore-python - version: 1.0.0a6 + version: 1.0.0b1 language: python spec_version: 1.65.0 maintainer: AI Perceivable diff --git a/python/pyproject.toml b/python/pyproject.toml index be5ba33d..2b969202 100644 --- a/python/pyproject.toml +++ b/python/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "apcore" -version = "1.0.0a6" +version = "1.0.0b1" description = "Build once, invoke by code or AI — with schema, ACL, approval, and audit enforced at every call" readme = "README.md" requires-python = ">=3.11" diff --git a/python/src/apcore/__init__.py b/python/src/apcore/__init__.py index 58b4a565..143a717f 100644 --- a/python/src/apcore/__init__.py +++ b/python/src/apcore/__init__.py @@ -22,8 +22,17 @@ ScopedApprovalHandler, ) from apcore.cancel import CancelToken, ExecutionCancelledError +from apcore.call_budget import CallBudget, CallBudgetSnapshot from apcore.capabilities import AccessHint, CallableDefinition, CapabilityPage, CapabilitySearchProvider, ModuleSummary -from apcore.context import Context, ContextFactory, GovernanceProjection, Identity +from apcore.context import ( + Context, + ContextFactory, + ElicitationHandler, + ElicitationResult, + GovernanceProjection, + Identity, + ProgressReporter, +) from apcore.context_key import ContextKey from apcore.context_keys import ( LOGGING_START, @@ -111,6 +120,7 @@ BindingSchemaModeConflictError, BindingStrictSchemaIncompatibleError, CallDepthExceededError, + CallBudgetExceededError, CallFrequencyExceededError, CircularCallError, CircularDependencyError, @@ -593,6 +603,9 @@ def enable(module_id: str, reason: str = "Enabled via APCore client") -> dict[st "ApprovalResult", "AutoApproveHandler", "BoundModule", + "CallBudget", + "CallBudgetExceededError", + "CallBudgetSnapshot", "CancelToken", "AccessHint", "CallableDefinition", @@ -601,6 +614,8 @@ def enable(module_id: str, reason: str = "Enabled via APCore client") -> dict[st "ModuleSummary", "VisibilityDecision", "Context", + "ElicitationHandler", + "ElicitationResult", "ErrorCodes", "ExecutionPolicy", "PolicyDeniedError", @@ -618,6 +633,7 @@ def enable(module_id: str, reason: str = "Enabled via APCore client") -> dict[st "PipelineEngine", "PreflightResult", "PreviewResult", + "ProgressReporter", "Registry", "ReloadOptions", "SchemaExporter", diff --git a/python/src/apcore/_post_validation_policy.py b/python/src/apcore/_post_validation_policy.py index e03a23af..09d55d17 100644 --- a/python/src/apcore/_post_validation_policy.py +++ b/python/src/apcore/_post_validation_policy.py @@ -9,7 +9,6 @@ import re import struct import time -from contextlib import suppress from copy import copy, deepcopy from typing import TYPE_CHECKING, Any, Annotated, get_args, get_origin from uuid import UUID, SafeUUID @@ -18,6 +17,7 @@ from pydantic.fields import FieldInfo from apcore.errors import PolicyEvaluationError +from apcore.cancel import _AwaitDeadlineExpired, _await_with_cancellation from apcore.context import _APPROVAL_TOKEN_KEY from apcore.decorator import FunctionModule from apcore.policy import PolicyEvaluationRequest, PolicyEvaluator, PolicyVerdict @@ -209,45 +209,13 @@ async def _evaluate_policy( deadline: float | None, ) -> PolicyVerdict: """Bound a trusted provider independently of its cancellation cooperation.""" - if token is not None: - token.check() remaining = _EVALUATOR_TIMEOUT_SECONDS if deadline is not None: remaining = min(remaining, deadline - time.time()) - if remaining <= 0: - raise PolicyEvaluationError() - - loop = asyncio.get_running_loop() - expires_at = loop.time() + remaining - cancelled = loop.create_future() - - def report_cancellation() -> None: - if not cancelled.done(): - cancelled.set_result(None) - - def signal_cancellation() -> None: - with suppress(RuntimeError): - loop.call_soon_threadsafe(report_cancellation) - - unsubscribe = token._listen(signal_cancellation) if token is not None else None - task = asyncio.create_task(_read_verdict(evaluator, request)) try: - await asyncio.wait((task, cancelled), timeout=remaining, return_when=asyncio.FIRST_COMPLETED) - if token is not None: - token.check() - # A non-yielding evaluator can finish before the loop services its timer. - if not task.done() or loop.time() >= expires_at: - raise PolicyEvaluationError() - return task.result() - finally: - if unsubscribe is not None: - unsubscribe() - cancelled.cancel() - if not task.done(): - task.cancel() - task.add_done_callback(_consume_result) - elif not task.cancelled(): - task.exception() + return await _await_with_cancellation(lambda: _read_verdict(evaluator, request), token, remaining) + except _AwaitDeadlineExpired: + raise PolicyEvaluationError() from None async def _read_verdict(evaluator: PolicyEvaluator, request: PolicyEvaluationRequest) -> PolicyVerdict: @@ -260,10 +228,5 @@ async def _read_verdict(evaluator: PolicyEvaluator, request: PolicyEvaluationReq raise PolicyEvaluationError() -def _consume_result(task: asyncio.Future[PolicyVerdict]) -> None: - if not task.cancelled(): - task.exception() - - def _safe_rule_id(rule_id: str | None) -> str | None: return rule_id if isinstance(rule_id, str) and _RULE_ID.fullmatch(rule_id) else None diff --git a/python/src/apcore/builtin_steps.py b/python/src/apcore/builtin_steps.py index c89ff6ec..e7a66551 100644 --- a/python/src/apcore/builtin_steps.py +++ b/python/src/apcore/builtin_steps.py @@ -25,6 +25,7 @@ from apcore._post_validation_policy import _evaluate_policy, _PolicyInvocation, _safe_rule_id from apcore.acl import ACL from apcore.approval import ApprovalRequest, ApprovalResult, ScopedApprovalHandler +from apcore.call_budget import _CallReservation from apcore.cancel import CancelToken, ExecutionCancelledError from apcore.context import Context, GovernanceProjection, _identity_audit_fields from apcore.context_keys import _current_trace_span @@ -389,6 +390,14 @@ async def execute(self, ctx: PipelineContext) -> StepResult: max_call_depth=self._max_call_depth, max_module_repeat=self._max_module_repeat, ) + if ctx._call_budget is not None: + if ctx.dry_run: + ctx._call_budget._check(ctx.module_id) + else: + if ctx.execution_scope is None: + raise ConfigurationError("CallBudget requires an execution scope") + reservation = ctx._budget_reservation = ctx._call_budget._reserve(ctx.module_id) + ctx.execution_scope.callback(reservation.release) return StepResult(action="continue") @@ -431,6 +440,7 @@ def _redact_payload(data: dict[str, Any] | None, schema_model: Any, rules: Redac sensitive_keys=rules.sensitive_keys, regex_patterns=rules.compiled_regex_patterns, replacement=rules.replacement, + max_regex_scan_length=rules.max_regex_scan_length, ) @@ -1522,6 +1532,20 @@ def _end_for_timeout(ctx: PipelineContext, timeout_ms: int) -> ModuleTimeoutErro token.cancel() return error + @staticmethod + def _start_budgeted_dispatch(ctx: PipelineContext) -> _CallReservation: + context = ctx.context + reservation = ctx._budget_reservation + if reservation is None or not isinstance(context, Context) or context._call_budget is not ctx._call_budget: + raise ConfigurationError("CallBudget requires a reserved invocation and its execution context") + if context.cancel_token is not None: + context.cancel_token.check() + if context.global_deadline is not None and time.time() >= context.global_deadline: + raise ModuleTimeoutError(ctx.module_id, 0, retryable=_is_idempotent(ctx.module)) + reservation.start() + context._budget_reservation = reservation + return reservation + async def execute(self, ctx: PipelineContext) -> StepResult: module = ctx.module if module is None: @@ -1559,6 +1583,13 @@ async def execute(self, ctx: PipelineContext) -> StepResult: except StreamingInterfaceError: pass # No compatible streaming method. Execute once as a fallback. else: + if ctx._call_budget is not None: + if ctx._budget_reservation is None or ctx.execution_scope is None: + raise ConfigurationError("CallBudget requires a reserved streaming invocation") + ctx.execution_scope.callback(ctx._budget_reservation.finish) + ctx._budget_stream_pending = inspect.isasyncgenfunction(module.stream) + if not ctx._budget_stream_pending: + self._start_budgeted_dispatch(ctx) stream = module.stream(inputs, ctx.context) if inspect.isawaitable(stream): stream = await stream @@ -1597,10 +1628,15 @@ async def execute(self, ctx: PipelineContext) -> StepResult: managed_reload = True is_async = inspect.iscoroutinefunction(execute) if is_async: - coro = execute(inputs, ctx.context) + coro = ( + _execute_budgeted_async_module(execute, inputs, ctx) + if ctx._call_budget is not None + else execute(inputs, ctx.context) + ) else: loop = asyncio.get_event_loop() - coro = loop.run_in_executor(None, _execute_sync_module, execute, inputs, ctx.context) + budgeted_ctx = ctx if ctx._call_budget is not None else None + coro = loop.run_in_executor(None, _execute_sync_module, execute, inputs, ctx.context, budgeted_ctx) task = ctx.module_task = asyncio.ensure_future(coro) # Consume late failures even when the call was cancelled while @@ -1630,6 +1666,10 @@ async def execute(self, ctx: PipelineContext) -> StepResult: if not isinstance(output, dict): raise ModuleExecuteError(module_id=ctx.module_id, message="Return value must be Map") ctx.output = output + except asyncio.CancelledError: + if ctx._budget_reservation is not None: + ctx._budget_reservation.release() + raise except asyncio.TimeoutError: timeout_ms = int((timeout_s or 0) * 1000) raise ModuleTimeoutError( @@ -1646,16 +1686,35 @@ class _SyncExecutionFailure: error: BaseException +async def _execute_budgeted_async_module( + execute: Callable[[dict[str, Any], Context], Awaitable[Any]], inputs: dict[str, Any], ctx: PipelineContext +) -> Any: + reservation = BuiltinExecute._start_budgeted_dispatch(ctx) + try: + return await execute(inputs, ctx.context) + finally: + reservation.finish() + + def _execute_sync_module( - execute: Callable[[dict[str, Any], Context], Any], inputs: dict[str, Any], context: Context + execute: Callable[[dict[str, Any], Context], Any], + inputs: dict[str, Any], + context: Context, + budgeted_ctx: PipelineContext | None = None, ) -> Any: + reservation = None try: + if budgeted_ctx is not None: + reservation = BuiltinExecute._start_budgeted_dispatch(budgeted_ctx) return execute(inputs, context) except BaseException as error: # The sync bridge can park or close the loop before its next-turn # callbacks run. Transfer a value so a late worker failure can be # discarded while an active waiter still receives the original error. return _SyncExecutionFailure(error) + finally: + if reservation is not None: + reservation.finish() def _discard_late_execution(task: asyncio.Future[Any]) -> None: diff --git a/python/src/apcore/call_budget.py b/python/src/apcore/call_budget.py new file mode 100644 index 00000000..ce9d105d --- /dev/null +++ b/python/src/apcore/call_budget.py @@ -0,0 +1,124 @@ +"""Opt-in call-tree budget and per-attempt accounting.""" + +from __future__ import annotations + +from collections.abc import Mapping +from dataclasses import dataclass +from threading import Lock +from types import MappingProxyType +from typing import Literal + +from apcore.errors import CallBudgetExceededError, InvalidInputError + +_MAX_SAFE_INTEGER = (1 << 53) - 1 + + +def _validate_cost(value: int, name: str) -> None: + if type(value) is not int or not 0 <= value <= _MAX_SAFE_INTEGER: + raise InvalidInputError(f"{name} must be a non-negative safe integer") + + +@dataclass(frozen=True, slots=True) +class CallBudgetSnapshot: + """An instantaneous view of the budget's accounting.""" + + calls_used: int + calls_reserved: int + cost_used: int + + +class CallBudget: + """Share an optional call count and cost budget across a Context tree.""" + + def __init__( + self, + max_calls: int | None = None, + max_cost: int | None = None, + estimated_costs: Mapping[str, int] | None = None, + ) -> None: + if max_calls is not None: + _validate_cost(max_calls, "max_calls") + if max_cost is not None: + _validate_cost(max_cost, "max_cost") + costs = dict(estimated_costs) if estimated_costs is not None else {} + for module_id, cost in costs.items(): + if not isinstance(module_id, str) or not module_id: + raise InvalidInputError("Estimated cost keys must be module IDs") + _validate_cost(cost, "estimated cost") + self._max_calls = max_calls + self._max_cost = max_cost + self._estimated_costs = MappingProxyType(costs) + self._lock = Lock() + self._calls_used = 0 + self._calls_reserved = 0 + self._cost_used = 0 + + def snapshot(self) -> CallBudgetSnapshot: + """Report calls and cost, clamped to the portable safe integer range.""" + with self._lock: + return CallBudgetSnapshot( + min(self._calls_used, _MAX_SAFE_INTEGER), + min(self._calls_reserved, _MAX_SAFE_INTEGER), + min(self._cost_used, _MAX_SAFE_INTEGER), + ) + + def _check_allowance(self, estimate: int) -> None: + if self._max_calls is not None and self._calls_used + self._calls_reserved >= self._max_calls: + raise CallBudgetExceededError("calls") + self._check_cost(self._cost_used + estimate) + + def _check_cost(self, cost: int) -> None: + if self._max_cost is not None and cost > self._max_cost: + raise CallBudgetExceededError("cost") + + def _check(self, module_id: str) -> None: + with self._lock: + self._check_allowance(self._estimated_costs.get(module_id, 0)) + + def _reserve(self, module_id: str) -> _CallReservation: + estimate = self._estimated_costs.get(module_id, 0) + with self._lock: + self._check_allowance(estimate) + self._calls_reserved += 1 + return _CallReservation(self, estimate) + + +class _CallReservation: + """One guarded attempt, held until it starts or exits.""" + + def __init__(self, budget: CallBudget, estimate: int) -> None: + self._budget = budget + self._estimate = estimate + self._state: Literal["reserved", "active", "closed"] = "reserved" + self._actual_reported = False + + def start(self) -> None: + with self._budget._lock: + if self._state != "reserved": + raise InvalidInputError("Call budget reservation is no longer available") + cost = self._budget._cost_used + self._estimate + self._budget._check_cost(cost) + self._budget._calls_reserved -= 1 + self._budget._calls_used += 1 + self._budget._cost_used = cost + self._state = "active" + + def record_cost(self, actual: int) -> None: + _validate_cost(actual, "actual cost") + with self._budget._lock: + if self._state != "active" or self._actual_reported: + raise InvalidInputError("Actual cost can be recorded once during an active budgeted call") + self._actual_reported = True + self._budget._cost_used += actual - self._estimate + self._budget._check_cost(self._budget._cost_used) + + def release(self) -> None: + with self._budget._lock: + if self._state == "reserved": + self._budget._calls_reserved -= 1 + self._state = "closed" + + def finish(self) -> None: + with self._budget._lock: + if self._state == "active": + self._state = "closed" diff --git a/python/src/apcore/cancel.py b/python/src/apcore/cancel.py index 1c8b4a21..1991ab2e 100644 --- a/python/src/apcore/cancel.py +++ b/python/src/apcore/cancel.py @@ -2,11 +2,16 @@ from __future__ import annotations +import asyncio import threading -from collections.abc import Callable +from collections.abc import Awaitable, Callable +from contextlib import suppress +from typing import TypeVar from apcore.errors import ModuleError +R = TypeVar("R") + class ExecutionCancelledError(ModuleError): """Raised when a module execution is cancelled via CancelToken.""" @@ -87,3 +92,61 @@ def reset(self) -> None: """Reset the token for reuse.""" with self._lock: self._cancelled = False + + +class _AwaitDeadlineExpired(TimeoutError): + """The framework's deadline elapsed while an asynchronous callback ran.""" + + +async def _await_with_cancellation( + operation: Callable[[], Awaitable[R]], token: CancelToken | None, timeout: float | None +) -> R: + """Bound an async operation independently of its cancellation cooperation.""" + if token is not None: + token.check() + if timeout is not None and timeout <= 0: + raise _AwaitDeadlineExpired() + loop = asyncio.get_running_loop() + expires_at = loop.time() + timeout if timeout is not None else None + cancelled = loop.create_future() + + def report_cancellation() -> None: + if not cancelled.done(): + cancelled.set_result(None) + + def signal_cancellation() -> None: + with suppress(RuntimeError): + loop.call_soon_threadsafe(report_cancellation) + + async def run() -> R: + if token is not None: + token.check() + if expires_at is not None and loop.time() >= expires_at: + raise _AwaitDeadlineExpired() + return await operation() + + unsubscribe = token._listen(signal_cancellation) if token is not None else None + task = asyncio.create_task(run()) + try: + await asyncio.wait((task, cancelled), timeout=timeout, return_when=asyncio.FIRST_COMPLETED) + if token is not None: + token.check() + if cancelled.done(): + raise ExecutionCancelledError() + if expires_at is not None and (not task.done() or loop.time() >= expires_at): + raise _AwaitDeadlineExpired() + return task.result() + finally: + if unsubscribe is not None: + unsubscribe() + cancelled.cancel() + if not task.done(): + task.cancel() + task.add_done_callback(_consume_task_result) + else: + _consume_task_result(task) + + +def _consume_task_result(task: asyncio.Future[R]) -> None: + if not task.cancelled(): + task.exception() diff --git a/python/src/apcore/config.py b/python/src/apcore/config.py index 633c41cf..14d90510 100644 --- a/python/src/apcore/config.py +++ b/python/src/apcore/config.py @@ -30,6 +30,7 @@ ) from apcore.version import _negotiate_document_version +from apcore.utils.redaction import DEFAULT_MAX_REGEX_SCAN_LENGTH, _validate_regex_scan_length __all__ = ["Config", "discover_config_file"] @@ -313,6 +314,7 @@ "logging.format", "logging.level", "middleware.disabled", + "obs.redaction.max_regex_scan_length", "obs.redaction.regex_patterns", "obs.redaction.replacement", "obs.redaction.sensitive_keys", @@ -1949,6 +1951,10 @@ def validate(self) -> None: if strict: errors.extend(_collect_unknown_framework_keys(data, prefix=prefix)) errors.extend(_collect_uncompilable_regex_patterns(data)) + try: + _validate_regex_scan_length(self.get("obs.redaction.max_regex_scan_length", DEFAULT_MAX_REGEX_SCAN_LENGTH)) + except ValueError as exc: + errors.append(f"Invalid value for 'obs.redaction.max_regex_scan_length': {exc}") if errors: raise ConfigError( message=f"Configuration validation failed ({len(errors)} error(s)):\n" @@ -2112,6 +2118,7 @@ def _instantiate_model(model_class: type, data: dict[str, Any], namespace: str) defaults={ "redaction": { "regex_patterns": [], + "max_regex_scan_length": DEFAULT_MAX_REGEX_SCAN_LENGTH, "sensitive_keys": list(_DEFAULT_OBS_REDACTION_SENSITIVE_KEYS), "replacement": "***REDACTED***", }, diff --git a/python/src/apcore/context.py b/python/src/apcore/context.py index f529de30..29c5444d 100644 --- a/python/src/apcore/context.py +++ b/python/src/apcore/context.py @@ -3,16 +3,18 @@ from __future__ import annotations import logging +import time import uuid -from collections.abc import Sequence -from copy import deepcopy +from collections.abc import Awaitable, Callable, Sequence +from copy import copy, deepcopy from dataclasses import dataclass, field, replace from types import MappingProxyType -from typing import TYPE_CHECKING, Any, Generic, Mapping, Protocol, TypeVar, runtime_checkable +from typing import TYPE_CHECKING, Any, Generic, Literal, Mapping, Protocol, TypeVar, runtime_checkable -from apcore.cancel import CancelToken +from apcore.call_budget import CallBudget, _CallReservation +from apcore.cancel import CancelToken, _AwaitDeadlineExpired, _await_with_cancellation from apcore.context_keys import TRACING_SAMPLED, _current_trace_span, _middleware_data -from apcore.errors import InvalidInputError +from apcore.errors import InvalidInputError, ModuleTimeoutError from apcore.trace_context import _valid_inbound_parent_id if TYPE_CHECKING: @@ -21,9 +23,18 @@ from apcore.trace_context import TraceParent -__all__ = ["Context", "Identity", "ContextFactory", "GovernanceProjection"] +__all__ = [ + "Context", + "Identity", + "ContextFactory", + "GovernanceProjection", + "ProgressReporter", + "ElicitationHandler", + "ElicitationResult", +] T = TypeVar("T") +R = TypeVar("R") _MAX_DELEGATION_DEPTH = 8 @@ -322,6 +333,25 @@ def type_of(self, key: str) -> str | None: return self.types.get(key) +@dataclass(frozen=True) +class ElicitationResult: + """A transport-neutral reply to a request for input.""" + + action: Literal["accept", "decline", "cancel"] + content: dict[str, Any] | None = None + + def __post_init__(self) -> None: + if self.action == "accept": + if not isinstance(self.content, dict) or not all(isinstance(key, str) for key in self.content): + raise InvalidInputError("Accepted elicitation content must be an object") + elif self.action not in ("decline", "cancel") or self.content is not None: + raise InvalidInputError("Declined or cancelled elicitation must have no content") + + +ProgressReporter = Callable[[float, float | None, str | None], Awaitable[None]] +ElicitationHandler = Callable[[str, dict[str, Any] | None], Awaitable[ElicitationResult]] + + @dataclass class Context(Generic[T]): """Module execution context.""" @@ -347,6 +377,10 @@ class Context(Generic[T]): _local_parent_span: Any = field(default=None, init=False, repr=False, compare=False) _parent_sampled: bool | None = field(default=None, init=False, repr=False, compare=False) _inbound_trace_parent: TraceParent | None = field(default=None, init=False, repr=False, compare=False) + _progress_reporter: ProgressReporter | None = field(default=None, init=False, repr=False, compare=False) + _elicitation_handler: ElicitationHandler | None = field(default=None, init=False, repr=False, compare=False) + _call_budget: CallBudget | None = field(default=None, init=False, repr=False, compare=False) + _budget_reservation: _CallReservation | None = field(default=None, init=False, repr=False, compare=False) @classmethod def create( @@ -424,6 +458,64 @@ def create( context._inbound_trace_parent = trace_parent return context + def with_progress_reporter(self, callback: ProgressReporter | None) -> Context[T]: + """Return a context with its own progress callback binding.""" + 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.""" + context = self._with_local_binding() + context._elicitation_handler = callback + return context + + def with_budget(self, budget: CallBudget | None) -> Context[T]: + """Return a context that gives future calls and their children this budget.""" + if budget is not None and not isinstance(budget, CallBudget): + raise InvalidInputError("Expected a CallBudget or None") + context = self._with_local_binding() + context._call_budget = budget + context._budget_reservation = None + return context + + def record_cost(self, actual: int) -> None: + """Replace this attempt's estimated cost with its one actual cost report.""" + if self._call_budget is not None: + reservation = self._budget_reservation + if reservation is None: + raise InvalidInputError("Actual cost can only be recorded during an active budgeted call") + reservation.record_cost(actual) + + def _with_local_binding(self) -> Context[T]: + context = copy(self) + context.call_chain = list(self.call_chain) + return context + + async def report_progress(self, progress: float, total: float | None = None, message: str | None = None) -> None: + """Report progress to the attached host callback when one is available.""" + callback = self._progress_reporter + if callback is not None: + await self._wait_for_interaction(lambda: callback(progress, total, message)) + + async def elicit(self, message: str, requested_schema: dict[str, Any] | None = None) -> ElicitationResult | None: + """Ask the host for optional structured input.""" + callback = self._elicitation_handler + if callback is None: + return None + result = await self._wait_for_interaction(lambda: callback(message, requested_schema)) + if not isinstance(result, ElicitationResult): + raise InvalidInputError("Expected an ElicitationResult from the handler") + return result + + async def _wait_for_interaction(self, callback: Callable[[], Awaitable[R]]) -> R: + remaining = self.global_deadline - time.time() if self.global_deadline is not None else None + try: + return await _await_with_cancellation(callback, self.cancel_token, remaining) + except _AwaitDeadlineExpired: + module_id = self.call_chain[-1] if self.call_chain else "" + raise ModuleTimeoutError(module_id, int(max(0, remaining or 0) * 1000)) from None + def bind_executor(self, executor: Any) -> None: """SDK-internal contract member. Bind the Executor to this Context. @@ -520,6 +612,9 @@ def child(self, target_module_id: str) -> Context[T]: child._local_parent_span = _current_trace_span(self, include_parent=True) child._parent_sampled = _middleware_data(self).get(TRACING_SAMPLED.name, self._parent_sampled) child._inbound_trace_parent = self._inbound_trace_parent + child._progress_reporter = self._progress_reporter + child._elicitation_handler = self._elicitation_handler + child._call_budget = self._call_budget return child diff --git a/python/src/apcore/errors.py b/python/src/apcore/errors.py index dca192ca..730cf90d 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 +from typing import Any, Literal __all__ = [ "ModuleError", @@ -34,6 +34,7 @@ "ModuleNotFoundError", "ModuleDisabledError", "ModuleTimeoutError", + "CallBudgetExceededError", "SchemaValidationError", "SchemaNotFoundError", "SchemaParseError", @@ -476,6 +477,19 @@ def __init__(self, module_id: str, **kwargs: Any) -> None: ) +class CallBudgetExceededError(ModuleError): + """Raised when a guarded call reaches a call or cost budget limit.""" + + _default_retryable: bool | None = False + + def __init__(self, dimension: Literal["calls", "cost"]) -> None: + super().__init__( + code="CALL_BUDGET_EXCEEDED", + message=f"Call budget exceeded ({dimension})", + details={"dimension": dimension}, + ) + + class ModuleTimeoutError(ModuleError): """Raised when module execution exceeds timeout.""" @@ -943,8 +957,7 @@ def __init__( super().__init__( code="BINDING_SCHEMA_INFERENCE_FAILED", message=( - f"{loc}{mod_part}auto schema inference failed for target '{target}'. " - f"{rem} See protocol-spec §5.12.5" + f"{loc}{mod_part}auto schema inference failed for target '{target}'. {rem} See protocol-spec §5.12.5" ), details={ "target": target, @@ -1455,6 +1468,7 @@ class ErrorCodes: SCHEMA_CIRCULAR_REF = "SCHEMA_CIRCULAR_REF" SCHEMA_MAX_DEPTH_EXCEEDED = "SCHEMA_MAX_DEPTH_EXCEEDED" CALL_DEPTH_EXCEEDED = "CALL_DEPTH_EXCEEDED" + CALL_BUDGET_EXCEEDED = "CALL_BUDGET_EXCEEDED" CIRCULAR_CALL = "CIRCULAR_CALL" CALL_FREQUENCY_EXCEEDED = "CALL_FREQUENCY_EXCEEDED" GENERAL_INVALID_INPUT = "GENERAL_INVALID_INPUT" diff --git a/python/src/apcore/executor.py b/python/src/apcore/executor.py index 921856b2..0ba3649c 100644 --- a/python/src/apcore/executor.py +++ b/python/src/apcore/executor.py @@ -20,7 +20,9 @@ from apcore.acl import ACL from apcore.approval import ApprovalHandler from apcore.builtin_steps import ( + BuiltinCallChainGuard, BuiltinContextCreation, + BuiltinExecute, BuiltinModuleLookup, _bind_post_validation_policy, _is_idempotent, @@ -38,6 +40,7 @@ from apcore.context_keys import _current_trace_span from apcore.errors import ( ACLDeniedError, + CallBudgetExceededError, CallDepthExceededError, CallFrequencyExceededError, CircularCallError, @@ -70,6 +73,7 @@ from apcore.policy import ExecutionPolicy, PolicyEvaluator, strip_approval_token from apcore.pipeline import ( AbortReason, + ConfigurationError, ExecutionStrategy, GovernanceState, PipelineAbortError, @@ -1118,6 +1122,7 @@ async def _run_call( effective_strategy = _bind_post_validation_policy(effective_strategy, evaluator) if context is None: context = Context.create() + self._check_budget_strategy(effective_strategy, module_id, context) context.bind_executor(self) invocation_deadline: float | None = None @@ -1222,7 +1227,7 @@ async def _recover_from_call_error( # typed cause is what middleware on_error handlers and the final # caller observe — not the chain-machinery wrapper. original = exc.original if isinstance(exc, MiddlewareChainError) else exc - if ( + if isinstance(original, CallBudgetExceededError) or ( isinstance(original, ACLDeniedError) and getattr(getattr(ctx_obj, "identity", None), "scopes", None) is not None ): @@ -1330,6 +1335,7 @@ async def _stream( # to the Context before pipeline step 1. if context is None: context = Context.create() + self._check_budget_strategy(strategy, module_id, context) context.bind_executor(self) context = copy(context) observation.cancel_token = CancelToken(parent=context.cancel_token) @@ -1504,6 +1510,9 @@ async def _stream_chunks(self, ctx: PipelineContext) -> AsyncIterator[tuple[int, index = 0 while True: self._check_stream_context(ctx) + if ctx._budget_stream_pending: + BuiltinExecute._start_budgeted_dispatch(ctx) + ctx._budget_stream_pending = False try: chunk = await anext(source) except StopAsyncIteration: @@ -1707,6 +1716,19 @@ def _effective_strategy( # a strategy, so its gates receive the executor's providers too. return self._bind_providers(resolved) + @staticmethod + def _check_budget_strategy(strategy: ExecutionStrategy, module_id: str, context: Any) -> None: + if getattr(context, "_call_budget", None) is None: + return + required = (BuiltinContextCreation, BuiltinCallChainGuard, BuiltinExecute) + active = tuple( + type(step) + for step in strategy.steps + if isinstance(step, required) and (step.match_modules is None or _any_match(step.match_modules, module_id)) + ) + if active != required: + raise ConfigurationError("CallBudget requires the stock context, call-chain guard, and execute steps") + # ------------------------------------------------------------------------- # Introspection # ------------------------------------------------------------------------- diff --git a/python/src/apcore/observability/context_logger.py b/python/src/apcore/observability/context_logger.py index 95f7e747..5338b894 100644 --- a/python/src/apcore/observability/context_logger.py +++ b/python/src/apcore/observability/context_logger.py @@ -23,10 +23,13 @@ # this surface; the two separator-folding helpers it used to call are internal # to the canonical matcher and are no longer duplicated here at all. from apcore.utils.redaction import ( + DEFAULT_MAX_REGEX_SCAN_LENGTH, REDACTED_VALUE, ValuePattern, _key_matches as _key_matches_sensitive, _value_matches, + _regex_scan_too_long, + _validate_regex_scan_length, compile_value_regexes, ) @@ -108,6 +111,7 @@ class RedactionConfig: sensitive_keys: list[str] = field(default_factory=list) regex_patterns: list[str] = field(default_factory=list) replacement: str = REDACTED_VALUE + max_regex_scan_length: int = DEFAULT_MAX_REGEX_SCAN_LENGTH compiled_regex_patterns: list[re.Pattern[str]] = field(init=False, repr=False, compare=False) invalid_regex_patterns: list[tuple[str, str]] = field(init=False, repr=False, compare=False) @@ -122,6 +126,7 @@ def __post_init__(self) -> None: broken pattern was told nothing — the reload case and the multi-tenant case, which are the two where an operator most needs telling. """ + _validate_regex_scan_length(self.max_regex_scan_length) self.compiled_regex_patterns, self.invalid_regex_patterns = compile_value_regexes(self.regex_patterns) @classmethod @@ -132,6 +137,7 @@ def from_config(cls, config: Any) -> RedactionConfig: - ``obs.redaction.regex_patterns`` (list[str]) - ``obs.redaction.sensitive_keys`` (list[str]) - ``obs.redaction.replacement`` (str) + - ``obs.redaction.max_regex_scan_length`` (UTF-8 bytes) Falls back to the namespace defaults registered in :mod:`apcore.config` when keys are missing. Empty lists are @@ -155,6 +161,7 @@ def from_config(cls, config: Any) -> RedactionConfig: sensitive_keys=list(sensitive_keys), regex_patterns=list(regex_patterns), replacement=str(replacement), + max_regex_scan_length=config.get("obs.redaction.max_regex_scan_length", DEFAULT_MAX_REGEX_SCAN_LENGTH), ) @classmethod @@ -215,9 +222,16 @@ def _apply_redaction_config(data: dict[str, Any], config: RedactionConfig) -> di field_match = any(match_glob(pattern, key) for pattern in config.field_patterns) # §10.6.1 requirement 2 binds the legacy value rule as much as # `regex_patterns`: string values only, never a stringified number or container. - value_match = isinstance(value, str) and any(re.search(pattern, value) for pattern in config.value_patterns) + value_match = ( + isinstance(value, str) + and bool(config.value_patterns) + and ( + _regex_scan_too_long(value, config.max_regex_scan_length) + or any(re.search(pattern, value) for pattern in config.value_patterns) + ) + ) sensitive_key_match = _key_matches_sensitive(key, config.sensitive_keys) - regex_value_match = _value_matches(value, config.compiled_regex_patterns) + regex_value_match = _value_matches(value, config.compiled_regex_patterns, config.max_regex_scan_length) if field_match or value_match or sensitive_key_match or regex_value_match: result[key] = config.replacement else: @@ -266,7 +280,11 @@ def _redact_secrets_recursive( protected = isinstance(k, str) and k in PROTECTED_LOG_FIELDS if not protected and isinstance(k, str) and _key_matches_sensitive(k, config.sensitive_keys): out[k] = config.replacement - elif not protected and isinstance(v, str) and _value_matches(v, config.compiled_regex_patterns): + elif ( + not protected + and isinstance(v, str) + and _value_matches(v, config.compiled_regex_patterns, config.max_regex_scan_length) + ): out[k] = config.replacement elif protected and not isinstance(v, (dict, list)): # Only the protected field's OWN scalar value is immune; a @@ -280,7 +298,7 @@ def _redact_secrets_recursive( # Array elements have no key of their own, so none of them is protected # — including elements directly under a protected key. return [_redact_secrets_recursive(item, depth + 1, config) for item in value] - if isinstance(value, str) and _value_matches(value, config.compiled_regex_patterns): + if isinstance(value, str) and _value_matches(value, config.compiled_regex_patterns, config.max_regex_scan_length): return config.replacement return value diff --git a/python/src/apcore/pipeline.py b/python/src/apcore/pipeline.py index 12999e96..325256bf 100644 --- a/python/src/apcore/pipeline.py +++ b/python/src/apcore/pipeline.py @@ -14,11 +14,19 @@ from typing import TYPE_CHECKING, Any, Callable, Protocol, runtime_checkable from apcore.context import Identity, _APPROVAL_TOKEN_KEY -from apcore.errors import ACLDeniedError, InvalidInputError, ModuleError, ModuleTimeoutError, PolicyEvaluationError +from apcore.errors import ( + ACLDeniedError, + CallBudgetExceededError, + InvalidInputError, + ModuleError, + ModuleTimeoutError, + PolicyEvaluationError, +) from apcore.middleware.manager import MiddlewareChainError from apcore.utils.pattern import match_pattern if TYPE_CHECKING: + from apcore.call_budget import CallBudget, _CallReservation from apcore._post_validation_policy import _PolicyInvocation from apcore.module import ModuleAnnotations from apcore.streaming import _StreamObservation @@ -148,6 +156,9 @@ class PipelineContext: _policy_enabled: bool = field(default=False, repr=False, compare=False) def __post_init__(self) -> None: + self._call_budget: CallBudget | None = getattr(self.context, "_call_budget", None) + self._budget_reservation: _CallReservation | None = None + self._budget_stream_pending = False # Keep the resume credential outside the public dataclass state. self._approval_token: str | None = None self._running_pipeline = False @@ -1003,7 +1014,8 @@ async def _run_steps( fail_closed = ( getattr(step, "_fail_closed_on_error", False) or ctx._policy_pending - or isinstance(exc, PolicyEvaluationError) + or isinstance(exc, (PolicyEvaluationError, CallBudgetExceededError)) + or (ctx._call_budget is not None and isinstance(exc, ConfigurationError)) or (scoped_frame is not None and isinstance(exc, ACLDeniedError)) ) recovery: Any = None diff --git a/python/src/apcore/utils/redaction.py b/python/src/apcore/utils/redaction.py index 86a77e5f..93f2d433 100644 --- a/python/src/apcore/utils/redaction.py +++ b/python/src/apcore/utils/redaction.py @@ -22,6 +22,7 @@ ValuePattern = Union[str, "re.Pattern[str]"] REDACTED_VALUE: str = "***REDACTED***" +DEFAULT_MAX_REGEX_SCAN_LENGTH = 65_536 # Correlation identifiers that MUST NEVER be redacted, whatever the configured # ``sensitive_keys`` or ``regex_patterns`` say. @@ -61,6 +62,7 @@ def redact_sensitive( sensitive_keys: list[str] | None = None, regex_patterns: Sequence[ValuePattern] | None = None, replacement: str | None = None, + max_regex_scan_length: int = DEFAULT_MAX_REGEX_SCAN_LENGTH, ) -> dict[str, Any]: """Redact fields marked with x-sensitive in the schema. @@ -91,10 +93,13 @@ def redact_sensitive( tested and never stringified (requirement 2). replacement: Optional replacement token; defaults to :data:`REDACTED_VALUE`. + max_regex_scan_length: UTF-8 byte cap for regex scans. Oversized + strings are fully replaced whenever a value regex is active. Returns: A new dict with sensitive values replaced. Original data is not modified. """ + _validate_regex_scan_length(max_regex_scan_length) keys = sensitive_keys if sensitive_keys is not None else _default_sensitive_keys() # Compiled ONCE here rather than at every node of the walk below # (PROTOCOL_SPEC 10.6.1 requirement 5), which is also what keeps the @@ -104,7 +109,7 @@ def redact_sensitive( redacted = copy.deepcopy(data) _redact_fields(redacted, schema_dict, token=token) - _redact_by_keys_and_regex(redacted, keys, value_regexes, token) + _redact_by_keys_and_regex(redacted, keys, value_regexes, token, max_regex_scan_length) return redacted @@ -312,7 +317,23 @@ def _key_matches(key: str, sensitive_keys: list[str]) -> bool: return False -def _value_matches(value: Any, value_regexes: Sequence[re.Pattern[str]]) -> bool: +def _validate_regex_scan_length(value: Any) -> None: + if type(value) is not int or not 0 <= value <= (1 << 53) - 1: + raise ValueError("max_regex_scan_length must be a non-negative safe integer (UTF-8 bytes)") + + +def _regex_scan_too_long(value: str, limit: int) -> bool: + if len(value) > limit: + return True + try: + return len(value.encode("utf-8")) > limit + except UnicodeEncodeError: + return True + + +def _value_matches( + value: Any, value_regexes: Sequence[re.Pattern[str]], max_regex_scan_length: int = DEFAULT_MAX_REGEX_SCAN_LENGTH +) -> bool: """Case-insensitive regex search over *value*, when *value* is a string. PROTOCOL_SPEC §10.6.1 requirement 2: the value rule applies to **string @@ -329,6 +350,8 @@ def _value_matches(value: Any, value_regexes: Sequence[re.Pattern[str]]) -> bool """ if not isinstance(value, str) or not value_regexes: return False + if _regex_scan_too_long(value, max_regex_scan_length): + return True for pat in value_regexes: if pat.search(value) is not None: return True @@ -391,6 +414,7 @@ def _redact_by_keys_and_regex( sensitive_keys: list[str], value_regexes: Sequence[re.Pattern[str]], token: str, + max_regex_scan_length: int, ) -> None: """In-place redaction by name (substring/glob) or value (regex), at any depth. @@ -415,13 +439,13 @@ def _redact_by_keys_and_regex( if not protected and _key_matches(key, sensitive_keys): data[key] = token continue - if not protected and _value_matches(value, value_regexes): + if not protected and _value_matches(value, value_regexes, max_regex_scan_length): data[key] = token continue if isinstance(value, dict): - _redact_by_keys_and_regex(value, sensitive_keys, value_regexes, token) + _redact_by_keys_and_regex(value, sensitive_keys, value_regexes, token, max_regex_scan_length) elif isinstance(value, list): - _redact_in_list(value, sensitive_keys, value_regexes, token) + _redact_in_list(value, sensitive_keys, value_regexes, token, max_regex_scan_length) def _redact_in_list( @@ -429,14 +453,15 @@ def _redact_in_list( sensitive_keys: list[str], value_regexes: Sequence[re.Pattern[str]], token: str, + max_regex_scan_length: int, ) -> None: """Traverse a list, redacting dict children and recursing into nested lists.""" for index, item in enumerate(items): if item is None: continue if isinstance(item, dict): - _redact_by_keys_and_regex(item, sensitive_keys, value_regexes, token) + _redact_by_keys_and_regex(item, sensitive_keys, value_regexes, token, max_regex_scan_length) elif isinstance(item, list): - _redact_in_list(item, sensitive_keys, value_regexes, token) - elif _value_matches(item, value_regexes): + _redact_in_list(item, sensitive_keys, value_regexes, token, max_regex_scan_length) + elif _value_matches(item, value_regexes, max_regex_scan_length): items[index] = token diff --git a/python/tests/test_call_budget.py b/python/tests/test_call_budget.py new file mode 100644 index 00000000..7905172c --- /dev/null +++ b/python/tests/test_call_budget.py @@ -0,0 +1,229 @@ +"""Budget accounting through SDK call, preflight, and stream entry points.""" + +import asyncio +from collections.abc import AsyncIterator +from typing import Any + +import pytest + +from apcore import APCore, CallBudget, CancelToken, Context, Executor, Middleware, Registry +from apcore.approval import ApprovalRequest, ApprovalResult, CallbackApprovalHandler +from apcore.errors import ApprovalPendingError, CallBudgetExceededError, InvalidInputError, ModuleError +from apcore.middleware.base import RetrySignal +from apcore.pipeline import ConfigurationError +from conformance.canonical_fixtures import load_fixture + + +@pytest.mark.parametrize("case", load_fixture("call_budget.json")["test_cases"], ids=lambda case: case["id"]) +async def test_canonical_call_budget(case: dict[str, Any]) -> None: + client = APCore() + module_id = case["module_id"] + + @client.module(module_id) + def account(actual_cost: int | None, ctx: Context[Any]) -> bool: + """Report the fixture's cost when provided.""" + if actual_cost is not None: + ctx.record_cost(actual_cost) + return True + + budget = CallBudget( + max_calls=case["max_calls"], + max_cost=case["max_cost"], + estimated_costs={module_id: case["estimated_cost"]}, + ) + root: Context[Any] = Context.create().with_budget(budget) + for invocation, expected in zip(case["calls"], case["expected"], strict=True): + inputs = {"actual_cost": invocation["actual_cost"]} + if expected["error_code"] is None: + assert await client.call_async(module_id, inputs, root) == {"result": True} + else: + with pytest.raises(CallBudgetExceededError) as denial: + await client.call_async(module_id, inputs, root) + assert denial.value.code == expected["error_code"] + snapshot = budget.snapshot() + assert snapshot.calls_used == expected["calls_used"] + assert snapshot.calls_reserved == expected["calls_reserved"] + assert snapshot.cost_used == expected["cost_used"] + + +async def test_large_aggregate_snapshot_stays_in_the_portable_integer_range() -> None: + client = APCore() + maximum = (1 << 53) - 1 + budget = CallBudget() + root = Context.create().with_budget(budget) + + @client.module("budget.maximum") + def charge(ctx: Context[Any]) -> None: + """Record one invocation's largest portable cost.""" + ctx.record_cost(maximum) + + await client.call_async("budget.maximum", {}, root) + await client.call_async("budget.maximum", {}, root) + assert budget.snapshot().calls_used == 2 + assert budget.snapshot().cost_used == maximum + + +async def test_budget_preflight_is_free_and_actual_cost_replaces_the_estimate() -> None: + client = APCore() + + @client.module("budget.calculate") + def calculate(actual: int, ctx: Context[Any]) -> int: + ctx.record_cost(actual) + return actual + + estimates = {"budget.calculate": 2} + budget = CallBudget(max_calls=2, max_cost=5, estimated_costs=estimates) + estimates["budget.calculate"] = 20 + base: Context[Any] = Context.create() + ctx = base.with_budget(budget) + assert ctx.serialize() == base.serialize() + initial = budget.snapshot() + assert (initial.calls_used, initial.calls_reserved, initial.cost_used) == (0, 0, 0) + assert (await client.validate_async("budget.calculate", {"actual": 0}, ctx)).valid + assert budget.snapshot() == initial + + assert await client.call_async("budget.calculate", {"actual": 0}, ctx) == {"result": 0} + assert budget.snapshot().cost_used == 0 + with pytest.raises(ModuleError) as denied: + await client.call_async("budget.calculate", {"actual": 6}, ctx) + assert denied.value.code == "CALL_BUDGET_EXCEEDED" + assert denied.value.details["dimension"] == "cost" + assert denied.value.retryable is False + spent = budget.snapshot() + assert (spent.calls_used, spent.calls_reserved, spent.cost_used) == (2, 0, 6) + + +async def test_budget_holds_a_concurrent_slot_then_releases_on_pending() -> None: + executor = Executor(Registry()) + client = APCore(executor=executor) + entered, unblock = asyncio.Event(), asyncio.Event() + + async def approve(request: ApprovalRequest) -> ApprovalResult: + entered.set() + await unblock.wait() + return ApprovalResult("pending", approval_id="review-1") + + executor.set_approval_handler(CallbackApprovalHandler(approve)) + + @client.module("budget.pending", requires_approval=True) + def pending() -> int: + raise AssertionError("Pending approval must never execute") + + @client.module("budget.direct") + def direct() -> int: + return 1 + + budget = CallBudget(max_calls=1) + ctx: Context[Any] = Context.create().with_budget(budget) + held = asyncio.create_task(client.call_async("budget.pending", {}, ctx)) + await entered.wait() + assert budget.snapshot().calls_reserved == 1 + with pytest.raises(ModuleError) as denied: + await client.call_async("budget.direct", {}, ctx) + assert denied.value.details["dimension"] == "calls" + unblock.set() + with pytest.raises(ApprovalPendingError): + await held + assert budget.snapshot().calls_reserved == budget.snapshot().calls_used == 0 + assert await client.call_async("budget.direct", {}, ctx) == {"result": 1} + + +async def test_budget_charges_started_retries_and_counts_streams_once() -> None: + executor = Executor(Registry()) + client = APCore(executor=executor) + + @client.module("budget.retry") + def fail(retry: bool) -> bool: + if not retry: + raise ValueError("once") + return retry + + class RetryOnce(Middleware): + def on_error( + self, module_id: str, inputs: dict[str, Any], error: Exception, context: Any + ) -> RetrySignal | None: + return RetrySignal({"retry": True}) if not inputs.get("retry") else None + + client.use(RetryOnce()) + budget = CallBudget(max_calls=3, estimated_costs={"budget.retry": 2, "budget.stream": 1}) + ctx: Context[Any] = Context.create().with_budget(budget) + assert (await executor.call_async_with_trace("budget.retry", {"retry": False}, ctx))[0] == {"result": True} + assert budget.snapshot().calls_used == 2 + assert budget.snapshot().cost_used == 4 + + class Stream: + description = "Return streaming results" + input_schema = output_schema = {"type": "object"} + annotations = {"streaming": True} + + def execute(self, inputs: dict[str, Any], context: Context[Any]) -> dict[str, Any]: + raise AssertionError("Streaming must not invoke execute") + + async def stream(self, inputs: dict[str, Any], context: Context[Any]) -> AsyncIterator[dict[str, Any]]: + context.record_cost(4) + yield {"first": True} + yield {"second": True} + + client.register("budget.stream", Stream()) + stream = client.stream("budget.stream", {}, ctx) + assert budget.snapshot().calls_used == 2 + assert [chunk async for chunk in stream] == [{"first": True}, {"second": True}] + spent = budget.snapshot() + assert (spent.calls_used, spent.calls_reserved, spent.cost_used) == (3, 0, 8) + + +async def test_budget_releases_a_reservation_on_pre_dispatch_cancellation() -> None: + from apcore.cancel import ExecutionCancelledError + + client = APCore() + token = CancelToken() + + @client.module("budget.cancel") + def never() -> int: + raise AssertionError("Cancelled execution must not dispatch") + + class Cancel(Middleware): + def before(self, module_id: str, inputs: dict[str, Any], context: Context[Any]) -> None: + token.cancel() + + client.use(Cancel()) + budget = CallBudget(max_calls=1) + base: Context[Any] = Context.create(cancel_token=token) + with pytest.raises(ExecutionCancelledError): + await client.call_async("budget.cancel", {}, base.with_budget(budget)) + assert budget.snapshot().calls_reserved == budget.snapshot().calls_used == 0 + + +async def test_budget_rejects_missing_guard_and_is_shared_by_nested_calls() -> None: + executor = Executor(Registry()) + client = APCore(executor=executor) + entered: list[str] = [] + + @client.module("budget.parent") + async def parent(ctx: Context[Any]) -> bool: + entered.append("parent") + await client.call_async("budget.child", {}, ctx) + return True + + @client.module("budget.child") + async def child() -> bool: + entered.append("child") + return True + + budget = CallBudget(max_calls=1) + ctx: Context[Any] = Context.create().with_budget(budget) + with pytest.raises(ConfigurationError): + await executor.call_async_with_trace("budget.parent", {}, ctx, strategy="minimal") + assert entered == [] + with pytest.raises(CallBudgetExceededError): + await client.call_async("budget.parent", {}, ctx) + assert entered == ["parent"] + assert budget.snapshot().calls_used == 1 + + +def test_call_cost_must_use_nonnegative_safe_integers() -> None: + for value in (-1, True, 1 << 53): + with pytest.raises(InvalidInputError): + CallBudget(max_calls=value) + with pytest.raises(InvalidInputError): + CallBudget(estimated_costs={"budget.action": value}) diff --git a/python/tests/test_public_api.py b/python/tests/test_public_api.py index b3bdf7ff..c478d742 100644 --- a/python/tests/test_public_api.py +++ b/python/tests/test_public_api.py @@ -456,6 +456,9 @@ class TestPublicAPIAll: "ApprovalResult", "AutoApproveHandler", "BoundModule", + "CallBudget", + "CallBudgetExceededError", + "CallBudgetSnapshot", "CancelToken", "AccessHint", "CallableDefinition", @@ -464,6 +467,8 @@ class TestPublicAPIAll: "ModuleSummary", "VisibilityDecision", "Context", + "ElicitationHandler", + "ElicitationResult", "ErrorCodes", "ExecutionPolicy", "PolicyDeniedError", @@ -481,6 +486,7 @@ class TestPublicAPIAll: "PipelineEngine", "PreflightResult", "PreviewResult", + "ProgressReporter", "Registry", "ReloadOptions", "SchemaExporter", diff --git a/python/tests/test_realtime_context.py b/python/tests/test_realtime_context.py new file mode 100644 index 00000000..0212a7c5 --- /dev/null +++ b/python/tests/test_realtime_context.py @@ -0,0 +1,66 @@ +"""Opt-in realtime interaction through regular executor contexts.""" + +import asyncio +import time +from typing import Any + +import pytest + +from apcore import APCore, CancelToken, Context, ElicitationResult +from apcore.cancel import ExecutionCancelledError +from apcore.errors import ModuleTimeoutError + + +async def test_callbacks_are_inherited_and_excluded_from_wire_context() -> None: + client = APCore() + base: Context[Any] = Context.create() + observed = [] + schema = {"type": "object"} + + async def progress(current: float, total: float | None, message: str | None) -> None: + observed.append((current, total, message)) + + async def elicit(message: str, request: dict[str, Any] | None) -> ElicitationResult: + assert (message, request) == ("Confirm", schema) + return ElicitationResult("accept", {"confirmed": True}) + + @client.module("realtime.confirm") + async def confirm(ctx: Context[Any]) -> bool: + await ctx.report_progress(1, 2, "Preparing") + response = await ctx.elicit("Confirm", schema) + return bool(response and response.content and response.content["confirmed"]) + + context = base.with_progress_reporter(progress).with_elicitation_handler(elicit) + assert context is not base + assert context.serialize() == base.serialize() + assert await base.elicit("Optional") is None + assert await Context.deserialize(context.serialize()).elicit("Optional") is None + assert await client.call_async("realtime.confirm", {}, context) == {"result": True} + assert observed == [(1, 2, "Preparing")] + assert await context.with_elicitation_handler(None).elicit("Optional") is None + await context.with_progress_reporter(None).report_progress(9) + assert observed == [(1, 2, "Preparing")] + + +async def test_realtime_wait_stops_on_parent_cancellation_and_expired_deadline() -> None: + token = CancelToken() + started = asyncio.Event() + + async def progress(current: float, total: float | None, message: str | None) -> None: + started.set() + await asyncio.Future() + + ctx: Context[Any] = Context.create(cancel_token=token.child()) + pending = asyncio.create_task(ctx.with_progress_reporter(progress).report_progress(1)) + await started.wait() + token.cancel() + with pytest.raises(ExecutionCancelledError): + await pending + + started.clear() + expired: Context[Any] = Context.create(global_deadline=time.time() - 1) + expired = expired.with_progress_reporter(progress).child("realtime.expired") + with pytest.raises(ModuleTimeoutError) as error: + await expired.report_progress(1) + assert error.value.module_id == "realtime.expired" + assert not started.is_set() diff --git a/python/tests/test_redaction_regex_cap.py b/python/tests/test_redaction_regex_cap.py new file mode 100644 index 00000000..9623ecf1 --- /dev/null +++ b/python/tests/test_redaction_regex_cap.py @@ -0,0 +1,57 @@ +"""Regex scans are bounded consistently at payload capture and log emission.""" + +import io +import json +from typing import Any + +import pytest + +from apcore import APCore, Config, Context, Middleware, REDACTED_VALUE, redact_sensitive +from apcore.errors import ConfigError +from apcore.observability.context_logger import ContextLogger, RedactionConfig + + +def test_regex_scan_cap_redacts_all_oversized_values_and_counts_utf8_bytes() -> None: + data = {"values": ["éé", "ééx", "matches"], "trace_id": "oversized", "auth": "x", "private": "x"} + schema = {"properties": {"private": {"x-sensitive": True}}} + result = redact_sensitive(data, schema, regex_patterns=["^never$"], max_regex_scan_length=4) + assert result == { + "values": ["éé", REDACTED_VALUE, REDACTED_VALUE], + "trace_id": "oversized", + "auth": REDACTED_VALUE, + "private": REDACTED_VALUE, + } + assert redact_sensitive(data, {}, max_regex_scan_length=0)["values"] == data["values"] + + +def test_configured_cap_applies_to_logger_and_executor_capture() -> None: + config = Config({"obs": {"redaction": {"regex_patterns": ["never"], "max_regex_scan_length": 2}}}) + output = io.StringIO() + logger = ContextLogger("test", output=output, redaction_config=RedactionConfig.from_config(config)) + logger.info("message", {"payload": ["é", "éé"]}) + assert json.loads(output.getvalue())["extra"] == {"payload": ["é", REDACTED_VALUE]} + + client = APCore(config=config) + + @client.module("redaction.check") + def check(value: str) -> str: + return value + + class Capture(Middleware): + def after(self, module_id: str, inputs: dict[str, Any], output: dict[str, Any], context: Context[Any]) -> None: + assert context.redacted_inputs == {"value": REDACTED_VALUE} + assert context.redacted_output == {"result": REDACTED_VALUE} + + client.use(Capture()) + assert client.call("redaction.check", {"value": "éé"}) == {"result": "éé"} + + +@pytest.mark.parametrize("invalid", [-1, True, 1.5, "2", 1 << 53]) +def test_invalid_regex_scan_cap_is_rejected(invalid: Any) -> None: + with pytest.raises(ValueError, match="max_regex_scan_length"): + redact_sensitive({}, {}, max_regex_scan_length=invalid) + config = Config( + {"version": "2.0.0", "project": {"name": "test"}, "obs": {"redaction": {"max_regex_scan_length": invalid}}} + ) + with pytest.raises(ConfigError, match="max_regex_scan_length"): + config.validate() diff --git a/python/uv.lock b/python/uv.lock index aa69082c..7152057b 100644 --- a/python/uv.lock +++ b/python/uv.lock @@ -199,7 +199,7 @@ wheels = [ [[package]] name = "apcore" -version = "1.0.0a6" +version = "1.0.0b1" source = { editable = "." } dependencies = [ { name = "jsonschema" }, diff --git a/rust/Cargo.lock b/rust/Cargo.lock index da10e69c..ad3bb8f5 100644 --- a/rust/Cargo.lock +++ b/rust/Cargo.lock @@ -42,7 +42,7 @@ checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" [[package]] name = "apcore" -version = "1.0.0-alpha.6" +version = "1.0.0-beta.1" dependencies = [ "apcore-macros", "async-stream", @@ -75,7 +75,7 @@ dependencies = [ [[package]] name = "apcore-macros" -version = "1.0.0-alpha.6" +version = "1.0.0-beta.1" dependencies = [ "proc-macro2", "quote", diff --git a/rust/Cargo.toml b/rust/Cargo.toml index 1cca036c..90511eaf 100644 --- a/rust/Cargo.toml +++ b/rust/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "apcore" -version = "1.0.0-alpha.6" +version = "1.0.0-beta.1" edition = "2021" # Minimum supported Rust version. Verified with `cargo +1.86 check --all-features`. # The binding language constraint is `std::task::Waker::noop()` (used by the @@ -156,7 +156,7 @@ path = "tests/test_otlp_proxy_routing.rs" required-features = ["events"] [dependencies] -apcore-macros = { version = "=1.0.0-alpha.6", path = "apcore-macros", optional = true } +apcore-macros = { version = "=1.0.0-beta.1", path = "apcore-macros", optional = true } tokio = { version = "1", features = ["rt-multi-thread", "macros", "sync", "time"] } serde = { version = "1", features = ["derive"] } serde_json = "1" diff --git a/rust/apcore-conformance.yaml b/rust/apcore-conformance.yaml index 909b0346..b55b296d 100644 --- a/rust/apcore-conformance.yaml +++ b/rust/apcore-conformance.yaml @@ -1,6 +1,6 @@ implementation: name: apcore-rust - version: 1.0.0-alpha.6 + version: 1.0.0-beta.1 language: rust spec_version: 1.65.0 maintainer: AI Perceivable diff --git a/rust/apcore-macros/Cargo.toml b/rust/apcore-macros/Cargo.toml index 45d94d4f..8816ba31 100644 --- a/rust/apcore-macros/Cargo.toml +++ b/rust/apcore-macros/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "apcore-macros" -version = "1.0.0-alpha.6" +version = "1.0.0-beta.1" edition = "2021" rust-version = "1.86" description = "Typed module declarations for the APCore Rust SDK" diff --git a/rust/src/builtin_steps.rs b/rust/src/builtin_steps.rs index fe1ee8a7..be270a87 100644 --- a/rust/src/builtin_steps.rs +++ b/rust/src/builtin_steps.rs @@ -1,7 +1,7 @@ // APCore Protocol — Built-in execution pipeline steps // Spec reference: docs/features/execution-pipeline.md (Built-in steps) -use std::time::Duration; +use std::{sync::Arc, time::Duration}; use async_trait::async_trait; use serde_json::Value; @@ -308,6 +308,11 @@ impl Step for BuiltinCallChainGuard { config.executor.max_call_depth as usize, config.executor.max_module_repeat as usize, )?; + if !ctx.dry_run && ctx.budget_reservation.is_none() { + if let Some(budget) = ctx.call_budget.as_ref() { + ctx.budget_reservation = Some(budget.reserve(&ctx.module_id)?); + } + } Ok(StepResult::continue_step()) } } @@ -1229,12 +1234,18 @@ impl Step for BuiltinExecute { .as_ref() .ok_or_else(|| missing_pipeline_input("module"))? .clone(); + let permit = ctx.budget_permit()?; + let mut started_budget = None; if ctx.stream.is_some() { - let producer = crate::executor::open_stream(ctx, &module).await?; + let (producer, active_budget) = + crate::executor::open_stream(ctx, &module, permit.clone()).await?; if let (Some(stream), Some(producer)) = (&mut ctx.stream, producer) { - stream.producer = Some(parking_lot::Mutex::new(producer)); + stream.producer = Some(parking_lot::Mutex::new( + crate::executor::with_stream_budget(producer, active_budget), + )); return Ok(StepResult::continue_step()); } + started_budget = active_budget; } let config = ctx .config @@ -1273,48 +1284,7 @@ impl Step for BuiltinExecute { token.check_for(&ctx.module_id)?; } - let execute_result = if timeout_ms > 0 { - // Own the invocation: timeout must not drop module code before cleanup. - let inputs = ctx.inputs.clone(); - let context = ctx.context.clone(); - let token = context.cancel_token.clone(); - // Read the retry-safety flag before `module` moves into the task. - let retryable = module.annotations().idempotent; - let lease = ctx.module_lease.clone(); - let execution = async move { - let _lease = lease; - let result = module.execute(inputs, &context).await; - if let Err(error) = &result { - tracing::debug!( - code = %error.wire_code(), - "Module invocation finished with an error" - ); - } - result - }; - let invocation = if let Some(token) = token { - token.spawn_tracked(execution) - } else { - tokio::spawn(execution) - }; - match tokio::time::timeout(Duration::from_millis(timeout_ms), invocation).await { - Ok(Ok(result)) => result, - Ok(Err(error)) => Err(ModuleError::new( - ErrorCode::GeneralInternalError, - format!("Module execution task failed: {error}"), - )), - Err(_elapsed) => { - let error = ModuleError::module_timeout(&ctx.module_id, timeout_ms) - .with_retryable(retryable); - if let Some(token) = &ctx.context.cancel_token { - token.cancel_after_timeout(&error); - } - Err(error) - } - } - } else { - module.execute(ctx.inputs.clone(), &ctx.context).await - }; + let execute_result = execute_unary(module, ctx, timeout_ms, permit, started_budget).await; match execute_result { Ok(output) if output.is_object() => { @@ -1329,31 +1299,106 @@ impl Step for BuiltinExecute { ErrorCode::ModuleExecuteError, "Return value must be Map", )), - Err(e) => { - // Cancellation short-circuit (D-20): an ExecutionCancelled - // error MUST bypass the on_error middleware chain even at the - // step level, so a recovering on_error middleware cannot - // swallow it into a success before reaching the executor-level - // guard in `Executor::call` / `call_with_trace`. Propagate it - // untouched. Mirrors apcore-python `_handle_error` - // (`_unwrap_cancellation` before any on_error recovery). - // Spec: docs/features/core-executor.md §Cancellation Short-Circuit - if matches!(e.code, ErrorCode::ExecutionCancelled) { - return Err(e); + // The executor owns the error recovery and retry loop. + Err(error) => Err(error), + } + } +} + +async fn execute_unary( + module: Arc, + ctx: &PipelineContext, + timeout_ms: u64, + permit: Option>, + started_budget: Option, +) -> Result { + if timeout_ms > 0 { + // Own the invocation: timeout must not drop module code before cleanup. + let inputs = ctx.inputs.clone(); + let context = ctx.context.clone(); + let token = context.cancel_token.clone(); + // Read the retry-safety flag before `module` moves into the task. + let retryable = module.annotations().idempotent; + let lease = ctx.module_lease.clone(); + let execution = async move { + let _lease = lease; + let result = + execute_with_budget(module.as_ref(), inputs, &context, permit, started_budget) + .await; + if let Err(error) = &result { + tracing::debug!( + code = %error.wire_code(), + "Module invocation finished with an error" + ); + } + result + }; + let invocation = if let Some(token) = token { + token.spawn_tracked(execution) + } else { + tokio::spawn(execution) + }; + match tokio::time::timeout(Duration::from_millis(timeout_ms), invocation).await { + Ok(Ok(result)) => result, + Ok(Err(error)) => Err(ModuleError::new( + ErrorCode::GeneralInternalError, + format!("Module execution task failed: {error}"), + )), + Err(_elapsed) => { + let error = ModuleError::module_timeout(&ctx.module_id, timeout_ms) + .with_retryable(retryable); + if let Some(token) = &ctx.context.cancel_token { + token.cancel_after_timeout(&error); } - // A-D-010 / A-D-012: do NOT run step-level on_error recovery - // here. The executor-level loop is the sole recovery site (it - // runs `execute_on_error_outcome` over `ctx.executed_middlewares` - // and honors Recovery + Retry). Step-level recovery double-fired - // on_error and silently dropped RetrySignals. Mirrors - // apcore-python `BuiltinExecute` (raises; no step-level on_error) - // and apcore-typescript. - Err(e) + Err(error) } } + } else { + execute_with_budget( + module.as_ref(), + ctx.inputs.clone(), + &ctx.context, + permit, + started_budget, + ) + .await } } +async fn execute_with_budget( + module: &dyn crate::Module, + inputs: Value, + context: &crate::Context, + permit: Option>, + started_budget: Option, +) -> Result { + if started_budget.is_none() && permit.is_none() { + return module.execute(inputs, context).await; + } + if let Some(token) = &context.cancel_token { + token.check()?; + } + if context + .global_deadline + .and_then(crate::cancel::deadline_remaining) + .is_some_and(|remaining| remaining.is_zero()) + { + let module_id = context.call_chain.last().map_or("", String::as_str); + return Err(ModuleError::module_timeout(module_id, 0) + .with_retryable(module.annotations().idempotent)); + } + let active = if let Some(started) = started_budget { + started + } else { + permit + .ok_or_else(|| missing_pipeline_input("budget_reservation"))? + .start()? + }; + let mut context = context.clone(); + active.bind(&mut context); + module.execute(inputs, &context).await +} + #[async_trait] impl Step for BuiltinOutputValidation { impl_step_meta!(BuiltinOutputValidation); diff --git a/rust/src/call_budget.rs b/rust/src/call_budget.rs new file mode 100644 index 00000000..0f0b2e69 --- /dev/null +++ b/rust/src/call_budget.rs @@ -0,0 +1,259 @@ +//! Execution-local accounting for a tree of module calls. + +use std::collections::HashMap; +use std::sync::{Arc, Weak}; + +use parking_lot::Mutex; +use schemars::JsonSchema; +use serde::{Deserialize, Serialize}; +use serde_json::json; + +use crate::{Context, ErrorCode, ExecutionCancelledError, ModuleError}; + +const MAX_SAFE_INTEGER: u64 = (1 << 53) - 1; + +/// A shareable ledger that bounds how many module attempts may start and their total cost. +#[derive(Debug)] +pub struct CallBudget { + max_calls: Option, + max_cost: Option, + estimates: HashMap, + state: Mutex, +} + +#[derive(Debug, Default)] +struct BudgetState { + calls_used: u128, + calls_reserved: u128, + cost_used: u128, +} + +/// A consistent view of the budget's counters. +/// +/// Counters above the largest portable integer are displayed at that bound. +/// Accounting and limit decisions continue to use the full totals. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] +pub struct CallBudgetSnapshot { + pub calls_used: u64, + pub calls_reserved: u64, + pub cost_used: u64, +} + +impl CallBudget { + /// Create a budget with optional call and cost limits. + /// + /// All limits and estimates are nonnegative safe integers. A module + /// without an estimate starts with a charge of zero. + pub fn new( + max_calls: Option, + max_cost: Option, + estimates: HashMap, + ) -> Result { + for units in max_calls + .into_iter() + .chain(max_cost) + .chain(estimates.values().copied()) + { + validate_units(units)?; + } + if estimates.keys().any(|id| { + id.len() > crate::MAX_MODULE_ID_LENGTH || !crate::module_id_pattern().is_match(id) + }) { + return Err(ModuleError::invalid_input( + "Call budget estimate module ID is invalid", + )); + } + Ok(Self { + max_calls, + max_cost, + estimates, + state: Mutex::new(BudgetState::default()), + }) + } + + /// Return the current counters without changing them. + pub fn snapshot(&self) -> CallBudgetSnapshot { + let state = self.state.lock(); + CallBudgetSnapshot { + calls_used: portable_counter(state.calls_used), + calls_reserved: portable_counter(state.calls_reserved), + cost_used: portable_counter(state.cost_used), + } + } + + pub(crate) fn reserve( + self: &Arc, + module_id: &str, + ) -> Result { + let mut state = self.state.lock(); + if self + .max_calls + .is_some_and(|limit| state.calls_used + state.calls_reserved >= u128::from(limit)) + { + return Err(exceeded("calls")); + } + state.calls_reserved += 1; + Ok(BudgetReservation { + permit: Arc::new(BudgetPermit { + budget: Arc::clone(self), + module_id: module_id.to_owned(), + estimate: self.estimates.get(module_id).copied().unwrap_or_default(), + phase: Mutex::new(AttemptPhase::Reserved), + }), + }) + } +} + +fn portable_counter(value: u128) -> u64 { + u64::try_from(value) + .unwrap_or(MAX_SAFE_INTEGER) + .min(MAX_SAFE_INTEGER) +} + +fn validate_units(units: u64) -> Result<(), ModuleError> { + if units > MAX_SAFE_INTEGER { + return Err(ModuleError::invalid_input( + "Call budget units must be nonnegative safe integers", + )); + } + Ok(()) +} + +fn exceeded(dimension: &str) -> ModuleError { + ModuleError::new( + ErrorCode::CallBudgetExceeded, + format!("The invocation exceeded its {dimension} budget."), + ) + .with_details(HashMap::from([("dimension".into(), json!(dimension))])) +} + +/// The pipeline owns this reservation until it ends or hands work to a producer. +pub(crate) struct BudgetReservation { + permit: Arc, +} + +impl BudgetReservation { + pub(crate) fn permit(&self, module_id: &str) -> Option> { + (self.permit.module_id == module_id).then(|| Arc::clone(&self.permit)) + } +} + +impl Drop for BudgetReservation { + fn drop(&mut self) { + let mut phase = self.permit.phase.lock(); + if *phase == AttemptPhase::Reserved { + self.permit.budget.state.lock().calls_reserved -= 1; + *phase = AttemptPhase::Closed; + } + } +} + +#[derive(Debug, PartialEq, Eq)] +enum AttemptPhase { + Reserved, + Started { reported: bool }, + Closed, +} + +pub(crate) struct BudgetPermit { + budget: Arc, + module_id: String, + estimate: u64, + phase: Mutex, +} + +impl BudgetPermit { + pub(crate) fn start(self: &Arc) -> Result { + let mut phase = self.phase.lock(); + if *phase != AttemptPhase::Reserved { + return Err(ExecutionCancelledError::without_module( + "The call no longer has a budget reservation", + ) + .into()); + } + let mut state = self.budget.state.lock(); + let cost = state.cost_used + u128::from(self.estimate); + if self + .budget + .max_cost + .is_some_and(|limit| cost > u128::from(limit)) + { + return Err(exceeded("cost")); + } + state.cost_used = cost; + state.calls_used += 1; + state.calls_reserved -= 1; + *phase = AttemptPhase::Started { reported: false }; + Ok(ActiveBudget { + permit: Arc::clone(self), + }) + } + + fn record_cost(&self, actual: u64) -> Result<(), ModuleError> { + validate_units(actual)?; + let mut phase = self.phase.lock(); + if *phase != (AttemptPhase::Started { reported: false }) { + return Err(ModuleError::invalid_input( + "Actual cost can only be recorded once per active attempt", + )); + } + let mut state = self.budget.state.lock(); + state.cost_used = state.cost_used - u128::from(self.estimate) + u128::from(actual); + *phase = AttemptPhase::Started { reported: true }; + if self + .budget + .max_cost + .is_some_and(|limit| state.cost_used > u128::from(limit)) + { + return Err(exceeded("cost")); + } + Ok(()) + } +} + +/// Keeps cost reporting open for the running handler or stream producer. +pub(crate) struct ActiveBudget { + permit: Arc, +} + +impl ActiveBudget { + pub(crate) fn bind(&self, context: &mut Context) { + context.runtime.active_budget = Arc::downgrade(&self.permit); + } +} + +impl Drop for ActiveBudget { + fn drop(&mut self) { + *self.permit.phase.lock() = AttemptPhase::Closed; + } +} + +impl Context { + /// Derive a context sharing the given call budget. + #[must_use] + pub fn with_budget(&self, budget: Option>) -> Self { + let mut derived = self.clone(); + derived.runtime.budget = budget; + derived.runtime.active_budget = Weak::new(); + derived + } +} + +impl Context { + /// Replace this invocation's estimated cost with its actual total cost. + /// + /// Without a budget this is a no-op. A charged actual amount remains in + /// the ledger even when it exceeds the cost limit and returns an error. + pub fn record_cost(&self, actual: u64) -> Result<(), ModuleError> { + if self.runtime.budget.is_none() { + return Ok(()); + } + self.runtime + .active_budget + .upgrade() + .ok_or_else(|| { + ModuleError::invalid_input("Actual cost requires an active call attempt") + })? + .record_cost(actual) + } +} diff --git a/rust/src/cancel.rs b/rust/src/cancel.rs index 4bdeb12a..93b3095d 100644 --- a/rust/src/cancel.rs +++ b/rust/src/cancel.rs @@ -516,6 +516,21 @@ impl Default for CancelToken { } } +pub(crate) fn deadline_remaining(deadline: f64) -> Option { + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap_or_default() + .as_secs_f64(); + std::time::Duration::try_from_secs_f64((deadline - now).max(0.0)).ok() +} + +pub(crate) async fn wait_for_cancellation(token: Option<&CancelToken>) { + match token { + Some(token) => token.cancelled().await, + None => std::future::pending().await, + } +} + #[cfg(test)] mod child_token_tests { use super::CancelToken; diff --git a/rust/src/config.rs b/rust/src/config.rs index 4f1c432b..f15e7fcc 100644 --- a/rust/src/config.rs +++ b/rust/src/config.rs @@ -11,6 +11,7 @@ use std::path::{Path, PathBuf}; use std::sync::OnceLock; use crate::errors::{ErrorCode, ModuleError}; +use crate::observability::redaction::{regex_scan_length, MAX_REGEX_SCAN_LENGTH}; /// Configuration mode detected from YAML content. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)] @@ -232,6 +233,7 @@ pub const FRAMEWORK_CONFIG_KEYS: &[&str] = &[ "logging.format", "logging.level", "middleware.disabled", + "obs.redaction.max_regex_scan_length", "obs.redaction.regex_patterns", "obs.redaction.replacement", "obs.redaction.sensitive_keys", @@ -1426,6 +1428,15 @@ impl Config { // linear in the input), so this fires on patterns that compile // perfectly well in Python and JavaScript: exactly the configuration // that redacts elsewhere and silently does nothing here. + if self + .get(MAX_REGEX_SCAN_LENGTH) + .as_ref() + .is_some_and(|length| regex_scan_length(length).is_none()) + { + errors.push(format!( + "{MAX_REGEX_SCAN_LENGTH} must be a nonnegative safe integer" + )); + } if let Some(serde_json::Value::Array(patterns)) = self.get("obs.redaction.regex_patterns") { for (index, entry) in patterns.iter().enumerate() { let Some(pattern) = entry.as_str() else { @@ -3092,6 +3103,7 @@ fn init_builtin_namespaces() { defaults: Some(serde_json::json!({ "redaction": { "regex_patterns": [], + "max_regex_scan_length": crate::observability::redaction::DEFAULT_MAX_REGEX_SCAN_LENGTH, "sensitive_keys": crate::observability::redaction::DEFAULT_SENSITIVE_KEYS, "replacement": crate::observability::redaction::DEFAULT_REPLACEMENT } diff --git a/rust/src/context.rs b/rust/src/context.rs index 0db20c35..489197c4 100644 --- a/rust/src/context.rs +++ b/rust/src/context.rs @@ -5,12 +5,15 @@ use async_trait::async_trait; use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; use std::collections::HashMap; +use std::fmt; use parking_lot::RwLock; -use std::sync::Arc; +use std::sync::{Arc, Weak}; +use crate::call_budget::{BudgetPermit, CallBudget}; use crate::cancel::CancelToken; use crate::errors::ModuleError; +use crate::interaction::{ElicitationHandler, ProgressReporter}; use crate::trace_context::TraceParent; /// Maximum number of active delegation edges an identity may carry. @@ -385,6 +388,34 @@ impl std::hash::Hash for Identity { /// Note: deserialization creates a new `Arc` (not shared with the original). pub type SharedData = Arc>>; +#[doc(hidden)] +#[derive(Clone, Default)] +pub struct ContextRuntime { + pub(crate) progress_reporter: Option, + pub(crate) elicitation_handler: Option, + pub(crate) budget: Option>, + pub(crate) active_budget: Weak, +} + +impl ContextRuntime { + fn child(&self) -> Self { + Self { + active_budget: Weak::new(), + ..self.clone() + } + } +} + +impl fmt::Debug for ContextRuntime { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("ContextRuntime") + .field("progress_reporter", &self.progress_reporter.is_some()) + .field("elicitation_handler", &self.elicitation_handler.is_some()) + .field("budget", &self.budget.is_some()) + .finish_non_exhaustive() + } +} + /// Generic execution context carrying identity, services, and data. #[derive(Debug, Clone, Serialize, Deserialize)] pub struct Context { @@ -419,6 +450,10 @@ pub struct Context { /// Opaque; use [`Context::executor`] to call through it. #[serde(skip)] pub executor: Option>, + /// Local attachments. Use the context derivation methods to configure them. + #[serde(skip)] + #[doc(hidden)] + pub runtime: ContextRuntime, } fn default_shared_data() -> SharedData { @@ -456,6 +491,7 @@ impl Context { cancel_token: None, global_deadline: None, executor: None, + runtime: ContextRuntime::default(), } } @@ -474,6 +510,7 @@ impl Context { cancel_token: None, global_deadline: None, executor: None, + runtime: ContextRuntime::default(), } } @@ -503,6 +540,7 @@ impl Context { cancel_token: self.cancel_token.clone(), global_deadline: self.global_deadline, executor: self.executor.clone(), + runtime: self.runtime.child(), } } @@ -675,6 +713,7 @@ impl Context { cancel_token: None, global_deadline: None, executor: None, + runtime: ContextRuntime::default(), }) } @@ -771,6 +810,7 @@ impl Context { cancel_token, global_deadline, executor: None, + runtime: ContextRuntime::default(), } } @@ -940,6 +980,7 @@ impl ContextBuilder { cancel_token: self.cancel_token, global_deadline: self.global_deadline, executor: None, + runtime: ContextRuntime::default(), } } } diff --git a/rust/src/errors.rs b/rust/src/errors.rs index 901787ab..d935bcad 100644 --- a/rust/src/errors.rs +++ b/rust/src/errors.rs @@ -65,6 +65,7 @@ pub enum ErrorCode { CallDepthExceeded, CircularCall, CallFrequencyExceeded, + CallBudgetExceeded, GeneralInvalidInput, /// Raised when a `module_id` is empty or fails the canonical ID grammar /// (empty / pattern / length / reserved-word checks in @@ -299,6 +300,7 @@ impl ErrorCode { ErrorCode::CallDepthExceeded, ErrorCode::CircularCall, ErrorCode::CallFrequencyExceeded, + ErrorCode::CallBudgetExceeded, ErrorCode::GeneralInvalidInput, ErrorCode::InvalidModuleId, ErrorCode::GeneralInternalError, @@ -515,6 +517,7 @@ pub fn retryable_for_code(code: ErrorCode) -> Option { | ErrorCode::CallDepthExceeded | ErrorCode::CircularCall | ErrorCode::CallFrequencyExceeded + | ErrorCode::CallBudgetExceeded // Resolution and wiring: needs a deployment or code change. | ErrorCode::ModuleNotFound | ErrorCode::ModuleLoadError @@ -607,6 +610,7 @@ pub fn user_fixable_for_code(code: ErrorCode) -> Option { | ErrorCode::CallDepthExceeded | ErrorCode::CircularCall | ErrorCode::CallFrequencyExceeded + | ErrorCode::CallBudgetExceeded | ErrorCode::GeneralInternalError => Some(false), // Unlisted codes (e.g. MODULE_EXECUTE_ERROR) stay unset. _ => None, diff --git a/rust/src/executor.rs b/rust/src/executor.rs index 90058ffe..897c5fc5 100644 --- a/rust/src/executor.rs +++ b/rust/src/executor.rs @@ -18,7 +18,7 @@ use crate::builtin_steps::{ build_internal_strategy, build_minimal_strategy, build_performance_strategy, build_standard_strategy, build_testing_strategy, BuiltinPostValidationPolicy, }; -use crate::cancel::CancelToken; +use crate::cancel::{deadline_remaining, wait_for_cancellation, CancelToken}; use crate::config::Config; use crate::context::Context; use crate::errors::{ErrorCode, ModuleError}; @@ -458,14 +458,6 @@ async fn next_stream_chunk( } } -fn stream_deadline_remaining(deadline: f64) -> Option { - let now = std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .unwrap_or_default() - .as_secs_f64(); - std::time::Duration::try_from_secs_f64((deadline - now).max(0.0)).ok() -} - fn stream_timeout_error( token: Option<&CancelToken>, module_id: &str, @@ -484,8 +476,15 @@ fn stream_timeout_error( pub(crate) async fn open_stream( ctx: &PipelineContext, module: &Arc, -) -> Result, ModuleError> { - let context = ctx.context.clone(); + permit: Option>, +) -> Result< + ( + Option, + Option, + ), + ModuleError, +> { + let mut context = ctx.context.clone(); let token = context.cancel_token.clone(); let deadline = context.global_deadline; let opening_module = Arc::clone(module); @@ -500,7 +499,7 @@ pub(crate) async fn open_stream( token.check_for(&module_id)?; } if deadline - .and_then(stream_deadline_remaining) + .and_then(deadline_remaining) .is_some_and(|remaining| remaining.is_zero()) { return Err(stream_timeout_error( @@ -509,11 +508,18 @@ pub(crate) async fn open_stream( opening_module.as_ref(), )); } + let active = permit + .as_ref() + .map(crate::call_budget::BudgetPermit::start) + .transpose()?; + if let Some(active) = active.as_ref() { + active.bind(&mut context); + } let producer = match opening_module.as_streaming() { Some(typed) => Some(typed.stream_typed(inputs, &context)), None => opening_module.stream(inputs, &context), }; - Ok(producer) + Ok((producer, active)) }; let opening = match token.as_ref() { Some(token) => token.spawn_blocking_tracked(open), @@ -530,20 +536,30 @@ pub(crate) async fn open_stream( } } +pub(crate) fn with_stream_budget( + producer: crate::module::ChunkStream, + active: Option, +) -> crate::module::ChunkStream { + let Some(active) = active else { + return producer; + }; + Box::pin(async_stream::stream! { + let _active = active; + let mut producer = producer; + while let Some(chunk) = producer.next().await { + yield chunk; + } + }) +} + async fn wait_stream_interruption( token: Option<&CancelToken>, global_deadline: Option, module_id: &str, module: &dyn crate::module::Module, ) -> ModuleError { - let cancellation = async { - match token { - Some(token) => token.cancelled().await, - None => std::future::pending().await, - } - }; let timeout = async { - let remaining = global_deadline.and_then(stream_deadline_remaining); + let remaining = global_deadline.and_then(deadline_remaining); match remaining { Some(delta) if delta.is_zero() => {} Some(delta) => tokio::time::sleep(delta).await, @@ -552,7 +568,7 @@ async fn wait_stream_interruption( }; tokio::select! { biased; - () = cancellation => { + () = wait_for_cancellation(token) => { // The unary fallback's execute step signals its token on timeout. // Preserve that error if the pipeline is still unwinding hooks. token.and_then(CancelToken::timeout_error).cloned().unwrap_or_else(|| { @@ -1423,6 +1439,7 @@ impl Executor { Self::validate_module_id(module_id)?; let mut parent = context.cloned().unwrap_or_else(Context::anonymous); self.ensure_scope_gate(strategy, module_id, &parent)?; + Self::ensure_budget_strategy(strategy, module_id, &parent)?; parent.bind_executor(self.instance_handle())?; let started = std::time::Instant::now(); let mut previous_steps = Vec::new(); @@ -1442,6 +1459,7 @@ impl Executor { (output.unwrap_or(Value::Null), trace) } Err(error) => { + attempt.budget_reservation.take(); let error = Self::call_error(module_id, &attempt, error); match Self::recover_call(module_id, &attempt, &error).await { Some(OnErrorOutcome::Recovery(output)) => (output, attempt.trace), @@ -1474,13 +1492,32 @@ impl Executor { propagate_module_error(error, module_id, &ctx.context) } + fn ensure_budget_strategy( + strategy: &ExecutionStrategy, + module_id: &str, + context: &Context, + ) -> Result<(), ModuleError> { + if context.runtime.budget.is_some() + && !crate::pipeline_config::builtin_budget_steps_apply(strategy, module_id) + { + return Err(ModuleError::new( + ErrorCode::PipelineConfigurationError, + "CallBudget requires the built-in call-chain guard and execute steps", + )); + } + Ok(()) + } + async fn recover_call( module_id: &str, ctx: &PipelineContext, error: &ModuleError, ) -> Option { if ctx.blocks_error_recovery() - || error.code == ErrorCode::ExecutionCancelled + || matches!( + error.code, + ErrorCode::ExecutionCancelled | ErrorCode::CallBudgetExceeded + ) || ctx.executed_middlewares.is_empty() { return None; @@ -2065,6 +2102,7 @@ impl Executor { if let Some(stream) = &mut setup.pipe_ctx.stream { stream.producer = None; } + setup.pipe_ctx.budget_reservation.take(); let interrupted = matches!( raw_error.code, ErrorCode::ExecutionCancelled | ErrorCode::ModuleTimeout @@ -2308,6 +2346,7 @@ impl Executor { // D-103: no synthetic principal for a call that supplied none. let context = ctx.unwrap_or_else(Context::::anonymous); self.ensure_scope_gate(&self.strategy, module_id, &context)?; + Self::ensure_budget_strategy(&self.strategy, module_id, &context)?; let mut pipe_ctx = PipelineContext::new(module_id, inputs, context, self.strategy.name()); pipe_ctx.validate_approval_credential()?; @@ -2331,6 +2370,7 @@ impl Executor { { Ok(pair) => pair, Err(e) => { + pipe_ctx.budget_reservation.take(); let underlying = Self::call_error(module_id, &pipe_ctx, e); match Self::recover_call(module_id, &pipe_ctx, &underlying).await { Some(OnErrorOutcome::Recovery(value)) => { diff --git a/rust/src/interaction.rs b/rust/src/interaction.rs new file mode 100644 index 00000000..3209416b --- /dev/null +++ b/rust/src/interaction.rs @@ -0,0 +1,191 @@ +//! Optional application-provided interaction for executing modules. + +use std::future::Future; +use std::sync::Arc; + +use futures_util::future::BoxFuture; +use schemars::JsonSchema; +use serde::{Deserialize, Serialize}; +use serde_json::{Map, Value}; +use tokio::time::{sleep_until, Instant}; + +use crate::cancel::{deadline_remaining, wait_for_cancellation, CancelToken}; +use crate::{Context, ModuleError}; + +/// Progress reported by a running module. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)] +pub struct ProgressUpdate { + pub progress: f64, + pub total: Option, + pub message: Option, +} + +/// A prompt and the JSON Schema for the requested response. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)] +pub struct ElicitationRequest { + pub message: String, + pub requested_schema: Option, +} + +/// A user response to an elicitation request. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)] +#[serde(tag = "action", rename_all = "lowercase")] +pub enum ElicitationResult { + Accept { content: Map }, + Decline, + Cancel, +} + +/// A callback that receives a progress update. +pub type ProgressReporter = + Arc BoxFuture<'static, Result<(), ModuleError>> + Send + Sync>; + +/// A callback that handles an elicitation request. +pub type ElicitationHandler = Arc< + dyn Fn(ElicitationRequest) -> BoxFuture<'static, Result> + + Send + + Sync, +>; + +impl Context { + /// Derive a context with the given progress callback. + #[must_use] + pub fn with_progress_reporter(&self, callback: Option) -> Self { + let mut derived = self.clone(); + derived.runtime.progress_reporter = callback; + derived + } + + /// Derive a context with the given elicitation callback. + #[must_use] + pub fn with_elicitation_handler(&self, callback: Option) -> Self { + let mut derived = self.clone(); + derived.runtime.elicitation_handler = callback; + derived + } +} + +impl Context { + /// Report progress through the host callback, if installed. + pub async fn report_progress( + &self, + progress: f64, + total: Option, + message: Option<&str>, + ) -> Result<(), ModuleError> { + let Some(callback) = self.runtime.progress_reporter.as_ref() else { + return Ok(()); + }; + if !progress.is_finite() || total.is_some_and(|value| !value.is_finite()) { + return Err(ModuleError::invalid_input( + "Progress and total must be finite", + )); + } + await_interaction(self, || { + callback(ProgressUpdate { + progress, + total, + message: message.map(str::to_owned), + }) + }) + .await + } + + /// Request a caller response through the host callback, if installed. + pub async fn elicit( + &self, + message: &str, + requested_schema: impl Into>, + ) -> Result, ModuleError> { + let Some(callback) = self.runtime.elicitation_handler.as_ref() else { + return Ok(None); + }; + let requested_schema = requested_schema.into(); + if requested_schema + .as_ref() + .is_some_and(|schema| !schema.is_object()) + { + return Err(ModuleError::invalid_input( + "Elicitation requires a schema object", + )); + } + await_interaction(self, || { + callback(ElicitationRequest { + message: message.to_owned(), + requested_schema, + }) + }) + .await + .map(Some) + } +} + +async fn await_interaction>>( + context: &Context, + callback: impl FnOnce() -> F, +) -> Result { + let module_id = context.call_chain.last().map(String::as_str); + let token = context.cancel_token.as_ref(); + let expiration = context + .global_deadline + .and_then(deadline_remaining) + .and_then(|remaining| Instant::now().checked_add(remaining)); + let deadline_error = || { + let mut error = ModuleError::module_timeout(module_id.unwrap_or(""), 0); + "Interaction exceeded its execution deadline".clone_into(&mut error.message); + error.details.remove("timeout_ms"); + if module_id.is_none() { + error.details.remove("module_id"); + } + error + }; + let check_interruption = || { + check_interaction_cancellation(token, module_id)?; + if expiration.is_some_and(|deadline| Instant::now() >= deadline) { + return Err(deadline_error()); + } + Ok(()) + }; + + check_interruption()?; + let timeout = async { + match expiration { + Some(expiration) => sleep_until(expiration).await, + None => std::future::pending().await, + } + }; + let result = tokio::select! { + biased; + () = wait_for_cancellation(token) => return Err(cancellation_error(token, module_id)), + () = timeout => return Err(deadline_error()), + reply = async { callback().await } => reply, + }; + check_interruption()?; + result +} + +fn check_interaction_cancellation( + token: Option<&CancelToken>, + module_id: Option<&str>, +) -> Result<(), ModuleError> { + if token.is_some_and(CancelToken::is_cancelled) { + return Err(cancellation_error(token, module_id)); + } + Ok(()) +} + +fn cancellation_error(token: Option<&CancelToken>, module_id: Option<&str>) -> ModuleError { + token + .and_then(CancelToken::timeout_error) + .cloned() + .unwrap_or_else(|| { + use crate::cancel::ExecutionCancelledError; + match module_id { + Some(module_id) => { + ExecutionCancelledError::new(module_id, "Execution was cancelled") + } + None => ExecutionCancelledError::without_module("Execution was cancelled"), + } + .into() + }) +} diff --git a/rust/src/lib.rs b/rust/src/lib.rs index bf04684b..138610b1 100644 --- a/rust/src/lib.rs +++ b/rust/src/lib.rs @@ -17,6 +17,7 @@ pub mod approval; pub mod async_task; pub mod bindings; pub mod builtin_steps; +mod call_budget; pub mod cancel; pub mod capability; pub mod client; @@ -30,6 +31,7 @@ pub mod errors; pub mod events; pub mod executor; pub mod extensions; +mod interaction; pub mod lifecycle; pub mod middleware; pub mod module; @@ -86,12 +88,15 @@ pub use builtin_steps::{ BuiltinExecute, BuiltinInputValidation, BuiltinMiddlewareAfter, BuiltinMiddlewareBefore, BuiltinModuleLookup, BuiltinOutputValidation, BuiltinReturnResult, }; +pub use call_budget::{CallBudget, CallBudgetSnapshot}; pub use cancel::{CancelToken, ExecutionCancelledError}; pub use client::{APCore, APCoreOptions, APCoreStartupError, TypedModuleOptions}; pub use config::{ Config, ConfigMode, EnvStyle, ExecutorConfig, MetricsConfig, MountSource, NamespaceInfo, NamespaceRegistration, ObservabilityConfig, TracingConfig, RESERVED_NAMESPACES, }; +#[doc(hidden)] +pub use context::ContextRuntime; pub use context::{Context, ContextFactory, Identity}; pub use context_key::ContextKey; pub use context_keys::{ @@ -120,6 +125,9 @@ pub use executor::{ list_strategies, redact_sensitive, register_strategy, Executor, GovernanceState, REDACTED_VALUE, }; pub use extensions::{ExtensionKind, ExtensionManager, ExtensionPoint}; +pub use interaction::{ + ElicitationHandler, ElicitationRequest, ElicitationResult, ProgressReporter, ProgressUpdate, +}; pub use lifecycle::{ DrainAbortReason, DrainAbortedContext, DrainContext, DrainReasonKind, DrainTimeoutPolicy, LifecycleCompensation, LifecycleEventFlush, LifecycleFailure, LifecycleHook, LifecycleKind, diff --git a/rust/src/observability/redaction.rs b/rust/src/observability/redaction.rs index d380cf75..b342ad78 100644 --- a/rust/src/observability/redaction.rs +++ b/rust/src/observability/redaction.rs @@ -61,6 +61,16 @@ pub const DEFAULT_SENSITIVE_KEYS: &[&str] = &[ /// these, apcore-typescript reads them first. const CANONICAL_SENSITIVE_KEYS: &str = "obs.redaction.sensitive_keys"; const CANONICAL_REGEX_PATTERNS: &str = "obs.redaction.regex_patterns"; +pub(crate) const MAX_REGEX_SCAN_LENGTH: &str = "obs.redaction.max_regex_scan_length"; +pub(crate) const DEFAULT_MAX_REGEX_SCAN_LENGTH: usize = 65_536; +const MAX_PORTABLE_SCAN_LENGTH: u64 = (1 << 53) - 1; + +pub(crate) fn regex_scan_length(value: &Value) -> Option { + let limit = value + .as_u64() + .filter(|limit| *limit <= MAX_PORTABLE_SCAN_LENGTH)?; + Some(usize::try_from(limit).unwrap_or(usize::MAX)) +} const CANONICAL_REPLACEMENT: &str = "obs.redaction.replacement"; /// The keys this SDK read before the canonical namespace was honoured. Still @@ -142,6 +152,7 @@ pub struct RedactionConfig { /// Plain substring patterns, pre-normalized via [`normalize_key_for_match`]. field_substrings: Vec, value_patterns: Vec, + max_regex_scan_length: Option, replacement: String, } @@ -173,6 +184,7 @@ impl RedactionConfig { field_patterns: Vec::new(), field_substrings: Vec::new(), value_patterns: Vec::new(), + max_regex_scan_length: None, replacement: DEFAULT_REPLACEMENT.to_string(), } } @@ -324,6 +336,10 @@ impl RedactionConfig { } cfg.value_patterns = value_patterns; + cfg.max_regex_scan_length = config + .get(MAX_REGEX_SCAN_LENGTH) + .as_ref() + .and_then(regex_scan_length); cfg.replacement = replacement .as_ref() .and_then(|v| v.as_str()) @@ -414,10 +430,16 @@ impl RedactionConfig { .any(|sub| normalized.contains(sub)) } - /// Check whether a value matches any value regex. + /// Check whether a string must be redacted by the regex rules. + /// Strings over the scan limit are redacted in full without running a pattern. #[must_use] pub fn value_matches(&self, value: &str) -> bool { - self.value_patterns.iter().any(|r| r.is_match(value)) + !self.value_patterns.is_empty() + && (value.len() + > self + .max_regex_scan_length + .unwrap_or(DEFAULT_MAX_REGEX_SCAN_LENGTH) + || self.value_patterns.iter().any(|r| r.is_match(value))) } /// The configured replacement string. @@ -433,6 +455,7 @@ pub struct RedactionConfigBuilder { field_patterns: Vec, sensitive_keys: Vec, value_patterns: Vec, + max_regex_scan_length: Option, replacement: Option, } @@ -448,6 +471,8 @@ pub enum RedactionConfigError { #[source] source: regex::Error, }, + #[error("max_regex_scan_length must be a nonnegative safe integer")] + InvalidScanLength, } impl RedactionConfigBuilder { @@ -473,6 +498,13 @@ impl RedactionConfigBuilder { self } + /// Limit regex scanning to this many UTF-8 bytes per string. + #[must_use] + pub fn max_regex_scan_length(mut self, bytes: usize) -> Self { + self.max_regex_scan_length = Some(bytes); + self + } + /// Append `sensitive_keys` entries (D-54). Each entry is auto-detected: /// strings containing `*` or `?` are glob-dialect patterns (A25); bare /// strings become case-insensitive substring matchers (with separator + @@ -503,6 +535,11 @@ impl RedactionConfigBuilder { /// [`RedactionConfig::add_sensitive_key`] does — the case fold has to /// reach the pattern, not only the field name. pub fn try_build(self) -> Result { + if self.max_regex_scan_length.is_some_and(|length| { + u64::try_from(length).map_or(true, |length| length > MAX_PORTABLE_SCAN_LENGTH) + }) { + return Err(RedactionConfigError::InvalidScanLength); + } let field_patterns: Vec = self .field_patterns .into_iter() @@ -528,6 +565,7 @@ impl RedactionConfigBuilder { field_patterns, field_substrings: Vec::new(), value_patterns, + max_regex_scan_length: self.max_regex_scan_length, replacement: self .replacement .unwrap_or_else(|| DEFAULT_REPLACEMENT.to_string()), @@ -546,6 +584,53 @@ impl RedactionConfigBuilder { } } +#[cfg(test)] +mod regex_scan_limit_tests { + use super::*; + use serde_json::json; + + #[test] + fn limits_the_default_scan_to_65536_utf8_bytes() { + let regex = RedactionConfig::builder() + .value_patterns(["sensitive"]) + .build(); + let boundary = "\u{00e9}".repeat(32_768); + let oversized = format!("{boundary}x"); + let mut value = json!({ + "within": boundary, + "nested": [oversized], + "trace_id": oversized, + }); + regex.redact(&mut value); + assert_eq!(value["within"], boundary); + assert_eq!(value["nested"][0], regex.replacement()); + assert_eq!(value["trace_id"], oversized); + let mut value = json!(oversized); + RedactionConfig::new().redact(&mut value); + assert_eq!(value, oversized); + } + + #[test] + fn reads_the_configured_scan_limit_and_uses_the_configured_replacement() { + let mut config = Config::in_memory(); + config.set("obs.redaction.regex_patterns", json!(["sensitive"])); + config.set("obs.redaction.max_regex_scan_length", json!(4)); + config.set("obs.redaction.replacement", json!("[HIDDEN]")); + let mut value = json!([ + "1234", + "12345", + "\u{00e9}\u{00e9}", + "\u{00e9}\u{00e9}x", + 12345 + ]); + RedactionConfig::from_config(&config).redact(&mut value); + assert_eq!( + value, + json!(["1234", "[HIDDEN]", "\u{00e9}\u{00e9}", "[HIDDEN]", 12345]) + ); + } +} + #[cfg(test)] mod tests { use std::sync::{Arc, Mutex}; diff --git a/rust/src/pipeline.rs b/rust/src/pipeline.rs index e0be8f10..244c51fa 100644 --- a/rust/src/pipeline.rs +++ b/rust/src/pipeline.rs @@ -297,6 +297,8 @@ pub struct PipelineContext { /// Set by `module_lookup` step. pub module: Option>, pub(crate) module_lease: Option>, + pub(crate) call_budget: Option>, + pub(crate) budget_reservation: Option, /// The §6.1.8 governance projection of `inputs` — the argument key set and /// each key's JSON type, and **never** a value. /// @@ -445,6 +447,7 @@ impl PipelineContext { .as_object_mut() .and_then(|object| object.remove(crate::policy::APPROVAL_TOKEN_KEY)); let initial_scope = ScopeInvocation::from_parent(&context, &module_id); + let call_budget = context.runtime.budget.clone(); Self { trace: PipelineTrace::new(module_id.clone(), strategy_name.clone()), module_id, @@ -453,6 +456,8 @@ impl PipelineContext { context, module: None, module_lease: None, + call_budget, + budget_reservation: None, governance_projection: None, acl_approval_required: false, acl_decision: None, @@ -499,6 +504,34 @@ impl PipelineContext { Ok(()) } + pub(crate) fn budget_permit( + &mut self, + ) -> Result>, ModuleError> { + let Some(budget) = &self.call_budget else { + return Ok(None); + }; + if self + .context + .runtime + .budget + .as_ref() + .is_some_and(|current| Arc::ptr_eq(current, budget)) + { + if let Some(permit) = self + .budget_reservation + .as_ref() + .and_then(|reservation| reservation.permit(&self.module_id)) + { + return Ok(Some(permit)); + } + } + self.terminal_gate_failure = true; + Err(ModuleError::new( + crate::ErrorCode::PipelineConfigurationError, + "CallBudget requires the reserved module and its execution context", + )) + } + pub(crate) fn take_approval_credential(&mut self) -> Result, ModuleError> { self.validate_approval_credential()?; Ok(match self.approval_credential.take() { diff --git a/rust/src/pipeline_config.rs b/rust/src/pipeline_config.rs index 71b40ffa..e70534dc 100644 --- a/rust/src/pipeline_config.rs +++ b/rust/src/pipeline_config.rs @@ -119,6 +119,22 @@ pub(crate) fn builtin_scope_gate_applies(strategy: &ExecutionStrategy, module_id false } +pub(crate) fn builtin_budget_steps_apply(strategy: &ExecutionStrategy, module_id: &str) -> bool { + let mut guard_ready = false; + for step in strategy.steps().iter().map(Box::as_ref) { + if !step_applies(step, module_id) { + continue; + } + if step.name() == "execute" { + return guard_ready && is_builtin_step::(step) && !step.ignore_errors(); + } + if is_builtin_step::(step) { + guard_ready = !step.ignore_errors(); + } + } + false +} + fn builtin_step_applies(step: &dyn Step, module_id: &str) -> bool { step_applies(step, module_id) && is_builtin_step::(step) } diff --git a/rust/src/sys_modules/audit.rs b/rust/src/sys_modules/audit.rs index 0e6dba53..b5084d16 100644 --- a/rust/src/sys_modules/audit.rs +++ b/rust/src/sys_modules/audit.rs @@ -225,6 +225,7 @@ mod tests { cancel_token: None, global_deadline: None, executor: None, + runtime: crate::ContextRuntime::default(), } } diff --git a/rust/tests/call_budget.rs b/rust/tests/call_budget.rs new file mode 100644 index 00000000..ffd9055b --- /dev/null +++ b/rust/tests/call_budget.rs @@ -0,0 +1,377 @@ +#![allow(clippy::result_large_err)] + +use std::collections::HashMap; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::Arc; + +use apcore::{ + build_minimal_strategy, APCore, APCoreOptions, ApprovalHandler, ApprovalRequest, + ApprovalResult, CallBudget, CancelToken, ChunkStream, Config, Context, ErrorCode, Executor, + Module, ModuleAnnotations, ModuleError, Registry, RetryConfig, RetryMiddleware, +}; +use async_trait::async_trait; +use futures_util::{stream, StreamExt}; +use serde_json::{json, Value}; + +struct Metered { + started: AtomicUsize, + needs_approval: bool, + streaming: bool, +} + +#[async_trait] +impl Module for Metered { + fn input_schema(&self) -> Value { + json!({"type":"object","properties":{"actual":{"type":"integer"}}}) + } + + fn output_schema(&self) -> Value { + json!({"type":"object"}) + } + + fn description(&self) -> &'static str { + "Test invocation charges" + } + + fn annotations(&self) -> ModuleAnnotations { + ModuleAnnotations { + requires_approval: self.needs_approval, + ..ModuleAnnotations::default() + } + } + + async fn execute(&self, input: Value, ctx: &Context) -> Result { + let index = self.started.fetch_add(1, Ordering::Relaxed); + if let Some(actual) = input["actual"].as_u64() { + ctx.record_cost(actual)?; + if input["record_again"] == true { + ctx.record_cost(actual)?; + } + } + if input["retry_once"] == true && index == 0 { + return Err(ModuleError::new( + ErrorCode::GeneralInternalError, + "retry this attempt", + )); + } + Ok(json!({"started":index + 1})) + } + + fn stream(&self, input: Value, ctx: &Context) -> Option { + if !self.streaming { + return None; + } + let context = ctx.clone(); + Some(Box::pin(stream::once(async move { + context.record_cost(input["actual"].as_u64().unwrap())?; + Ok(json!({"streamed":true})) + }))) + } +} + +fn register(client: &APCore, needs_approval: bool, streaming: bool) { + client + .register( + "test.cost", + Box::new(Metered { + started: AtomicUsize::new(0), + needs_approval, + streaming, + }), + ) + .unwrap(); +} + +fn budget(max_calls: Option, max_cost: Option) -> Arc { + Arc::new( + CallBudget::new( + max_calls, + max_cost, + HashMap::from([("test.cost".into(), 3)]), + ) + .unwrap(), + ) +} + +#[tokio::test] +async fn call_budget_matches_the_shared_conformance_fixture() { + let fixture_path = super::conformance_env::find_fixtures_root().join("call_budget.json"); + let fixture: Value = + serde_json::from_str(&std::fs::read_to_string(fixture_path).unwrap()).unwrap(); + for test in fixture["test_cases"].as_array().unwrap() { + let id = test["id"].as_str().unwrap(); + let module_id = test["module_id"].as_str().unwrap(); + let budget = Arc::new( + CallBudget::new( + test["max_calls"].as_u64(), + test["max_cost"].as_u64(), + HashMap::from([( + module_id.to_owned(), + test["estimated_cost"].as_u64().unwrap(), + )]), + ) + .unwrap(), + ); + let context = Context::::anonymous().with_budget(Some(Arc::clone(&budget))); + let executor = Executor::new(Registry::new(), Config::in_memory()); + executor + .registry() + .register_module( + module_id, + Box::new(Metered { + started: AtomicUsize::new(0), + needs_approval: false, + streaming: false, + }), + ) + .unwrap(); + for (index, call) in test["calls"].as_array().unwrap().iter().enumerate() { + let inputs = call["actual_cost"] + .as_u64() + .map_or_else(|| json!({}), |actual| json!({"actual":actual})); + let result = executor.call(module_id, inputs, Some(&context), None).await; + let mut observed = serde_json::to_value(budget.snapshot()).unwrap(); + observed["error_code"] = result + .err() + .map_or(Value::Null, |error| json!(error.wire_code())); + assert_eq!(observed, test["expected"][index], "{id} call {index}"); + } + } +} + +#[tokio::test] +async fn charges_only_started_calls_and_replaces_the_estimate_with_actual() { + let client = APCore::new(); + register(&client, false, false); + let budget = budget(Some(4), Some(5)); + let context = Context::::anonymous().with_budget(Some(Arc::clone(&budget))); + assert!(CallBudget::new(Some(1u64 << 53), None, HashMap::new()).is_err()); + assert!(context.record_cost(2).is_err()); + assert_eq!( + context.clone().serialize(), + context.with_budget(None).serialize() + ); + + let preflight = client + .validate("test.cost", &json!({}), Some(&context)) + .await + .unwrap(); + assert!(preflight.valid); + let _ = client + .call("test.missing", json!({}), Some(&context), None) + .await + .unwrap_err(); + let _ = client + .call( + "test.cost", + json!({"actual":"invalid"}), + Some(&context), + None, + ) + .await + .unwrap_err(); + assert_eq!(budget.snapshot().calls_reserved, 0); + assert_eq!(budget.snapshot().calls_used, 0); + assert_eq!(budget.snapshot().cost_used, 0); + + client + .call("test.cost", json!({"actual":0}), Some(&context), None) + .await + .unwrap(); + assert_eq!(budget.snapshot().cost_used, 0); + let error = client + .call("test.cost", json!({"actual":6}), Some(&context), None) + .await + .unwrap_err(); + assert_eq!(error.code, ErrorCode::CallBudgetExceeded); + assert_eq!(error.details["dimension"], "cost"); + assert_eq!(error.retryable, Some(false)); + assert_eq!(budget.snapshot().calls_used, 2); + assert_eq!(budget.snapshot().cost_used, 6); + + let denied = client + .call("test.cost", json!({}), Some(&context), None) + .await + .unwrap_err(); + assert_eq!(denied.code, ErrorCode::CallBudgetExceeded); + assert_eq!(denied.details["dimension"], "cost"); + assert_eq!(budget.snapshot().calls_used, 2); + assert_eq!(budget.snapshot().calls_reserved, 0); +} + +#[derive(Debug, Clone, Default)] +struct Pending { + requested: Arc, + release: Arc, +} + +#[async_trait] +impl ApprovalHandler for Pending { + async fn request_approval(&self, _: &ApprovalRequest) -> Result { + self.requested.notify_one(); + self.release.notified().await; + let mut result = ApprovalResult::default(); + result.status = "pending".into(); + result.approval_id = Some("budget-approval".to_owned()); + Ok(result) + } + + async fn check_approval(&self, _: &str) -> Result { + Ok(ApprovalResult::approved("budget-reviewer")) + } +} + +#[tokio::test] +async fn pending_and_cancelled_calls_release_a_concurrent_reservation() { + let pending = Pending::default(); + let client = Arc::new( + APCore::try_start(APCoreOptions { + approval_handler: Some(Box::new(pending.clone())), + ..APCoreOptions::default() + }) + .unwrap(), + ); + register(&client, true, false); + let budget = budget(Some(1), None); + let context = Context::::anonymous().with_budget(Some(Arc::clone(&budget))); + + let worker = tokio::spawn({ + let client = Arc::clone(&client); + let context = context.clone(); + async move { + client + .call("test.cost", json!({}), Some(&context), None) + .await + } + }); + pending.requested.notified().await; + assert_eq!(budget.snapshot().calls_reserved, 1); + let error = client + .call("test.cost", json!({}), Some(&context), None) + .await + .unwrap_err(); + assert_eq!(error.details["dimension"], "calls"); + pending.release.notify_one(); + assert_eq!( + worker.await.unwrap().unwrap_err().code, + ErrorCode::ApprovalPending + ); + assert_eq!(budget.snapshot().calls_used, 0); + assert_eq!(budget.snapshot().calls_reserved, 0); + + let mut cancelled = context; + let token = CancelToken::new(); + token.cancel(); + cancelled.cancel_token = Some(token); + let error = client + .call("test.cost", json!({}), Some(&cancelled), None) + .await + .unwrap_err(); + assert_eq!(error.code, ErrorCode::ExecutionCancelled); + assert_eq!(budget.snapshot().calls_reserved, 0); +} + +#[tokio::test] +async fn retries_spend_once_per_started_attempt_and_streams_charge_once() { + let client = APCore::new(); + register(&client, false, false); + let mut retry = RetryConfig::default(); + retry.max_retries = 1; + retry.base_delay_ms = 0; + retry.jitter = false; + client + .use_middleware(Box::new(RetryMiddleware::new(retry))) + .unwrap(); + let retry_budget = budget(None, None); + let context = Context::::anonymous().with_budget(Some(Arc::clone(&retry_budget))); + let output = client + .call( + "test.cost", + json!({"retry_once":true}), + Some(&context), + None, + ) + .await + .unwrap(); + assert_eq!(output["started"], 2); + assert_eq!(retry_budget.snapshot().calls_used, 2); + assert_eq!(retry_budget.snapshot().cost_used, 6); + let chunks = client + .stream("test.cost", json!({"actual":4}), Some(&context), None) + .collect::>() + .await; + assert_eq!(chunks[0].as_ref().unwrap()["started"], 3); + assert_eq!(retry_budget.snapshot().calls_used, 3); + assert_eq!(retry_budget.snapshot().cost_used, 10); + + let streaming = APCore::new(); + register(&streaming, false, true); + let streaming_budget = budget(Some(1), Some(10)); + let context = context.with_budget(Some(Arc::clone(&streaming_budget))); + let chunks = streaming + .stream("test.cost", json!({"actual":8}), Some(&context), None) + .collect::>() + .await; + assert_eq!(chunks[0].as_ref().unwrap()["streamed"], true); + assert_eq!(streaming_budget.snapshot().calls_used, 1); + assert_eq!(streaming_budget.snapshot().cost_used, 8); + let denied = streaming + .stream("test.cost", json!({"actual":1}), Some(&context), None) + .next() + .await + .unwrap() + .unwrap_err(); + assert_eq!(denied.code, ErrorCode::CallBudgetExceeded); + assert_eq!(denied.details["dimension"], "calls"); +} + +#[tokio::test] +async fn redundant_cost_reporting_cannot_replace_a_charge_and_wide_totals_remain_portable() { + let client = APCore::new(); + register(&client, false, false); + let base = Context::::anonymous(); + assert!(base.record_cost(u64::MAX).is_ok()); + let budget = budget(None, None); + let ctx = base.with_budget(Some(Arc::clone(&budget))); + let duplicated = client + .call( + "test.cost", + json!({"actual": 4, "record_again":true}), + Some(&ctx), + None, + ) + .await + .unwrap_err(); + assert_eq!(duplicated.code, ErrorCode::GeneralInvalidInput); + assert_eq!(budget.snapshot().cost_used, 4); + let max_safe = (1u64 << 53) - 1; + client + .call("test.cost", json!({"actual":max_safe}), Some(&ctx), None) + .await + .unwrap(); + assert_eq!(budget.snapshot().cost_used, max_safe); +} + +#[tokio::test] +async fn custom_strategy_without_a_stock_call_chain_guard_cannot_spend_budget() { + let config = Config::in_memory(); + let executor = + Executor::with_strategy(Registry::new(), config.clone(), build_minimal_strategy()); + let client = APCore::with_options(None, Some(executor), Some(config), None); + register(&client, false, false); + let budget = budget(Some(1), None); + let ctx = Context::::anonymous().with_budget(Some(Arc::clone(&budget))); + + let denied = client + .call("test.cost", json!({}), Some(&ctx), None) + .await + .unwrap_err(); + assert_eq!(denied.code, ErrorCode::PipelineConfigurationError); + assert_eq!(budget.snapshot().calls_used, 0); + assert_eq!(budget.snapshot().calls_reserved, 0); + let approved = client + .call("test.cost", json!({}), None, None) + .await + .unwrap(); + assert_eq!(approved["started"], 1); +} diff --git a/rust/tests/context_serialization_test.rs b/rust/tests/context_serialization_test.rs index 65b7f707..b0f75fa3 100644 --- a/rust/tests/context_serialization_test.rs +++ b/rust/tests/context_serialization_test.rs @@ -30,6 +30,7 @@ fn make_ctx() -> Context<()> { cancel_token: None, global_deadline: None, executor: None, + runtime: apcore::ContextRuntime::default(), } } @@ -229,6 +230,7 @@ fn make_top_level_ctx() -> Context<()> { cancel_token: None, global_deadline: None, executor: None, + runtime: apcore::ContextRuntime::default(), } } diff --git a/rust/tests/core_profile.rs b/rust/tests/core_profile.rs index 8d870cca..e0257fed 100644 --- a/rust/tests/core_profile.rs +++ b/rust/tests/core_profile.rs @@ -12,10 +12,12 @@ use async_trait::async_trait; use futures_util::{stream, StreamExt}; use serde_json::{json, Value}; +mod call_budget; mod capability_discovery; #[path = "conformance_env.rs"] mod conformance_env; mod post_validation_policy; +mod realtime_context; #[derive(Default)] struct Report { diff --git a/rust/tests/realtime_context.rs b/rust/tests/realtime_context.rs new file mode 100644 index 00000000..fb417d65 --- /dev/null +++ b/rust/tests/realtime_context.rs @@ -0,0 +1,130 @@ +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::Arc; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; + +use apcore::{ + APCore, CancelToken, Context, ElicitationHandler, ElicitationResult, ErrorCode, Module, + ModuleError, ProgressReporter, +}; +use async_trait::async_trait; +use serde_json::{json, Value}; + +struct InteractionModule; + +#[async_trait] +impl Module for InteractionModule { + fn input_schema(&self) -> Value { + json!({"type": "object"}) + } + + fn output_schema(&self) -> Value { + json!({"type": "object"}) + } + + fn description(&self) -> &'static str { + "Test execution-local interaction" + } + + async fn execute(&self, _inputs: Value, ctx: &Context) -> Result { + ctx.report_progress(1.0, Some(2.0), Some("starting")) + .await?; + let result = ctx.elicit("Continue?", json!({"type": "object"})).await?; + Ok(json!({"answer": result})) + } +} + +#[tokio::test] +async fn callbacks_are_derived_and_local_to_rust_contexts() { + let base = Context::::anonymous(); + let calls = Arc::new(AtomicUsize::new(0)); + let reporter: ProgressReporter = Arc::new({ + let calls = Arc::clone(&calls); + move |update| { + let calls = Arc::clone(&calls); + Box::pin(async move { + assert_eq!(update.progress.to_bits(), 1.0f64.to_bits()); + assert_eq!(update.total.map(f64::to_bits), Some(2.0f64.to_bits())); + assert_eq!(update.message.as_deref(), Some("starting")); + calls.fetch_add(1, Ordering::Relaxed); + Ok(()) + }) + } + }); + let handler: ElicitationHandler = Arc::new(|request| { + Box::pin(async move { + assert_eq!(request.message, "Continue?"); + assert_eq!(request.requested_schema.as_ref().unwrap()["type"], "object"); + Ok(ElicitationResult::Accept { + content: serde_json::Map::from_iter([("confirm".into(), json!(true))]), + }) + }) + }); + let interactive = base + .with_progress_reporter(Some(reporter)) + .with_elicitation_handler(Some(handler)); + assert_eq!(base.serialize(), interactive.serialize()); + let mut wire = serde_json::to_value(&interactive).unwrap(); + assert_eq!(wire, serde_json::to_value(&base).unwrap()); + wire["runtime"] = json!({"progress_reporter":"untrusted"}); + let decoded: Context = serde_json::from_value(wire).unwrap(); + + let client = APCore::new(); + client + .register("test.interaction", Box::new(InteractionModule)) + .unwrap(); + let output = client + .call("test.interaction", json!({}), Some(&interactive), None) + .await + .unwrap(); + assert_eq!( + output, + json!({"answer": {"action":"accept","content":{"confirm":true}}}) + ); + for context in [ + base, + decoded, + interactive + .with_progress_reporter(None) + .with_elicitation_handler(None), + ] { + let output = client + .call("test.interaction", json!({}), Some(&context), None) + .await + .unwrap(); + assert_eq!(output, json!({"answer": null})); + } + assert_eq!(calls.load(Ordering::Relaxed), 1); +} + +#[tokio::test] +async fn interruption_of_a_pending_callback_preserves_cancellation_and_timeout_errors() { + let token = CancelToken::new(); + let started = Arc::new(tokio::sync::Notify::new()); + let reporter: ProgressReporter = Arc::new({ + let started = Arc::clone(&started); + move |_| { + started.notify_one(); + Box::pin(std::future::pending()) + } + }); + let context = Context::create(None, None, Some(token.clone()), None, Value::Null, None) + .with_progress_reporter(Some(reporter)); + let worker = tokio::spawn(async move { context.report_progress(1.0, None, None).await }); + started.notified().await; + token.cancel(); + let error = worker.await.unwrap().unwrap_err(); + assert_eq!(error.code, ErrorCode::ExecutionCancelled); + + let deadline = (SystemTime::now() + Duration::from_millis(20)) + .duration_since(UNIX_EPOCH) + .unwrap() + .as_secs_f64(); + let handler: ElicitationHandler = Arc::new(|_| Box::pin(std::future::pending())); + let context = Context::create(None, None, None, None, Value::Null, Some(deadline)) + .with_elicitation_handler(Some(handler)); + let error = context + .elicit("Continue?", json!({"type":"object"})) + .await + .unwrap_err(); + assert_eq!(error.code, ErrorCode::ModuleTimeout); +} diff --git a/rust/tests/test_config_load_framework_sections.rs b/rust/tests/test_config_load_framework_sections.rs index 2187eb20..86f78bb0 100644 --- a/rust/tests/test_config_load_framework_sections.rs +++ b/rust/tests/test_config_load_framework_sections.rs @@ -115,6 +115,7 @@ bindings: pattern: "*.bind.yaml" obs: redaction: + max_regex_scan_length: 2048 sensitive_keys: - vendor_token replacement: "[GONE]" @@ -207,6 +208,7 @@ fn declared_pairs() -> Vec<(&'static str, Value)> { // default cannot supply proves the file was read. ("bindings.dir", json!("./my-bindings")), ("bindings.pattern", json!("*.bind.yaml")), + ("obs.redaction.max_regex_scan_length", json!(2048)), ("obs.redaction.sensitive_keys", json!(["vendor_token"])), ("obs.redaction.replacement", json!("[GONE]")), ] @@ -238,7 +240,7 @@ fn expected_subtrees() -> Vec<(&'static str, Value)> { ), ( "obs", - json!({"redaction": {"regex_patterns": [], "sensitive_keys": ["vendor_token"], "replacement": "[GONE]"}}), + json!({"redaction": {"max_regex_scan_length": 2048, "regex_patterns": [], "sensitive_keys": ["vendor_token"], "replacement": "[GONE]"}}), ), ] } @@ -398,7 +400,7 @@ fn container_fetches_agree_with_their_leaves() { let (_dir, config) = loaded_ns(); for (section, subtree) in expected_subtrees() { let declared_subtree = if section == "obs" { - json!({"redaction": {"sensitive_keys": ["vendor_token"], "replacement": "[GONE]"}}) + json!({"redaction": {"max_regex_scan_length": 2048, "sensitive_keys": ["vendor_token"], "replacement": "[GONE]"}}) } else { subtree.clone() }; diff --git a/rust/tests/test_event_naming_canonical.rs b/rust/tests/test_event_naming_canonical.rs index 4c033714..90fe1c64 100644 --- a/rust/tests/test_event_naming_canonical.rs +++ b/rust/tests/test_event_naming_canonical.rs @@ -112,6 +112,7 @@ fn build_ctx_with_caller(caller_id: Option, identity_id: Option<&str>) - cancel_token: None, global_deadline: None, executor: None, + runtime: apcore::ContextRuntime::default(), } } diff --git a/rust/tests/test_reload_order_registration_paths.rs b/rust/tests/test_reload_order_registration_paths.rs index 1ff6009c..3161ff0c 100644 --- a/rust/tests/test_reload_order_registration_paths.rs +++ b/rust/tests/test_reload_order_registration_paths.rs @@ -170,6 +170,7 @@ fn make_ctx() -> Context { cancel_token: None, global_deadline: None, executor: None, + runtime: apcore::ContextRuntime::default(), } } diff --git a/rust/tests/test_system_modules_hardening_conformance.rs b/rust/tests/test_system_modules_hardening_conformance.rs index b925d779..ceb4986b 100644 --- a/rust/tests/test_system_modules_hardening_conformance.rs +++ b/rust/tests/test_system_modules_hardening_conformance.rs @@ -234,6 +234,7 @@ fn make_ctx(id: Option<(&str, &str)>) -> Context { cancel_token: None, global_deadline: None, executor: None, + runtime: apcore::ContextRuntime::default(), } } diff --git a/rust/tests/test_trace_context_conformance.rs b/rust/tests/test_trace_context_conformance.rs index 990704c0..421d0002 100644 --- a/rust/tests/test_trace_context_conformance.rs +++ b/rust/tests/test_trace_context_conformance.rs @@ -115,6 +115,7 @@ fn context_from(tp: &TraceParent) -> Context { cancel_token: None, global_deadline: None, executor: None, + runtime: apcore::ContextRuntime::default(), } } diff --git a/schemas/apcore-config.schema.json b/schemas/apcore-config.schema.json index 445015e7..faa61fed 100644 --- a/schemas/apcore-config.schema.json +++ b/schemas/apcore-config.schema.json @@ -787,6 +787,13 @@ "description": "Declarative redaction rules applied by ContextLogger and the executor.", "additionalProperties": false, "properties": { + "max_regex_scan_length": { + "type": "integer", + "description": "Maximum UTF-8 bytes scanned per string value when a regex rule is configured. Replace the whole value when it exceeds the limit.", + "minimum": 0, + "maximum": 9007199254740991, + "default": 65536 + }, "regex_patterns": { "type": "array", "description": "Regular expressions matched case-insensitively against STRING field VALUES by UNANCHORED SEARCH — a value matches when the pattern occurs anywhere within it; write ^...$ for a whole-value match. A matching value is replaced by `replacement`. The rule applies to strings ONLY: a number, boolean, null, object or array is never tested and is never stringified in order to test it (protocol-spec 10.6.1 requirement 2) — the three host languages render the same non-string value three different ways, so a rule defined over that rendering would be three rules. Containers are descended into, so a string inside one is still reached. Patterns SHOULD stay inside the portable subset (no lookaround, no backreferences, no inline (?i) flags): those are exactly where the three engines disagree. A pattern that does not compile MUST NOT be dropped silently — see protocol-spec 9.2.3 requirement 6 and 10.6.1.", diff --git a/typescript/apcore-conformance.yaml b/typescript/apcore-conformance.yaml index 50023ba9..dcae1c0c 100644 --- a/typescript/apcore-conformance.yaml +++ b/typescript/apcore-conformance.yaml @@ -2,7 +2,7 @@ # It does not certify every fixture required by Level 1 or Level 2. implementation: name: apcore-typescript - version: "1.0.0-alpha.6" + version: "1.0.0-beta.1" language: typescript spec_version: "1.65.0" maintainer: AI Perceivable diff --git a/typescript/package.json b/typescript/package.json index b9d6a3d2..616b9c09 100644 --- a/typescript/package.json +++ b/typescript/package.json @@ -1,6 +1,6 @@ { "name": "apcore-js", - "version": "1.0.0-alpha.6", + "version": "1.0.0-beta.1", "description": "Build once, invoke by code or AI — with schema, ACL, approval, and audit enforced at every call", "type": "module", "main": "./dist/index.js", diff --git a/typescript/src/async-task.ts b/typescript/src/async-task.ts index caaea9b6..f7aa8c2d 100644 --- a/typescript/src/async-task.ts +++ b/typescript/src/async-task.ts @@ -5,7 +5,7 @@ import { uuidV4 as uuidv4 } from './utils/uuid.js'; import { CancelToken } from './cancel.js'; import type { Context } from './context.js'; -import { ErrorCodes, ModuleError, TaskLimitExceededError } from './errors.js'; +import { CallBudgetExceededError, ErrorCodes, ModuleError, TaskLimitExceededError } from './errors.js'; import type { Executor } from './executor.js'; export enum TaskStatus { @@ -687,7 +687,7 @@ export class AsyncTaskManager { return; } - if (retry && info.retryCount < retry.maxRetries) { + if (retry && info.retryCount < retry.maxRetries && !(attempt.error instanceof CallBudgetExceededError)) { const delay = retry.computeDelayMs(info.retryCount); const pending = await this._saveRunnerState(taskId, internal, (current) => ({ ...current, status: TaskStatus.PENDING, retryCount: current.retryCount + 1, @@ -788,19 +788,6 @@ export class AsyncTaskManager { // removes `executor` from Context.create()'s public surface. return CtxClass.create(undefined, undefined, cancelToken); } - // Shallow clone (preserve identity/data/etc.) and overwrite cancelToken. - const cloned = new CtxClass( - callerContext.traceId, - callerContext.callerId, - [...callerContext.callChain], - callerContext.executor, - callerContext.identity, - callerContext.redactedInputs, - callerContext.data, - cancelToken, - callerContext.services, - callerContext.globalDeadline, - ); - return cloned; + return callerContext._withCancellationScope(cancelToken); } } diff --git a/typescript/src/browser/index.ts b/typescript/src/browser/index.ts index 264cb5bb..383ac2bf 100644 --- a/typescript/src/browser/index.ts +++ b/typescript/src/browser/index.ts @@ -29,6 +29,8 @@ export type { Discoverer, ModuleValidator } from '../registry/registry.js'; // ---- Context / identity / cancel ----------------------------------------- export { CancelToken, ExecutionCancelledError } from '../cancel.js'; export { Context, Identity, createIdentity } from '../context.js'; +export { CallBudget } from '../call-budget.js'; +export type { CallBudgetOptions, CallBudgetSnapshot } from '../call-budget.js'; export { ContextKey } from '../context-key.js'; export { TRACING_SPANS, @@ -38,7 +40,7 @@ export { REDACTED_OUTPUT, RETRY_COUNT_BASE, } from '../context-keys.js'; -export type { IdentityOptions, ContextFactory } from '../context.js'; +export type { IdentityOptions, ContextFactory, ElicitationHandler, ElicitationResult, ProgressReporter } from '../context.js'; export { TraceContext } from '../trace-context.js'; export type { TraceParent } from '../trace-context.js'; @@ -95,6 +97,7 @@ export type { // ---- Errors -------------------------------------------------------------- export { ModuleError, + CallBudgetExceededError, ConfigNotFoundError, ConfigError, ACLRuleError, diff --git a/typescript/src/builtin-steps.ts b/typescript/src/builtin-steps.ts index 68323970..cf529b2d 100644 --- a/typescript/src/builtin-steps.ts +++ b/typescript/src/builtin-steps.ts @@ -17,6 +17,7 @@ import { createApprovalRequest, createApprovalResult, takeApprovalToken } from ' import type { Config } from './config.js'; import { getDefault } from './config-defaults.js'; import { CancelToken, awaitExecution } from './cancel.js'; +import { assertBudgetDispatch, bindBudgetContext, commitBudgetCall, recordBudgetProducer, reserveBudgetCall } from './call-budget.js'; import { Context } from './context.js'; import { assertDeclarationInvocation, recordDeclarationDispatch } from './declaration-invocation.js'; import { authorityKeyOf, hasScopeCeiling } from './identity.js'; @@ -154,6 +155,7 @@ export class BuiltinContextCreation implements Step { ); } + bindBudgetContext(ctx, derived); ctx.context = derived; if (invocation) { invocation.context = derived; @@ -206,6 +208,7 @@ export class BuiltinCallChainGuard implements Step { // Call chain safety guard — throws CallDepthExceededError, CircularCallError, etc. guardCallChain(ctx.moduleId, ctx.context.callChain, this._maxCallDepth, this._maxModuleRepeat); + reserveBudgetCall(ctx); return { action: 'continue' }; } @@ -994,21 +997,17 @@ export class BuiltinExecute implements Step { if (invocation?.stream ?? ctx.stream) { const candidate = ctx.module as Module; if (isStreamingModule(candidate)) { - if (invocation) { - const protectedProducer = this._streamWithLease(ctx, () => { - assertScopedInvocation(ctx, true); - assertPolicyBinding(ctx, invocation); - invocation.dispatched = true; - return candidate.stream(inputs, context); - }); - invocation.producer = protectedProducer; - ctx.outputStream = protectedProducer; - } else { - ctx.outputStream = this._streamWithLease(ctx, () => { - assertScopedInvocation(ctx, true); - return candidate.stream(ctx.inputs, ctx.context); - }); - } + const producer = this._streamWithLease(ctx, () => { + assertScopedInvocation(ctx, true); + if (invocation) assertPolicyBinding(ctx, invocation); + }, () => { + if (!invocation) return candidate.stream(ctx.inputs, ctx.context); + invocation.dispatched = true; + return candidate.stream(inputs, context); + }); + if (invocation) invocation.producer = producer; + ctx.outputStream = producer; + recordBudgetProducer(ctx, producer); return { action: 'continue' }; } // fallback: execute normally and wrap as single-chunk @@ -1049,7 +1048,9 @@ export class BuiltinExecute implements Step { const release = moduleExecutionLeases.get(ctx)?.(); let executionPromise: Promise>; + let settleBudget: (() => void) | undefined; try { + settleBudget = commitBudgetCall(ctx); recordDeclarationDispatch(ctx); if (invocation) invocation.dispatched = true; executionPromise = Promise.resolve( @@ -1061,10 +1062,14 @@ export class BuiltinExecute implements Step { ).call(mod, inputs, ctx.context), ); } catch (error) { + settleBudget?.(); release?.(); throw error; } - if (release) void executionPromise.then(release, release); + if (release || settleBudget) { + const settle = (): void => { settleBudget?.(); release?.(); }; + void executionPromise.then(settle, settle); + } const output = await awaitExecution( executionPromise, @@ -1073,6 +1078,7 @@ export class BuiltinExecute implements Step { timeoutMs, isModuleIdempotent(mod), ); + assertBudgetDispatch(ctx); if (output == null) { throw new ModuleExecuteError(ctx.moduleId, 'Return value cannot be None'); } @@ -1087,12 +1093,27 @@ export class BuiltinExecute implements Step { private async *_streamWithLease( ctx: PipelineContext, + assertAuthorized: () => void, createStream: () => AsyncGenerator>, ): AsyncGenerator> { + ctx.context.cancelToken?.check(); + assertAuthorized(); const release = moduleExecutionLeases.get(ctx)?.(); + let settleBudget: (() => void) | undefined; try { - yield* createStream(); + settleBudget = commitBudgetCall(ctx); + const stream = createStream(); + if (!settleBudget) { + yield* stream; + return; + } + for await (const chunk of stream) { + assertBudgetDispatch(ctx); + yield chunk; + } + assertBudgetDispatch(ctx); } finally { + settleBudget?.(); release?.(); } } diff --git a/typescript/src/call-budget.ts b/typescript/src/call-budget.ts new file mode 100644 index 00000000..cdaebe34 --- /dev/null +++ b/typescript/src/call-budget.ts @@ -0,0 +1,217 @@ +import { CallBudgetExceededError, InvalidInputError, ModuleError } from './errors.js'; +import type { Context } from './context.js'; +import type { PipelineContext } from './pipeline.js'; + +export interface CallBudgetOptions { + readonly maxCalls?: number; + readonly maxCost?: number; + readonly estimatedCosts?: Readonly>; +} + +export interface CallBudgetSnapshot { + readonly callsUsed: number; + readonly callsReserved: number; + readonly costUsed: number; +} + +interface Ledger { + readonly maxCalls: number; + readonly maxCost: bigint | null; + readonly estimates: ReadonlyMap; + callsUsed: number; + callsReserved: number; + costUsed: bigint; +} + +const MAX_SAFE_COST = BigInt(Number.MAX_SAFE_INTEGER); +const ledgers = new WeakMap(); + +function amount(value: number, label: string): number { + if (!Number.isSafeInteger(value) || value < 0) { + throw new InvalidInputError(`${label} must be a non-negative safe integer`); + } + return value; +} + +/** In-process shared limits for all invocations in a call tree. */ +export class CallBudget { + constructor(options: CallBudgetOptions = {}) { + const estimates = new Map(Object.entries(options.estimatedCosts ?? {}).map(([id, estimate]) => + [id, BigInt(amount(estimate, `Estimated cost for '${id}'`))] as const)); + ledgers.set(this, { + maxCalls: options.maxCalls === undefined ? Number.MAX_SAFE_INTEGER : amount(options.maxCalls, 'Maximum calls'), + maxCost: options.maxCost === undefined ? null : BigInt(amount(options.maxCost, 'Maximum cost')), + estimates, callsUsed: 0, callsReserved: 0, costUsed: 0n, + }); + } + + /** Report usage. An overrun beyond the numeric range is clamped in this view. */ + snapshot(): CallBudgetSnapshot { + const { callsUsed, callsReserved, costUsed } = ledgers.get(this)!; + return Object.freeze({ callsUsed, callsReserved, costUsed: Number(costUsed > MAX_SAFE_COST ? MAX_SAFE_COST : costUsed) }); + } +} + +class BudgetPipelineError extends ModuleError { + static override readonly DEFAULT_RETRYABLE = false; + + constructor() { + super('PIPELINE_CONFIGURATION_ERROR', 'A budgeted call requires its original context, call-chain guard, and dispatch'); + } +} + +interface Attempt { + readonly id: string; + readonly parent: Context; + readonly ledger: Ledger; + readonly estimate: bigint; + context?: Context; + state: 'initial' | 'reserved' | 'running' | 'settled' | 'released'; + removeCancelListener?: () => void; + actualRecorded?: boolean; + overrun?: CallBudgetExceededError; + producer?: AsyncGenerator>; +} + +const budgets = new WeakMap, CallBudget>(); +const scopes = new WeakMap, Attempt>(); +const attempts = new WeakMap(); + +/** @internal Set a budget on a derived context. */ +export function attachBudget(context: Context, budget: CallBudget | null): void { + if (budget !== null && !ledgers.has(budget)) throw new InvalidInputError('Budget must be a CallBudget'); + if (budget === null) budgets.delete(context); + else budgets.set(context, budget); + scopes.delete(context); +} + +/** @internal Copy the budget to a runtime derivation, sharing settlement only within the same invocation. */ +export function inheritBudget(source: Context, target: Context, inheritSettlement: boolean): void { + const budget = budgets.get(source); + if (budget) budgets.set(target, budget); + const attempt = inheritSettlement ? scopes.get(source) : undefined; + if (attempt) scopes.set(target, attempt); +} + +/** @internal Return whether budgeting has been enabled on this context. */ +export function hasCallBudget(context: Context): boolean { + return budgets.has(context); +} + +/** @internal Open attempt state before running arbitrary pipeline hooks. */ +export function beginBudgetAttempt(ctx: PipelineContext): void { + const budget = budgets.get(ctx.context); + if (!budget) return; + const ledger = ledgers.get(budget)!; + attempts.set(ctx, { id: ctx.moduleId, parent: ctx.context, ledger, estimate: ledger.estimates.get(ctx.moduleId) ?? 0n, state: 'initial' }); +} + +/** @internal Bind the invocation child created by the stock context step. */ +export function bindBudgetContext(ctx: PipelineContext, context: Context): void { + const attempt = attempts.get(ctx); + if (!attempt) return; + if (ctx.context !== attempt.parent || ctx.moduleId !== attempt.id) throw new BudgetPipelineError(); + attempt.context = context; +} + +function boundAttempt(ctx: PipelineContext): Attempt | undefined { + const attempt = attempts.get(ctx); + if (attempt && (attempt.context !== ctx.context || attempt.id !== ctx.moduleId)) throw new BudgetPipelineError(); + return attempt; +} + +function releaseReservation(attempt: Attempt): void { + if (attempt.state !== 'reserved') return; + attempt.ledger.callsReserved--; + attempt.state = 'released'; + attempt.removeCancelListener?.(); +} + +/** @internal Reserve the call at the stock call-chain guard. */ +export function reserveBudgetCall(ctx: PipelineContext): void { + const attempt = boundAttempt(ctx); + if (!attempt) return; + if (attempt.state !== 'initial') throw new BudgetPipelineError(); + const { ledger } = attempt; + if (ledger.callsUsed + ledger.callsReserved >= ledger.maxCalls) throw new CallBudgetExceededError('calls'); + ledger.callsReserved++; + attempt.state = 'reserved'; + const signal = ctx.context.signal; + const release = (): void => releaseReservation(attempt); + signal.addEventListener('abort', release, { once: true }); + attempt.removeCancelListener = () => signal.removeEventListener('abort', release); +} + +/** @internal Spend the reserved call and its estimate together at business dispatch. */ +export function commitBudgetCall(ctx: PipelineContext): (() => void) | undefined { + const attempt = boundAttempt(ctx); + if (!attempt) return undefined; + if (attempt.state !== 'reserved') throw new BudgetPipelineError(); + const { ledger } = attempt; + const cost = ledger.costUsed + attempt.estimate; + if (ledger.maxCost !== null && cost > ledger.maxCost) throw new CallBudgetExceededError('cost'); + ledger.callsReserved--; + ledger.callsUsed++; + ledger.costUsed = cost; + attempt.removeCancelListener?.(); + attempt.state = 'running'; + scopes.set(ctx.context, attempt); + return () => { attempt.state = 'settled'; }; +} + +/** @internal Replace an active attempt's estimate with actual cost once. */ +export function recordBudgetCost(context: Context, actual: number): void { + if (!budgets.has(context)) return; + const attempt = scopes.get(context); + if (attempt?.state !== 'running' || attempt.actualRecorded) { + throw new InvalidInputError('Cost can be reported once during an active budgeted execution'); + } + const settled = BigInt(amount(actual, 'Actual cost')); + attempt.actualRecorded = true; + const { ledger } = attempt; + ledger.costUsed += settled - attempt.estimate; + if (ledger.maxCost !== null && ledger.costUsed > ledger.maxCost) { + attempt.overrun = new CallBudgetExceededError('cost'); + throw attempt.overrun; + } +} + +/** @internal Keep the registered stream producer separate from mutable step state. */ +export function recordBudgetProducer(ctx: PipelineContext, producer: AsyncGenerator>): void { + const attempt = boundAttempt(ctx); + if (!attempt) return; + if (attempt.state !== 'reserved') throw new BudgetPipelineError(); + attempt.producer = producer; +} + +/** @internal Resolve the registered producer for budgeted calls or the existing producer for other calls. */ +export function budgetStreamProducer(ctx: PipelineContext): PipelineContext['outputStream'] { + const attempt = attempts.get(ctx); + return attempt ? attempt.producer : ctx.outputStream; +} + +/** @internal Fail a budgeted traversal if it bypassed stock dispatch. */ +export function assertBudgetDispatch(ctx: PipelineContext, allowProducer: boolean = false): void { + const attempt = boundAttempt(ctx); + if (attempt && attempt.state !== 'running' && attempt.state !== 'settled' && !(allowProducer && attempt.producer)) { + throw new BudgetPipelineError(); + } + if (attempt?.overrun) throw attempt.overrun; +} + +/** @internal Release a count that could not reach business dispatch. */ +export function releaseBudgetReservation(ctx: PipelineContext): void { + const attempt = attempts.get(ctx); + if (attempt) releaseReservation(attempt); +} + +/** @internal Clear attempt state before a retry or after a completed traversal. */ +export function endBudgetAttempt(ctx: PipelineContext): void { + releaseBudgetReservation(ctx); + attempts.delete(ctx); +} + +/** @internal Budget control failures cannot be recovered into successful outputs. */ +export function isBudgetControlError(error: unknown): boolean { + return error instanceof CallBudgetExceededError || error instanceof BudgetPipelineError; +} diff --git a/typescript/src/cancel.ts b/typescript/src/cancel.ts index dc7697c1..9de0893f 100644 --- a/typescript/src/cancel.ts +++ b/typescript/src/cancel.ts @@ -13,6 +13,7 @@ import { drainExecutions, linkExecutionParent, trackExecution } from './execution-lifetime.js'; import { ModuleError, ModuleTimeoutError } from './errors.js'; +import type { Context } from './context.js'; export class ExecutionCancelledError extends ModuleError { // Retryable with a fresh CancelToken (protocol-spec §8.6, D-135): the @@ -204,3 +205,28 @@ export async function awaitExecution( if (onAbort) token?.signal.removeEventListener('abort', onAbort); } } + +/** @internal Wait within a context's cancellation scope and global deadline. */ +export async function awaitContextOperation( + start: () => Promise, + context: Pick, + moduleId: string, + retryable: boolean, +): Promise { + const token = context.cancelToken; + const deadline = context.globalDeadline; + const checkInterruption = (): number => { + if (context.signal.aborted) throw new ExecutionCancelledError(); + const remainingMs = deadline === null ? 0 : deadline * 1000 - Date.now(); + if (deadline !== null && remainingMs <= 0) { + token?.cancel(); + throw new ModuleTimeoutError(moduleId, 0, { retryable }); + } + return Math.ceil(remainingMs); + }; + + const timeoutMs = checkInterruption(); + const result = await awaitExecution(start(), token, moduleId, timeoutMs, retryable); + checkInterruption(); + return result; +} diff --git a/typescript/src/config-defaults.ts b/typescript/src/config-defaults.ts index aeb6b758..1c7758ba 100644 --- a/typescript/src/config-defaults.ts +++ b/typescript/src/config-defaults.ts @@ -13,6 +13,14 @@ * existing `import { getDefault } from './config.js'` paths keep working. */ +/** @internal Maximum UTF-8 bytes scanned by a configured redaction regex. */ +export const DEFAULT_MAX_REGEX_SCAN_LENGTH = 65_536; + +/** @internal Validate a programmatic or configured regex scan length. */ +export function isRegexScanLength(value: unknown): value is number { + return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0; +} + /** * Default configuration values for legacy mode. * diff --git a/typescript/src/config-key-surface.ts b/typescript/src/config-key-surface.ts index 8e0f9815..b0699b58 100644 --- a/typescript/src/config-key-surface.ts +++ b/typescript/src/config-key-surface.ts @@ -86,6 +86,7 @@ export const FRAMEWORK_CONFIG_KEYS: readonly string[] = [ "logging.format", "logging.level", "middleware.disabled", + "obs.redaction.max_regex_scan_length", "obs.redaction.regex_patterns", "obs.redaction.replacement", "obs.redaction.sensitive_keys", diff --git a/typescript/src/config.ts b/typescript/src/config.ts index af042c3b..d5d51a5c 100644 --- a/typescript/src/config.ts +++ b/typescript/src/config.ts @@ -21,7 +21,7 @@ import { import { appendFilesystemPath } from './utils/filesystem-path.js'; import { jsonSchemaToTypeBox } from './schema/loader-pure.js'; import { SchemaValidator } from './schema/validator.js'; -import { DEFAULTS, getDefault } from './config-defaults.js'; +import { DEFAULT_MAX_REGEX_SCAN_LENGTH, DEFAULTS, isRegexScanLength } from './config-defaults.js'; import { collectUndeclaredFrameworkKeys, PATH_TYPED_CONFIG_KEYS } from './config-key-surface.js'; import { negotiateDocumentVersion } from './version.js'; @@ -139,6 +139,7 @@ export const CONSTRAINTS: Record boolean, string]> = { ], 'executor.max_call_depth': [(v) => isInteger(v) && v >= 1, 'must be a positive integer'], 'executor.max_module_repeat': [(v) => isInteger(v) && v >= 1, 'must be a positive integer'], + 'obs.redaction.max_regex_scan_length': [isRegexScanLength, 'must be a non-negative safe integer'], 'sys_modules.error_history.max_entries_per_module': [ (v) => isInteger(v) && v >= 1, 'must be a positive integer', @@ -1480,6 +1481,10 @@ export class Config { ...uncompilableRegexPatternErrors(this.get('obs.redaction.regex_patterns')), ...otlpEndpointMismatchErrors(this), ]; + const scanLength = this.get('obs.redaction.max_regex_scan_length'); + if (this._mode === 'namespace' && this._data['obs'] != null && scanLength != null && !isRegexScanLength(scanLength)) { + errors.push("Invalid value for 'obs.redaction.max_regex_scan_length': must be a non-negative safe integer"); + } for (const field of REQUIRED_FIELDS) { const value = this.getDeclared(field); if (value != null && typeof value !== 'string') { @@ -1774,6 +1779,7 @@ Config.registerNamespace({ defaults: { redaction: { regex_patterns: [] as string[], + max_regex_scan_length: DEFAULT_MAX_REGEX_SCAN_LENGTH, sensitive_keys: [..._DEFAULT_OBS_REDACTION_SENSITIVE_KEYS], replacement: '***REDACTED***', }, diff --git a/typescript/src/context.ts b/typescript/src/context.ts index 363eecfb..e94dd35a 100644 --- a/typescript/src/context.ts +++ b/typescript/src/context.ts @@ -3,8 +3,9 @@ */ import { uuidV4 as uuidv4 } from './utils/uuid.js'; -import type { CancelToken } from './cancel.js'; -import { ContextBindingError } from './errors.js'; +import { awaitContextOperation, type CancelToken } from './cancel.js'; +import { attachBudget, inheritBudget, recordBudgetCost, type CallBudget } from './call-budget.js'; +import { ContextBindingError, InvalidInputError } from './errors.js'; import { copyObservationState, inheritObservationParent, setRemoteSpanParent } from './execution-lifetime.js'; import { ContextLogger } from './observability/context-logger.js'; import type { TraceParent } from './trace-context.js'; @@ -14,6 +15,18 @@ import { hasScopeCeiling, identityFromWire, identityToWire, type Identity } from export { Identity, createIdentity } from './identity.js'; export type { IdentityOptions } from './identity.js'; +/** An invocation-local provider for progress updates. */ +export type ProgressReporter = (progress: number, total?: number, message?: string) => void | Promise; + +/** The result of a real-time elicitation request. */ +export type ElicitationResult = + | { readonly action: 'accept'; readonly content: Record } + | { readonly action: 'decline' | 'cancel' }; + +/** An invocation-local provider for structured input. */ +export type ElicitationHandler = (message: string, requestedSchema?: Record) => + ElicitationResult | Promise; + export class Context { readonly traceId: string; readonly callerId: string | null; @@ -26,6 +39,8 @@ export class Context { readonly services: T; readonly cancelToken: CancelToken | null; readonly globalDeadline: number | null; + private _progressReporter: ProgressReporter | null = null; + private _elicitationHandler: ElicitationHandler | null = null; private _logger: ContextLogger | null = null; /** One notice per process: this accessor can be hit once per module call. */ private static _loggerDeprecationWarned = false; @@ -163,21 +178,7 @@ export class Context { 'Context already bound to a different Executor instance', ); } - const bound = new Context( - this.traceId, - this.callerId, - [...this.callChain], - executor, - this.identity, - this.redactedInputs, - this.data, - this.cancelToken, - this.services, - this.globalDeadline, - this.redactedOutput, - ); - copyObservationState(this, bound); - return bound; + return this._derive({ executor }); } /** @deprecated Use {@link withExecutor}. Retained for older callers; will be removed in a future major. */ @@ -197,21 +198,7 @@ export class Context { * first call's remaining time — or fail immediately, having already expired. */ _withGlobalDeadline(globalDeadline: number | null): Context { - const bound = new Context( - this.traceId, - this.callerId, - [...this.callChain], - this.executor, - this.identity, - this.redactedInputs, - this.data, - this.cancelToken, - this.services, - globalDeadline, - this.redactedOutput, - ); - copyObservationState(this, bound); - return bound; + return this._derive({ globalDeadline }); } /** @@ -237,23 +224,85 @@ export class Context { /** @internal Carry an invocation-owned token without changing call-chain identity. */ _withCancellationScope(cancelToken: CancelToken): Context { + return this._derive({ cancelToken }); + } + + /** Derive a context that shares a call-tree budget, or clear it with null. */ + withBudget(budget: CallBudget | null): Context { + const context = this._derive(); + attachBudget(context, budget); + return context; + } + + /** Settle the active invocation's estimated cost with its actual cost once. */ + recordCost(actual: number): void { + recordBudgetCost(this, actual); + } + + /** Derive a context with a progress reporter, or clear it with null. */ + withProgressReporter(reporter: ProgressReporter | null): Context { + if (reporter !== null && typeof reporter !== 'function') throw new InvalidInputError('Progress reporter must be a function'); + const context = this._derive(); + context._progressReporter = reporter; + return context; + } + + /** Derive a context with an elicitation handler, or clear it with null. */ + withElicitationHandler(handler: ElicitationHandler | null): Context { + if (handler !== null && typeof handler !== 'function') throw new InvalidInputError('Elicitation handler must be a function'); + const context = this._derive(); + context._elicitationHandler = handler; + return context; + } + + /** Report progress if the invocation has a reporter. */ + async reportProgress(progress: number, total?: number, message?: string): Promise { + const reporter = this._progressReporter; + if (reporter !== null) await this._runInteraction(async () => reporter(progress, total, message)); + } + + /** Request structured input if the invocation has an elicitation handler. */ + async elicit(message: string, requestedSchema?: Record): Promise { + const handler = this._elicitationHandler; + if (handler === null) return null; + const result = await this._runInteraction(async () => handler(message, requestedSchema)); + if (result?.action === 'decline' || result?.action === 'cancel') return { action: result.action }; + if (result?.action === 'accept' && isRecord(result.content)) return { action: 'accept', content: result.content }; + throw new InvalidInputError('Elicitation handler returned an invalid result'); + } + + private _runInteraction(start: () => Promise): Promise { + const moduleId = this.callChain.at(-1) ?? 'context'; + return awaitContextOperation(start, this, moduleId, false); + } + + private _derive({ + executor = this.executor, cancelToken = this.cancelToken, globalDeadline = this.globalDeadline, + }: { executor?: unknown; cancelToken?: CancelToken | null; globalDeadline?: number | null } = {}): Context { const bound = new Context( this.traceId, this.callerId, [...this.callChain], - this.executor, + executor, this.identity, this.redactedInputs, this.data, cancelToken, this.services, - this.globalDeadline, + globalDeadline, this.redactedOutput, ); + this._inheritCapabilities(bound); + inheritBudget(this, bound, true); copyObservationState(this, bound); return bound; } + private _inheritCapabilities(target: Context): void { + target._progressReporter = this._progressReporter; + target._elicitationHandler = this._elicitationHandler; + } + /** * Serialize Context to a plain object suitable for JSON encoding. * @@ -441,11 +490,19 @@ export class Context { this.services, this.globalDeadline, ); + this._inheritCapabilities(child); + inheritBudget(this, child, false); inheritObservationParent(this, child); return child; } } +function isRecord(value: unknown): value is Record { + if (value === null || typeof value !== 'object') return false; + const prototype = Object.getPrototypeOf(value); + return prototype === Object.prototype || prototype === null; +} + /** * Interface for creating Context from runtime-specific requests. * diff --git a/typescript/src/errors.ts b/typescript/src/errors.ts index abf45a3c..edaacaf4 100644 --- a/typescript/src/errors.ts +++ b/typescript/src/errors.ts @@ -1047,6 +1047,16 @@ export class PolicyDeniedError extends ModuleError { } } +/** A call tree exhausted its call-count or cost limit. */ +export class CallBudgetExceededError extends ModuleError { + static override readonly DEFAULT_RETRYABLE = false; + + constructor(dimension: 'calls' | 'cost') { + super(ErrorCodes.CALL_BUDGET_EXCEEDED, `The invocation exceeded its ${dimension} budget.`, { dimension }); + this.name = 'CallBudgetExceededError'; + } +} + export class PolicyEvaluationError extends ModuleError { static override readonly DEFAULT_RETRYABLE = true; @@ -1589,6 +1599,7 @@ export const ErrorCodes = Object.freeze({ CALL_DEPTH_EXCEEDED: 'CALL_DEPTH_EXCEEDED', CIRCULAR_CALL: 'CIRCULAR_CALL', CALL_FREQUENCY_EXCEEDED: 'CALL_FREQUENCY_EXCEEDED', + CALL_BUDGET_EXCEEDED: 'CALL_BUDGET_EXCEEDED', GENERAL_INVALID_INPUT: 'GENERAL_INVALID_INPUT', GENERAL_INTERNAL_ERROR: 'GENERAL_INTERNAL_ERROR', INVALID_MODULE_ID: 'INVALID_MODULE_ID', diff --git a/typescript/src/executor.ts b/typescript/src/executor.ts index e7cfe482..13649895 100644 --- a/typescript/src/executor.ts +++ b/typescript/src/executor.ts @@ -30,6 +30,7 @@ import { import { BuiltinACLCheck, BuiltinApprovalGate, + BuiltinCallChainGuard, BuiltinContextCreation, BuiltinExecute, BuiltinModuleLookup, @@ -41,7 +42,11 @@ import { withPostValidationPolicy, } from './builtin-steps.js'; import type { StandardStrategyDeps } from './builtin-steps.js'; -import { awaitExecution, CancelToken, ExecutionCancelledError } from './cancel.js'; +import { awaitContextOperation, CancelToken, ExecutionCancelledError } from './cancel.js'; +import { + assertBudgetDispatch, beginBudgetAttempt, budgetStreamProducer, endBudgetAttempt, hasCallBudget, + isBudgetControlError, releaseBudgetReservation, +} from './call-budget.js'; import { finishCall, trackExecution } from './execution-lifetime.js'; import type { Config } from './config.js'; import { buildStrategyFromConfigSync, ConfigurationError } from './pipeline-config.js'; @@ -508,31 +513,6 @@ function bindExecutorToCtx(ctx: C, executor: unknown): C { : c._withExecutor(executor)) as C; } -/** Bound a stream operation, preserving ownership of work that outlives interruption. */ -async function awaitStreamOperation( - start: () => Promise, - context: Context, - moduleId: string, - retryable: boolean, -): Promise { - const token = context.cancelToken; - const deadline = context.globalDeadline; - const checkInterruption = (): number => { - if (context.signal.aborted) throw new ExecutionCancelledError(); - const remainingMs = deadline === null ? 0 : deadline * 1000 - Date.now(); - if (deadline !== null && remainingMs <= 0) { - token?.cancel(); - throw new ModuleTimeoutError(moduleId, 0, { retryable }); - } - return Math.ceil(remainingMs); - }; - - const timeoutMs = checkInterruption(); - const result = await awaitExecution(start(), token, moduleId, timeoutMs, retryable); - checkInterruption(); - return result; -} - /** Bound each pull while retaining the physical producer until its queued close settles. */ async function* streamWithinDeadline( stream: AsyncGenerator>, @@ -545,7 +525,7 @@ async function* streamWithinDeadline( let interrupted = false; try { for (;;) { - const next = await awaitStreamOperation(() => stream.next(), context, moduleId, retryable); + const next = await awaitContextOperation(() => stream.next(), context, moduleId, retryable); if (next.done) { complete = true; return; @@ -1196,6 +1176,23 @@ export class Executor { execute.execute === BuiltinExecute.prototype.execute; } + private _assertBudgetStrategy(context: Context, strategy: ExecutionStrategy, moduleId: string): void { + if (!hasCallBudget(context)) return; + const required = [ + ['context_creation', BuiltinContextCreation], ['call_chain_guard', BuiltinCallChainGuard], ['execute', BuiltinExecute], + ] as const; + let previous = -1; + for (const [name, type] of required) { + const index = strategy.findStepIndex(name); + const step = index === undefined ? undefined : strategy.steps[index]; + if (index === undefined || index <= previous || !step || Object.getPrototypeOf(step) !== type.prototype || + step.execute !== type.prototype.execute || !stepMatchesModule(step, moduleId) || step.ignoreErrors === true) { + throw new ConfigurationError('Call budgets require built-in context creation, call-chain guard, and dispatch.'); + } + previous = index; + } + } + use(middleware: Middleware): Executor { this._middlewareManager.add(middleware); return this; @@ -1293,6 +1290,7 @@ export class Executor { let ctx = context ?? Context.create(); ctx = bindExecutorToCtx(ctx, this); if (hasScopeCeiling(ctx.identity)) assertScopeGate(ctx, moduleId, this._hasScopeGate(strategy, moduleId)); + this._assertBudgetStrategy(ctx, strategy, moduleId); const pipeCtx: PipelineContext = { moduleId, inputs: inputs ?? {}, @@ -1314,6 +1312,7 @@ export class Executor { try { while (true) { try { + beginBudgetAttempt(pipeCtx); beginDeclarationInvocation(pipeCtx, declaration); beginScopedInvocation(pipeCtx); if (protectedCall) { @@ -1324,9 +1323,11 @@ export class Executor { const [output, trace] = await this._pipelineEngine.run(strategy, pipeCtx); assertScopedInvocation(pipeCtx, true); assertDeclarationDispatch(pipeCtx); + assertBudgetDispatch(pipeCtx); if (protectedCall && !policyInvocationOf(pipeCtx)?.dispatched) throw new PolicyEvaluationError(moduleId); return [(output ?? {}) as Record, trace]; } catch (exc) { + releaseBudgetReservation(pipeCtx); if (exc instanceof ExecutionCancelledError) throw exc; // PipelineStepError is the engine-level contract (protocol-spec §5.16 requirement 1). Unwrap the cause // so the executor's public API surfaces the original typed error. @@ -1343,7 +1344,8 @@ export class Executor { unwrapped instanceof MiddlewareChainError ? unwrapped.original : (unwrapped as Error); if (underlying instanceof ExecutionCancelledError) throw underlying; const wrapped = propagateError(underlying, moduleId, ctxObj); - if (isScopedAdmissionError(pipeCtx, underlying) || isDeclarationAdmissionError(pipeCtx, underlying)) { + if (isScopedAdmissionError(pipeCtx, underlying) || isDeclarationAdmissionError(pipeCtx, underlying) || + isBudgetControlError(underlying)) { throw wrapped; } if (protectedCall && !policyInvocationOf(pipeCtx)?.dispatched) throw wrapped; @@ -1357,6 +1359,7 @@ export class Executor { executedMw as Middleware[], ); if (recovery instanceof RetrySignal) { + endBudgetAttempt(pipeCtx); this._resetPipeCtxForRetry(pipeCtx, recovery.inputs); this._finishCallContext(pipeCtx.context, ctx); pipeCtx.context = ctx; @@ -1368,6 +1371,7 @@ export class Executor { } } } finally { + endBudgetAttempt(pipeCtx); discardApprovalToken(pipeCtx); if (protectedCall) endPolicyInvocation(pipeCtx); this._finishCallContext(pipeCtx.context, ctx); @@ -1490,6 +1494,7 @@ export class Executor { let ctx = context ?? Context.create(); ctx = bindExecutorToCtx(ctx, this); if (hasScopeCeiling(ctx.identity)) assertScopeGate(ctx, moduleId, this._hasScopeGate(strategy, moduleId)); + this._assertBudgetStrategy(ctx, strategy, moduleId); const pipeCtx: PipelineContext = { moduleId, inputs: inputs ?? {}, @@ -1521,13 +1526,15 @@ export class Executor { if (output !== null) tracker.output = copyChunkValue(output) as Record; } }; - const pipeline = this._pipelineEngine.runWithPause( - strategy, pipeCtx, () => (protectedCall ? policyInvocationOf(pipeCtx)?.producer : pipeCtx.outputStream) != null, observeStep, - ); + const producer = (): AsyncGenerator> | null | undefined => + protectedCall ? policyInvocationOf(pipeCtx)?.producer : + budgetStreamProducer(pipeCtx) as AsyncGenerator> | null | undefined; + const pipeline = this._pipelineEngine.runWithPause(strategy, pipeCtx, () => producer() != null, observeStep); try { // Run through producer creation, or finish the unary fallback. try { + beginBudgetAttempt(pipeCtx); beginScopedInvocation(pipeCtx); if (protectedCall) { beginPolicyInvocation(pipeCtx); @@ -1536,9 +1543,11 @@ export class Executor { prepareApprovalInputs(pipeCtx); await pipeline.next(); assertScopedInvocation(pipeCtx, true); + assertBudgetDispatch(pipeCtx, true); const invocation = policyInvocationOf(pipeCtx); if (protectedCall && !invocation?.dispatched && !invocation?.producer) throw new PolicyEvaluationError(moduleId); } catch (exc) { + releaseBudgetReservation(pipeCtx); if (exc instanceof ExecutionCancelledError) throw exc; const ctxObj = pipeCtx.context; // Unwrap PipelineStepError to expose the original typed cause (protocol-spec §5.16 requirement 1). @@ -1551,7 +1560,7 @@ export class Executor { unwrapped instanceof MiddlewareChainError ? unwrapped.original : (unwrapped as Error); if (underlying instanceof ExecutionCancelledError) throw underlying; const wrapped = propagateError(underlying, moduleId, ctxObj); - if (isScopedAdmissionError(pipeCtx, underlying)) throw wrapped; + if (isScopedAdmissionError(pipeCtx, underlying) || isBudgetControlError(underlying)) throw wrapped; if (protectedCall && !policyInvocationOf(pipeCtx)?.dispatched) throw wrapped; if (pipeCtx.executedMiddlewares && pipeCtx.executedMiddlewares.length > 0) { const recovery = await this._middlewareManager.executeOnError( @@ -1578,8 +1587,7 @@ export class Executor { // If no outputStream, pipeline already executed normally — yield single result if (tracker) pipeCtx.context.cancelToken?.check(); - const outputStream = protectedCall ? policyInvocationOf(pipeCtx)?.producer - : pipeCtx.outputStream as AsyncGenerator> | null; + const outputStream = producer(); if (outputStream == null) { const output = pipeCtx.output ?? {}; if (tracker && tracker.output === null) tracker.output = copyChunkValue(output) as Record; @@ -1626,10 +1634,11 @@ export class Executor { chunkIndex += 1; } } catch (exc) { + releaseBudgetReservation(pipeCtx); if (exc instanceof ExecutionCancelledError) throw exc; const ctxObj = pipeCtx.context; const wrapped = propagateError(exc as Error, moduleId, ctxObj); - if (isScopedAdmissionError(pipeCtx, exc)) throw wrapped; + if (isScopedAdmissionError(pipeCtx, exc) || isBudgetControlError(exc)) throw wrapped; if (protectedCall && !policyInvocationOf(pipeCtx)?.dispatched) throw wrapped; if (exc instanceof ModuleTimeoutError && ctxObj.signal.aborted) throw wrapped; if (pipeCtx.executedMiddlewares && pipeCtx.executedMiddlewares.length > 0) { @@ -1659,7 +1668,7 @@ export class Executor { await pipeline.next(); } else { const context = pipeCtx.context; - await awaitStreamOperation( + await awaitContextOperation( () => pipeline.next(), context, moduleId, isModuleIdempotent(pipeCtx.module), ); @@ -1719,6 +1728,7 @@ export class Executor { } } } finally { + endBudgetAttempt(pipeCtx); discardApprovalToken(pipeCtx); if (protectedCall) endPolicyInvocation(pipeCtx); this._finishCallContext(pipeCtx.context, ctx); diff --git a/typescript/src/node-api.ts b/typescript/src/node-api.ts index 72bd8100..5c9d65ab 100644 --- a/typescript/src/node-api.ts +++ b/typescript/src/node-api.ts @@ -7,6 +7,8 @@ export type { DrainAbortedContext, DrainAbortReason, DrainContext, LifecycleErro // Core export { CancelToken, ExecutionCancelledError } from './cancel.js'; export { Context, Identity, createIdentity } from './context.js'; +export { CallBudget } from './call-budget.js'; +export type { CallBudgetOptions, CallBudgetSnapshot } from './call-budget.js'; export { ContextKey } from './context-key.js'; export { TRACING_SPANS, @@ -16,7 +18,7 @@ export { REDACTED_OUTPUT, RETRY_COUNT_BASE, } from './context-keys.js'; -export type { IdentityOptions, ContextFactory } from './context.js'; +export type { IdentityOptions, ContextFactory, ElicitationHandler, ElicitationResult, ProgressReporter } from './context.js'; export { Registry, REGISTRY_EVENTS, @@ -87,6 +89,7 @@ export type { PolicyEvaluationRequest, PolicyEvaluator, PolicyVerdict } from './ // Errors export { ModuleError, + CallBudgetExceededError, ConfigNotFoundError, ConfigError, ACLRuleError, diff --git a/typescript/src/observability/context-logger.ts b/typescript/src/observability/context-logger.ts index 9b2c3073..341223d7 100644 --- a/typescript/src/observability/context-logger.ts +++ b/typescript/src/observability/context-logger.ts @@ -3,7 +3,9 @@ */ import type { Config } from '../config.js'; +import { DEFAULT_MAX_REGEX_SCAN_LENGTH, isRegexScanLength } from '../config-defaults.js'; import type { Context } from '../context.js'; +import { InvalidInputError } from '../errors.js'; import { startMiddlewareTiming, takeMiddlewareTiming } from '../execution-lifetime.js'; import { Middleware } from '../middleware/base.js'; import { matchGlob } from '../utils/pattern.js'; @@ -181,6 +183,7 @@ export class RedactionConfig { readonly invalidValuePatterns: readonly (readonly [string, string])[]; readonly replacement: string; + readonly maxRegexScanLength: number; private readonly _additionalFieldMatcher?: (fieldName: string) => boolean; constructor( @@ -188,6 +191,8 @@ export class RedactionConfig { fieldPatterns?: string[]; valuePatterns?: (RegExp | string)[]; replacement?: string; + /** Maximum UTF-8 bytes passed to a regex. Longer strings are redacted wholesale. */ + maxRegexScanLength?: number; /** @internal Extra fields treated as sensitive for config updates. */ additionalFieldMatcher?: (fieldName: string) => boolean; } = {}, @@ -198,6 +203,10 @@ export class RedactionConfig { this.valuePatterns = compiled; this.invalidValuePatterns = invalid; this.replacement = options.replacement ?? '***REDACTED***'; + this.maxRegexScanLength = options.maxRegexScanLength ?? DEFAULT_MAX_REGEX_SCAN_LENGTH; + if (!isRegexScanLength(this.maxRegexScanLength)) { + throw new InvalidInputError('Maximum regex scan length must be a non-negative safe integer'); + } } /** @@ -258,12 +267,17 @@ export class RedactionConfig { const valueStrings = Array.isArray(rawValues) ? (rawValues as unknown[]).filter((p): p is string => typeof p === 'string') : []; + const maxRegexScanLength = config.get('obs.redaction.max_regex_scan_length') ?? DEFAULT_MAX_REGEX_SCAN_LENGTH; + if (!isRegexScanLength(maxRegexScanLength)) { + throw new InvalidInputError('Maximum regex scan length must be a non-negative safe integer'); + } return new RedactionConfig({ fieldPatterns, // Compiled by the constructor — one compile site, one place the // requirement-4 diagnostic can fire. valuePatterns: valueStrings, replacement: typeof replacement === 'string' ? replacement : undefined, + maxRegexScanLength, }); } @@ -307,6 +321,7 @@ export class RedactionConfig { * apcore-python's `_redact_secrets_recursive`. */ redact(value: unknown, depth: number = 0): unknown { + if (typeof value === 'string' && this._valueMatches(value)) return this.replacement; return this._redactTree(value, depth, new Set()); } @@ -408,6 +423,8 @@ export class RedactionConfig { * costs no compile per record. */ private _valueMatches(value: string): boolean { + if (this.valuePatterns.length === 0) return false; + if (exceedsUtf8ByteLength(value, this.maxRegexScanLength)) return true; for (const re of this.valuePatterns) { if (re.test(value)) return true; } @@ -415,6 +432,20 @@ export class RedactionConfig { } } +function exceedsUtf8ByteLength(value: string, limit: number): boolean { + // UTF-8 uses between one and three bytes per UTF-16 code unit, including + // surrogate pairs and isolated surrogates represented as replacement characters. + if (value.length > limit) return true; + if (value.length * 3 <= limit) return false; + let bytes = 0; + for (const character of value) { + const codePoint = character.codePointAt(0)!; + bytes += codePoint < 0x80 ? 1 : codePoint < 0x800 ? 2 : codePoint < 0x10000 ? 3 : 4; + if (bytes > limit) return true; + } + return false; +} + function readSensitiveKeyPatterns(config: Config, legacyKeysUsed: string[]): string[] { let rawFields = config.get('obs.redaction.sensitive_keys'); if (rawFields == null) { diff --git a/typescript/src/pipeline.ts b/typescript/src/pipeline.ts index e1fa2f50..ca8f2592 100644 --- a/typescript/src/pipeline.ts +++ b/typescript/src/pipeline.ts @@ -5,6 +5,7 @@ import type { GovernanceProjection } from './acl-handlers.js'; import type { Context } from './context.js'; import { isDeclarationAdmissionError } from './declaration-invocation.js'; +import { isBudgetControlError } from './call-budget.js'; import { ModuleError, ModuleTimeoutError } from './errors.js'; import type { ErrorOptions } from './errors.js'; import { MiddlewareChainError } from './middleware/manager.js'; @@ -1260,7 +1261,7 @@ export class PipelineEngine { // 3 b onStepError hooks: reverse registration order (onion model), // first non-null recovery wins and short-circuits the rest (§2.2). const isGovernanceGate = governanceGateOf(step) !== null || isScopedAdmissionError(ctx, cause) || - isDeclarationAdmissionError(ctx, cause) || + isDeclarationAdmissionError(ctx, cause) || isBudgetControlError(cause) || (policyInvocation !== undefined && !policyInvocation.dispatched); const observedCancellation = observeStep !== undefined && cause instanceof ModuleError && cause.code === 'EXECUTION_CANCELLED'; diff --git a/typescript/tests/conformance-call-budget.test.ts b/typescript/tests/conformance-call-budget.test.ts new file mode 100644 index 00000000..542869ce --- /dev/null +++ b/typescript/tests/conformance-call-budget.test.ts @@ -0,0 +1,61 @@ +import { readFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { Type } from '@sinclair/typebox'; +import { describe, expect, it } from 'vitest'; +import { CallBudget, Context, Executor, ModuleError, Registry } from '../src/index.js'; +import { findFixturesRoot } from './spec-repo.js'; + +interface Case { + id: string; + module_id: string; + max_calls: number | null; + max_cost: number | null; + estimated_cost: number; + calls: Array<{ actual_cost: number | null }>; + expected: Array<{ calls_used: number; calls_reserved: number; cost_used: number; error_code: string | null }>; +} + +const fixture = JSON.parse(readFileSync(join(findFixturesRoot(), 'call_budget.json'), 'utf8')) as { + test_cases: Case[]; +}; + +describe('call_budget.json', () => { + it.each(fixture.test_cases)('$id', async testCase => { + const registry = new Registry(); + const executor = new Executor({ registry }); + await registry.register(testCase.module_id, { + description: 'Settle the actual cost when supplied', + inputSchema: Type.Object({ actual_cost: Type.Optional(Type.Integer({ minimum: 0 })) }), + outputSchema: Type.Object({ ok: Type.Boolean() }), + execute(inputs: Record, context: Context) { + const actual = inputs.actual_cost; + if (typeof actual === 'number') context.recordCost(actual); + return { ok: true }; + }, + }); + const budget = new CallBudget({ + maxCalls: testCase.max_calls ?? undefined, + maxCost: testCase.max_cost ?? undefined, + estimatedCosts: { [testCase.module_id]: testCase.estimated_cost }, + }); + const context = Context.create().withBudget(budget); + + expect(testCase.expected).toHaveLength(testCase.calls.length); + for (const [index, { actual_cost }] of testCase.calls.entries()) { + const expected = testCase.expected[index]; + const inputs = actual_cost === null ? {} : { actual_cost }; + const invocation = executor.call(testCase.module_id, inputs, context); + if (expected.error_code === null) { + await expect(invocation).resolves.toEqual({ ok: true }); + } else { + await expect(invocation).rejects.toMatchObject({ code: expected.error_code }); + await expect(invocation).rejects.toBeInstanceOf(ModuleError); + } + expect(budget.snapshot()).toEqual({ + callsUsed: expected.calls_used, + callsReserved: expected.calls_reserved, + costUsed: expected.cost_used, + }); + } + }); +}); diff --git a/typescript/tests/observability/test-redaction-config-keys.test.ts b/typescript/tests/observability/test-redaction-config-keys.test.ts index cb6f2dc6..3d534a6c 100644 --- a/typescript/tests/observability/test-redaction-config-keys.test.ts +++ b/typescript/tests/observability/test-redaction-config-keys.test.ts @@ -24,6 +24,38 @@ describe('RedactionConfig key alignment (CRITICAL #4)', () => { warnSpy.mockRestore(); }); + it('redacts over-cap strings without running any regex, using UTF-8 byte length', () => { + const config = new Config(); + config.set('obs.redaction.regex_patterns', ['^match$']); + config.set('obs.redaction.max_regex_scan_length', 4); + config.set('obs.redaction.replacement', ''); + const redaction = RedactionConfig.fromConfig(config); + const test = vi.spyOn(redaction.valuePatterns[0], 'test'); + expect(redaction.redact({ notes: ['å🙂', '🙂'], item: 'still too long' })).toEqual({ + notes: ['', '🙂'], item: '', + }); + expect(test).toHaveBeenCalledExactlyOnceWith('🙂'); + expect(redaction.redact('also too long')).toBe(''); + expect(new RedactionConfig({ maxRegexScanLength: 0 }).apply({ item: 'unchanged' })).toEqual({ item: 'unchanged' }); + }); + + it('uses a 65,536-byte limit by default while leaving same-size strings scannable', () => { + const redaction = new RedactionConfig({ valuePatterns: ['^match$'] }); + const test = vi.spyOn(redaction.valuePatterns[0], 'test'); + const atLimit = 'é'.repeat(32_768); + const redacted = redaction.apply({ atLimit, overLimit: `${atLimit}x` }); + expect(redacted.atLimit).toBe(atLimit); + expect(redacted.overLimit === '***REDACTED***').toBe(true); + expect(test).toHaveBeenCalledExactlyOnceWith(atLimit); + }); + + it('rejects non-integer or negative redaction limits from programmatic and file config', () => { + expect(() => new RedactionConfig({ maxRegexScanLength: -1 })).toThrow('non-negative safe integer'); + const config = new Config({ version: '1.0', project: { name: 'check-scan-limit' } }); + config.set('obs.redaction.max_regex_scan_length', 2.5); + expect(() => config.validate()).toThrow('obs.redaction.max_regex_scan_length'); + }); + it('reads canonical obs.redaction.* keys (sensitive_keys, regex_patterns, replacement)', () => { const config = new Config(); config.set('obs.redaction.sensitive_keys', ['_secret_*', 'apiKey', 'authorization']); diff --git a/typescript/tests/test-call-budget.test.ts b/typescript/tests/test-call-budget.test.ts new file mode 100644 index 00000000..de4cc35b --- /dev/null +++ b/typescript/tests/test-call-budget.test.ts @@ -0,0 +1,207 @@ +import { Type } from '@sinclair/typebox'; +import { describe, expect, it, vi } from 'vitest'; +import { + APCore, CallBudget, CallbackApprovalHandler, CancelToken, Context, Executor, Middleware, Registry, + RetrySignal, STREAMING_MARKER, createAnnotations, createApprovalResult, +} from '../src/index.js'; +import { AsyncTaskManager, RetryConfig } from '../src/async-task.js'; + +const id = 'budget.run'; +const emptySchema = Type.Object({}); + +function deferred() { + let release!: () => void; + const promise = new Promise(resolve => { release = resolve; }); + return { promise, release }; +} + +function definition(execute: (_inputs: unknown, context: Context) => unknown) { + return { description: 'Run a budgeted module', inputSchema: emptySchema, outputSchema: emptySchema, execute }; +} + +describe('CallBudget', () => { + it('settles actual cost once, copies estimates, and keeps capabilities out of wire contexts', async () => { + const estimatedCosts = { [id]: 4 }; + const budget = new CallBudget({ maxCalls: 2, maxCost: 6, estimatedCosts }); + estimatedCosts[id] = 9; + const client = new APCore(); + const root = Context.create(); + const context = root.withBudget(budget); + root.recordCost(1); + expect(() => context.recordCost(1)).toThrow(expect.objectContaining({ code: 'GENERAL_INVALID_INPUT' })); + expect(context.child(id).toJSON().data).toEqual({}); + expect(context.toJSON()).toEqual(root.toJSON()); + + const execute = vi.fn((_inputs: unknown, invocation: Context) => { + expect(budget.snapshot()).toEqual({ callsUsed: 1, callsReserved: 0, costUsed: 4 }); + invocation.recordCost(0); + expect(() => invocation.recordCost(1)).toThrow(expect.objectContaining({ code: 'GENERAL_INVALID_INPUT' })); + return {}; + }); + await client.register(id, definition(execute)); + expect((await client.validate(id, {}, context)).valid).toBe(true); + expect(budget.snapshot()).toEqual({ callsUsed: 0, callsReserved: 0, costUsed: 0 }); + await expect(client.call(id, {}, context)).resolves.toEqual({}); + expect(budget.snapshot()).toEqual({ callsUsed: 1, callsReserved: 0, costUsed: 0 }); + expect(execute).toHaveBeenCalledOnce(); + }); + + it('keeps concurrent call reservations and releases pending approval without spending', async () => { + const registry = new Registry(); + const handlerEntered = deferred(); + const answer = deferred(); + const approvalHandler = new CallbackApprovalHandler(async () => { + handlerEntered.release(); + await answer.promise; + return createApprovalResult({ status: 'pending', approvalId: 'wait' }); + }); + const executor = new Executor({ registry, approvalHandler }); + const execute = vi.fn(() => ({})); + await registry.register(id, { ...definition(execute), annotations: createAnnotations({ requiresApproval: true }) }); + const budget = new CallBudget({ maxCalls: 1 }); + const context = Context.create().withBudget(budget); + const pending = executor.call(id, {}, context); + await handlerEntered.promise; + try { + expect(budget.snapshot()).toEqual({ callsUsed: 0, callsReserved: 1, costUsed: 0 }); + await expect(executor.call(id, {}, context.child('budget.parent'))).rejects.toMatchObject({ + code: 'CALL_BUDGET_EXCEEDED', retryable: false, details: { dimension: 'calls' }, + }); + } finally { + answer.release(); + } + await expect(pending).rejects.toMatchObject({ code: 'APPROVAL_PENDING' }); + expect(budget.snapshot()).toEqual({ callsUsed: 0, callsReserved: 0, costUsed: 0 }); + expect(execute).not.toHaveBeenCalled(); + }); + + it('charges a failing business attempt and its actual retry, including traced calls', async () => { + const registry = new Registry(); + const execute = vi.fn().mockImplementationOnce(() => { throw new Error('retry'); }).mockReturnValue({}); + const executor = new Executor({ registry }); + class RetryOnce extends Middleware { + override onError(): RetrySignal { return new RetrySignal({}); } + } + executor.use(new RetryOnce()); + await registry.register(id, definition(execute)); + const budget = new CallBudget({ maxCalls: 2, maxCost: 6, estimatedCosts: { [id]: 3 } }); + const [output, trace] = await executor.callWithTrace(id, {}, Context.create().withBudget(budget)); + expect(output).toEqual({}); + expect(trace.success).toBe(true); + expect(budget.snapshot()).toEqual({ callsUsed: 2, callsReserved: 0, costUsed: 6 }); + }); + + it('rejects estimates above the remaining limit and keeps reported overrun charged', async () => { + const client = new APCore(); + const execute = vi.fn((_inputs: unknown, context: Context) => { + context.recordCost(7); + return {}; + }); + await client.register(id, definition(execute)); + const estimatedCosts = { [id]: 3 }; + const low = new CallBudget({ maxCost: 2, estimatedCosts }); + await expect(client.call(id, {}, Context.create().withBudget(low))).rejects.toMatchObject({ + code: 'CALL_BUDGET_EXCEEDED', details: { dimension: 'cost' }, + }); + expect(low.snapshot()).toEqual({ callsUsed: 0, callsReserved: 0, costUsed: 0 }); + expect(execute).not.toHaveBeenCalled(); + const high = new CallBudget({ maxCost: 6, estimatedCosts }); + await expect(client.call(id, {}, Context.create().withBudget(high))).rejects.toMatchObject({ + code: 'CALL_BUDGET_EXCEEDED', details: { dimension: 'cost' }, + }); + expect(high.snapshot()).toEqual({ callsUsed: 1, callsReserved: 0, costUsed: 7 }); + }); + + it('charges a stream only when its registered producer starts and supports actual settlement', async () => { + const client = new APCore(); + const stream = vi.fn(async function* (_inputs: unknown, context: Context) { + context.recordCost(2); + yield { done: true }; + }); + await client.register(id, { ...definition(() => ({})), stream, [STREAMING_MARKER]: true, + annotations: createAnnotations({ streaming: true }) }); + const budget = new CallBudget({ maxCalls: 1, maxCost: 6, estimatedCosts: { [id]: 3 } }); + const context = Context.create().withBudget(budget); + const abandoned = client.streamWithCompletion(id, {}, context); + await abandoned.close(); + expect(budget.snapshot()).toEqual({ callsUsed: 0, callsReserved: 0, costUsed: 0 }); + const running = client.streamWithCompletion(id, {}, context); + expect(budget.snapshot()).toEqual({ callsUsed: 0, callsReserved: 0, costUsed: 0 }); + await expect(running.chunks.next()).resolves.toMatchObject({ value: { done: true }, done: false }); + await expect(running.chunks.next()).resolves.toMatchObject({ done: true }); + await expect(running.completion).resolves.toMatchObject({ reason: 'completed' }); + expect(budget.snapshot()).toEqual({ callsUsed: 1, callsReserved: 0, costUsed: 2 }); + expect(stream).toHaveBeenCalledOnce(); + }); + + it('releases pre-dispatch cancellation reservations and rejects a strategy without a guard', async () => { + const registry = new Registry(); + const execute = vi.fn(() => ({})); + await registry.register(id, definition(execute)); + const executor = new Executor({ registry }); + const guardPassed = deferred(); + const release = deferred(); + executor.addStepMiddleware({ async beforeStep(name) { + if (name === 'execute') { + guardPassed.release(); + await release.promise; + } + } }); + const token = new CancelToken(); + const budget = new CallBudget({ maxCalls: 1 }); + const invocation = executor.call(id, {}, Context.create(null, null, token).withBudget(budget)); + await guardPassed.promise; + expect(budget.snapshot()).toEqual({ callsUsed: 0, callsReserved: 1, costUsed: 0 }); + token.cancel(); + expect(budget.snapshot()).toEqual({ callsUsed: 0, callsReserved: 0, costUsed: 0 }); + release.release(); + await expect(invocation).rejects.toMatchObject({ code: 'EXECUTION_CANCELLED' }); + expect(budget.snapshot()).toEqual({ callsUsed: 0, callsReserved: 0, costUsed: 0 }); + const minimal = new Executor({ registry, strategy: 'minimal' }); + await expect(minimal.call(id, {}, Context.create().withBudget(budget))).rejects.toMatchObject({ + code: 'PIPELINE_CONFIGURATION_ERROR', + }); + expect(execute).not.toHaveBeenCalled(); + }); + + it('rejects skipped dispatch and does not spend the reserved call or return injected output', async () => { + const registry = new Registry(); + const execute = vi.fn(() => ({})); + await registry.register(id, definition(execute)); + const executor = new Executor({ registry }); + executor.currentStrategy.insertAfter('input_validation', { + name: 'skip_dispatch', description: 'Skip the business body', removable: true, replaceable: true, + async execute(ctx) { + ctx.output = { injected: true }; + return { action: 'skip_to', skipTo: 'return_result' }; + }, + }); + const budget = new CallBudget({ maxCalls: 1 }); + const context = Context.create().withBudget(budget); + await expect(executor.call(id, {}, context)).rejects.toMatchObject({ code: 'PIPELINE_CONFIGURATION_ERROR' }); + const stream = executor.streamWithCompletion(id, {}, context); + await expect(stream.chunks.next()).rejects.toMatchObject({ code: 'PIPELINE_CONFIGURATION_ERROR' }); + await expect(stream.completion).resolves.toMatchObject({ reason: 'failed' }); + expect(execute).not.toHaveBeenCalled(); + expect(budget.snapshot()).toEqual({ callsUsed: 0, callsReserved: 0, costUsed: 0 }); + }); + + it('does not retry exhausted budgets in the background task loop', async () => { + const client = new APCore(); + const execute = vi.fn(() => ({})); + await client.register(id, definition(execute)); + const manager = new AsyncTaskManager({ executor: client.executor }); + const budget = new CallBudget({ maxCalls: 0 }); + try { + const taskId = await manager.submit(id, {}, { + context: Context.create().withBudget(budget), + retry: new RetryConfig({ maxRetries: 1, retryDelayMs: 0 }), + }); + await vi.waitFor(async () => expect((await manager.getStatus(taskId))?.status).toBe('failed')); + expect(await manager.getStatus(taskId)).toMatchObject({ retryCount: 0 }); + expect(execute).not.toHaveBeenCalled(); + } finally { + await manager.shutdown(); + } + }); +}); diff --git a/typescript/tests/test-context-interactions.test.ts b/typescript/tests/test-context-interactions.test.ts new file mode 100644 index 00000000..ca9df592 --- /dev/null +++ b/typescript/tests/test-context-interactions.test.ts @@ -0,0 +1,100 @@ +import { Type } from '@sinclair/typebox'; +import { describe, expect, it, vi } from 'vitest'; +import { APCore, CallBudget, CancelToken, Context } from '../src/index.js'; +import { AsyncTaskManager } from '../src/async-task.js'; + +describe('Context interaction callbacks', () => { + it('derives independent capabilities and excludes them from the wire context', async () => { + const progress = vi.fn(); + const elicit = vi.fn(() => ({ action: 'accept' as const, content: { name: 'A' } })); + const schema = { type: 'object' }; + const base = Context.create(); + const derived = base.withProgressReporter(progress).withElicitationHandler(elicit); + const child = derived.child('interaction.run').withProgressReporter(null); + const clearedElicitation = derived.withElicitationHandler(null); + + await base.reportProgress(1, 2, 'starting'); + await child.reportProgress(1, 2, 'starting'); + expect(progress).not.toHaveBeenCalled(); + await derived.reportProgress(1, 2, 'starting'); + expect(progress).toHaveBeenCalledExactlyOnceWith(1, 2, 'starting'); + await expect(clearedElicitation.elicit('Name?', schema)).resolves.toBeNull(); + await expect(child.elicit('Name?', schema)).resolves.toEqual({ action: 'accept', content: { name: 'A' } }); + expect(elicit).toHaveBeenCalledExactlyOnceWith('Name?', schema); + expect(derived.toJSON()).toEqual(base.toJSON()); + await expect(Context.fromJSON(derived.toJSON()).elicit('Name?')).resolves.toBeNull(); + }); + + it('carries callbacks through unary and stream execution contexts', async () => { + const client = new APCore(); + const progress = vi.fn(async () => {}); + const elicit = vi.fn(async () => ({ action: 'decline' as const })); + const ctx = Context.create().withProgressReporter(progress).withElicitationHandler(elicit); + const id = 'interaction.run'; + await client.register(id, { + description: 'Report work and request a response', inputSchema: Type.Object({}), outputSchema: Type.Object({}), + async execute(_input: unknown, context: Context) { + await context.reportProgress(1); + return { result: await context.elicit('Continue?') }; + }, + }); + + await expect(client.call(id, {}, ctx)).resolves.toEqual({ result: { action: 'decline' } }); + await expect(client.streamWithCompletion(id, {}, ctx).chunks.next()).resolves.toMatchObject({ + value: { result: { action: 'decline' } }, + }); + expect(progress).toHaveBeenCalledTimes(2); + expect(elicit).toHaveBeenCalledTimes(2); + }); + + it('interrupts callbacks on cancellation and checks deadlines before invoking the provider', async () => { + const token = new CancelToken(); + let finish!: () => void; + let entered!: () => void; + const started = new Promise(resolve => { entered = resolve; }); + const context = Context.create(null, null, token).withProgressReporter(() => new Promise(resolve => { + finish = resolve; + entered(); + })); + const report = context.reportProgress(1); + await started; + token.cancel(); + try { + await expect(report).rejects.toMatchObject({ code: 'EXECUTION_CANCELLED' }); + } finally { + finish(); + } + const expiredProvider = vi.fn(() => ({ action: 'cancel' as const })); + const expired = Context.create(null, null, null, undefined, undefined, Date.now() / 1000 - 1) + .withElicitationHandler(expiredProvider); + await expect(expired.elicit('Continue?')).rejects.toMatchObject({ code: 'MODULE_TIMEOUT' }); + expect(expiredProvider).not.toHaveBeenCalled(); + }); + + it('preserves interactions and budget on the background task cancellation context', async () => { + const client = new APCore(); + const manager = new AsyncTaskManager({ executor: client.executor }); + const id = 'interaction.background'; + await client.register(id, { + description: 'Call back from a background task', inputSchema: Type.Object({}), outputSchema: Type.Object({}), + async execute(_input: unknown, context: Context) { + await context.reportProgress(1); + context.recordCost(2); + return { response: await context.elicit('Continue?') }; + }, + }); + const progress = vi.fn(); + const budget = new CallBudget({ maxCalls: 1, maxCost: 2 }); + const context = Context.create().withProgressReporter(progress).withElicitationHandler(() => ({ action: 'cancel' })) + .withBudget(budget); + try { + const task = await manager.submit(id, {}, { context }); + await vi.waitFor(async () => expect((await manager.getStatus(task))?.status).toBe('completed')); + await expect(manager.getResult(task)).resolves.toEqual({ response: { action: 'cancel' } }); + expect(progress).toHaveBeenCalledOnce(); + expect(budget.snapshot()).toEqual({ callsUsed: 1, callsReserved: 0, costUsed: 2 }); + } finally { + await manager.shutdown(); + } + }); +}); From 55ecb527dff7282d9493038ca4aebc1e40692d84 Mon Sep 17 00:00:00 2001 From: tercel Date: Sat, 28 Nov 2026 21:25:59 +0800 Subject: [PATCH 2/3] docs(conformance): record beta candidate coverage Signed-off-by: tercel --- docs/spec/conformance.md | 5 +++-- planning/beta-closeout/state.json | 6 +++--- planning/beta-closeout/tasks/verification.md | 16 ++++++++++++++++ 3 files changed, 22 insertions(+), 5 deletions(-) diff --git a/docs/spec/conformance.md b/docs/spec/conformance.md index 9a1149ae..80aafe28 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 **101 cross-language fixture files** under `conformance/fixtures/` covering **1269 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 **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). ### 8.1 Fixture Inventory @@ -353,6 +353,7 @@ The repository ships **101 cross-language fixture files** under `conformance/fix | [`binding_errors`](https://github.com/aiperceivable/apcore/blob/main/conformance/fixtures/binding_errors.json) | 6 | Binding error message conformance (protocol-spec §5.12.8) | | [`binding_file_validation`](https://github.com/aiperceivable/apcore/blob/main/conformance/fixtures/binding_file_validation.json) | 9 | Binding files fail loudly: unknown keys, a one-sided schema pair and an invalid `auto_schema` are `BINDING_FILE_INVALID`; an uninferable schema is `BINDING_SCHEMA_INFERENCE_FAILED` in every mode (spec §5.12.2, §5.12.5, D-139) | | [`binding_schema_ref_scope`](https://github.com/aiperceivable/apcore/blob/main/conformance/fixtures/binding_schema_ref_scope.json) | 6 | Binding-relative Schema references and typed failures for invalid references and documents (spec §5.12.4) | +| [`call_budget`](https://github.com/aiperceivable/apcore/blob/main/conformance/fixtures/call_budget.json) | 3 | Call-tree reservations, actual-cost settlement, and count and cost exhaustion | | [`call_chain`](https://github.com/aiperceivable/apcore/blob/main/conformance/fixtures/call_chain.json) | 11 | Call-chain safety guard (Algorithm A20) | | [`config_defaults`](https://github.com/aiperceivable/apcore/blob/main/conformance/fixtures/config_defaults.json) | 18 | Config default values cross-SDK identity (spec §9.1.1) | | [`config_env`](https://github.com/aiperceivable/apcore/blob/main/conformance/fixtures/config_env.json) | 13 | Env-var → Config path mapping (Algorithm A12-NS, spec §9.8) | @@ -433,7 +434,7 @@ The repository ships **101 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** | **1269** | **101 fixtures** | +| **Total** | **1272** | **102 fixtures** | ### 8.2 Loading Fixtures from a Test Runner diff --git a/planning/beta-closeout/state.json b/planning/beta-closeout/state.json index 2dc3de9c..3668884e 100644 --- a/planning/beta-closeout/state.json +++ b/planning/beta-closeout/state.json @@ -12,8 +12,8 @@ ], "progress": { "total_tasks": 5, - "completed": 3, - "in_progress": 2, + "completed": 4, + "in_progress": 1, "pending": 0 }, "tasks": [ @@ -39,7 +39,7 @@ "id": "surfaces", "file": "tasks/surfaces.md", "title": "Guarded media reference pilot", - "status": "in_progress" + "status": "completed" }, { "id": "verification", diff --git a/planning/beta-closeout/tasks/verification.md b/planning/beta-closeout/tasks/verification.md index eb79fb92..7c4719d2 100644 --- a/planning/beta-closeout/tasks/verification.md +++ b/planning/beta-closeout/tasks/verification.md @@ -2,3 +2,19 @@ Check the shared behaviors, existing full suites, typed and protocol integration tests, and installed candidates listed in [the plan](../plan.md). + +The shared call budget fixture runs in Python, TypeScript, and Rust. The +focused case-pinning run detected mutations of all three cases in every SDK. +The conformance inventory covers 102 fixtures and 1,272 cases. + +The paired run installs the wheel, npm tarball, and Rust crate from the Core +distribution run, validates their digests, and checks the supported minimum +for each applicable adapter. All 16 jobs passed. The four routine Surfaces +SDK and documentation workflows passed for the same Surfaces commit. + +- Core runtime commit `7573f0de32634e00ba0585d42094613c0add9a76`. [Distribution verification](https://github.com/aiperceivable/apcore/actions/runs/46143380753) +- Surfaces commit `33e4d6d864d163ae3f297e04454fcba28da1a584`. [Paired compatibility](https://github.com/aiperceivable/apcore-surfaces/actions/runs/46143692117) + +The proposed protocol revision awaits maintainer approval before the final PRs. +Released packages and external pilot evidence are tracked separately in +the blueprint's GA criteria. From a3fe0245eecf65bb57c7cca324a7a7b29c6ff553 Mon Sep 17 00:00:00 2001 From: tercel Date: Sun, 29 Nov 2026 08:12:10 +0800 Subject: [PATCH 3/3] feat(protocol): finalize 2.0.0 draft revision 5 Signed-off-by: tercel --- CHANGELOG.md | 1 + docs/features/context-object.md | 6 +-- docs/spec/protocol-spec.md | 55 +++++++++++++++++++- planning/beta-closeout/tasks/verification.md | 8 +-- python/src/apcore/builtin_steps.py | 13 ++--- python/src/apcore/call_budget.py | 12 +---- python/tests/test_call_budget.py | 54 +++++++++++++++++++ rust/tests/call_budget.rs | 18 +++++++ typescript/src/builtin-steps.ts | 14 +---- typescript/src/call-budget.ts | 5 +- typescript/tests/test-call-budget.test.ts | 49 +++++++++++++++++ 11 files changed, 193 insertions(+), 42 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a154314b..aedfe1d6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,6 +17,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - **Protocol 2.0.0 draft revision 2.** Add opt-in policy evaluation after input validation. The enabled pipeline combines approval requirements at one gate, binds approval to the selected module version and effective arguments, and enforces the gate before ordinary and streaming execution. Final-scope pending approvals require an explicitly compatible scoped handler. - **Protocol 2.0.0 draft revision 3.** Add caller-scoped capability summaries and full-schema lookup using silent ACL visibility. Add the read-only `system.manifest.search` module with opaque cursors bound to the original requester. - **Protocol 2.0.0 draft revision 4.** Add trusted identity delegation, scope-aware ACL grants, root-subject conditions, and authority binding for discovery cursors, policy input, and pending approval resumption. +- **Protocol 2.0.0 draft revision 5.** Define in-process call-tree budgets, progress and elicitation callbacks across the three SDKs. Bound the regex scan length in configured redaction. ([#244](https://github.com/aiperceivable/apcore/issues/244)) ### Changed diff --git a/docs/features/context-object.md b/docs/features/context-object.md index 3798079e..a9291546 100644 --- a/docs/features/context-object.md +++ b/docs/features/context-object.md @@ -167,9 +167,9 @@ A budget counts invocations that start business execution. Pending approval, input rejection, and cancellation before dispatch release their reservations. Each dispatched retry consumes a call. A host can assign a cost estimate in integer units to each module. During execution, `record_cost` or `recordCost` -replaces the estimate once with the actual total for that attempt. A reported -overrun remains charged and returns `CALL_BUDGET_EXCEEDED`. Preflight leaves -the budget unchanged. +replaces the estimate once with the actual total for that attempt. On an +overrun, the method raises `CALL_BUDGET_EXCEEDED` and the actual charge stays +in the budget. Preflight runs independently of the budget. === "Python" diff --git a/docs/spec/protocol-spec.md b/docs/spec/protocol-spec.md index 166a621e..03228bb8 100644 --- a/docs/spec/protocol-spec.md +++ b/docs/spec/protocol-spec.md @@ -8,8 +8,8 @@ description: "The canonical apcore protocol specification (RFC 2119): module, sc > Version: 2.0.0 > Status: Draft -> Draft Revision: 4 -> Last Updated: 2026-11-28 +> Draft Revision: 5 +> Last Updated: 2026-11-29 --- @@ -2560,6 +2560,22 @@ context_serialization: - "redacted_inputs: MAY serialize as JSON object" ``` +#### 5.7.1 In-process invocation attachments + +SDKs **MUST** provide derivation methods to attach a call budget, progress +reporter, or elicitation handler to a Context without changing the D-24 +constructor. Child calls **MUST** inherit the attachments unless the host +explicitly replaces them. The attachments **MUST NOT** be serialized. + +A progress report carries a finite progress value and optional finite total +and message. Reporting without a reporter completes without sending a report. +An elicitation request carries a message and an optional JSON Schema object. +Without a handler, elicitation returns an empty optional result. A reply +indicates `accept` with object content, `decline`, or `cancel`. +The invocation's cancellation and deadline **MUST** bound the wait for +either callback. The adapter owns transport authorization, capability +negotiation, and the association with the active caller. + ### 5.8 Async Module Specification Async module state transitions **MUST** follow this state machine: @@ -5347,6 +5363,31 @@ Preflight evaluates policy on the same validated input its dry traversal obtains An evaluator has a finite timeout, defaulting to 1,000 milliseconds and bounded by the invocation deadline. Its timeout, malformed verdict, unsupported input representation, or exception is reported as `POLICY_EVALUATION_ERROR` with `retryable: true` and `user_fixable: false`. A denied verdict is `POLICY_DENIED` with `retryable: false`, `user_fixable: true`, and safe user guidance. External cancellation retains the invocation's cancellation outcome. Policy errors and `apcore.policy.decision` telemetry **MUST NOT** carry raw arguments, argument digests, credentials, or evaluator exceptions. A pending credential uses the caller-only approval delivery in §7.4. The policy event **MAY** include the decision, a safe static rule ID, and sensitive schema field paths. +#### 7.4.2 Optional call-tree budgets + +A host **MAY** attach a budget with optional call and cost limits and +per-module cost estimates. The limits, estimates, and actual costs are +nonnegative integers no greater than 9007199254740991. A missing module +estimate is zero. Child calls share the same ledger. + +For a budgeted invocation, the stock call-chain guard **MUST** reserve one +slot before dispatch. A budgeted strategy without the guard **MUST** fail +before business execution. Pending approval, rejection, or cancellation +before dispatch **MUST** release the slot. The dispatcher **MUST** atomically +check the estimate against the cost limit and commit the slot and its initial +charge before calling the handler or starting a stream producer. Each retry +that starts business execution **MUST** consume a slot and charge. Preflight +**MUST NOT** check, reserve, or commit budget. + +The module **MAY** record an actual total once per active attempt. This +replacement is atomic. On an actual overrun, the cost report **MUST** raise +an error and the charge **MUST** remain in the ledger. If the module handles +that error, normal output validation and completion apply to its result. +Recording cost without a budget has no effect. Exceeding a limit raises +nonretryable `CALL_BUDGET_EXCEEDED` with `details.dimension` set to `calls` +or `cost`. Snapshots report used calls, reserved calls, and total charged +cost, capping the reported numbers at the largest portable integer. + ### 7.5 Error Types Implementations **MUST** define the following error types under `ModuleError`: @@ -5870,6 +5911,10 @@ error_codes: description: "Same module call frequency exceeded limit" http_status: 508 + CALL_BUDGET_EXCEEDED: + description: "Call-tree count or cost limit exceeded (§7.4.2)" + http_status: 429 + # Approval-related (APPROVAL_*) APPROVAL_DENIED: description: "Approval was explicitly rejected" @@ -6050,6 +6095,7 @@ Implementations **MUST NOT** default retry failed module invocations. Retry beha | `CALL_DEPTH_EXCEEDED` | **No** | Call chain structure issue, retry won't change | | `CIRCULAR_CALL` | **No** | Call chain structure issue, retry won't change | | `CALL_FREQUENCY_EXCEEDED` | **No** | Call chain structure issue, retry won't change | +| `CALL_BUDGET_EXCEEDED` | **No** | The shared call or cost limit has been reached | | `GENERAL_INVALID_INPUT` | **No** | Invalid input, caller_id must fix before retry | | `FUNC_MISSING_TYPE_HINT` | **No** | Code-level issue, needs developer fix | | `FUNC_MISSING_RETURN_TYPE` | **No** | Code-level issue, needs developer fix | @@ -8702,6 +8748,10 @@ Each entry is interpreted per-entry, by its own spelling: Rationale: a process-wide "already reported" set silences the *second* configuration that loads the same broken pattern — the reload case and the multi-tenant case, exactly the two where an operator most needs to be told. +6. The scan limit `obs.redaction.max_regex_scan_length` defaults to 65536 + UTF-8 bytes per string value and accepts nonnegative safe integers. + If at least one value regex is active and the encoded string exceeds + the limit, SDKs **MUST** replace the entire value before any regex scan. ##### Protected fields @@ -10410,6 +10460,7 @@ The specification and the SDK have independent version numbers. `CHANGELOG.md` r | Version | Date | Summary | Records | |---|---|---|---| +| 2.0.0 (draft revision 5) | Unreleased | Define in-process call budgets, progress and elicitation, and limit configured regex scans (§5.7.1, §7.4.2, §8.2, §10.6.1). | [#244](https://github.com/aiperceivable/apcore/issues/244), [Changelog](https://github.com/aiperceivable/apcore/blob/main/CHANGELOG.md) | | 2.0.0 (draft revision 4) | Unreleased | Define trusted identity delegation, ACL scope enforcement, and authority binding for discovery and approvals (§6.11, §7.4.1). | D-155, [Changelog](https://github.com/aiperceivable/apcore/blob/main/CHANGELOG.md) | | 2.0.0 (draft revision 3) | Unreleased | Add silent ACL visibility, caller-scoped summaries and schema lookup, and `system.manifest.search` (§6.10, §11.3). | D-154, [Changelog](https://github.com/aiperceivable/apcore/blob/main/CHANGELOG.md) | | 2.0.0 (draft revision 2) | Unreleased | Add the opt-in post-validation policy evaluator, final-input approval binding, and preflight semantics (§7.2–§7.4.1, §11.3, §12.8). | [Changelog](https://github.com/aiperceivable/apcore/blob/main/CHANGELOG.md) | diff --git a/planning/beta-closeout/tasks/verification.md b/planning/beta-closeout/tasks/verification.md index 7c4719d2..ec281dde 100644 --- a/planning/beta-closeout/tasks/verification.md +++ b/planning/beta-closeout/tasks/verification.md @@ -15,6 +15,8 @@ SDK and documentation workflows passed for the same Surfaces commit. - Core runtime commit `7573f0de32634e00ba0585d42094613c0add9a76`. [Distribution verification](https://github.com/aiperceivable/apcore/actions/runs/46143380753) - Surfaces commit `33e4d6d864d163ae3f297e04454fcba28da1a584`. [Paired compatibility](https://github.com/aiperceivable/apcore-surfaces/actions/runs/46143692117) -The proposed protocol revision awaits maintainer approval before the final PRs. -Released packages and external pilot evidence are tracked separately in -the blueprint's GA criteria. +The maintainer approved draft revision 5 during candidate preparation. +[Specification discussion](https://github.com/aiperceivable/apcore/issues/244) + +Released packages and external pilot evidence are tracked in the blueprint's +GA criteria. diff --git a/python/src/apcore/builtin_steps.py b/python/src/apcore/builtin_steps.py index e7a66551..3fe686f5 100644 --- a/python/src/apcore/builtin_steps.py +++ b/python/src/apcore/builtin_steps.py @@ -390,14 +390,11 @@ async def execute(self, ctx: PipelineContext) -> StepResult: max_call_depth=self._max_call_depth, max_module_repeat=self._max_module_repeat, ) - if ctx._call_budget is not None: - if ctx.dry_run: - ctx._call_budget._check(ctx.module_id) - else: - if ctx.execution_scope is None: - raise ConfigurationError("CallBudget requires an execution scope") - reservation = ctx._budget_reservation = ctx._call_budget._reserve(ctx.module_id) - ctx.execution_scope.callback(reservation.release) + if ctx._call_budget is not None and not ctx.dry_run: + if ctx.execution_scope is None: + raise ConfigurationError("CallBudget requires an execution scope") + reservation = ctx._budget_reservation = ctx._call_budget._reserve(ctx.module_id) + ctx.execution_scope.callback(reservation.release) return StepResult(action="continue") diff --git a/python/src/apcore/call_budget.py b/python/src/apcore/call_budget.py index ce9d105d..b5f9deb3 100644 --- a/python/src/apcore/call_budget.py +++ b/python/src/apcore/call_budget.py @@ -62,23 +62,15 @@ def snapshot(self) -> CallBudgetSnapshot: min(self._cost_used, _MAX_SAFE_INTEGER), ) - def _check_allowance(self, estimate: int) -> None: - if self._max_calls is not None and self._calls_used + self._calls_reserved >= self._max_calls: - raise CallBudgetExceededError("calls") - self._check_cost(self._cost_used + estimate) - def _check_cost(self, cost: int) -> None: if self._max_cost is not None and cost > self._max_cost: raise CallBudgetExceededError("cost") - def _check(self, module_id: str) -> None: - with self._lock: - self._check_allowance(self._estimated_costs.get(module_id, 0)) - def _reserve(self, module_id: str) -> _CallReservation: estimate = self._estimated_costs.get(module_id, 0) with self._lock: - self._check_allowance(estimate) + if self._max_calls is not None and self._calls_used + self._calls_reserved >= self._max_calls: + raise CallBudgetExceededError("calls") self._calls_reserved += 1 return _CallReservation(self, estimate) diff --git a/python/tests/test_call_budget.py b/python/tests/test_call_budget.py index 7905172c..50863373 100644 --- a/python/tests/test_call_budget.py +++ b/python/tests/test_call_budget.py @@ -93,6 +93,60 @@ def calculate(actual: int, ctx: Context[Any]) -> int: assert (spent.calls_used, spent.calls_reserved, spent.cost_used) == (2, 0, 6) +@pytest.mark.parametrize("max_calls, max_cost", [(0, None), (None, 0)]) +async def test_preflight_ignores_budget_limits(max_calls: int | None, max_cost: int | None) -> None: + client = APCore() + + @client.module("budget.preflight") + def target() -> bool: + raise AssertionError("Preflight must not execute the module") + + budget = CallBudget(max_calls=max_calls, max_cost=max_cost, estimated_costs={"budget.preflight": 1}) + context = Context.create().with_budget(budget) + initial = budget.snapshot() + assert (await client.validate_async("budget.preflight", {}, context)).valid + assert budget.snapshot() == initial + + +async def test_handler_can_preserve_its_result_after_a_reported_cost_overrun() -> None: + client = APCore() + budget = CallBudget(max_cost=1) + context = Context.create().with_budget(budget) + + @client.module("budget.report") + def report(ctx: Context[Any]) -> bool: + with pytest.raises(CallBudgetExceededError, match="cost"): + ctx.record_cost(2) + return True + + assert await client.call_async("budget.report", {}, context) == {"result": True} + with pytest.raises(CallBudgetExceededError, match="cost"): + await client.call_async("budget.report", {}, context) + snapshot = budget.snapshot() + assert (snapshot.calls_used, snapshot.calls_reserved, snapshot.cost_used) == (1, 0, 2) + + +async def test_pending_approval_precedes_the_dispatch_cost_check() -> None: + executor = Executor(Registry()) + client = APCore(executor=executor) + + async def approve(request: ApprovalRequest) -> ApprovalResult: + return ApprovalResult("pending", approval_id="cost-review") + + executor.set_approval_handler(CallbackApprovalHandler(approve)) + + @client.module("budget.review", requires_approval=True) + def review() -> bool: + raise AssertionError("Pending approval must not execute the module") + + budget = CallBudget(max_calls=1, max_cost=0, estimated_costs={"budget.review": 1}) + context = Context.create().with_budget(budget) + initial = budget.snapshot() + with pytest.raises(ApprovalPendingError): + await client.call_async("budget.review", {}, context) + assert budget.snapshot() == initial + + async def test_budget_holds_a_concurrent_slot_then_releases_on_pending() -> None: executor = Executor(Registry()) client = APCore(executor=executor) diff --git a/rust/tests/call_budget.rs b/rust/tests/call_budget.rs index ffd9055b..ebea9634 100644 --- a/rust/tests/call_budget.rs +++ b/rust/tests/call_budget.rs @@ -139,6 +139,24 @@ async fn call_budget_matches_the_shared_conformance_fixture() { } } +#[tokio::test] +async fn preflight_ignores_call_and_cost_limits() { + let client = APCore::new(); + register(&client, false, false); + + for (max_calls, max_cost) in [(Some(0), None), (None, Some(0))] { + let budget = budget(max_calls, max_cost); + let context = Context::::anonymous().with_budget(Some(Arc::clone(&budget))); + let initial = budget.snapshot(); + let preflight = client + .validate("test.cost", &json!({}), Some(&context)) + .await + .unwrap(); + assert!(preflight.valid); + assert_eq!(budget.snapshot(), initial); + } +} + #[tokio::test] async fn charges_only_started_calls_and_replaces_the_estimate_with_actual() { let client = APCore::new(); diff --git a/typescript/src/builtin-steps.ts b/typescript/src/builtin-steps.ts index cf529b2d..b2477606 100644 --- a/typescript/src/builtin-steps.ts +++ b/typescript/src/builtin-steps.ts @@ -17,7 +17,7 @@ import { createApprovalRequest, createApprovalResult, takeApprovalToken } from ' import type { Config } from './config.js'; import { getDefault } from './config-defaults.js'; import { CancelToken, awaitExecution } from './cancel.js'; -import { assertBudgetDispatch, bindBudgetContext, commitBudgetCall, recordBudgetProducer, reserveBudgetCall } from './call-budget.js'; +import { bindBudgetContext, commitBudgetCall, recordBudgetProducer, reserveBudgetCall } from './call-budget.js'; import { Context } from './context.js'; import { assertDeclarationInvocation, recordDeclarationDispatch } from './declaration-invocation.js'; import { authorityKeyOf, hasScopeCeiling } from './identity.js'; @@ -1078,7 +1078,6 @@ export class BuiltinExecute implements Step { timeoutMs, isModuleIdempotent(mod), ); - assertBudgetDispatch(ctx); if (output == null) { throw new ModuleExecuteError(ctx.moduleId, 'Return value cannot be None'); } @@ -1102,16 +1101,7 @@ export class BuiltinExecute implements Step { let settleBudget: (() => void) | undefined; try { settleBudget = commitBudgetCall(ctx); - const stream = createStream(); - if (!settleBudget) { - yield* stream; - return; - } - for await (const chunk of stream) { - assertBudgetDispatch(ctx); - yield chunk; - } - assertBudgetDispatch(ctx); + yield* createStream(); } finally { settleBudget?.(); release?.(); diff --git a/typescript/src/call-budget.ts b/typescript/src/call-budget.ts index cdaebe34..ae3f05d0 100644 --- a/typescript/src/call-budget.ts +++ b/typescript/src/call-budget.ts @@ -69,7 +69,6 @@ interface Attempt { state: 'initial' | 'reserved' | 'running' | 'settled' | 'released'; removeCancelListener?: () => void; actualRecorded?: boolean; - overrun?: CallBudgetExceededError; producer?: AsyncGenerator>; } @@ -171,8 +170,7 @@ export function recordBudgetCost(context: Context, actual: number): voi const { ledger } = attempt; ledger.costUsed += settled - attempt.estimate; if (ledger.maxCost !== null && ledger.costUsed > ledger.maxCost) { - attempt.overrun = new CallBudgetExceededError('cost'); - throw attempt.overrun; + throw new CallBudgetExceededError('cost'); } } @@ -196,7 +194,6 @@ export function assertBudgetDispatch(ctx: PipelineContext, allowProducer: boolea if (attempt && attempt.state !== 'running' && attempt.state !== 'settled' && !(allowProducer && attempt.producer)) { throw new BudgetPipelineError(); } - if (attempt?.overrun) throw attempt.overrun; } /** @internal Release a count that could not reach business dispatch. */ diff --git a/typescript/tests/test-call-budget.test.ts b/typescript/tests/test-call-budget.test.ts index de4cc35b..6e1e2976 100644 --- a/typescript/tests/test-call-budget.test.ts +++ b/typescript/tests/test-call-budget.test.ts @@ -112,6 +112,55 @@ describe('CallBudget', () => { expect(high.snapshot()).toEqual({ callsUsed: 1, callsReserved: 0, costUsed: 7 }); }); + it.each([{ maxCalls: 0 }, { maxCost: 0 }])('does not apply budget limits during preflight (%o)', async (limits) => { + const client = new APCore(); + const execute = vi.fn(() => ({})); + await client.register(id, definition(execute)); + const budget = new CallBudget({ ...limits, estimatedCosts: { [id]: 1 } }); + const context = Context.create().withBudget(budget); + const initial = budget.snapshot(); + expect((await client.validate(id, {}, context)).valid).toBe(true); + expect(budget.snapshot()).toEqual(initial); + expect(execute).not.toHaveBeenCalled(); + }); + + it('preserves the handler result after a handled cost overrun and retains the charge', async () => { + const client = new APCore(); + const execute = vi.fn((_inputs: unknown, context: Context) => { + expect(() => context.recordCost(2)).toThrow(expect.objectContaining({ + code: 'CALL_BUDGET_EXCEEDED', details: { dimension: 'cost' }, + })); + return {}; + }); + await client.register(id, definition(execute)); + const budget = new CallBudget({ maxCost: 1 }); + const context = Context.create().withBudget(budget); + await expect(client.call(id, {}, context)).resolves.toEqual({}); + await expect(client.call(id, {}, context)).rejects.toMatchObject({ + code: 'CALL_BUDGET_EXCEEDED', details: { dimension: 'cost' }, + }); + expect(budget.snapshot()).toEqual({ callsUsed: 1, callsReserved: 0, costUsed: 2 }); + expect(execute).toHaveBeenCalledOnce(); + }); + + it('continues a stream after its producer handles a reported cost overrun', async () => { + const client = new APCore(); + const stream = vi.fn(async function* (_inputs: unknown, context: Context) { + expect(() => context.recordCost(2)).toThrow(expect.objectContaining({ code: 'CALL_BUDGET_EXCEEDED' })); + yield { done: true }; + }); + await client.register(id, { ...definition(() => ({})), stream, [STREAMING_MARKER]: true, + annotations: createAnnotations({ streaming: true }) }); + const budget = new CallBudget({ maxCost: 1 }); + const context = Context.create().withBudget(budget); + const running = client.streamWithCompletion(id, {}, context); + await expect(running.chunks.next()).resolves.toMatchObject({ value: { done: true }, done: false }); + await expect(running.chunks.next()).resolves.toMatchObject({ done: true }); + await expect(running.completion).resolves.toMatchObject({ reason: 'completed' }); + expect(budget.snapshot()).toEqual({ callsUsed: 1, callsReserved: 0, costUsed: 2 }); + expect(stream).toHaveBeenCalledOnce(); + }); + it('charges a stream only when its registered producer starts and supports actual settlement', async () => { const client = new APCore(); const stream = vi.fn(async function* (_inputs: unknown, context: Context) {