Sessions¶
Session Container¶
agora_workbench.code_execution.sessions.session.Session(session_id, data, session_type, user_identity, user_token, token_claims, metadata=None, data_manager=None, extensions=None)
¶
Bases: Generic[T]
Generic session container managing stateful data across MCP server interactions.
Sessions provide lifecycle management, ownership tracking, and metadata storage for persistent resources like code execution environments, database connections, or computation state. Each session is owned by a specific user (identified via JWT token claims) and tracks access patterns, status transitions, and cleanup requirements.
Attributes:
| Name | Type | Description |
|---|---|---|
session_id |
str
|
Unique identifier for the session. |
data |
T
|
The session's payload data, type-parameterized for type safety. |
session_type |
str
|
Categorizes session type (e.g., "python", "database"). |
user_identity |
str
|
Owner's composite identifier from JWT token ( |
user_token |
str
|
User's bearer token for authentication. |
metadata |
Dict
|
Optional key-value metadata for session configuration. |
token_claims |
Dict
|
Optional cached JWT token claims for session authorization. These claims are used to restore authentication context without re-validating the JWT token. Intentionally excluded from get_info() for security. |
created_at |
datetime
|
Timestamp when session was created. |
last_accessed |
datetime
|
Timestamp of most recent session access. |
status |
str
|
Current session state (e.g., "created", "active", "error"). |
data_manager |
DataLakeDataManager
|
Manager for DataLake asset access. Owned by
the session — :meth: |
Example
from .session import Session session = Session( ... session_id="sess_123", ... data={"counter": 0}, ... session_type="demo", ... user_identity="user-oid-xyz", ... user_token="eyJ...", ... metadata={"version": "1.0"}, ... token_claims={"oid": "user-oid-xyz", "exp": 1234567890}, ... ) session.touch() # Update last accessed time session.update_status("active") info = session.get_info()
Initialize a session.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
session_id
|
str
|
Unique identifier for the session. |
required |
data
|
T
|
The session's payload data. |
required |
session_type
|
str
|
Categorizes session type (e.g. |
required |
user_identity
|
str
|
Owner's composite identifier from JWT token ( |
required |
user_token
|
str
|
User's bearer token for authentication. |
required |
token_claims
|
Dict
|
Cached JWT claims for the user token. |
required |
metadata
|
Optional[Dict]
|
Optional key-value metadata for session configuration. |
None
|
data_manager
|
Optional[DataLakeDataManager]
|
Optional pre-built data manager for DataLake asset
access. When omitted, a default :class: |
None
|
Source code in src/agora_workbench/code_execution/sessions/session.py
touch()
¶
update_status(new_status)
¶
Update session status with history tracking.
get_info()
¶
Return session information.
Source code in src/agora_workbench/code_execution/sessions/session.py
cleanup()
¶
Start cleanup of every session resource, including async-only clients.
Async cleanup tasks are retained until the SessionManager claims them;
callers that need completion should use :meth:aclose.
Source code in src/agora_workbench/code_execution/sessions/session.py
aclose()
async
¶
Attempt all asynchronous cleanup steps, then report aggregated failures.
Source code in src/agora_workbench/code_execution/sessions/session.py
take_cleanup_tasks()
¶
Transfer ownership of sync-scheduled cleanup tasks to the manager.
Source code in src/agora_workbench/code_execution/sessions/session.py
claim_session_file_cleanup()
¶
Remove the owned session file before its session ID can be reused.
Source code in src/agora_workbench/code_execution/sessions/session.py
Session Manager¶
agora_workbench.code_execution.sessions.manager.SessionManager(config=None, kernel_name='tools-py')
¶
Manages the lifecycle of code-execution sessions and their Jupyter kernels.
Responsibilities include session creation, retrieval, timeout-based cleanup,
kernel provisioning (one AsyncKernelManager per session), background-job
tracking, and artifact registration for the /artifacts download endpoint.
Thread-safety is provided by an internal RLock for session-lifecycle
mutations and per-session asyncio.Lock instances for kernel access.
Source code in src/agora_workbench/code_execution/sessions/manager.py
set_kernel_network_mode(kernel_network_mode)
¶
Change the launch policy only when no kernel can retain the old policy.
Source code in src/agora_workbench/code_execution/sessions/manager.py
create_session(data, user_identity, user_token, token_claims, metadata=None, session_id=None)
¶
Create a new session and return its ID.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
Any
|
The data/object to store in the session |
required |
user_identity
|
str
|
User identity (Entra ID, email, etc.) |
required |
user_token
|
str
|
User's bearer token for authentication |
required |
metadata
|
Optional[dict]
|
Optional metadata dict |
None
|
session_id
|
Optional[str]
|
Optional custom session ID (default: UUID) |
None
|
token_claims
|
dict
|
Cached JWT claims for the user token. Stored on the session so that background tasks can restore the full auth context without re-validating the token. |
required |
Returns:
| Type | Description |
|---|---|
str
|
Session ID string |
Note
When SessionConfig.data_manager_factory is configured it is
invoked here, once per session, and the resulting manager is passed
to the Session. The session owns it and cleans it up.
Raises:
| Type | Description |
|---|---|
MaxSessionsReachedError
|
If the session limit has been reached. |
TypeError
|
If a configured |
Source code in src/agora_workbench/code_execution/sessions/manager.py
337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 | |
get_session(session_id)
¶
Get a session by ID, updating its access time.
Returns:
| Type | Description |
|---|---|
Session
|
Session object |
Raises:
| Type | Description |
|---|---|
ValueError
|
If session not found or expired |
Source code in src/agora_workbench/code_execution/sessions/manager.py
update_session(session_id, session)
¶
Update an existing session.
Source code in src/agora_workbench/code_execution/sessions/manager.py
update_status(session_id, status)
¶
Update the status of a session.
Source code in src/agora_workbench/code_execution/sessions/manager.py
close_session(session_id)
¶
Explicitly close a session.
Attempts to clean up resources first. If cleanup fails, the session is still deleted to prevent session accumulation, but the error is logged.
Kernel teardown is asynchronous. This method schedules it and returns
the task, so the session is removed from storage immediately but its
kernel process may still be running when the call returns. Callers that
need the kernel's resources actually released — GPU memory, for
instance — should use :meth:aclose_session instead, or await the
returned task.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
session_id
|
str
|
ID of the session to close |
required |
Returns:
| Type | Description |
|---|---|
Optional[Task[None]]
|
The teardown task, or |
Optional[Task[None]]
|
down or no running event loop to schedule it on. |
Source code in src/agora_workbench/code_execution/sessions/manager.py
rollback_factory_resources(data_manager, extensions)
¶
Roll back resources from a factory result that cannot be retained.
Source code in src/agora_workbench/code_execution/sessions/manager.py
await_resource_cleanup()
async
¶
Wait for all async cleanup started by synchronous session closure.
Source code in src/agora_workbench/code_execution/sessions/manager.py
aclose_session(session_id, *, expected_generation=None, expected_closing_session=None)
async
¶
Close a session and wait for its kernel to actually shut down.
The awaitable counterpart to :meth:close_session. Prefer this
wherever the kernel's resources must be released before proceeding —
freeing GPU memory, tearing down a batch's child sessions, or
reclaiming capacity before starting new work.
Source code in src/agora_workbench/code_execution/sessions/manager.py
aclose_all_sessions()
async
¶
Close every active session and wait for all kernel/resource teardown.
Source code in src/agora_workbench/code_execution/sessions/manager.py
954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 | |
get_kernel_generation(session_id)
¶
Return the generation id of the session's current kernel.
Generation ids are globally unique and monotonically increasing across the lifetime of this manager: restarting a session's kernel always yields a strictly greater id, and an id is never reused. Callers can therefore cache per-kernel state keyed on this value and detect a rebuilt kernel by comparing against the value they captured.
Returns None when the session has no live kernel.
Source code in src/agora_workbench/code_execution/sessions/manager.py
is_kernel_bootstrapped(session_id, key)
¶
Whether key has been completed against the session's current kernel.
Returns False when the session has no kernel, or when its kernel
has been rebuilt since the bootstrap step ran.
Source code in src/agora_workbench/code_execution/sessions/manager.py
mark_kernel_bootstrapped(session_id, key)
¶
Record that key has been completed against the current kernel.
Returns False (and records nothing) when the session has no live
kernel, so the caller's work will be retried against the next one.
Source code in src/agora_workbench/code_execution/sessions/manager.py
get_artifact_record(session_id, token)
¶
Look up an artifact for the download endpoint.
Returns None for unknown sessions/tokens and for tokens whose
backing file has been removed — both surface as 404 at the HTTP
layer.
Source code in src/agora_workbench/code_execution/sessions/manager.py
find_artifact_by_name(session_id, artifact_name)
¶
Find a registered artifact by its relative name within a session.
Looks up a previously registered artifact (i.e. one that was discovered during a snapshot-diff after an execute) by its relative filename. This is used by the publish pipeline to resolve the local path of an artifact before pushing it to remote storage.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
session_id
|
str
|
The session that owns the artifact. |
required |
artifact_name
|
str
|
Relative filename as registered (e.g. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
The |
Optional[_ArtifactRecord]
|
class: |
Optional[_ArtifactRecord]
|
exists, otherwise |
Source code in src/agora_workbench/code_execution/sessions/manager.py
start_background_execution_for_session(session_id, code, timeout, working_dir=None)
async
¶
Start execution and return immediately with a background job id.
Source code in src/agora_workbench/code_execution/sessions/manager.py
start_promoted_execution_for_session(session_id, code, timeout, promotion_threshold_s, working_dir=None)
async
¶
Execute code synchronously, promoting to a background job if it exceeds the threshold.
Starts executing like the normal foreground path. If the kernel reaches
idle within promotion_threshold_s seconds the result is returned
as a (stdout, stderr, success, displays, artifacts) tuple — identical
to :meth:execute_code_for_session. If the threshold expires while the
kernel is still busy, the in-flight execution is registered as a
:class:_BackgroundJob and a job-handle dict is returned instead.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
session_id
|
str
|
Session identifier. |
required |
code
|
str
|
Python code to execute. This method applies the outputs and token preambles internally (same as the foreground path), so callers should pass the raw user code — not pre-preambled. |
required |
timeout
|
float
|
Total execution timeout in seconds. |
required |
promotion_threshold_s
|
float
|
Seconds to wait before promoting. |
required |
working_dir
|
Optional[str]
|
Optional working directory for the kernel. |
None
|
Returns:
| Type | Description |
|---|---|
Tuple[str, str, bool, list[dict], list[dict]] | dict[str, Any]
|
Either the 5-tuple |
Tuple[str, str, bool, list[dict], list[dict]] | dict[str, Any]
|
when the execution completes within the threshold, or a dict with |
Tuple[str, str, bool, list[dict], list[dict]] | dict[str, Any]
|
|
Source code in src/agora_workbench/code_execution/sessions/manager.py
check_background_job(job_id, caller_identity=None)
¶
Return current status/output for a background job.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
job_id
|
str
|
Background job identifier. |
required |
caller_identity
|
Optional[str]
|
When provided, the caller's user identity is compared to
the identity that submitted the job. Both a missing job and an identity
mismatch raise |
None
|
Source code in src/agora_workbench/code_execution/sessions/manager.py
await_background_job(job_id)
async
¶
Wait for a background job's task to reach a terminal state, then return its status.
Returns None if the job was never registered or has already been purged.
Used by the activity publisher to emit job_finished events; callers must
treat exceptions on the underlying task as terminal (a failed task still
leaves _BackgroundJob.status set by _collect_background_job).
Source code in src/agora_workbench/code_execution/sessions/manager.py
session_resource_operation(session_id)
¶
Keep session-owned data resources alive for one admitted operation.
Source code in src/agora_workbench/code_execution/sessions/manager.py
execute_code_for_session(session_id, code, timeout, working_dir=None)
async
¶
Execute code in the session's Jupyter kernel.
Concurrent calls for the same session_id are serialized by a
per-session asyncio.Lock so they cannot race on the shared
Jupyter KernelClient iopub stream.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
session_id
|
str
|
Session identifier |
required |
code
|
str
|
Python code to execute |
required |
timeout
|
float
|
Execution timeout in seconds |
required |
working_dir
|
Optional[str]
|
Optional working directory for kernel |
None
|
Returns:
| Type | Description |
|---|---|
str
|
Tuple of |
str
|
|
bool
|
with MIME type, data, and metadata fields. |
list[dict]
|
metadata for each new or modified file under the session output |
list[dict]
|
directory, including its name, size, MIME type, modification time, |
Tuple[str, str, bool, list[dict], list[dict]]
|
and download token. |
Source code in src/agora_workbench/code_execution/sessions/manager.py
await_kernel_shutdown(session_id)
async
¶
Wait for any in-flight teardown of this session's kernel to finish.
No-op when none is running. Shielded, so a cancelled caller does not cancel the teardown itself; failures are already reported by the done-callback, so awaiting is purely for sequencing.
Source code in src/agora_workbench/code_execution/sessions/manager.py
cleanup_idle_kernels(max_idle_time=3600.0)
async
¶
Cleanup kernels that have been idle for too long.
Source code in src/agora_workbench/code_execution/sessions/manager.py
list_sessions()
¶
List all active sessions with metadata.
Returns:
| Type | Description |
|---|---|
list[dict[str, Any]]
|
List of session info dicts |
Source code in src/agora_workbench/code_execution/sessions/manager.py
Session Configuration¶
agora_workbench.code_execution.sessions.manager.SessionConfig(max_sessions=100, timeout_minutes=30, cleanup_interval_seconds=300, storage_backend=None, data_manager_factory=None, kernel_network_mode='inherit')
¶
Configuration for session manager.
Initialize session manager configuration.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
max_sessions
|
int
|
Maximum number of concurrent sessions. |
100
|
timeout_minutes
|
int
|
Idle time after which a session is cleaned up. |
30
|
cleanup_interval_seconds
|
int
|
Minimum interval between cleanup sweeps. |
300
|
storage_backend
|
Optional[SessionStorageBackend]
|
Optional session storage backend. |
None
|
data_manager_factory
|
Optional[Callable[[SessionContext], DataLakeDataManager | SessionResources]]
|
Optional callable invoked once per session to
build its :class: The factory must return a fresh data manager or
:class: When omitted, each session builds a default
A factory that returns |
None
|
kernel_network_mode
|
Literal['inherit', 'isolated']
|
|
'inherit'
|