Skip to content

Latest commit

 

History

History
262 lines (187 loc) · 16.4 KB

architecture.md

File metadata and controls

262 lines (187 loc) · 16.4 KB
description apcore architecture from big picture to runtime internals: layers, system invariants, the 11-step execution pipeline, project layout, concurrency, and memory model.

Architecture Design

How apcore is structured — starting with the high-level picture, followed by concurrency, memory, and extension details for production and SDK developers.

1. Big Picture: Two Ways to Look at the Stack

apcore separates how the framework runs calls (vertical technical layers) from how you organize your own modules (horizontal business layers).

1.1 Framework Technical Layers (Vertical)

HTTP endpoints, CLI commands, agent surfaces, and direct code can invoke modules through the Executor. The figure shows the main layers and selected steps of the standard strategy.

┌─────────────────────────────────────────────────────────────────┐
│                    Application / Surface Layer                  │
│   ┌─────────────────┐  ┌─────────────────┐  ┌────────────────┐  │
│   │   HTTP API      │  │   CLI           │  │   MCP / A2A    │  │
│   └────────┬────────┘  └────────┬────────┘  └───────┬────────┘  │
│            │                    │                    │           │
│            └────────────────────┼────────────────────┘           │
│                                 ▼                                │
├─────────────────────────────────────────────────────────────────┤
│                    Execution Layer (Executor)                    │
│   ┌────────┐ ┌────────┐ ┌────────┐ ┌────────┐ ┌─────────────┐   │
│   │  ACL   │→│Approval│→│Middlew.│→│Validate│→│   Execute   │   │
│   │ Check  │ │  Gate  │ │ Before │ │ Input  │ │   Module    │   │
│   └────────┘ └────────┘ └────────┘ └────────┘ └─────────────┘   │
│                                 ▲                                │
│                                 │ Look up module                 │
├─────────────────────────────────┼───────────────────────────────┤
│                    Registry Layer (Registry)                     │
│   ┌──────────┐  ┌──────────┐  ┌──────────┐  ┌──────────────┐    │
│   │ Discover │→ │  ID Map  │→ │ Validate │→ │ Module Store │    │
│   └──────────┘  └──────────┘  └──────────┘  └──────────────┘    │
│                                 ▲                                │
│                                 │ Register / scan                │
├─────────────────────────────────┼───────────────────────────────┤
│                    Module Layer (Your Code)                      │
│          Registered functions, YAML bindings, or extensions/     │
└─────────────────────────────────────────────────────────────────┘

1.2 Suggested Business Layers (Horizontal)

For larger projects using directory discovery under extensions/, apcore recommends grouping modules into four layers enforced by ACL rules (downward calls only — e.g., api.* calls orchestrator.*, never executor.* directly):

extensions/
├── api/            # External entry-point modules (ACL: calls orchestrator.* only)
├── orchestrator/   # Workflow coordination (ACL: calls executor.* and common.*)
├── executor/       # Concrete operations: email, billing, database (ACL: calls common.*)
└── common/         # Shared read-only utilities (callable by all layers)

Small projects do not need this four-folder structure — you can start with flat IDs like billing.refund registered in memory and introduce layered directories later as the codebase grows.


2. System Invariants & the 11-Step Pipeline

2.1 The Five Invariants

Regardless of language (Python, TypeScript, or Rust), apcore preserves five guarantees:

Invariant Rule Why it matters
ID Persistence Module ID = Relative Path (when discovered) The same folder layout produces identical IDs across Python, TypeScript, and Rust.
Schema Mandate Every module declares input_schema, output_schema, and description The standard strategy validates inputs and module outputs against JSON Schema Draft 2020-12.
Trace Continuity One trace_id propagates through nested calls Every parent and child invocation correlates in traces and audit logs.
ACL Default-Deny Attach an ACL with default_effect: deny and use a strategy with acl_check. The ruleset denies unmatched calls.
Context Sharing context.data is shared by reference down a call chain Parent and child modules can coordinate request-scoped state without globals.

2.2 The 11-Step Execution Pipeline

The standard strategy defines 11 ordered steps. The work done at each step depends on the call and the Executor configuration.

 1. context_creation    Build Context (trace_id, caller_id, call_chain, identity)
 2. call_chain_guard    Block circular calls, depth overflow, and repeat spikes
 3. module_lookup       Resolve target_id in Registry (and check toggle state)
 4. acl_check           Evaluate the attached ACL for caller_id → target_id
 5. approval_gate       Require approval if annotated, gated by policy, or required by ACL
 6. middleware_before   Run before() hooks in priority order (may transform inputs)
 7. input_validation    Validate inputs against input_schema
 8. execute             Invoke module.execute() (or stream())
 9. output_validation   Validate the module output against output_schema
10. middleware_after    Run after() hooks in reverse order (may replace output)
11. return_result       Return the resulting output
    on error:           Run on_error() hooks in reverse order, then surface ModuleError

!!! tip "Customizing the pipeline" The standard strategy covers most apps. For step protocols, preset strategies (standard, minimal, performance, testing, internal), and custom step insertion, see Core Executor and Execution Pipeline.


3. Core Flows

3.1 Call & Error Flow

