Skip to content

Commit cdbb3fc

Browse files
author
Mark Pollack
committed
acp-micronaut: write the SSE closing comment before the event loops stop
With Micronaut's graceful shutdown off, the runtime drained the HTTP endpoint in its @PreDestroy, whose place in the context's destroy order varies between runs. When the event loop registry was destroyed first, Netty closed every connection and the client saw the stream cut (IOException: closed, chunked transfer encoding) instead of the closing comment. CI hit it in AcpMicronautServerTest.closingTheApplicationEndsOpenStreamsAndWebSockets. The runtime now closes the agent as the context's stop begins (ShutdownEvent), before any bean is destroyed. Ending a stream only hands its last frame to Micronaut, so the endpoint's host records each SSE stream it answers with and, after the endpoint's close, waits until Micronaut has written each stream's end (HttpRequestTerminatedEvent, published once the last content is written and flushed), at most two seconds. theClosingCommentIsWrittenBeforeTheEventLoopsStop shuts the event loops down just before the runtime is destroyed, the order that loses the comment; it failed every time before, for both a server stop and a context close.
1 parent 792339e commit cdbb3fc

11 files changed

Lines changed: 254 additions & 11 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -298,6 +298,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
298298
closes the context, as Micronaut's hook does, so one hook waits for the other. The agent still closes
299299
gracefully, an `AutoCloseable` agent bean is still closed, and a stdio or in-process application, which has no
300300
hook of Micronaut's, still has its context closed on SIGTERM.
301+
- **acp-micronaut: an SSE stream ends with its closing comment also with Micronaut's graceful shutdown off.** The
302+
runtime drained the endpoint in its `@PreDestroy`, whose place in the context's destroy order varies between
303+
runs; when Netty's event loops were destroyed first, they closed every connection and the client saw the
304+
stream cut (`IOException: closed`) instead of the closing comment. The runtime now drains as the context's stop
305+
begins (`ShutdownEvent`), before any bean is destroyed, and waits until Micronaut has written each stream's end
306+
(`HttpRequestTerminatedEvent`), at most two seconds beyond the endpoint's own close.
301307
- The `acp-agent-support` README gave the default request timeout as 30 seconds; it is 60.
302308

303309
## [0.82.0] - 2026-11-28

