Class JobContext<T>
- Type Parameters:
T- the type of result this job produces
- All Implemented Interfaces:
Identifiable
- Since:
- 0.1 (2025-08-11)
- Author:
- Andrey Santrosyan
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic classThe runtime's cancellation signal: thrown bycheckCancellation()inside a running job, raised by the dispatcher for a job cancelled before it started or one that finished without observing its cancel, and wrapped byJobCancelledExceptionon the way to the caller.static classCancellation token for cooperative cancellation. -
Constructor Summary
ConstructorsConstructorDescriptionJobContext(Job<T> job, String userId, Duration timeout, JobRequirements requirements) Creates a new job context. -
Method Summary
Modifier and TypeMethodDescriptionvoidaddLlmResponse(LLMResponse<?> response) Adds an LLM response to this context.<D> List<D> Gets all dependency results as a typed list.voidcancel()Marks the operation as cancelled.voidThrows CancellationException if job has been cancelled.voidClears the accumulated LLM responses to release memory.static JobContext<?> The context of the job executing on the current thread - any kind, resource-free orchestrators included - or null on a thread running no job (an entry point).Gets all metadata as a copy.static JobContext<?> Gets the currently executing job context for this thread.Gets the dependencies for this job.Gets exceptions from failed dependency jobs.Gets the results from completed dependency jobs.Gets elapsed execution time.getError()getJob()getJobId()Gets the job ID.List<LLMResponse<?>> The LLM responses this job has recorded so far, while it runs: a copy, for the job itself and whoever observes it mid-flight.getMetadata(String key) Gets a metadata value.Gets the parent job ID if this job was spawned by another job.intGets remaining time before timeout.Gets the current job snapshot with metadata attached.getState()Gets the current job state.Get the user ID who submitted the job.Gets the workflow ID that groups all jobs in this workflow tree.booleanChecks if the job has been cancelled.booleanstatic booleanChecks if the current thread is executing a job.static booleanChecks if the current thread is executing a job that holds resources.booleanChecks if execution has exceeded timeout.booleanChecks if cooperative termination phase has been signaled.voidRegisters a callback to be executed once when the job is cancelled.voidRegisters a callback to be executed once on timeout.voidPublishes any JobEvent to the message bus.<P> voidpublish(P data) Publishes data to the message bus.<P> voidpublish(P data, int percent) Publishes data with progress information.voidpublishUserNotification(UserNotificationEvent.Severity severity, String title, String message) Publishes a user-facing notification event.voidpublishUserProgress(String title, String message, int percent) Publishes a user-facing progress event.voidputMetadata(String key, Object value) Stores a metadata value.voidrecordAdmissionWait(long waitTimeMs) Records the wall-clock time from entering admission to being granted, summed over the job's attempts.voidrecordResourceWait(String resourceName, long waitTimeMs) Records time an account kept this job waiting in admission.voidsetDependencies(Collection<JobHandle<?>> deps) Sets the dependencies for this job.voidSignals cooperative termination phase during timeout enforcement.<D> DGets the single dependency result, cast to the expected type.
-
Constructor Details
-
JobContext
Creates a new job context.- Parameters:
job- the job to executeuserId- the user who submitted the job; a null or blank id is refused withIllegalArgumentException, since every job runs on behalf of a principaltimeout- maximum execution timerequirements- the dispatcher's submit-time requirements capture - passed in rather than re-invoked here, because every getRequirements() call mints fresh model bindings and the dispatcher owns the one-capture-at-submit, one-per-attempt discipline
-
-
Method Details
-
publish
public <P> void publish(P data) Publishes data to the message bus.Heartbeat control values are intercepted BEFORE the progress wrap - a
ScheduleHeartbeatbecomes a framework-mintedHeartbeatcarrying this context's identity and the publishing orchestrator's sealed guard (the publisher never touches either), and aCancelHeartbeatrides as itself. Neither mints a progress event. Scheduling is deferred submission, so it mirrors the submission door's first wall: a non-orchestrator cannot schedule.- Type Parameters:
P- the type of the payload data- Parameters:
data- the data to publish
-
publish
public <P> void publish(P data, int percent) Publishes data with progress information.- Type Parameters:
P- the type of the payload data- Parameters:
data- the data to publishpercent- progress percentage (0-100)
-
publishUserProgress
Publishes a user-facing progress event. Convenience method to reduce boilerplate for user notifications.- Parameters:
title- short title (included in message for context)message- user-friendly messagepercent- progress percentage (0-100)
-
publishUserNotification
public void publishUserNotification(UserNotificationEvent.Severity severity, String title, String message) Publishes a user-facing notification event.- Parameters:
severity- the severity level (info, success, warning, error)title- short title for the notificationmessage- the notification message
-
publish
Publishes any JobEvent to the message bus. Generic method for publishing any event type.- Parameters:
event- the event to publish
-
isCancelled
public boolean isCancelled()Checks if the job has been cancelled. Jobs should periodically check this and terminate gracefully.- Returns:
- true if cancelled
-
checkCancellation
Throws CancellationException if job has been cancelled.- Throws:
JobContext.CancellationException- if cancelled
-
isTimedOut
public boolean isTimedOut()Checks if execution has exceeded timeout.- Returns:
- true if timed out
-
isTimeoutSignaled
public boolean isTimeoutSignaled()Checks if cooperative termination phase has been signaled.- Returns:
- true if timeout signaled
-
onTimeout
Registers a callback to be executed once on timeout. A callback registered after the deadline runs immediately, once: either as part of the first timeout observation, which runs every registered callback, or on its own when that observation already happened. Registration and firing share one monitor, so a callback is in the fired list or is run here, never both and never neither. A completed job never times out, so a callback registered once the job has completed is dropped, not queued.- Parameters:
callback- the timeout callback
-
onCancel
Registers a callback to be executed once when the job is cancelled. A callback registered after cancellation runs immediately, once: either in the firing that the cancellation is about to perform, when it is registered while that cancellation is under way, or here. Registration and firing share one monitor, so a callback is in the fired list or is run here, never both and never neither.- Parameters:
callback- the cancel callback
-
getElapsedTime
-
getRemainingTime
Gets remaining time before timeout.- Returns:
- remaining duration, or null if the job has no deadline (orchestrators)
-
getState
Gets the current job state. Returns the state from the snapshot - the single source of truth. State transitions happen explicitly via setState() in the dispatcher.- Returns:
- current job state
-
getJob
-
getJobId
Gets the job ID.- Specified by:
getJobIdin interfaceIdentifiable- Returns:
- the job ID
-
getParentJobId
Gets the parent job ID if this job was spawned by another job.- Specified by:
getParentJobIdin interfaceIdentifiable- Returns:
- the parent job ID, or null for root jobs
-
getWorkflowId
Gets the workflow ID that groups all jobs in this workflow tree.- Specified by:
getWorkflowIdin interfaceIdentifiable- Returns:
- the workflow ID
-
getUserId
Get the user ID who submitted the job.- Specified by:
getUserIdin interfaceIdentifiable- Returns:
- the user ID
-
getExecutionId
-
getStartTime
-
getProgressPercent
public int getProgressPercent() -
getProgressMessage
-
cancel
public void cancel()Marks the operation as cancelled. -
signalTimeout
public void signalTimeout()Signals cooperative termination phase during timeout enforcement. Sets both timeout and cancellation flags for job to detect. -
isCompleted
public boolean isCompleted() -
getResult
-
getError
-
getSnapshot
Gets the current job snapshot with metadata attached. Returns an immutable snapshot of the job's identity, state, and current metadata.- Returns:
- immutable job snapshot
-
setDependencies
Sets the dependencies for this job.- Parameters:
deps- collection of JobHandles this job depends on
-
getDependencies
-
getDependencyResults
Gets the results from completed dependency jobs.Dependencies are guaranteed to be completed before this job executes. The JobDispatcher waits for all dependencies to finish, extracts their results, and passes them to this job via the context. This eliminates the need for jobs to call blocking
handle.get()methods, preventing deadlock scenarios.Results are indexed by the final
JobSnapshotof each dependency job, which provides rich metadata including:- Job ID and class name
- Completion timestamp
- Execution duration
- Job-specific metadata
Usage Examples:
// Single dependency - get first result Map<JobSnapshot, Object> results = context.getDependencyResults(); MyData data = (MyData) results.values().iterator().next(); // Multiple dependencies - identify by job class for (Map.Entry<JobSnapshot, Object> entry : results.entrySet()) { if (entry.getKey().jobClass().equals(ExtractDataJob.class)) { Data data = (Data) entry.getValue(); // Use data } } // Check for failed dependencies (if toleratesDependencyFailures=true) for (Object result : results.values()) { if (result == null) { // Dependency failed, handle gracefully } }- Returns:
- unmodifiable map from job snapshot to result object. Empty if no dependencies.
Results are
nullfor failed dependencies whentoleratesDependencyFailures=true. - See Also:
-
getDependencyErrors
Gets exceptions from failed dependency jobs.This map is only populated when
toleratesDependencyFailures=trueand provides access to the actual exceptions thrown by failed dependencies.Jobs can use this information to make informed decisions about how to handle partial failures. For example, a job might proceed if only 2 out of 10 dependencies failed, or take different actions based on the exception type.
Usage Example:
// Check if any dependencies failed Map<JobSnapshot, Throwable> errors = context.getDependencyErrors(); if (!errors.isEmpty()) { for (Map.Entry<JobSnapshot, Throwable> entry : errors.entrySet()) { JobSnapshot snapshot = entry.getKey(); Throwable error = entry.getValue(); log.warn("Dependency {} failed: {}", snapshot.jobId(), error.getMessage()); } }- Returns:
- unmodifiable map from job snapshot to exception. Empty if no dependencies failed.
- See Also:
-
singleDependencyResult
public <D> D singleDependencyResult()Gets the single dependency result, cast to the expected type.Convenience method for jobs with exactly one dependency. The type is inferred from the assignment target, eliminating the need for explicit casting.
Usage Example:
// Type inferred from assignment Summary result = context.singleDependencyResult();- Type Parameters:
D- the dependency result type (inferred from assignment)- Returns:
- the dependency result, cast to type D
- Throws:
IllegalStateException- if there are zero or multiple dependencies
-
allDependencyResults
Gets all dependency results as a typed list.Convenience method for jobs with multiple dependencies of the same type. Results are returned in the order dependencies were declared. The type is inferred from the assignment target.
Usage Example:
// Type inferred from assignment List<ExtractionResult> results = context.allDependencyResults(); for (ExtractionResult result : results) { // Process each result (no casting needed) }- Type Parameters:
D- the dependency result type (inferred from assignment)- Returns:
- list of all dependency results in declaration order
-
addLlmResponse
Adds an LLM response to this context. Thread-safe.- Parameters:
response- the LLM response to add
-
getLlmResponses
The LLM responses this job has recorded so far, while it runs: a copy, for the job itself and whoever observes it mid-flight. Empty once the job has finished - the list is released before its handle completes (clearCompletionData()) - so a finished job's calls are read from its terminal event (TerminalEvent.getLlmResponses), never from here.- Returns:
- list of LLM responses
-
clearCompletionData
public void clearCompletionData()Clears the accumulated LLM responses to release memory. Called by the dispatcher when the job finishes, after its terminal events have been published (they carry their own copy) and before its handle completes. -
putMetadata
-
getMetadata
-
getAllMetadata
-
recordResourceWait
Records time an account kept this job waiting in admission. Keyed by the account'sLimiterIdentity.limiterName()and summed per account; accounts overlap in time, so the values do not sum to the wall wait recorded byrecordAdmissionWait(long).- Parameters:
resourceName- the account's limiter name (a model's catalog id,"http","db:default")waitTimeMs- time the account was short for this job, in milliseconds
-
recordAdmissionWait
public void recordAdmissionWait(long waitTimeMs) Records the wall-clock time from entering admission to being granted, summed over the job's attempts. This is the job's total wait a recorder reports.- Parameters:
waitTimeMs- wall wait in milliseconds
-
isExecutingJob
public static boolean isExecutingJob()Checks if the current thread is executing a job.- Returns:
- true if currently inside job execution
-
isExecutingJobWithResources
public static boolean isExecutingJobWithResources()Checks if the current thread is executing a job that holds resources.- Returns:
- true if currently inside job execution with resources
-
currentJob
The context of the job executing on the current thread - any kind, resource-free orchestrators included - or null on a thread running no job (an entry point). The submission rules key on this. -
getCurrentExecution
Gets the currently executing job context for this thread.- Returns:
- the job context, or null if not executing a job
-