Client.call(target_id, inputs, context)
   │
   ├─ Guard / Lookup / ACL / Approval fail ─► ModuleError (middleware NOT run)
   │
   ├─ Middleware before() runs
   ├─ Input validation fails ───────────────► Middleware on_error() ─► SchemaValidationError
   ├─ Module.execute() raises ──────────────► Middleware on_error() ─► ModuleError
   ├─ Output validation fails ──────────────► Middleware on_error() ─► SchemaValidationError
   │
   └─ Middleware after() runs ──────────────► Result returned

Output validation checks the module’s return value. An after() hook that replaces it is responsible for conforming to the output schema. An on_error() recovery can also supply the final result. See Middleware System.

Non-apcore exceptions raised inside execute() are wrapped into MODULE_EXECUTE_ERROR with the original exception preserved as the cause. To help callers or AI agents recover, raise ModuleError with retryable, user_fixable, suggestion, and ai_guidance (see Error System).

3.2 Preflight (validate()) Flow

client.validate(target_id, inputs) runs the applicable pure steps, computes whether approval is required without requesting it, and can run permitted module.preflight() and module.preview() hooks. Callers and UIs use it to check permissions, approval requirements, and input validity before invoking the module. See Validate and dry-runs.


4. Recommended Project Layout

For a full, config-driven service (see Runtime Profiles for in-memory vs. full setup):

my-service/
├── apcore.yaml          # Framework & ecosystem configuration (Config Bus)
├── acl/
│   └── global_acl.yaml  # ACL rules (default_effect: deny) and audit config
├── bindings/            # Optional zero-code YAML bindings for existing callables
├── schemas/             # Optional shared cross-language YAML schemas
└── extensions/          # Auto-discovered modules (path = canonical module ID)
    ├── api/
    ├── orchestrator/
    ├── executor/
    └── common/

5. Extension Points

Use the ExtensionManager API{ #51-extensionmanager-api } to register extensions.

Extension point Purpose Reference
Discoverer Load modules from custom sources (databases, packages, remote manifests) Custom discoverer{ #52-custom-discoverer } · Registry System
Module validator Enforce deployment-specific module constraints Custom module validator{ #53-custom-validator }
ApprovalHandler Connect approvals to Slack, tickets, UI prompts, or policy engines Approval System · Approval Cookbook
ACL / Condition Handlers Enforce static YAML rules, dynamic rules, or custom condition evaluators ACL System{ #54-custom-acl }
Middleware Wrap calls with logging, tracing, metrics, retries, or input normalization Middleware System · Middleware Guide
Pipeline Steps & Strategies Insert, replace, or reorder execution pipeline stages Execution Pipeline
Exporters & Subscribers Send traces, metrics, and framework events to OTLP, Prometheus, or webhooks Observability{ #64-observable } · Event System

6. Concurrency Model

Method names below follow the Python SDK; TypeScript and Rust provide equivalent APIs with the same guarantees.

6.1 Thread Safety Guarantees

Component Thread Safety Notes
Registry (read) Safe get(), has(), list() can run concurrently
Registry (write) Synchronized register(), unregister() use internal synchronization
Executor Safe call() / call_async() execute concurrently with isolated per-call contexts
Context Partially safe Immutable metadata is safe; concurrent mutation of context.data requires caller sync
ACL Safe Reads are lock-free/safe; runtime mutations (add_rule, remove_rule, reload) are internally locked
Middleware & Modules Caller responsibility Instances are shared singletons — keep per-call state in context.data, not instance fields

6.2 Module Reentrancy & Hot Reload

  • Singleton model: Each registered module_id maps to one module instance (on_load() runs once). execute() must be safe for concurrent calls.
  • Hot reload draining: When unregistering or reloading a module, the runtime tracks in-flight invocations and waits for them to complete before unloading (up to the drain timeout, default 5 s). See protocol-spec §12.7.4.

6.3 Sync/Async Bridging (Python)

TypeScript and Rust execute asynchronously by default. Python supports both sync and async modules and bridges them automatically:

Caller Target Module Bridging Behavior
Sync (call) Sync Direct call
Sync (call) Async Runs on cached loop / worker thread and waits
Async (call_async) Sync Offloaded to thread pool
Async (call_async) Async Direct await

6.4 Timeouts & Cooperative Cancellation

  • executor.default_timeout (default 30000 ms) bounds a single module call; executor.global_timeout (default 60000 ms) bounds the entire call tree.
  • Cancellation is cooperative across all three SDKs: long-running modules check context.cancel_token between units of work. See Cancellation and the Cancellation Cookbook.

7. Memory & Context.data Lifecycle

7.1 Object Lifetimes

Object Created Destroyed Scope
Registry, Executor, Middleware App startup App shutdown Application-level
Module instance register() / discover() unregister() / shutdown Application-level (singleton)
Context Each call() When call() returns Invocation-level

7.2 context.data Sharing Rules

  • Shared within one call chain: When a parent module creates a child context (context.child(...)), data is shared by reference — updates made by a parent are visible to child modules and vice versa.
  • Isolated across separate calls: Concurrent top-level call() invocations never share context.data.
  • Memory hygiene: Keep context.data lightweight (avoid storing multi-megabyte payloads; use Artifact References or external storage instead). Schemas are cached after loading rather than reparsed on each call.

See protocol-spec §12.7.2 for normative details.


Next Steps