Skip to content

CXF-9290: Serialize the event delivery of SseSubscription - #3824

Open
rzo1 wants to merge 3 commits into
apache:mainfrom
rzo1:CXF-9290
Open

rzo1 wants to merge 3 commits into
apache:mainfrom
rzo1:CXF-9290

Conversation

@rzo1

@rzo1 rzo1 commented Dec 4, 2026

Copy link
Copy Markdown
Contributor

https://issues.apache.org/jira/browse/CXF-9290

SseSubscription (MicroProfile Rest Client SSE publisher) delivers events from the SSE reader thread while the subscriber requests them from another thread without coordinating the two:

  • fireEvent() calls onNext() or buffers the event inside the function passed to AtomicLong.updateAndGet(), which is re-run when a concurrent request(n) changes the counter, so an event can be delivered twice.
  • Directly delivered events can overtake buffered ones.
  • onComplete is lost when the stream completes while events are buffered.
  • Repeated request(Long.MAX_VALUE) overflows the demand (rule 3.17).

This makes the MP Rest Client TCK test ReactiveStreamsPublisherTckTest#required_createPublisher3MustProduceAStreamOfExactly3Elements flaky ("Expected end-of-stream but got element").

Events are now only delivered from a drain loop that never runs concurrently (work-in-progress counter). fireEvent(), request(), complete() and fireError() update the state and drain, the terminal event is signalled exactly once after the buffer is empty, the demand is capped at Long.MAX_VALUE, and the buffer size limit only drops events that have not been requested yet.

New tests in SseSubscriptionTest: concurrent events and requests (the TCK scenario, 2000 iterations), onComplete after buffered events are requested, unbounded demand, and requested events with bufferSize=0. The first three fail without the change. cxf-rt-rs-mp-client builds with all tests and checks.

fireEvent() called onNext() or buffered the event inside the function passed
to AtomicLong.updateAndGet(), which is re-run when a concurrent request(n)
changes the counter, so an event could be delivered twice. Directly delivered
events could also overtake buffered ones, onComplete was lost when the stream
completed with buffered events, and the demand overflowed on repeated
request(Long.MAX_VALUE).

Events are now only delivered from a drain loop that never runs concurrently;
fireEvent(), request(), complete() and fireError() update the state and drain.
The demand is capped at Long.MAX_VALUE, and the buffer limit only drops events
that have not been requested yet.

@coheigea coheigea 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, the drain loop is the right approach.

A few points:

  1. If onNext throws, the subscription stops delivering anything (please fix). drain() has no try/finally, so wip is never decremented. Every later drain() returns at once: later events are only buffered and onComplete never arrives. A test confirmed it: after a throwing onNext, three more events plus complete() delivered nothing and no onComplete. Rule 2.13 makes this the subscriber's fault, but the old code failed noisily and this fails silently. Suggestion: catch the exception, cancel the subscription and log it.
  2. Memory with unbounded demand. After request(Long.MAX_VALUE), the buffer limit never applies. If the subscriber calls request() from its own thread, that thread takes over draining. The reader then only adds events to the buffer and no longer waits for the subscriber, so the buffer can grow without limit. That's how this pattern usually behaves, but it would be worth a comment.
  3. Minor: if events are still buffered after complete(), request(n <= 0) is ignored because of the !completed.get() check in fireError. Rule 3.9 says it must signal onError; checking terminated would fix it. This was already the case before the PR.
  4. Nit: the request(1) before polling COMPLETE in testConcurrentEventsAndRequests isn't needed, because completion doesn't need demand.

A subscriber throwing from onNext left the drain loop without decrementing
its work counter, so the subscription silently stopped delivering. Subscriber
signals are now guarded: the failure is logged and the subscription
cancelled. request(n <= 0) after complete() with buffered events signals
onError (rule 3.9), and the effect of unbounded demand on the buffer is
documented.
@rzo1

rzo1 commented Dec 4, 2026

Copy link
Copy Markdown
Contributor Author

Thanks, addressed in the second commit:

  1. All subscriber signals (onNext, onComplete, onError) go through a guard that logs the failure and cancels the subscription, so the drain loop always decrements its counter. testThrowingSubscriberCancelsTheSubscription covers it (failed with the exception escaping before). cancel() now also tolerates a subscription without publisher, as in the unit tests.
  2. Added a note on buffer(): with unbounded demand the limit never applies, and a subscriber draining from its own thread lets the buffer grow if it is slower than the stream.
  3. fireError checks terminated instead of completed, so request(n <= 0) after complete() with buffered events signals onError; testNonPositiveRequestAfterCompleteWithBufferedEventsSignalsError covers it.
  4. Removed the request(1) before polling COMPLETE.

@coheigea coheigea 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.

A few more things to change:

  1. Don't let a failed close turn a completed stream into an error. fireError now checks terminated instead of completed, and SsePublisher's IOException catch also catches a failing br2.close() after complete(). If events are still buffered, the subscriber gets onError instead of onComplete and the buffered events are dropped. Fix: give request(n <= 0) its own error path that skips the completed check, and keep !completed.get() in fireError. Add a test that buffers events, calls complete(), then fireError(...), then request(...), and expects the events followed by onComplete.
  2. Don't swallow Error in signal(). Catching Error also catches OutOfMemoryError and StackOverflowError. Catch only RuntimeException, or rethrow VirtualMachineError.

…Error

fireError() again leaves a completed stream alone, so a failing close of the
event stream after complete() no longer replaces onComplete and drops the
buffered events; only an invalid request(n) signals onError behind buffered
events (rule 3.9). Subscriber failures no longer swallow VirtualMachineErrors;
the subscription is cancelled before the error is rethrown. A negative buffer
size behaves like 0 again.
@rzo1

rzo1 commented Dec 4, 2026

Copy link
Copy Markdown
Contributor Author

Thanks, addressed in the third commit:

  1. fireError keeps the !completed.get() check again, so a failing close after complete() leaves the stream completed. request(n <= 0) goes through its own rejectRequest path that only checks terminated, so rule 3.9 still holds behind buffered events. testErrorAfterCompleteKeepsTheCompletedStream follows your recipe (buffer, complete(), fireError(...), request(...), then the events and onComplete).
  2. signal() rethrows VirtualMachineError. It cancels the subscription first, otherwise it would stay registered and look active while the drain loop can never run again (testVirtualMachineErrorCancelsTheSubscription).

While re-checking I also found that a negative buffer size (org.apache.cxf.microprofile.client.sse.bufferSize=-1) made buffer() throw an IndexOutOfBoundsException with outstanding demand; it now behaves like 0 again, as on main (testNegativeBufferSizeBehavesLikeNoBuffer). The module builds with all tests and checks.

@coheigea coheigea 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.

LGTM, @reta please check it as well

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.

2 participants