Skip to content

Commit f0c6d7a

Browse files
author
Mark Pollack
committed
Document that closing the stdio agent transport does not release System.in
A read of System.in cannot be interrupted, so a closed StdioAcpAgentTransport built on it keeps its reader blocked, holding System.in's lock, until the next line or the end of input. Under Maven Surefire that is the fork's command stream, and such a reader stalled the fork's exit until Surefire killed it. The class, the System.in constructors and closeGracefully() now say so and point embedders and tests to explicit streams, the in-memory transport, or an empty standard input. A test covers that a reader waking after close hands nothing on and ends; the one test that built the transport on System.in now passes explicit streams; the AcpAgentSupport example no longer calls a create() that does not exist.
1 parent b095ede commit f0c6d7a

4 files changed

Lines changed: 144 additions & 4 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -436,6 +436,19 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
436436
servlet Javadoc now documents the remedy: call `closeGracefully()` before the server stops (a
437437
`SmartLifecycle` in the default phase).
438438

439+
- **The stdio agent transport's hold on `System.in` is documented.** Closing a
440+
`StdioAcpAgentTransport` built on `System.in` cannot end a read already in progress, because a
441+
read of `System.in` cannot be interrupted: its `acp-agent-inbound` thread stays blocked, holding
442+
`System.in`'s lock, until the next line or the end of standard input, then discards what it read
443+
and ends (now covered by a test). Under Maven Surefire, standard input is the fork's command
444+
stream, so such a reader, left by a test that builds the transport on `System.in`, took the
445+
fork's commands and stalled its exit until Surefire killed it 30 seconds after `System.exit(0)`.
446+
The class, its `System.in` constructors and `closeGracefully()` now say so, and that embedders and
447+
tests should pass explicit streams, use `acp-test`'s in-memory transport, or install an empty
448+
standard input before the tests run. The SDK's own tests never start a reader on `System.in`; the
449+
one that built the transport on it now passes explicit streams. The `AcpAgentSupport` Javadoc
450+
example no longer calls a `StdioAcpAgentTransport.create()` that does not exist.
451+
439452
- **A handler that threw an `Error` left the peer waiting.** Reactor rethrows what it treats as
440453
JVM-fatal (`LinkageError`, `VirtualMachineError`) instead of signalling it, so a handler that
441454
threw, say, the `NoSuchMethodError` of code compiled against 0.18.0 calling a removed constructor

‎acp-agent-support/src/main/java/com/agentclientprotocol/sdk/agent/support/AcpAgentSupport.java‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -112,7 +112,7 @@
112112
*
113113
* // Bootstrap
114114
* AcpAgentSupport.create(new MyAgent())
115-
* .transport(StdioAcpAgentTransport.create())
115+
* .transport(new StdioAcpAgentTransport())
116116
* .run();
117117
* }</pre>
118118
*

‎acp-core/src/main/java/com/agentclientprotocol/sdk/agent/transport/StdioAcpAgentTransport.java‎

Lines changed: 38 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,29 @@
7474
* without waiting for it; its handler's late answer is dropped.
7575
* </p>
7676
*
77+
* <p>
78+
* <b>Closing does not release {@code System.in}.</b> The transport reads standard input on
79+
* its own thread ({@code acp-agent-inbound}), and a read of {@code System.in} cannot be
80+
* interrupted. Closing the transport stops it handing on messages, but a reader blocked in
81+
* a read stays blocked, holding {@code System.in}'s lock, until the next line arrives or
82+
* standard input ends; it then reads that line, discards it and ends. The transport never
83+
* closes {@code System.in} itself, which belongs to the process. In an agent process that
84+
* is harmless: the process owns its standard input and exits with it. In a process whose
85+
* standard input belongs to someone else it is not: under Maven Surefire, for instance,
86+
* standard input carries the test fork's command stream, and a reader left on it takes
87+
* those bytes and can stall the fork's exit. Embedders and tests should therefore use the
88+
* {@linkplain #StdioAcpAgentTransport(AcpJsonMapper, InputStream, OutputStream) constructor
89+
* taking explicit streams}, or the in-memory transport of {@code acp-test}, and keep the
90+
* {@code System.in} constructors for an agent process's {@code main}. A test suite that
91+
* cannot avoid them (an application whose configuration builds this transport by
92+
* default) can install an empty standard input before any test runs, for instance with
93+
* {@code System.setIn(new ByteArrayInputStream(new byte[0]))} in a JUnit
94+
* {@code LauncherSessionListener}: the transport takes {@code System.in} when it is
95+
* constructed, so its reader then sees the end of the stream and ends (and, as at any end
96+
* of input, the transport closes the output stream it was given), while Surefire keeps its
97+
* own reference to the real standard input.
98+
* </p>
99+
*
77100
* @author Mark Pollack
78101
*/
79102
public class StdioAcpAgentTransport implements AcpAgentTransport {
@@ -134,15 +157,19 @@ public class StdioAcpAgentTransport implements AcpAgentTransport {
134157

135158
/**
136159
* Creates a new StdioAcpAgentTransport with the default JsonMapper using
137-
* System.in and System.out for communication.
160+
* System.in and System.out for communication. For an agent process's {@code main}:
161+
* closing the transport does not release {@code System.in} (see the class
162+
* documentation); embedders and tests pass explicit streams instead.
138163
*/
139164
public StdioAcpAgentTransport() {
140165
this(AcpJsonMapper.createDefault());
141166
}
142167

143168
/**
144169
* Creates a new StdioAcpAgentTransport with the specified JsonMapper using
145-
* System.in and System.out for communication.
170+
* System.in and System.out for communication. For an agent process's {@code main}:
171+
* closing the transport does not release {@code System.in} (see the class
172+
* documentation); embedders and tests pass explicit streams instead.
146173
* @param jsonMapper The JsonMapper to use for JSON serialization/deserialization
147174
*/
148175
@SuppressWarnings("SystemOut") // the stdio transport is the one owner of System.out
@@ -507,6 +534,15 @@ public Mono<Void> sendMessage(JSONRPCMessage message) {
507534
}));
508535
}
509536

