Home/Docs/Core Services/ContextRouter

ContextRouter architectureπŸ”—

ContextRouter compiles validated manifests into tenant-scoped LangGraph execution and exposes the Router gRPC service on port 50050 by default. Source is under services/router/src/contextunity/router/. Model-pool execution strategies and multimodal catalog invariants are canonically defined in ADR-0022 and ADR-0023.

Important
  • INV-ROUTER-SERVICE-ISOLATION: DispatcherService, PlatformToolRegistry, and shield_scan interact with peer services exclusively through contextunity.core SDK/gRPC contracts and fail closed when a peer transport is unavailable (enforced by ARCH-ROUTER-ISOLATION in .acdd/lint/rules.yaml).
  • INV-ROUTER-CORTEX-NO-PG: Router cortex orchestration (services/router/src/contextunity/router/cortex/**) never imports PostgreSQL or SQLAlchemy drivers (psycopg, psycopg_pool, asyncpg, sqlalchemy); durable memory and traces are delegated to ContextBrain over gRPC.

Key symbols and inputs/outputsπŸ”—

flowchart LR
  Callers["SDK / CLI / Worker Callers"] --> Interceptor["RouterPermissionInterceptor"]
  Interceptor --> Dispatcher["DispatcherService"]
  Dispatcher --> Compiler["cortex/compiler/* + PlatformToolRegistry"]
  Compiler --> Models["modules/models/* (Gateway / Pools)"]
  Compiler --> Peers["Brain / Worker / Shield gRPC Clients"]
  Dispatcher --> Recorder["RunRecorder (Execution Trace)"]
SymbolRoleInputs / Outputs
DispatcherServiceRouter gRPC servicerContextUnit requests -> unary ContextUnit responses (RegisterManifest, ExecuteAgent, ExecuteTool, IntrospectRegistrations) or streamed ContextUnit responses (StreamAgent)
RouterPermissionInterceptorRouter gRPC authz guardgRPC metadata -> verified caller token context before dispatch (delegates RegisterManifest to handler-owned registration authority verification in service/mixins/registration.py)
PlatformToolRegistryBuilt-in platform tool registryTool name + manifest bindings -> typed Brain/Worker/Shield/generation callables
RunRecorderBounded in-memory execution evidence portSecured graph run events -> bounded in-memory ControlEvidenceSnapshot and, on close, one immutable TerminalTraceSnapshot (submitted to Brain persistence via the separate finalization path)

Runtime layersπŸ”—

LayerCurrent locationResponsibility
gRPC boundaryservice/authentication, stream/request adaptation, server lifecycle
manifest compilercortex/compiler/validation, topology, node construction, prompt/config resolution
graph runtimecortex/services/, cortex/dispatcher.pygraph invocation, checkpoints, dispatch
security/shadowingcortex/shadower/masking/, cortex/secure_node.pymasking, scope attenuation, secure node boundary
platform toolscortex/compiler/platform_tools/ and PlatformToolRegistrytyped Brain, Worker, Shield, RAG, SQL, content and utility adapters
model registrymodules/models/registry/provider/model resolution and fallback policy
conductorconductor/catalog, evidence, quality, selection, federated routing
Engram consolidationcortex/consolidation/bounded source prompt, model call, Brain-owned operation receipt
CLIcli/contextrouter serve and registered commands

Templates are under cortex/compiler/templates/. The manifest contract supports the mutually exclusive graph forms defined by the current schema: inline graph, YAML template reference, or supported builtin dispatcher mode. Reusable platform graphs should prefer templates; inline graphs remain an implemented contract.

Compile and executeπŸ”—

  1. Parse and validate the manifest, including security and mutually exclusive graph-source rules.
  2. Resolve prompts, model/tool configuration, topology, memory/trace settings, and runtime endpoints.
  3. Construct nodes through the compiler and PlatformToolRegistry.
  4. Execute through the secure graph boundary with tenant/token context.
  5. Emit stream events/traces and persist configured checkpoints/memory through their service adapters.

No compiler success is sufficient without a production runtime caller. Missing prompt evidence, invalid security configuration, unknown tools, or unresolved models must fail before provider invocation.

Brain-read controlπŸ”—

The three secured DAG readers brain_search, brain_memory_read, and brain_synapse_query resolve verified token authority and an immutable concrete query before Brain I/O. Optional C0 controls under memory.brain_reads are independent and default off: pure depth degradation, exact in-flight coalescing, and a fair global/per-tenant bulkhead. Coalescing has independent global and per-tenant in-flight limits. Coalescing tracks active requests; the existing graph-local caches remain run-scoped and authority-keyed when enabled. Only the coalesced owner consumes a bulkhead slot. Queueing and SDK execution use one monotonic deadline, and native task cancellation removes a waiter while preserving a shared owner until its last waiter leaves.

Controlled outcomes enter the active RunRecorder and terminal Execution Trace without query text or result content. Execution outcome (executed, coalesced, or cache_hit) and the degradation flag are orthogonal. Routine successful execution does not enter UDB. Degradation, queue drop, deadline and Brain unavailability produce one bounded linked UDB occurrence; enabling any Router Brain-read control therefore requires Router UDB plus FaultSpool. A missing direct UDB client falls back to FaultSpool. If neither path can durably preserve the occurrence, the controlled caller fails with the typed BrainReadEvidenceUnavailableError; gate-off callers preserve the direct Phase-3 exception path.

Operator env keys are CU_ROUTER_BRAIN_READS_BULKHEAD_ENABLED, CU_ROUTER_BRAIN_READS_COALESCING_ENABLED, and CU_ROUTER_BRAIN_READS_DEGRADATION_ENABLED, with the bounded GLOBAL_LIMIT, PER_TENANT_LIMIT, DEADLINE_MS, MAX_QUEUE, PER_TENANT_QUEUE_LIMIT, MAX_INFLIGHT, PER_TENANT_MAX_INFLIGHT, pressure-threshold, and max-degrade-step keys defined by core/config/main.py. Invalid combinations fail config parsing. When only MAX_INFLIGHT is lowered, the omitted per-tenant bound resolves to the smaller of 64 and that global limit; an explicit per-tenant value above the global bound is rejected. A zero-length bulkhead queue permits immediately runnable work but rejects every request that would have to wait.

Engram consolidationπŸ”—

RunEngramConsolidation, GetEngramConsolidationStatus, and ExplainEngramConsolidation accept exact Project or Tenant audiences through the authenticated Router gRPC boundary. The caller must have a signed ProjectBound identity and the requested tenant; a Project audience must also match the caller's project. Router signs a narrower service request to Brain for that audience and its registered producer project. Status and explanation read Brain's typed operation receipt. Router has no receipt store.

When memory.engram_consolidation.enabled is true, Router starts a bounded timer after registered projects have been restored. The timer schedules active registered Project and Tenant scopes with deterministic operation identifiers for each interval. Each run asks Brain for a bounded, grant-authorized source selection, removes credential and contact data from source text, then records the operation attempt in Brain. An empty or unusable selection is finalized as no_change without invoking a model. Otherwise Router invokes the configured model through its model gateway and submits the draft for Brain to validate and commit. Brain remains the authority for grants, canonical engrams, and receipts; Router errors do not turn into a local success record. For each Brain receipt, the timer emits a bounded Router completion log with the same operation_id, receipt status, and optional engram_id. A failure before a receipt emits the attempted operation ID and exception class only. The log contains no source text, prompt, draft, or exception message. Brain's receipt is the audit authority; background consolidation creates no Execution Trace. When memory.engram_consolidation.model_id is omitted, Router uses the C0 models.default_llm value. Startup checks the effective model against the C0 catalog and the configured worst-case cost limit before serving requests.

ConfigurationπŸ”—

Router configuration lives under core/config/. Parsing is pure: Redis/mesh discovery occurs only in the runtime resolve/startup path. Brain defaults to localhost:50051, Worker to localhost:50052, and Shield to localhost:50054 unless configured/resolved otherwise.

Provider and model entries are resolved by modules/models/registry/. Additions require configuration/model validation, adapter registration, invocation tests, and fail-fast tests for missing credentials or unsupported capabilities.

Security and observabilityπŸ”—

Important

Invariant: Router derives tenant and authorization from verified token context; payload tenant hints cannot widen authority, and trace evidence does not expose secrets or raw sensitive payloads.

Every request derives tenant and authorization from the verified token/context; payload tenant hints cannot widen it. Masking/encryption and pass-by-reference middleware guard sensitive payload seams. Traces must preserve execution identity without logging secrets or raw sensitive payloads.

DevelopmentπŸ”—

contextrouter serve
uv run pytest services/router/tests

Manifest and API detail are documented in the protobuf contracts and live source. Track future work in the current work record.