This page explains the Kasal platform's layers, request lifecycles, and security model.
Visual workflow designer for creating AI agent collaborations.
Kasal is an AI agent workflow orchestration platform for Databricks. The sections below cover its core design principles and the layers that make them work.
| Principle | Implementation | Where to look |
|---|---|---|
| Async-first | Non-blocking I/O; blocking waits run on dedicated thread pools | services/execution/blocking_pools.py |
| Layered | Routers call services, services call repositories | src/backend/src/services/CLAUDE.md |
| Fail-closed identity | A request with no identity gets 401 | dependencies/providers.py |
| Multi-tenant | Every row and query is scoped to a group (workspace) | utils/user_context.py |
| Swappable agent runtime | Kasal's own runtime by default, CrewAI as an alternative | services/execution/harnesses/ |
A big-picture view of the client, application, agent and data layers.
graph TB
subgraph "Client"
WEB[React SPA]
EXT[API, MCP and A2A callers]
end
subgraph "Application (FastAPI)"
MW[Identity and security middleware]
API[Routers in api/]
SVC[Services]
REPO[Repositories]
end
subgraph "Agent execution"
HUB[KasalEngineService hub]
CHAT[Chat path, in-process]
AB[Agent Builder path, subprocess]
FB[Flow Builder path, subprocess]
RT[Runtime: Kasal or CrewAI harness]
LLM[LLM transport]
end
subgraph "Data"
DB[(SQLite, PostgreSQL or Lakebase)]
VEC[(Memory: local, Databricks Vector Search or Lakebase pgvector)]
MLF[(MLflow traces)]
end
WEB --> MW
EXT --> MW
MW --> API
API --> SVC
SVC --> REPO
REPO --> DB
SVC --> HUB
HUB --> CHAT
HUB --> AB
HUB --> FB
CHAT --> RT
AB --> RT
FB --> RT
RT --> LLM
RT --> VEC
RT --> MLF
The layered approach and how requests flow through components. Paths in this section are relative to src/backend/src/.
- Layered architecture: frontend (React SPA) to API (FastAPI routers) to services to repositories to the database.
- Async-first: async SQLAlchemy 2.0 sessions, background tasks and queues.
- Configuration comes from environment variables read by
config/settings.py; models, judges and most integrations are configured in the UI. See the configuration reference. - Swappable agent runtime, or harness (
services/execution/harnesses/): Kasal's own runtime by default, CrewAI as an alternative. See Harnesses.
From HTTP request to response: validation, business logic, and persistence.
- A router in
api/receives the request and validates it withschemas/. - The router resolves the caller's
GroupContextwithget_group_contextand gets an injected session (SessionDep). - The router calls a service in
services/for business logic. The service owns the transaction scope. - The service reads and writes through repositories in
repositories/. Repositories build queries; they never open or commit sessions. - The response is serialized with Pydantic schemas.
The rules CI enforces are in src/backend/src/services/CLAUDE.md: a service never builds queries or persists rows, never opens a session, and reaches another domain's data through that domain's service rather than its repository.
How a run is prepared, executed and observed. The execution_type on the request selects one of three paths.
execution_type |
UI name | Package | Where it runs |
|---|---|---|---|
agent |
Chat | services/chat/ |
In-process, a single agent |
crew |
Agent Builder | services/agent_builder/ |
Spawned subprocess (agent_builder/process_executor.py) |
flow |
Flow Builder | services/flow_builder/ |
Spawned subprocess (flow_builder/process_executor.py) |
- Entry:
api/executions_router.pycallsExecutionService(services/execution/service.py). - Hub:
KasalEngineService(services/execution/engine_service.py) resolves the path and delegates. It holds no path-specific logic. - Build:
services/execution/kernel/is the single place both subprocess paths build agents, tasks and tools from. It callsactive_harness().build_*, so the chosen harness supplies the agent, task and crew classes. - Run: the Kasal runtime in
services/execution/runtime/(agent, task, crew and the tool-call loop) or the CrewAI harness inservices/execution/harnesses/crewai/. Either way, model calls go through the transport incore/llm/transport/. See the LLM architecture. - Observe: the run event bus (
core/events/) has one trace subscriber,OTelEventBridge(services/otel_tracing/event_bridge.py). Execution logs are captured byservices/execution/logs/, traces are stored and broadcast byservices/trace/. - Persist: status and history go through
repositories/execution_repository.pyandrepositories/execution_history_repository.py. Terminal outcomes are written byservices/execution/finalization.py. - Resume: crash-resume for crews and flows lives in
services/execution/checkpointing/. See Checkpointing.
Four modules keep the subprocess paths from harming the server they run in, and from harming each other:
services/execution/run_admission.pyis one concurrent-run limit shared by crew and flow runs, per server process. Runs are admitted asynchronously (the API, the scheduler, event triggers and resume return before the subprocess spawns), so a run over the limit is queued rather than rejected: its row goes toPENDINGwith aQueued: …message naming the limit and its position, it waits on an asyncio future rather than a pool thread, and it is admitted first in, first out as slots free, then set toRUNNING. A stop request removes a queued run from the queue, so it never spawns. The limit comes from the engine-config rowengine_name="kasal",config_key="max_concurrent_runs", defaults to 16 and is capped at the pool size below, because a higher limit would bring back runs waiting silently inside a pool.services/execution/run_wait.pywaits for a run's subprocess and collects its result. It reads the result queue while the child runs, since a result larger than the pipe buffer would otherwise deadlock a child that cannot finish its write. Each run holds exactly one pool thread (its result reader); the exit wait polls on the event loop. The run's timeout deadline is computed when the process starts, so time spent queued for admission does not count.services/execution/blocking_pools.pygives the subprocess paths two bounded thread pools (16 threads each): one for the result readers and one for event-relay reads. Keeping these off the event loop's default executor stops a few long builds from starving Chat turns, and keeping the two pools apart prevents a deadlock where readers fill the pool and the relays that let a child exit cannot run. Because admission keeps live runs at or below the pool size, nothing waits for a thread.services/execution/process_tree.pyterminates only the process trees this server spawned. A run's subprocess is themultiprocessing.Processthe executor holds, and its children are found throughpsutil. When that handle is gone, the only fallback is a descendant of this server whoseKASAL_EXECUTION_IDequals the execution ID exactly. The module never scans the whole host, so it cannot kill an unrelateduvicorn,mlflow serveror test process. Errors are narrowed topsutilerrors, and a stop that did not happen is reported as failed.
For how to set the limit, see the configuration reference.
Schedulers and queues for recurring and long-running tasks, started from the lifespan handler in main.py:
- Scheduled runs:
services/scheduling/scheduler.py. - Documentation embeddings queue:
services/knowledge/embedding_queue.py. - Stale and zombie execution cleanup at startup and every two minutes:
services/execution/cleanup.py. - Seeders run in the background after database initialization when
AUTO_SEED_DATABASEis true.
ORM entities, Pydantic schemas, and repository boundaries.
- ORM entities live in
models/; API contracts live inschemas/. - Repositories encapsulate SQL and external calls (Databricks APIs, Vector Search, MLflow).
db/session.pyprovides the async engine and session factory, SQLite WAL mode with lock retry and backoff, and SQL echo whenSQL_DEBUG=true.db/database_router.pyroutes sessions to Lakebase when it is enabled.
User context, group isolation, and authorization controls.
- Kasal does not authenticate users itself. A reverse proxy does, and
utils/request_identity.pyis the one place that reads the identity it forwards. Inside Databricks Apps onlyX-Forwarded-Email,X-Forwarded-UserandX-Forwarded-Access-Tokenare trusted, andUntrustedIdentityHeadersMiddlewarestripsX-Auth-Request-*headers. get_group_context(dependencies/providers.py) turns the identity into aGroupContext. A request without an identity gets 401.- For local development,
LOCAL_DEV_AUTH(set byrun.sh) injects a development identity throughLocalDevAuthMiddlewareinmain.py. - Role checks live in
core/permissions.py; admin-only routes usedependencies/admin_auth.py.
For the full security model, see Security.
Where different data types live and why.
| Data type | Storage | Purpose |
|---|---|---|
| Transactional | SQLite (local), PostgreSQL, or Databricks Lakebase | Workflows, runs, configuration |
| Agent memory | Local store, Databricks Vector Search, or Lakebase pgvector | Semantic recall across runs |
| Traces | Execution trace table, optionally exported to MLflow | Observability |
Logs, traces, metrics, and how to access them.
- Central log manager:
core/logger.pywrites toLOG_DIR. - Logging toggles:
KASAL_LOG_LEVELandSQL_DEBUG. - Execution logs and traces are persisted and queryable through
api/execution_logs_router.pyandapi/execution_trace_router.py.
Important toggles that affect developer and runtime experience. See the configuration reference for the full list.
- The FastAPI
/api-docspages are on locally and off inside Databricks Apps; the seeders always run in the background after database initialization. Neither is an environment variable. DATABASE_TYPE:sqlite(the default, withSQLITE_DB_PATHdefaulting tosrc/backend/app.db) orpostgres.
Back to the documentation hub.
