fix: synchronize automation termination and stabilize headless tests
This commit is contained in:
@@ -9,8 +9,14 @@ import java.util.*;
|
||||
/** Deliberately adversarial child process. Never packaged into production. */
|
||||
public final class HeadlessFixture {
|
||||
static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
// Allow normal JVM startup under load; call/cancel deadlines remain deliberately short.
|
||||
static final HeadlessLimits LIMITS = new HeadlessLimits(600, 4096, 4096, 5000, 500, 150);
|
||||
// Successful JVM/ImageIO startup and fragmented IO need headroom on CI. Only
|
||||
// fixtures that deliberately hang use short call or shutdown deadlines.
|
||||
static HeadlessLimits limits(String mode) {
|
||||
boolean hungCall = mode.equals("hang-call") || mode.equals("hang-cancel");
|
||||
boolean hungShutdown = hungCall || mode.equals("descendant");
|
||||
return new HeadlessLimits(600, 4096, 4096, 5000,
|
||||
hungCall ? 500 : 5000, hungShutdown ? 150 : 2000);
|
||||
}
|
||||
static String mode;
|
||||
static void emit(JsonNode value) throws Exception {
|
||||
byte[] bytes = (value.toString() + "\r\n").getBytes(java.nio.charset.StandardCharsets.UTF_8);
|
||||
@@ -30,7 +36,7 @@ public final class HeadlessFixture {
|
||||
var hello = MAPPER.createObjectNode().put("type", "hello").put("sessionId", "fixture").put("runtimeVersion", "fixture-only");
|
||||
hello.putObject("protocolVersion").put("major", mode.equals("major") ? 2 : 1).put("minor", 3);
|
||||
hello.set("capabilities", MAPPER.valueToTree(mode.equals("capabilities") ? Set.of("boot") : HeadlessWire.CAPABILITIES));
|
||||
hello.set("limits", MAPPER.valueToTree(LIMITS));
|
||||
hello.set("limits", MAPPER.valueToTree(limits(mode)));
|
||||
if (mode.equals("limits")) ((com.fasterxml.jackson.databind.node.ObjectNode) hello.path("limits")).put("maxFrames", 900);
|
||||
emit(hello);
|
||||
if (mode.equals("descendant")) {
|
||||
|
||||
@@ -12,11 +12,10 @@ import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class HeadlessProcessSessionTest {
|
||||
@TempDir Path root;
|
||||
static final HeadlessLimits LIMITS = HeadlessFixture.LIMITS;
|
||||
final List<HeadlessProcessSession> sessions = new ArrayList<>();
|
||||
HeadlessProcessSession start(String mode) throws Exception {
|
||||
var process = new ProcessBuilder(HeadlessFixture.java(), "-cp", System.getProperty("java.class.path"), HeadlessFixture.class.getName(), mode).directory(root.toFile()).start();
|
||||
var session = new HeadlessProcessSession(process, new ObjectMapper(), LIMITS, "build"); sessions.add(session); return session;
|
||||
var session = new HeadlessProcessSession(process, new ObjectMapper(), HeadlessFixture.limits(mode), "build"); sessions.add(session); return session;
|
||||
}
|
||||
@AfterEach void cleanup() { sessions.forEach(session -> session.abort("test cleanup")); }
|
||||
@Test void fragmentedProtocolPreservesUnsignedFrameIdentityLayoutAndSeparateStderr() throws Exception {
|
||||
@@ -58,11 +57,11 @@ class HeadlessProcessSessionTest {
|
||||
var entered = new CountDownLatch(1);
|
||||
try (var workers = Executors.newSingleThreadExecutor()) {
|
||||
var result = workers.submit(() -> session.advance(30, ignored -> entered.countDown()));
|
||||
assertTrue(entered.await(2, TimeUnit.SECONDS));
|
||||
assertTrue(entered.await(5, TimeUnit.SECONDS));
|
||||
assertEquals(AutomationFailure.Code.BUSY, assertThrows(AutomationException.class,
|
||||
() -> session.call(TaskTools.HeadlessAction.STATE, Map.of())).failure().code());
|
||||
session.cancel();
|
||||
var outcome = result.get(2, TimeUnit.SECONDS);
|
||||
var outcome = result.get(10, TimeUnit.SECONDS);
|
||||
assertEquals(AutomationOutcome.Kind.CANCELLED, outcome.kind()); assertEquals(2, outcome.completedFrames()); assertNotNull(outcome.capture());
|
||||
}
|
||||
session.shutdown().toCompletableFuture().get(3, TimeUnit.SECONDS); assertFalse(session.alive());
|
||||
|
||||
@@ -30,8 +30,11 @@ public final class TaskLanguageQueries implements LanguageQueries {
|
||||
return new AutomationOutcome(AutomationOutcome.Kind.SUCCEEDED, 0, 0, List.of(), null);
|
||||
});
|
||||
try {
|
||||
handle.completion().toCompletableFuture().get(12, TimeUnit.SECONDS);
|
||||
handle.termination().toCompletableFuture().get(1, TimeUnit.SECONDS);
|
||||
// A failed result must also wait for worker termination and admission
|
||||
// cleanup before the caller can issue its next query.
|
||||
handle.completion().handle((outcome, failure) -> null)
|
||||
.thenCompose(ignored -> handle.termination()).toCompletableFuture().get(12, TimeUnit.SECONDS);
|
||||
handle.completion().toCompletableFuture().get();
|
||||
requireTask(session, taskId);
|
||||
return Objects.requireNonNull(result.get());
|
||||
} catch (ExecutionException failure) {
|
||||
|
||||
+12
-2
@@ -236,11 +236,21 @@ public final class DefaultAutomationSession implements AutomationSession {
|
||||
publish();
|
||||
}
|
||||
});
|
||||
operation.termination().whenComplete((v, f) -> {
|
||||
var settled = operation.termination().whenComplete((v, f) -> {
|
||||
subscription.unsubscribe();
|
||||
synchronized (this) { if (active == operation) { busy = false; publish(); } }
|
||||
});
|
||||
publish(); return operation;
|
||||
// Waiting on the raw worker future does not wait for its dependent
|
||||
// callbacks. Expose the stage that also releases session admission.
|
||||
var handle = new OperationHandle<AutomationOutcome>() {
|
||||
@Override public OperationId id() { return operation.id(); }
|
||||
@Override public OperationSnapshot snapshot() { return operation.snapshot(); }
|
||||
@Override public CompletionStage<AutomationOutcome> completion() { return operation.completion(); }
|
||||
@Override public CompletionStage<Void> termination() { return settled; }
|
||||
@Override public boolean cancel() { return operation.cancel(); }
|
||||
@Override public OperationSubscription subscribe(Consumer<OperationSnapshot> observer) { return operation.subscribe(observer); }
|
||||
};
|
||||
publish(); return handle;
|
||||
}
|
||||
|
||||
@Override public synchronized void attachRuntime(TaskIdentity identity, ManagedHeadlessSession next) {
|
||||
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
package p.studio.core.language;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import p.studio.api.automation.*;
|
||||
import p.studio.api.operation.*;
|
||||
import p.studio.core.project.ProjectAccessRegistry;
|
||||
import p.studio.core.session.DefaultAutomationSession;
|
||||
import p.studio.core.support.ControlledOperations;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.*;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class TaskLanguageQueriesTest {
|
||||
@TempDir Path root;
|
||||
|
||||
@Test void failedQueryWaitsForTerminationBeforeReturningAndAcceptingTheNextQuery() throws Exception {
|
||||
var operations = new ControlledOperations();
|
||||
var submitted = new LinkedBlockingQueue<ControlledOperations.Handle<?>>();
|
||||
var executor = new OperationExecutor() {
|
||||
@Override public <R> OperationHandle<R> submit(String summary, Callable<R> work) {
|
||||
var handle = operations.submit(summary, work);
|
||||
submitted.add(operations.last);
|
||||
return handle;
|
||||
}
|
||||
};
|
||||
var session = new DefaultAutomationSession(root, executor);
|
||||
var projects = new ProjectAccessRegistry();
|
||||
var registration = projects.register(root, session::enterManual, () -> true, session);
|
||||
var queries = new TaskLanguageQueries(projects, new LanguageQueryPort() {
|
||||
@Override public Map<String, Object> query(TaskIdentity task, String operation, Map<String, Object> parameters) {
|
||||
return Map.of("operation", operation);
|
||||
}
|
||||
@Override public void endTask(TaskIdentity task) { }
|
||||
});
|
||||
assertTrue(session.grant(false).toCompletableFuture().join().success());
|
||||
var task = session.acquire().task();
|
||||
try (var caller = Executors.newSingleThreadExecutor()) {
|
||||
var failed = caller.submit(() -> queries.query(root, task.value(), "formatting", Map.of()));
|
||||
var worker = submitted.poll(5, TimeUnit.SECONDS);
|
||||
assertNotNull(worker);
|
||||
var failure = new AutomationException(AutomationFailure.Code.READ_ONLY_SCOPE, "Read-only dependency");
|
||||
worker.completed.completeExceptionally(failure);
|
||||
try {
|
||||
assertThrows(TimeoutException.class, () -> failed.get(100, TimeUnit.MILLISECONDS));
|
||||
assertEquals(ControlResult.Status.BUSY, assertThrows(ControlDeniedException.class,
|
||||
() -> session.submit(task, "overlap", () -> null)).status());
|
||||
} finally { worker.stopped.complete(null); }
|
||||
assertSame(failure, assertThrows(ExecutionException.class, () -> failed.get(5, TimeUnit.SECONDS)).getCause());
|
||||
var next = caller.submit(() -> queries.query(root, task.value(), "definition", Map.of()));
|
||||
var nextWorker = submitted.poll(5, TimeUnit.SECONDS);
|
||||
assertNotNull(nextWorker);
|
||||
nextWorker.finish();
|
||||
assertEquals("definition", next.get(5, TimeUnit.SECONDS).get("operation"));
|
||||
} finally {
|
||||
if (operations.last != null) operations.last.stopped.complete(null);
|
||||
session.closeAsync().toCompletableFuture().join();
|
||||
registration.unsubscribe();
|
||||
}
|
||||
}
|
||||
}
|
||||
+12
@@ -18,6 +18,18 @@ class DefaultAutomationSessionTest {
|
||||
ControlResult await(CompletionStage<ControlResult> result) { return result.toCompletableFuture().join(); }
|
||||
TaskIdentity start(DefaultAutomationSession s) { assertEquals(GRANTED, await(s.grant(false)).status()); return s.acquire().task(); }
|
||||
|
||||
@Test void terminationObserversCanSubmitTheNextOperation() {
|
||||
var s = session(); var task = start(s);
|
||||
var first = s.submit(task, "first", () -> new AutomationOutcome(AutomationOutcome.Kind.SUCCEEDED, 0, 0, List.of(), null));
|
||||
var worker = operations.last;
|
||||
var next = first.termination().thenRun(() -> s.submit(task, "next",
|
||||
() -> new AutomationOutcome(AutomationOutcome.Kind.SUCCEEDED, 0, 0, List.of(), null)));
|
||||
worker.finish();
|
||||
assertDoesNotThrow(() -> next.toCompletableFuture().join());
|
||||
operations.last.finish();
|
||||
assertEquals(RETURNED, await(s.release(task)).status());
|
||||
}
|
||||
|
||||
@Test void taskCleanupRunsAfterWorkerTerminationAndBeforeManualControl() {
|
||||
var s = session(); var task = start(s);
|
||||
var cleaned = new java.util.concurrent.atomic.AtomicInteger();
|
||||
|
||||
Reference in New Issue
Block a user