‎acp-micronaut/README.md‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -114,8 +114,14 @@ public final class Application {
114114
ever, and the context closes once.
115115
- **Closing over HTTP.** Open SSE streams end with a closing comment and in-flight prompts
116116
are cancelled, within `acp.agent.transport.http.shutdown-timeout`, so a stop never waits for
117-
a stream that does not end by itself. With `micronaut.lifecycle.graceful-shutdown.enabled=true`
118-
this drain runs as part of Micronaut's graceful shutdown. Micronaut closes its WebSocket
117+
a stream that does not end by itself. The drain runs as the context's stop begins, before any
118+
bean is destroyed, and waits until Micronaut has written each stream's end, so the closing
119+
comment reaches the client before Netty's event loops stop and close the connections. With
120+
`micronaut.lifecycle.graceful-shutdown.enabled=true` this drain runs as part of Micronaut's
121+
graceful shutdown. One case remains: a server with worker event loops of its own (the
122+
deprecated `micronaut.server.netty.worker` settings) stops them before the context when the
123+
server itself is stopped, as Micronaut's SIGTERM hook does, so its streams can end without the
124+
comment. Micronaut closes its WebSocket
119125
connections itself when its server stops, before any application hook runs, so a WebSocket
120126
client sees the connection drop (1006) rather than a 1001 close frame.
121127
- **Over stdio, standard output is the protocol.** Turn off the banner and send every log line to

‎acp-micronaut/src/main/java/com/agentclientprotocol/sdk/micronaut/agent/AcpAgentRuntime.java‎

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -91,7 +91,9 @@
9191
* <p>Stopping: closing the context closes the agent gracefully, then at once: over stdio after at
9292
* most {@code acp.agent.shutdown-timeout} (10 seconds by default), over HTTP after at most
9393
* {@code acp.agent.transport.http.shutdown-timeout} (5 seconds by default) plus 5 seconds: open
94-
* SSE streams end with a closing comment. With
94+
* SSE streams end with a closing comment. The agent closes as the context's stop begins
95+
* ({@code ShutdownEvent}), before any bean is destroyed, Netty's event loops included, and over
96+
* HTTP the close waits until Micronaut has written each stream's end. With
9597
* {@code micronaut.lifecycle.graceful-shutdown.enabled} the endpoint drains through Micronaut's
9698
* graceful shutdown, beside the server's own, which would otherwise wait for streams that never
9799
* end. On SIGTERM a JVM shutdown hook of the runtime's closes the agent, then the context. It is
@@ -225,7 +227,16 @@ else if (!settings.servesHttp()) {
225227
* @return the endpoint, or null over another transport, before the start and after the close
226228
*/
227229
@Nullable AcpHttpEndpoint endpoint() {
228-
return (currentHost() instanceof AcpEndpointHost http) ? http.endpoint() : null;
230+
AcpEndpointHost http = endpointHost();
231+
return (http != null) ? http.endpoint() : null;
232+
}
233+
234+
/**
235+
* The host of the endpoint, while an agent is served over HTTP.
236+
* @return the host, or null over another transport, before the start and after the close
237+
*/
238+
@Nullable AcpEndpointHost endpointHost() {
239+
return (currentHost() instanceof AcpEndpointHost http) ? http : null;
229240
}
230241

231242
/**
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
/*
2+
* Copyright 2025-2026 the original author or authors.
3+
*/
4+
5+
package com.agentclientprotocol.sdk.micronaut.agent;
6+
7+
import io.micronaut.context.annotation.Requires;
8+
import io.micronaut.context.event.ApplicationEventListener;
9+
import io.micronaut.context.event.ShutdownEvent;
10+
import jakarta.inject.Singleton;
11+
12+
/**
13+
* Closes the agent ({@link AcpAgentRuntime#close()}) as the context's stop begins, before any
14+
* bean is destroyed. The runtime's own {@code @PreDestroy} comes in the context's destroy order,
15+
* which may put Netty's event loops first: they close every connection when they stop, so an SSE
16+
* stream would end without its closing comment. With Micronaut's graceful shutdown on, the agent
17+
* has drained already, and this does nothing more.
18+
*/
19+
@Singleton
20+
@Requires(bean = AcpAgentRuntime.class)
21+
final class AcpContextStopping implements ApplicationEventListener<ShutdownEvent> {
22+
23+
private final AcpAgentRuntime runtime;
24+
25+
AcpContextStopping(AcpAgentRuntime runtime) {
26+
this.runtime = runtime;
27+
}
28+
29+
@Override
30+
public void onApplicationEvent(ShutdownEvent event) {
31+
runtime.close();
32+
}
33+
34+
}

‎acp-micronaut/src/main/java/com/agentclientprotocol/sdk/micronaut/agent/AcpEndpointHost.java‎

Lines changed: 58 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,9 @@
66

77
import java.time.Duration;
88
import java.util.OptionalInt;
9+
import java.util.Set;
910
import java.util.concurrent.CompletableFuture;
11+
import java.util.concurrent.ConcurrentHashMap;
1012
import java.util.concurrent.CompletionStage;
1113
import java.util.concurrent.ExecutionException;
1214
import java.util.concurrent.TimeUnit;
@@ -24,13 +26,19 @@
2426
* framework-neutral {@link AcpHttpEndpoint} that {@link AcpHttpController},
2527
* {@link AcpGetFilter} and {@link AcpWebSocket} hand their requests to. Starting it starts the endpoint's keep-alive;
2628
* stopping it closes every connection as {@link AcpHttpEndpoint#closeGracefully()} does, bounded
27-
* by the endpoint's shutdown timeout. Micronaut's server owns the port, so {@link #port()} is
28-
* always empty. Safe for use from several threads.
29+
* by the endpoint's shutdown timeout, and then waits until Micronaut has written the end of each
30+
* SSE stream the endpoint answered with ({@link #streamOpened()}), at most {@link #WRITE_BOUND}:
31+
* ending a stream only hands its last frame to Micronaut, which writes it on the event loop, and
32+
* an event loop that stops first loses it. Micronaut's server owns the port, so {@link #port()}
33+
* is always empty. Safe for use from several threads.
2934
*/
3035
final class AcpEndpointHost implements AcpHost {
3136

3237
private static final Logger logger = LoggerFactory.getLogger(AcpEndpointHost.class);
3338

39+
/** How long stopping waits for Micronaut to write the streams' ends, once they have ended. */
40+
static final Duration WRITE_BOUND = Duration.ofSeconds(2);
41+
3442
private final AcpHttpEndpoint endpoint;
3543

3644
private final CompletableFuture<@Nullable Void> termination = new CompletableFuture<>();
@@ -41,6 +49,9 @@ final class AcpEndpointHost implements AcpHost {
4149

4250
private @Nullable CompletableFuture<@Nullable Void> stopped;
4351

52+
/** The SSE streams whose end Micronaut has not written yet. */
53+
private final Set<StreamEnd> unwritten = ConcurrentHashMap.newKeySet();
54+
4455
AcpEndpointHost(AcpHttpEndpoint endpoint) {
4556
this.endpoint = endpoint;
4657
}
@@ -76,13 +87,57 @@ public void start() {
7687
return Mono.empty();
7788
})
7889
.toFuture();
79-
current = current.whenComplete((ignored, error) -> termination.complete(null));
90+
current = current.<@Nullable Void>thenCompose(ignored -> allWritten())
91+
.whenComplete((ignored, error) -> termination.complete(null));
8092
stopped = current;
8193
}
8294
return current;
8395
}
8496
}
8597

98+
/**
99+
* Records an SSE stream the endpoint answered with, which stopping waits for until Micronaut
100+
* has written its end.
101+
* @return what to run once Micronaut has written the stream's end, or given up on its
102+
* connection
103+
*/
104+
Runnable streamOpened() {
105+
StreamEnd end = new StreamEnd(unwritten);
106+
unwritten.add(end);
107+
return end;
108+
}
109+
110+
/** Completes once every recorded stream's end is written, or after {@link #WRITE_BOUND}. */
111+
private CompletableFuture<@Nullable Void> allWritten() {
112+
CompletableFuture<?>[] pending = unwritten.stream().map(StreamEnd::written).toArray(CompletableFuture<?>[]::new);
113+
return CompletableFuture.allOf(pending)
114+
.<@Nullable Void>handle((ignored, error) -> null)
115+
.completeOnTimeout(null, WRITE_BOUND.toMillis(), TimeUnit.MILLISECONDS);
116+
}
117+
118+
/** One SSE stream's end: run once Micronaut has written it. */
119+
private static final class StreamEnd implements Runnable {
120+
121+
private final Set<StreamEnd> unwritten;
122+
123+
private final CompletableFuture<@Nullable Void> written = new CompletableFuture<>();
124+
125+
StreamEnd(Set<StreamEnd> unwritten) {
126+
this.unwritten = unwritten;
127+
}
128+
129+
CompletableFuture<@Nullable Void> written() {
130+
return written;
131+
}
132+
133+
@Override
134+
public void run() {
135+
unwritten.remove(this);
136+
written.complete(null);
137+
}
138+
139+
}
140+
86141
@Override
87142
public void stop(Duration timeout) {
88143
CompletableFuture<@Nullable Void> stopping = stopGracefully().toCompletableFuture();

‎acp-micronaut/src/main/java/com/agentclientprotocol/sdk/micronaut/agent/AcpGetFilter.java‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -63,10 +63,11 @@ public Publisher<MutableHttpResponse<?>> doFilter(HttpRequest<?> request, Server
6363
if ((method != HttpMethod.GET && method != HttpMethod.HEAD) || !onPath(request.getPath())) {
6464
return chain.proceed(request);
6565
}
66-
AcpHttpEndpoint endpoint = runtime.endpoint();
66+
AcpEndpointHost host = runtime.endpointHost();
67+
AcpHttpEndpoint endpoint = (host != null) ? host.endpoint() : null;
6768
MicronautExchange exchange = new MicronautExchange(request);
68-
if (endpoint == null || !isUpgrade(request)) {
69-
return AcpReplies.answer(endpoint, served -> served.handle(exchange)).map(response -> response);
69+
if (host == null || endpoint == null || !isUpgrade(request)) {
70+
return AcpReplies.answer(host, request, served -> served.handle(exchange)).map(response -> response);
7071
}
7172
AcpWsHandshake handshake = endpoint.webSocketHandshake(exchange);
7273
if (handshake instanceof AcpWsHandshake.Refused refused) {

‎acp-micronaut/src/main/java/com/agentclientprotocol/sdk/micronaut/agent/AcpHttpController.java‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -85,7 +85,8 @@ Mono<HttpResponse<AcpReplies.RawBody>> patch(HttpRequest<?> request) {
8585
}
8686

8787
private Mono<HttpResponse<AcpReplies.RawBody>> handle(HttpRequest<?> request) {
88-
return AcpReplies.answer(runtime.endpoint(), endpoint -> endpoint.handle(new MicronautExchange(request)))
88+
return AcpReplies.answer(runtime.endpointHost(), request,
89+
endpoint -> endpoint.handle(new MicronautExchange(request)))
8990
.map(response -> response);
9091
}
9192

‎acp-micronaut/src/main/java/com/agentclientprotocol/sdk/micronaut/agent/AcpReplies.java‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,12 @@ final class AcpReplies {
5555

5656
private static final Logger logger = LoggerFactory.getLogger(AcpReplies.class);
5757

58+
/**
59+
* The request attribute holding what to run once Micronaut has written the end of the SSE
60+
* stream answering the request ({@link AcpStreamWritten}).
61+
*/
62+
static final String STREAM_WRITTEN = AcpReplies.class.getName() + ".stream-written";
63+
5864
private AcpReplies() {
5965
}
6066

@@ -74,6 +80,27 @@ static Mono<MutableHttpResponse<RawBody>> answer(@Nullable AcpHttpEndpoint endpo
7480
}).map(AcpReplies::toResponse);
7581
}
7682

83+
/**
84+
* The response for the endpoint's answer to a request, as {@link #answer(AcpHttpEndpoint, Function)};
85+
* an SSE stream is recorded with the host, so that stopping it waits until Micronaut has
86+
* written the stream's end.
87+
* @param host the endpoint's host, or null when no agent is served over HTTP
88+
* @param request the request answered
89+
* @param handle what the endpoint answers
90+
* @return the response
91+
*/
92+
static Mono<MutableHttpResponse<RawBody>> answer(@Nullable AcpEndpointHost host, HttpRequest<?> request,
93+
Function<AcpHttpEndpoint, Mono<AcpHttpReply>> handle) {
94+
if (host == null) {
95+
return answer((AcpHttpEndpoint) null, handle);
96+
}
97+
return answer(host.endpoint(), handle).doOnNext(response -> {
98+
if (response.getBody().map(RawBody::reply).filter(AcpHttpReply.EventStream.class::isInstance).isPresent()) {
99+
request.setAttribute(STREAM_WRITTEN, host.streamOpened());
100+
}
101+
});
102+
}
103+
77104
/**
78105
* The response for a reply: its status and headers, and its body as it is.
79106
* @param reply the endpoint's reply
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
/*
2+
* Copyright 2025-2026 the original author or authors.
3+
*/
4+
5+
package com.agentclientprotocol.sdk.micronaut.agent;
6+
7+
import io.micronaut.context.annotation.Requires;
8+
import io.micronaut.context.event.ApplicationEventListener;
9+
import io.micronaut.http.annotation.Controller;
10+
import io.micronaut.http.context.event.HttpRequestTerminatedEvent;
11+
import io.micronaut.websocket.annotation.ServerWebSocket;
12+
import jakarta.inject.Singleton;
13+
14+
/**
15+
* Tells the endpoint's host that Micronaut has written the end of an SSE stream: Micronaut
16+
* publishes {@code HttpRequestTerminatedEvent} once a response's last content is written and
17+
* flushed, or its connection is given up. Stopping the host waits for this, so that a stream's
18+
* closing comment reaches its connection before Netty's event loops stop.
19+
*/
20+
@Singleton
21+
@Requires(classes = { Controller.class, ServerWebSocket.class })
22+
@Requires(bean = AcpAgentRuntime.class)
23+
final class AcpStreamWritten implements ApplicationEventListener<HttpRequestTerminatedEvent> {
24+
25+
@Override
26+
public void onApplicationEvent(HttpRequestTerminatedEvent event) {
27+
event.getSource().getAttribute(AcpReplies.STREAM_WRITTEN, Runnable.class).ifPresent(Runnable::run);
28+
}
29+
30+
}

‎acp-micronaut/src/test/java/com/agentclientprotocol/sdk/micronaut/agent/AcpMicronautServerTest.java‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -160,6 +160,40 @@ void closingTheApplicationEndsOpenStreamsAndWebSockets(boolean gracefulShutdown,
160160
assertThat(socketEvents.closed.get(5, TimeUnit.SECONDS)).isIn(1001, 1006);
161161
}
162162

163+
/**
164+
* With Micronaut's graceful shutdown off, the SSE stream still ends with the closing comment
165+
* when the context shuts Netty's event loops down before it destroys the agent runtime, which
166+
* closes every connection: the runtime drains the endpoint as the context's stop begins
167+
* ({@code ShutdownEvent}), before any bean is destroyed, and waits until each stream's end has
168+
* been written to its connection.
169+
*/
170+
@ParameterizedTest
171+
@CsvSource({ "false", "true" })
172+
void theClosingCommentIsWrittenBeforeTheEventLoopsStop(boolean contextClose) throws Exception {
173+
EmbeddedServer server = server(Map.of(TestAgents.ECHO, "true", TestAgents.EVENT_LOOPS_FIRST, "true",
174+
"acp.agent.transport.http.shutdown-timeout", "2s"));
175+
String connection = initialize(server);
176+
HttpResponse<InputStream> stream = http.send(HttpRequest.newBuilder(uri(server))
177+
.header("Accept", "text/event-stream")
178+
.header("Acp-Connection-Id", connection)
179+
.build(), HttpResponse.BodyHandlers.ofInputStream());
180+
List<String> frames = new CopyOnWriteArrayList<>();
181+
CompletableFuture<Void> streamEnded = CompletableFuture.runAsync(() -> readAll(stream.body(), frames));
182+
TestAgents.EventLoopsFirst.STREAM_ENDED = streamEnded;
183+
eventually(Duration.ofSeconds(5), () -> assertThat(frames).isNotEmpty());
184+
185+
if (contextClose) {
186+
server.getApplicationContext().close();
187+
}
188+
else {
189+
server.close();
190+
}
191+
192+
streamEnded.get(5, TimeUnit.SECONDS);
193+
assertThat(frames).hasSizeGreaterThanOrEqualTo(2).last().asString().startsWith(":");
194+
assertThat(frames).last().asString().isNotEqualTo(frames.get(0));
195+
}
196+
163197
@Test
164198
void aWebSocketFromAForeignOriginIsRefusedWith403() throws Exception {
165199
try (EmbeddedServer server = server(Map.of(TestAgents.ECHO, "true"))) {

0 commit comments

Comments
 (0)