537+
/**
538+
* Closes the transport: nothing more is handed on or written, standard output is
539+
* closed once the agent's requests to the client are settled, and
540+
* {@link #awaitTermination()} completes. The input stream is not closed, and a read of
541+
* it already in progress is not ended: on {@code System.in}, which cannot be
542+
* interrupted, the reader thread stays blocked until the next line or the end of
543+
* standard input, then discards what it read and ends (see the class documentation).
544+
* {@link #close()} does the same without waiting.
545+
*/
510546
@Override
511547
public Mono<Void> closeGracefully() {
512548
return Mono.fromRunnable(() -> {

‎acp-core/src/test/java/com/agentclientprotocol/sdk/agent/transport/StdioAcpAgentTransportTest.java‎

Lines changed: 92 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -69,10 +69,101 @@ void startTwiceFails() {
6969

7070
@Test
7171
void protocolVersionsReturnsLatest() {
72-
StdioAcpAgentTransport transport = new StdioAcpAgentTransport(jsonMapper);
72+
// Never System.in in a test: under Surefire it carries the fork's command stream.
73+
StdioAcpAgentTransport transport = new StdioAcpAgentTransport(jsonMapper,
74+
new ByteArrayInputStream(new byte[0]), new ByteArrayOutputStream());
7375
assertThat(transport.protocolVersions()).contains(AcpSchema.LATEST_PROTOCOL_VERSION);
7476
}
7577

78+
/**
79+
* A read on System.in cannot be interrupted, so closing cannot end it: the reader stays
80+
* blocked until the next line arrives. That line, and anything after it, is not handed
81+
* on and not answered, and the reader thread ends at once without reading again.
82+
*/
83+
@Test
84+
void aReaderThatWakesAfterCloseHandsNothingOnAndEnds() throws Exception {
85+
String line = jsonMapper.writeValueAsString(AcpTestFixtures.createJsonRpcRequest(AcpSchema.METHOD_INITIALIZE,
86+
"1", AcpTestFixtures.createInitializeRequest())) + "\n";
87+
UninterruptibleInput in = new UninterruptibleInput(line.getBytes(StandardCharsets.UTF_8));
88+
ByteArrayOutputStream out = new ByteArrayOutputStream();
89+
StdioAcpAgentTransport transport = new StdioAcpAgentTransport(jsonMapper, in, out);
90+
List<AcpSchema.JSONRPCMessage> handed = new CopyOnWriteArrayList<>();
91+
transport.start(messages -> messages.doOnNext(handed::add).then(Mono.empty())).block(TIMEOUT);
92+
Thread reader = in.awaitReader();
93+
94+
transport.closeGracefully().block(TIMEOUT);
95+
assertThat(reader.isAlive()).as("a blocked read outlives the close").isTrue();
96+
in.release();
97+
98+
reader.join(TIMEOUT.toMillis());
99+
assertThat(reader.isAlive()).as("the reader ends once its read returns").isFalse();
100+
assertThat(in.reads()).as("the reader does not read again").isEqualTo(1);
101+
assertThat(handed).isEmpty();
102+
assertThat(out.toString(StandardCharsets.UTF_8)).isEmpty();
103+
}
104+
105+
/** Blocks its first read, ignoring interrupts as a read on System.in does, until released. */
106+
private static final class UninterruptibleInput extends java.io.InputStream {
107+
108+
private final byte[] line;
109+
110+
private final CountDownLatch released = new CountDownLatch(1);
111+
112+
private final java.util.concurrent.CompletableFuture<Thread> reader = new java.util.concurrent.CompletableFuture<>();
113+
114+
private final java.util.concurrent.atomic.AtomicInteger reads = new java.util.concurrent.atomic.AtomicInteger();
115+
116+
UninterruptibleInput(byte[] line) {
117+
this.line = line;
118+
}
119+
120+
@Override
121+
public int read() {
122+
throw new UnsupportedOperationException();
123+
}
124+
125+
@Override
126+
public int read(byte[] buffer, int offset, int length) {
127+
if (reads.incrementAndGet() > 1) {
128+
awaitUninterruptibly(new CountDownLatch(1));
129+
}
130+
reader.complete(Thread.currentThread());
131+
awaitUninterruptibly(released);
132+
int count = Math.min(length, line.length);
133+
System.arraycopy(line, 0, buffer, offset, count);
134+
return count;
135+
}
136+
137+
Thread awaitReader() throws Exception {
138+
return reader.get(5, TimeUnit.SECONDS);
139+
}
140+
141+
void release() {
142+
released.countDown();
143+
}
144+
145+
int reads() {
146+
return reads.get();
147+
}
148+
149+
private static void awaitUninterruptibly(CountDownLatch latch) {
150+
boolean interrupted = false;
151+
while (true) {
152+
try {
153+
latch.await();
154+
break;
155+
}
156+
catch (InterruptedException e) {
157+
interrupted = true;
158+
}
159+
}
160+
if (interrupted) {
161+
Thread.currentThread().interrupt();
162+
}
163+
}
164+
165+
}
166+
76167
@Test
77168
void receivesMessageFromInputStream() throws Exception {
78169
// Create a message to send

0 commit comments

Comments
 (0)