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)
¶
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()
¶
Cleanup session resources including session files.
Raises:
| Type | Description |
|---|---|
Exception
|
If cleanup fails, to allow calling code to handle the failure |
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
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
269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 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 | |
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.
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
aclose_session(session_id)
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
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
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 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 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 | |
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
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)
¶
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]]
|
Optional callable invoked once per session to
build its :class: The factory must return a fresh instance per call. The
session takes ownership of the manager and calls When omitted, each session builds a default
A factory that returns |
None
|