Skip to content

fix(server-common): read and tap a subscribed task under the event bus lock - #1371

Open
joulook wants to merge 3 commits into
a2aproject:mainfrom
joulook:issue-1370
Open

joulook wants to merge 3 commits into
a2aproject:mainfrom
joulook:issue-1370

Conversation

@joulook

@joulook joulook commented Nov 30, 2026

Copy link
Copy Markdown
Contributor

Description

This change was found and re-checked with Daavar, a conformance checker we develop at MPI-SWS (https://github.com/joulook/daavar); the issue it fixes is #1370.

Change. MainEventBusProcessor gets a private monitor, held by processEvent from step 1 (persist the event) to the end of step 3 (distribute it to the children), so step 2 (the replication hook and push-notification scheduling) runs under it too, and a slow push scheduler now delays subscribes. A new public method, withEventProcessingPaused(Supplier), runs an action under the monitor; onSubscribeToTask runs its store read, not-found and terminal checks, tap and createOrTap fallback through it, unchanged (a private readAndTap); processEvent's step order is unchanged.

This closes both findings: an event is now persisted either before the read (the snapshot has it, and a terminal one makes the subscribe refused, as §3.1.6 requires) or distributed after the tap (it reaches the new child queue).

Both paths take the monitor before any queue or store lock; distribution uses the non-blocking offer. Code inside the section (a TaskStore, a replication hook or strategy, the lifecycle hook's onSubscribe/onUnsubscribe) must not wait for the bus. The monitor is per JVM: replicated multi-instance deployments are not covered.

Of the in-repo implementations (InMemoryTaskStore, JpaDatabaseTaskStore, InMemoryQueueManager, ReplicatedQueueManager with ReactiveMessagingReplicationStrategy, BasePushNotificationSender with both push-config stores, DefaultTaskStreamLifecycleHook, CloseStreamsHook), none waits for the bus or, with the default push executor, for I/O other than database round trips (with a synchronous executor, which setPushNotificationExecutor allows for tests, the HTTP sends run under the lock); third-party ones are not checked. With this change, a subscribe's task-store read and queue tap run while the event bus is paused, so with JpaDatabaseTaskStore each subscribe holds up the events of all tasks for one primary-key query (two if a stream lifecycle hook closes the task's last stream), next to the read and write the bus already does for each persisted task update. We have not measured this cost and can measure it on request. Alternatives: tapping first with a sequence filter, as a2a-rs does, needs a sequence that Task and the stores lack (a TaskStore contract, JPA schema and replication change, or an in-process cache like a2a-rs's). A per-task lock needs a registry whose cleanup never hands out two locks for one live task (cancelLocks removes its lock safely only because a cancelled task is terminal), and gains little: the bus is one loop, so once it reaches the subscribed task's event every task waits anyway. An optimistic read (sample a counter the bus bumps per event, read the store outside the lock, tap if the counter is unchanged, else retry) keeps the query out of the lock while the bus is quiet, but retries under load and needs a bound falling back to the locked read; we can offer it as a follow-up.

Tests. New SubscribeWindowTest (server-common, requesthandlers): eventPublishedBetweenReadAndTap_reachesSnapshotOrStream and terminalStateBetweenReadAndTap_closesTheStream (#1370). A QueueManager subclass stops the subscribe at its tap, after the store read, while the agent publishes. Each run checks that the window was exercised (the bus finished inside it, or ThreadMXBean shows the bus blocked on a lock the subscriber holds), so they cannot pass by timing. With the change, each waits out the hook's 3 s timeout by design (class: 6.8 s). Both fail on main 3f321f1c and at 369ee867 (#1353's merge, the issue's pin) without the change, and pass with it.

Verification (JDK 17.0.21, Maven 3.10.2). On main 3f321f1c, where the diff applies without conflict: 4,135 tests, 0 failures, 0 errors, 121 skipped; at 369ee867: 4,082 tests, 0 failures, 0 errors, 121 skipped. On both, all 83 reactor modules succeeded under mvn -B -fae install plus mvn -B clean install -pl boms/extras (the Extras BOM test needed the rebuild after a stale invoker-repository entry). NullAway passes.

Re-check with Daavar (model at d83d3b7, A2ATaskFixed2). In our model of a2a-java with the subscribe's read and tap made one step, as in the fix, the behaviours the specification program does not produce fell from 2,060 to 0 over the 15 scenarios of #1370, with no new kind of difference. Against our a2a-rs model, every behaviour only the fixed Java model shows (11,041) conforms to the specification.

Per scenario and reproduction

Uncovered behaviours, before → after. Columns: (a) both streams kept, (b) A disconnects, (d) B subscribes at once. Rows: the executor answers with a Message (msg) or opens the task with a Task (tasks) or a status update (taskw), split by how it completes (done).

executor (a) (b) (d)
msg 0 → 0 0 → 0 0 → 0
tasks,done-yes 3 → 0 4 → 0 3 → 0
tasks,done-no 323 → 0 58 → 0 323 → 0
taskw,done-yes 28 → 0 4 → 0 28 → 0
taskw,done-no 614 → 0 58 → 0 614 → 0
git clone --recurse-submodules https://github.com/joulook/daavar.git && cd daavar
git checkout d83d3b7f2e1d9c8a8a1215c6f8e6e0ff5e46d7ca && git submodule update --init --recursive
(cd traceforge && cargo build --release -p traceforge --bin conf-join)
cd benchmarks/a2a-task/rust && cargo build --release
R=target/release/tf_a2a_task; J=../../../traceforge/target/release/conf-join
(cd ../../../jmc && ./gradlew -q --no-daemon --init-script ../scripts/print-classpath.gradle :core:printTestClasspath)
CP=$(cat ../../../jmc/cp.txt); mkdir -p classes report && javac -d classes -cp "$CP" ../java/bench/a2a_task/*.java
C=n,col-a,part-tasks,done-no
$R export spec --out spec.jsonl --program a2a-task --size $C --threads 16 --model fifo -- spec,$C
java -Xss4m -Xmx2g -cp "classes:$CP" org.mpi_sws.jmc.mp.cli.MpLauncher bench.a2a_task.A2ATaskFixed2:impl,$C \
  must 0 1 "$PWD/report" "$PWD/java.jsonl" 43200 --split 16 --k 16
$J --decide spec.jsonl java.jsonl > join.out; grep -m1 '^uncovered' join.out   # 0 (323 with A2ATaskFixed)

Requirements as in #1370; the join takes about 3.5 minutes and 20 GiB, as there. It prints warnings that some tag names of the A2A vocabulary are written both as a unit and with one field, and a note that Err occurs only in the specification; neither is a failure.

This PR was prepared with AI assistance and reviewed by us.

Fixes #1370

…s lock

onSubscribeToTask read the task from the store and tapped its queue in
two unordered steps, while the bus thread persisted and distributed
each event. An event persisted after the read and distributed before
the tap reached neither the snapshot nor the stream: an artifact was
lost, or a terminal status was lost and the stream never closed
(A2A spec 3.1.6).

MainEventBusProcessor.processEvent now holds a private monitor from
persisting an event to distributing it to the child queues, and
onSubscribeToTask runs its read, checks, tap and createOrTap fallback
under the same monitor (withEventProcessingPaused).

Adds SubscribeWindowTest.

Fixes a2aproject#1370

@Shay-Deng Shay-Deng left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Thanks for this, and for the clear reproduction in #1370. I checked it locally: mvn -pl server-common test passes on 74c8886 (665 tests). With server-common/src/main reverted to the merge base (3f321f1), both SubscribeWindowTest cases fail the way the issue describes: the artifact published in the window reaches neither the snapshot nor the stream, and the stream never closes after the terminal update. So the test pins the bug, and the change fixes it.

One question about the lock's scope. persistAndDistributeLock is one monitor per MainEventBusProcessor, which is @ApplicationScoped and processes the events of all tasks on a single thread. While a subscriber to task A runs taskStore.get(A) and the tap under the monitor, the bus can't persist or distribute an event for any other task. With the in-memory store that window is short. With JpaDatabaseTaskStore, every subscribe puts a database read on the path of every task's events. The invariant only needs ordering within one task (the read and tap of A against the persist and distribute of A). Would a monitor keyed by task ID, for example a small striped set, keep the fix and leave other tasks unaffected? I'm happy to try that variant against SubscribeWindowTest if it helps.

…e's read and tap

The subscribe fix held one processor-wide monitor while a subscriber read the
task and tapped its queue, and while the bus persisted and distributed any
event. The ordering it protects is per task, so a subscribe on one task held up
every other task's events, with a database read on that path when the
TaskStore is JDBC-backed.

The monitor becomes 64 lock stripes indexed by a hash of the task ID:
processEvent holds the stripe of the event's task, and
withEventProcessingPaused(taskId, action) holds the same stripe for the read and
the tap. A fixed stripe set keeps memory bounded and needs no cleanup when a
task ends; tasks that share a stripe only share contention. The Javadoc states
the remaining limit (the processor is single-threaded, so an event of the held
task makes later events wait) and forbids nesting the stripes of two tasks.

Adds MainEventBusProcessorTaskLockTest: while a subscriber holds task A's
stripe, a task-B event is persisted and distributed and a task-A event waits; a
second subscriber to A blocks, one to B does not.
@joulook

joulook commented Dec 2, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for checking this so carefully, and for running SubscribeWindowTest against the reverted sources. You're right
that the invariant only concerns one task: the subscriber's read and tap of task A against the persist and distribute
of A's events. Holding one processor-wide monitor serialises every task behind a subscribe, which is not needed and,
with JpaDatabaseTaskStore, puts a database read on every task's event path.

I've pushed a follow-up commit, 32e658d, that makes the lock per task:

  • A fixed set of 64 lock stripes, indexed by a hash of the task ID. processEvent holds the stripe of the event's
    task from persisting it until it has been distributed. withEventProcessingPaused(taskId, action), used by
    subscribe, holds the same stripe for the read and the tap. So the ordering for one task is the one the original fix
    gave, and a subscribe to A no longer blocks events of tasks on other stripes.

  • Why stripes rather than a per-task monitor map: a fixed set keeps memory bounded and needs no cleanup when a task
    ends. A map with removal at task end has a race: a subscriber could synchronise on a monitor that is removed and
    replaced, so two threads would hold different monitors for the same task. Two tasks sharing a stripe only share
    contention, never correctness.

  • One limit, now stated in the Javadoc: the processor runs on a single thread. While a subscriber holds A's stripe,
    B's events go through; but if the processor takes an event of A in that window, it waits for the stripe, and the
    events queued behind it wait too. That window is the subscriber's read and tap of A only.

  • The Javadoc also asks callers not to nest: the action, and callbacks it runs such as a TaskStreamLifecycleHook,
    must not call withEventProcessingPaused for another task, since two subscribers taking two stripes in opposite
    orders could deadlock.

  • New test, MainEventBusProcessorTaskLockTest:

    • while a subscriber holds task A's stripe, a task-B event is persisted and distributed;
    • a task-A event waits until the subscriber is done (the test checks that the processor thread is blocked in
      processEvent before releasing A);
    • a second subscriber to A blocks, while one to B does not.

    With the stripes collapsed into one lock, the two behavioural cases fail.

Results with the commit (mvn -f server-common/pom.xml test, JDK 17): SubscribeWindowTest and
MainEventBusProcessorTaskLockTest 5/5, and the whole server-common suite 668/668 (the 665 you ran plus the 3 new
ones).

Thanks again for offering to try the variant; if you see a case the stripes don't cover, I'm happy to change it.

@joulook

joulook commented Dec 2, 2026

Copy link
Copy Markdown
Contributor Author

Two jobs failed on 32e658d; both look unrelated to the change, so could a maintainer rerun them?

  • build (ubuntu-latest, 17), KafkaReplicationIntegrationTest.testKafkaEventReceivedByA2AServer (line 287, "task
    is in terminal state: TASK_STATE_COMPLETED").
    • The test starts subscribeToTask asynchronously and sends the COMPLETED event to Kafka right away. When the Kafka
      event is processed first, the subscribe correctly finds a terminal task.
    • fix(test): stabilize KafkaReplicationIntegrationTest by waiting for first SSE event #864 fixed the same race in testQueueClosedEventTerminatesRemoteSubscribers by waiting for the first SSE event
      before sending.
    • The 21 and 25 builds of this commit, and the 17 build of 74c8886, passed; locally (JDK 17) it passed 5/5 on each
      commit.
  • test-cloud-deployment. Both agent pods were still failing their readiness probes ~22-24 s before the client
    ran, and one pod's JPA startup hit relation "a2a_tasks" already exists (two pods creating the schema at once). The
    client's first send then failed. Subscribe is the only path that takes the new per-task lock, and the same job also
    failed on main today (run 46879988509).

I can open a PR making this test wait for the first event, as #864 did.

…LETED

testKafkaEventReceivedByA2AServer starts subscribeToTask, which returns
before the server has handled the subscribe request, and then sends the
COMPLETED event to Kafka at once. When the server processes the COMPLETED
event before the subscribe reads the task, the subscribe correctly rejects
the task as terminal, and the test fails with "Cannot subscribe to task ...
task is in terminal state". In local runs the subscribe reached the server
only a few milliseconds before the COMPLETED event.

Wait until the subscription delivers its first event (the initial task
snapshot) before sending COMPLETED, as a2aproject#864 did for
testQueueClosedEventTerminatesRemoteSubscribers. The assertions are
unchanged.
@Shay-Deng

Copy link
Copy Markdown
Contributor

Thanks for the quick follow-up. I reran it on 32e658d: server-common passes (668 tests), and with LOCK_STRIPES set to 1 the two behavioural cases in MainEventBusProcessorTaskLockTest fail, as you describe. Fixed stripes rather than a removable per-task map makes sense to me for the reason you gave, and the Javadoc's note on nesting covers the lock-order case. Nothing further from me.

@joulook

joulook commented Dec 3, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the rerun, @Shay-Deng.

We looked into both failures again instead of asking for a rerun.

build (17), testKafkaEventReceivedByA2AServer

  • The test calls subscribeToTask, which can return before the server has handled the request, and then sends COMPLETED immediately.
  • In 40 interleaved local runs per tree (the merge-base 3f321f1, 74c8886 and 32e658d, JDK 17), every run passed, but the subscribe reached the server only a few milliseconds before COMPLETED (1 to 16 ms, median 6 to 7), with similarly small margins on all three trees. On a slower runner COMPLETED can win, and the subscribe then correctly sees a terminal task.
  • The per-task lock does not change this: the subscribe and the Kafka-delivered event are for the same task, so they take the same lock and exclude each other as they did under the processor-wide lock. The only serialisation the change removes is against other tasks.
  • I have pushed a test-only commit that waits for the subscription's first event before sending COMPLETED, as fix(test): stabilize KafkaReplicationIntegrationTest by waiting for first SSE event #864 did for testQueueClosedEventTerminatesRemoteSubscribers. With it, 40 of 40 runs pass with a margin of 31 to 62 ms. The assertions are unchanged.
  • The JDK 25 build did not exercise this test: the pom excludes it on JDK 24 and later.

test-cloud-deployment

  • The first message/send reached pod nmntz, which logged no error. The relation "a2a_tasks" already exists warning came from the other pod, lq8tn, which did not serve the request. Both pods were Ready before the client ran.
  • The error is raised in ResultAggregator when, after the send's consumer ends, no Task or Message was captured and the store has none either. We suspect slow first processing on a just-started pod, but the logs do not show why the consumer ended first.
  • No lock contention from this PR is involved: the processor's lock was uncontended on that pod, and no competing subscriber exists, since the example client exits on the first-send failure before it subscribes. The same workflow also failed on main on December 2 (run 46879988509).

The new push should show the Kafka test green. If the cloud job fails again, we are happy to dig further.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

2 participants