Class JobContext<T>

java.lang.Object
ai.redouble.nucleo.harness.JobContext<T>
Type Parameters:
T - the type of result this job produces
All Implemented Interfaces:
Identifiable

public class JobContext<T> extends Object implements Identifiable
Runtime context for an executing job. Provides monitoring, control, and event publishing capabilities.
Since:
0.1 (2025-08-11)
Author:
Andrey Santrosyan
  • Constructor Details

    • JobContext

      public JobContext(Job<T> job, String userId, Duration timeout, JobRequirements requirements)
      Creates a new job context.
      Parameters:
      job - the job to execute
      userId - the user who submitted the job; a null or blank id is refused with IllegalArgumentException, since every job runs on behalf of a principal
      timeout - maximum execution time
      requirements - 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 ScheduleHeartbeat becomes a framework-minted Heartbeat carrying this context's identity and the publishing orchestrator's sealed guard (the publisher never touches either), and a CancelHeartbeat rides 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 publish
      percent - progress percentage (0-100)
    • publishUserProgress

      public void publishUserProgress(String title, String message, int percent)
      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 message
      percent - 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 notification
      message - the notification message
    • publish

      public void publish(JobEvent event)
      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

      public void checkCancellation() throws JobContext.CancellationException
      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

      public void onTimeout(Runnable callback)
      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

      public void onCancel(Runnable callback)
      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

      public Duration getElapsedTime()
      Gets elapsed execution time.
      Returns:
      duration since start
    • getRemainingTime

      public Duration getRemainingTime()
      Gets remaining time before timeout.
      Returns:
      remaining duration, or null if the job has no deadline (orchestrators)
    • getState

      public JobState 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

      public Job<T> getJob()
    • getJobId

      public String getJobId()
      Gets the job ID.
      Specified by:
      getJobId in interface Identifiable
      Returns:
      the job ID
    • getParentJobId

      public String getParentJobId()
      Gets the parent job ID if this job was spawned by another job.
      Specified by:
      getParentJobId in interface Identifiable
      Returns:
      the parent job ID, or null for root jobs
    • getWorkflowId

      public String getWorkflowId()
      Gets the workflow ID that groups all jobs in this workflow tree.
      Specified by:
      getWorkflowId in interface Identifiable
      Returns:
      the workflow ID
    • getUserId

      public String getUserId()
      Get the user ID who submitted the job.
      Specified by:
      getUserId in interface Identifiable
      Returns:
      the user ID
    • getExecutionId

      public String getExecutionId()
    • getStartTime

      public Instant getStartTime()
    • getProgressPercent

      public int getProgressPercent()
    • getProgressMessage

      public String 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

      public Optional<T> getResult()
    • getError

      public Optional<Throwable> getError()
    • getSnapshot

      public JobSnapshot 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

      public void setDependencies(Collection<JobHandle<?>> deps)
      Sets the dependencies for this job.
      Parameters:
      deps - collection of JobHandles this job depends on
    • getDependencies

      public List<JobHandle<?>> getDependencies()
      Gets the dependencies for this job.
      Returns:
      list of JobHandles this job depends on
    • getDependencyResults

      public Map<JobSnapshot, Object> 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 JobSnapshot of 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 null for failed dependencies when toleratesDependencyFailures=true.
      See Also:
    • getDependencyErrors

      public Map<JobSnapshot, Throwable> getDependencyErrors()
      Gets exceptions from failed dependency jobs.

      This map is only populated when toleratesDependencyFailures=true and 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

      public <D> List<D> 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

      public void addLlmResponse(LLMResponse<?> response)
      Adds an LLM response to this context. Thread-safe.
      Parameters:
      response - the LLM response to add
    • getLlmResponses

      public List<LLMResponse<?>> 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

      public void putMetadata(String key, Object value)
      Stores a metadata value.
      Parameters:
      key - the metadata key
      value - the metadata value
    • getMetadata

      public Object getMetadata(String key)
      Gets a metadata value.
      Parameters:
      key - the metadata key
      Returns:
      the metadata value, or null if not present
    • getAllMetadata

      public Map<String,Object> getAllMetadata()
      Gets all metadata as a copy.
      Returns:
      copy of all metadata
    • recordResourceWait

      public void recordResourceWait(String resourceName, long waitTimeMs)
      Records time an account kept this job waiting in admission. Keyed by the account's LimiterIdentity.limiterName() and summed per account; accounts overlap in time, so the values do not sum to the wall wait recorded by recordAdmissionWait(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

      public static JobContext<?> 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

      public static JobContext<?> getCurrentExecution()
      Gets the currently executing job context for this thread.
      Returns:
      the job context, or null if not executing a job