Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,12 @@ public String apply(Request request, ToolContext toolContext) {
BackgroundTask bgTask = this.taskRepository.getTask(request.taskId(), callerTenantId);

if (bgTask == null) {
// The task was removed, cleared or expired in the repository: release the
// correlation so an idle shared store converges without new submissions
// (#370 review gap 2).
if (this.traceCorrelation != null) {
this.traceCorrelation.forget(request.taskId());
}
return "Error: No background task found with ID: " + request.taskId();
}

Expand Down Expand Up @@ -150,6 +156,18 @@ else if (!bgTask.isCompleted()) {
}
}

/**
* Terminal outcomes no longer drop the correlation (issue #370 review): the receive
* span was linked above and every poll slides the retention forward through the
* lookup, so later polls can still establish the same link until the correlation
* expires unused.
*/
private void releaseCorrelation(String taskId) {
if (this.traceCorrelation != null) {
this.traceCorrelation.forget(taskId);
}
}

/**
* Start the receive span as a consumer; when the delegation context is known (fan-in
* or long-running waits), the span links back to the delegation id instead of
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,28 @@ public String apply(Request request, ToolContext toolContext) {
if (this.traceCorrelation != null && taskContext != null) {
this.traceCorrelation.record(taskId, taskContext);
}
this.taskRepository.putTask(taskId, () -> executeSubAgent(subAgent, prompt, parentConfig, taskContext));
try {
this.taskRepository.putTask(taskId, () -> {
try {
return executeSubAgent(subAgent, prompt, parentConfig, taskContext);
}
finally {
// The pollable result window is measured from completion, not
// submission: a long-running task must not lose its link before
// the first result poll (#370 review).
if (this.traceCorrelation != null) {
this.traceCorrelation.refresh(taskId);
}
}
});
}
catch (RuntimeException e) {
// A rejected submission must not leave a stranded correlation record.
if (this.traceCorrelation != null) {
this.traceCorrelation.forget(taskId);
}
throw e;
}
return String.format(
"task_id: %s%n%nBackground task started. Use TaskOutput tool with task_id='%s' to retrieve results.",
taskId, taskId);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,16 @@

package io.github.agentic.ai.agent.orchestration.tools.task;

import java.time.Clock;
import java.time.Duration;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;

import io.github.agentic.ai.workflow.graph.observation.trace.AgentTraceContext;

import org.springframework.util.Assert;

/**
* Shared, in-memory correlation store between the {@link TaskTool} delegation site and the
* {@link TaskOutputTool} receive site of background tasks.
Expand All @@ -31,43 +35,137 @@
* cannot be its child. Both sides instead reference the same {@link AgentTraceContext},
* whose delegation identifier becomes the span link key of the consumer. Entries are only
* recorded when an {@link AgentTracer} is enabled.
* <p>
* Entries have a three-layer lifecycle (issue #228): a rejected submission rolls the record
* back at the delegation site, a terminal polled result releases it at the receive site once
* the receive span has been linked, and the retention window below sweeps whatever survives
* (tasks nobody polls for, repository clear or shutdown). The retention is deliberately long
* relative to a polling window and independent of the repository type, so the default, the
* bounded and any injected repository all converge without the store needing repository
* lifecycle hooks; a live entry is never dropped early just to reclaim space.
*/
public final class TaskTraceCorrelation {

private final Map<String, AgentTraceContext> contextsByTaskId = new ConcurrentHashMap<>();
private final Map<String, StampedContext> contextsByTaskId = new ConcurrentHashMap<>();

private final Clock clock;

private final Duration retention;

public TaskTraceCorrelation() {
this(Clock.systemUTC(), Duration.ofMinutes(30));
}

/**
* @param clock the time source driving retention
* @param retention how long a recorded correlation may live without being consumed
*/
public TaskTraceCorrelation(Clock clock, Duration retention) {
Assert.notNull(clock, "clock must not be null");
Assert.notNull(retention, "retention must not be null");
Assert.isTrue(!retention.isNegative(), "retention must not be negative");
this.clock = clock;
this.retention = retention;
}

/** @return an empty correlation store */
public static TaskTraceCorrelation empty() {
return new TaskTraceCorrelation();
}

/**
* Record the correlation facts of a background delegation.
* Record the correlation facts of a background delegation. Expired entries are swept
* along the way so a store without consumers still converges to its live entries.
* @param taskId the background task id
* @param context the correlation facts captured at the delegation site
*/
public void record(String taskId, AgentTraceContext context) {
if (taskId != null && context != null) {
this.contextsByTaskId.put(taskId, context);
sweepExpired();
this.contextsByTaskId.put(taskId, new StampedContext(context, deadline()));
}
}

/**
* @param taskId the background task id
* @return the correlation facts recorded at the delegation site, if any
* @return the correlation facts recorded at the delegation site, if any; an expired
* entry is removed and never served. Any lookup also sweeps expired entries across
* the whole store, so convergence never depends on a new submission (#370 review).
*/
public Optional<AgentTraceContext> correlation(String taskId) {
return taskId == null ? Optional.empty() : Optional.ofNullable(this.contextsByTaskId.get(taskId));
if (taskId == null) {
return Optional.empty();
}
sweepExpired();
StampedContext stamped = this.contextsByTaskId.get(taskId);
if (stamped == null) {
return Optional.empty();
}
if (isExpired(stamped)) {
this.contextsByTaskId.remove(taskId, stamped);
return Optional.empty();
}
// Sliding retention: reading a live entry re-anchors its expiry, so the receive
// link of a still-pollable task result never lapses between polls.
StampedContext refreshed = new StampedContext(stamped.context(), deadline());
this.contextsByTaskId.replace(taskId, stamped, refreshed);
return Optional.of(refreshed.context());
}

/**
* Drop the correlation facts of a finished background task.
* Re-anchor the retention of a recorded entry, even one whose submission-anchored
* window has already lapsed (#370 review): the delegation site calls this when the
* background task finishes, so the pollable result window is measured from
* completion rather than submission and a long-running task keeps its link.
* @param taskId the background task id
*/
public void refresh(String taskId) {
if (taskId == null) {
return;
}
StampedContext stamped = this.contextsByTaskId.get(taskId);
if (stamped != null) {
this.contextsByTaskId.replace(taskId, stamped, new StampedContext(stamped.context(), deadline()));
}
}

/**
* Drop the correlation facts of a finished background task. Sweeping expired entries
* along the way ties the cleanup to every release event, so a repository removal,
* clear or shutdown reported through this call converges the whole store without a
* new submission (#370 review gap 2).
* @param taskId the background task id
*/
public void forget(String taskId) {
if (taskId != null) {
sweepExpired();
this.contextsByTaskId.remove(taskId);
}
}

/** Test observation point for the retention assertions. */
int retainedCount() {
return this.contextsByTaskId.size();
}

private void sweepExpired() {
this.contextsByTaskId.forEach((taskId, stamped) -> {
if (isExpired(stamped)) {
this.contextsByTaskId.remove(taskId, stamped);
}
});
}

private boolean isExpired(StampedContext stamped) {
return this.clock.instant().isAfter(stamped.expiresAt());
}

private java.time.Instant deadline() {
return this.clock.instant().plus(this.retention);
}

private record StampedContext(AgentTraceContext context, java.time.Instant expiresAt) {

}

}
Loading
Loading