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
configure_kernel_environment(variables)
¶
Set framework-owned, non-secret environment values for future kernels.
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
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 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 | |
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
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 | |
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
1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 | |
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. A task that
raised or was cancelled (for example by close_session) is terminal: the
snapshot reflects the status recorded by the collector or by the canceller.
Cancelling this waiter does not cancel the underlying 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
ensure_kernel_for_session(session_id, working_dir=None)
async
¶
Ensure the session has a live kernel before checking kernel-local state.
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', 'seccomp']
|
|
'inherit'
|