Skip to content

fix(agent): give task trace correlations a complete lifecycle (issue #228) - #380

Open
konlue wants to merge 4 commits into
agentic-ai-java:mainfrom
konlue:fix/issue228-task-trace-correlation-lifecycle
Open

konlue wants to merge 4 commits into
agentic-ai-java:mainfrom
konlue:fix/issue228-task-trace-correlation-lifecycle

Conversation

@konlue

@konlue konlue commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

Describe what this PR does / why we need it

Issue #228 reports that TaskTraceCorrelation — the in-memory store linking the TaskTool delegation site to the TaskOutputTool receive site of background tasks — has no lifecycle at all: it has a forget method with zero production callers, entries are recorded before the repository submission so a rejection strands the record, and the map grows without bound. This PR gives the store a three-layer lifecycle and adds regression tests for the rejection, terminal-delivery, running-task and repository-lifecycle paths.

Root cause

TaskTool.apply records the correlation facts before calling taskRepository.putTask unguarded, so a rejected submission — the bounded repository throws RejectedExecutionException on full capacity, a duplicate task id or a closed repository — leaves a stranded record that nothing ever removes. On the happy path, TaskOutputTool returns terminal results without releasing the entry either, and the store itself has no retention, so with the default repository (which has no capacity or TTL at all) entries accumulate for the life of the process.

The fix

Three layers, all inside the tools/task package, plus one repository hook. First, TaskTool wraps putTask in a try/catch and rolls the record back with forget before rethrowing, which covers every rejection mode of the bounded repository plus executor submission failures; the record-then-submit ordering already guarantees the task cannot start before its correlation exists. Second, retention follows the task instead of the submission: a recorded entry has no expiry while its task runs, and the delegation site calls refresh when the task finishes, so the window is measured from completion and a task that runs longer than the retention keeps its delegation link for the first poll. Polls of a completed entry slide the window, correlation() never serves an expired completed entry, and record()/forget() lazily sweep those entries, so the store converges without a janitor thread; running entries are never swept by intervening submissions or polls. Third, no sweep can observe a task that leaves the repository through removeTask, clear, clearCompletedTasks, shutdown or the bounded repository's close, so TaskRepository gains a default addLifecycleListener(TaskLifecycleListener): both implementations notify listeners with the affected task ids outside their monitors, and both TaskTool and TaskOutputTool register the shared store itself as the listener, so any number of tool builds sharing one store add exactly one registration and a tool-private store (no receive-site reader) adds none. An idle shared store therefore drops removed, cleared or shut-down tasks immediately instead of retaining them until the next poll; retention now only has to cover results that leave the repository through internal expiry.

Three follow-up review findings are folded into the same lifecycle. The not-found branch of the receive tool releases the correlation only when an unfiltered lookup also finds nothing, so a tenant-filtered miss never deletes another tenant's correlation. The completion refresh is driven by the task's terminal callback (BackgroundTask.whenComplete on the underlying future) rather than the supplier body, so a task cancelled while it is still queued — whose supplier never runs — still gets a retention deadline instead of staying active forever. Lifecycle listeners deduplicate by store instance in both repositories through addIfAbsent.

Testing

The TaskTraceCorrelationLifecycleTest drives retention with a mutable clock: a completed entry is never served after its window and is swept by the next record, a completed entry slides on polls and lapses when idle, a running entry survives the retention window plus intervening record/poll/refresh/forget traffic (and an eight-thread concurrent record/poll/refresh/forget loop), forgetAll releases only the given ids, and forget stays idempotent. The new TaskTraceCorrelationRepositoryLifecycleTest asserts cleanup without any subsequent poll: removeTask, clear and shutdown on the default repository and removeTask, clear and close on the bounded repository release the correlations, both tools wire the listener, a tenant-filtered miss keeps the owner's correlation, repeated tool builds share one registration on both repositories, and a tool-private store registers none. TaskToolTraceCorrelationTests covers the tool chain: a 31-minute task keeps its link for the first poll after completion, a poll of an unknown task sweeps expired completed entries, a capacity-full bounded repository rejects the background submission with RejectedExecutionException and leaves zero retained records, a poll of a removed task releases its correlation, and a task cancelled while queued behind a busy worker expires after the retention window. The task package is 95 tests green, and checkstyle plus spotless are clean.

Fixes #228

@konlue

konlue commented Nov 21, 2026

Copy link
Copy Markdown
Contributor Author

Note on the failing build job: it fails in pnpm --dir argi-studio/agent-chat-ui audit --prod, which queries the vulnerability database live. This surfaced today — the same step passed on main on 2026-11-19 (run 44558278320) and fails identically on the unrelated #370 branch (run 44882915599), while every Java-side job (test, check-style, format, license, linter, secret) is green on this PR. It is the studio UI's dependency disclosure, not this change; the lockfile fix belongs to the argi-studio maintainers.

@konlue
konlue force-pushed the fix/issue228-task-trace-correlation-lifecycle branch from 09c7700 to aeb62a5 Compare November 21, 2026 08:41

@yuluo-yx yuluo-yx left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Two lifecycle gaps remain:

  1. Retention expires 30 minutes after submission even while a task is running or its result remains pollable. A task finishing after 31 minutes loses its delegation link before the first result poll; deleting on the first terminal poll also removes the link for subsequent polls. Align correlation retention with the supported task/result lifetime and test the receive-span links.
  2. Repository remove/clear/shutdown never clears correlations. Expiry only runs on record() or lookup of that same task, so an idle shared store retains cleared tasks indefinitely. Add cleanup tied to those lifecycle events and verify convergence without another submission.

@konlue
konlue force-pushed the fix/issue228-task-trace-correlation-lifecycle branch from aeb62a5 to d2e3242 Compare November 22, 2026 15:09
@konlue

konlue commented Nov 22, 2026

Copy link
Copy Markdown
Contributor Author

@yuluo-yx Fixed and pushed (d2e3242, branch rebased onto the current main first — it carries the merged #215 work cleanly).

Gap 1 — retention anchored to the task and result lifetime: the delegation site now re-anchors the retention when the background task finishes (refresh(taskId) in the task closure, unconditionally — even a submission-anchored window that already lapsed is re-anchored by the completion), so a 31-minute task no longer loses its link before the first poll. Terminal outcomes no longer drop the entry: every lookup slides the window forward, so a later poll still establishes the same receive-span link, and an entry that is never polled again converges after one idle retention window.

Gap 2 — repository lifecycle convergence: forget() now sweeps expired entries across the whole store on every release event, and the not-found poll branch of TaskOutputTool calls it, so a repository removal, clear or shutdown reported through a poll converges the shared store without any new submission; lookups sweep too, so any touch of the store converges it. No repository listener API was added — the release events flow through the existing polling path.

Regression coverage: the 31-minute task now keeps its link on the second poll (red before: the second receive span had no delegation link); a terminal poll keeps the correlation so a second poll still links (red before: it was dropped); polling an unknown task sweeps every expired entry without a new submission (red before: stranded); polling a removed task releases its correlation (red before: stranded). The retention tests now assert the sliding-window semantics explicitly, and the task package is 39/39 green with checkstyle and format clean.

@yuluo-yx yuluo-yx left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Two lifecycle gaps remain:

  1. A 31-minute running task is swept by any intervening record()/poll; completion refresh() cannot recreate the deleted entry, so result polls permanently lose the delegation link. Retain active-task correlations and test concurrent store traffic.
  2. Repository remove/clear/shutdown still trigger no cleanup unless another poll occurs. An idle shared store therefore retains those entries indefinitely. Connect cleanup to repository lifecycle events and test without subsequent polling.

@konlue

konlue commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor Author

@yuluo-yx Fixed and pushed (de275aa, rebased onto the current branch head after the main merge). Both gaps are closed at the store and at the repository boundary.

Gap 1 — running tasks were swept. An entry recorded at delegation has no expiry while its task runs; only the delegation site's completion refresh() starts the retention window, so it is measured from completion rather than submission. sweepExpired() skips active entries, which means any intervening record() or poll can only remove completed entries, and refresh() deliberately does not recreate an absent entry so a repository removal still wins over a late completion. Coverage: a running entry survives the retention window plus intervening record/poll/refresh/forget traffic, and an eight-thread concurrent record/poll/refresh/forget loop leaves the running link intact.

Gap 2 — cleanup waited for a poll. TaskRepository gains a default addLifecycleListener(TaskLifecycleListener). The default repository notifies it from removeTask, clear, clearCompletedTasks and shutdown; the bounded repository notifies it from removeTask, clear and close, outside its monitor. Both TaskTool and TaskOutputTool register the shared store as a listener, so an idle store drops removed, cleared or shut-down tasks immediately instead of waiting for the next poll. Coverage: remove/clear/shutdown on the default repository and remove/clear/close on the bounded repository release the correlations, asserted without any subsequent poll, plus the TaskTool wiring.

Verification: the task package is 91 tests green (TaskTraceCorrelationLifecycleTest 6, new TaskTraceCorrelationRepositoryLifecycleTest 5, TaskToolTraceCorrelationTests 11), and checkstyle plus spotless are clean on the rebased head.

@yuluo-yx yuluo-yx left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

TaskOutputTool.java:103: a tenant-filtered miss can delete another tenant trace correlation. TaskTool.java:141: cancelling queued tasks skips refresh and leaves correlations without expiry. TaskTool.java:108: every tool build permanently adds listeners retaining its correlation store; add deregistration or reuse one registration.

…gentic-ai-java#228)

TaskTraceCorrelation recorded entries at the TaskTool delegation site
before taskRepository.putTask, so a rejected submission (bounded
repository capacity, duplicate id, closed repository) stranded the
record forever; and nothing in production ever called forget, so even
happy-path entries outlived their tasks and the map grew without bound.

The correlation now has a three-layer lifecycle: TaskTool rolls the
record back when putTask throws; TaskOutputTool releases the entry once
a terminal (completed or failed) result has been delivered - after the
receive span was linked, never before, so the polling window keeps
working and non-terminal outcomes (still-running, timeout, interrupted)
retain the entry for the next poll; and a retention window with an
injectable clock lazily sweeps whatever survives, independent of the
repository type, so default, bounded and injected repositories all
converge without new repository lifecycle APIs.

Tests: a capacity-rejected submission leaves zero retained records; a
terminal poll releases the correlation while the repository result stays
pollable; expired entries are never served and swept on the next record;
forget stays idempotent.
…time (issue agentic-ai-java#370 review)

Two lifecycle gaps: a task finishing after the retention window lost its
delegation link before the first result poll (retention was anchored at
submission), and a terminal poll dropped the link for later polls; and
repository removal, clear or shutdown never released correlations, so an
idle shared store kept them indefinitely.

The delegation site now re-anchors the retention when the background
task finishes (refresh() in the task closure), reads slide the window
forward, terminal outcomes keep the entry so every later poll can still
link, and forget() sweeps expired entries so repository removal, clear,
shutdown and not-found polls converge the whole store without a new
submission. Tests drive the 31-minute task, the repeated-poll links,
the no-submission sweep and the removed-task release.
…itory lifecycle (issue agentic-ai-java#370 review)

A running task's correlation no longer expires with the submission window:
only completion refresh starts retention, so intervening record/poll traffic
cannot sweep a live delegation link. Task repositories now report removals,
clears and shutdown through a lifecycle listener that releases the shared
correlations immediately, without waiting for another poll.
…e lifecycle listeners (issue agentic-ai-java#370 review)

Tenant-filtered polls only release a correlation when the task is truly absent;
cancelled queued tasks start their retention window through the task's terminal
callback; the store registers itself once per repository so repeated tool builds
do not accumulate listeners.
@konlue
konlue force-pushed the fix/issue228-task-trace-correlation-lifecycle branch from de275aa to 10adebf Compare December 2, 2026 12:16
@konlue

konlue commented Dec 2, 2026

Copy link
Copy Markdown
Contributor Author

@yuluo-yx Fixed and pushed (10adebf, rebased onto the current main so the durable-delegation guard from #716d55bc0 applies cleanly).

Tenant-filtered miss. The not-found branch of TaskOutputTool now releases the correlation only when an unfiltered getTask(taskId) also finds nothing. A miss caused by the caller's tenant hiding another tenant's task leaves that task's correlation untouched. Regression: a task owned by tenant-b polled from tenant-a still gets the hidden-task error while its correlation stays readable.

Cancelled queued tasks. refresh moved from the supplier's finally to the task's terminal callback (BackgroundTask.whenComplete, backed by the repository future). A task cancelled while still queued never runs its supplier, but cancellation now fires the callback, so the entry gets a retention deadline instead of staying active forever. Regression: a delegated task queued behind a busy single worker is cancelled, the clock advances past the window, and the entry is no longer served (red before: it was still active and never expired).

Listener accumulation. TaskTraceCorrelation is now the TaskLifecycleListener itself and both built-in repositories register it with addIfAbsent, so any number of tool builds sharing one store add exactly one registration; a store created privately by a TaskTool (caller passed no store) is not registered at all because it has no receive-site reader. Regressions assert one registration for repeated TaskTool/TaskOutputTool builds on both repositories and zero for a private store.

Verification on the rebased head: the task package is 95 tests green (TaskToolTraceCorrelationTests 12, TaskTraceCorrelationLifecycleTest 6, TaskTraceCorrelationRepositoryLifecycleTest 8, plus the pre-existing task suites), and checkstyle plus spotless are clean. CI is re-running on the new head; the PR body's change size will be updated if it shifts again.

@konlue konlue closed this Dec 2, 2026
@konlue konlue reopened this Dec 2, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[BUG] 为任务追踪关联记录补齐提交回滚与保留期清理

2 participants