compose real headless runtime with task build and lifecycle

This commit is contained in:
2026-09-29 11:27:42 +01:00
parent bc76f08bbd
commit 379420e7a9
10 changed files with 272 additions and 27 deletions
@@ -30,12 +30,13 @@ class StudioApplicationConfigurationTest {
assertFalse(executor.isShutdown());
assertTrue(mcp.isRunning());
var tools = context.getBean(p.studio.app.mcp.McpToolRegistry.class).descriptors();
org.junit.jupiter.api.Assertions.assertEquals(8, tools.size());
org.junit.jupiter.api.Assertions.assertEquals(17, tools.size());
assertTrue(context.getBean(p.studio.core.runtime.HeadlessGateway.class) instanceof p.studio.app.runtime.HeadlessProcessGateway);
org.junit.jupiter.api.Assertions.assertEquals("studio_project_context", tools.get(0).path("name").asText());
org.junit.jupiter.api.Assertions.assertEquals("studio_reference_read", tools.get(1).path("name").asText());
assertTrue(tools.toString().contains("studio_language_query"));
assertTrue(tools.toString().contains("studio_build_start"));
assertFalse(tools.toString().contains("studio_headless_boot"));
assertTrue(tools.toString().contains("studio_headless_boot"));
}
assertTrue(executor.isShutdown());
assertFalse(mcp.isRunning());
@@ -56,7 +56,7 @@ class McpTaskToolsTest {
}
@AfterEach void close() throws Exception {
buildGate.countDown();
if (runtime != null) runtime.gate.countDown();
if (runtime != null) { runtime.gate.countDown(); runtime.shutdownGate.complete(null); }
session.closeAsync().toCompletableFuture().get(5, TimeUnit.SECONDS);
workers.shutdownNow();
}
@@ -70,7 +70,7 @@ class McpTaskToolsTest {
JsonNode completed(String request) throws Exception {
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5);
JsonNode result;
do { result = poll(request); if (!List.of("RUNNING", "PENDING").contains(result.path("state").asText())) return result; Thread.sleep(5); }
do { result = poll(request); if (result.path("workerTerminated").asBoolean()) return result; Thread.sleep(5); }
while (System.nanoTime() < deadline);
fail("Operation did not finish: " + result); return null;
}
@@ -156,6 +156,34 @@ class McpTaskToolsTest {
assertEquals(ControlState.AGENT_WORKING, session.snapshot().state());
}
@Test void resetAllowsOnlyExplicitRebootOfTheSameKnownBuild() throws Exception {
acquire(); String build = buildAndBoot();
var original = runtime;
error("BUSY", call("studio_headless_boot", args().put("buildId", build)));
value(call("studio_headless_reset", args()));
error("BUILD_NOT_FOUND", call("studio_headless_boot", args().put("buildId", "unknown")));
value(call("studio_headless_boot", args().put("buildId", build)));
assertSame(original, runtime);
assertEquals(TaskTools.HeadlessAction.BOOT, runtime.lastAction);
error("BUSY", call("studio_headless_boot", args().put("buildId", build)));
}
@Test void rebuildWaitsForShutdownAcknowledgementBeforeTouchingArtifacts() throws Exception {
acquire(); String build = buildAndBoot();
runtime.shutdownGate = new CompletableFuture<>();
failBuild = true;
value(call("studio_build_start", args().put("clientRequestId", "blocked-rebuild")));
assertTrue(runtime.shutdownEntered.await(2, TimeUnit.SECONDS));
assertEquals(1, builds.get());
assertFalse(poll("blocked-rebuild").path("workerTerminated").asBoolean());
error("BUSY", call("studio_headless_boot", args().put("buildId", build)));
runtime.shutdownGate.complete(null);
assertEquals("FAILED", completed("blocked-rebuild").path("result").path("status").asText());
assertEquals(2, builds.get());
error("BUILD_NOT_FOUND", call("studio_headless_boot", args().put("buildId", build)));
assertEquals(ControlState.AGENT_WORKING, session.snapshot().state());
}
@Test void cancellationPreservesKnownProgressAndReclaimWaitsForWorkerTermination() throws Exception {
acquire(); buildAndBoot(); runtime.hold = true;
String operation = value(call("studio_headless_advance", args().put("clientRequestId", "long").put("frames", 50))).path("operationId").asText();
@@ -354,18 +382,22 @@ class McpTaskToolsTest {
final String id = UUID.randomUUID().toString(), build;
final AtomicInteger advances = new AtomicInteger();
final CountDownLatch entered = new CountDownLatch(1), gate = new CountDownLatch(1);
final CountDownLatch shutdownEntered = new CountDownLatch(1);
CompletableFuture<Void> shutdownGate = CompletableFuture.completedFuture(null);
TaskTools.HeadlessAction lastAction;
volatile boolean stopped, hold, cancelled;
volatile AutomationOutcome.Kind kind = AutomationOutcome.Kind.SUCCEEDED;
Map<String, Object> input;
FakeRuntime(String build) { this.build = build; }
public String sessionId() { return id; }
public void cancel() { cancelled = true; }
public CompletionStage<Void> shutdown() { stopped = true; return CompletableFuture.completedFuture(null); }
public CompletionStage<Void> shutdown() { shutdownEntered.countDown(); return shutdownGate.thenRun(() -> stopped = true); }
public long maxFramesPerAdvance() { return 600; }
CanonicalCapture capture(long logical) { return new CanonicalCapture(id, build, logical, 900, 1, 1, 1,
Base64.getDecoder().decode("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aK1kAAAAASUVORK5CYII=")); }
public TaskTools.HeadlessReply call(TaskTools.HeadlessAction action, Map<String, Object> input) {
this.input = input;
lastAction = action;
return new TaskTools.HeadlessReply(Map.of("sessionId", id), action == TaskTools.HeadlessAction.CAPTURE ? capture(5) : null);
}
public AutomationOutcome advance(long frames, Consumer<TrackedOperation.Progress> progress) {
@@ -9,6 +9,8 @@ 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);
static String mode;
static void emit(JsonNode value) throws Exception {
byte[] bytes = (value.toString() + "\r\n").getBytes(java.nio.charset.StandardCharsets.UTF_8);
@@ -28,7 +30,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(new HeadlessLimits(600, 4096, 4096, 1000, 500, 150)));
hello.set("limits", MAPPER.valueToTree(LIMITS));
if (mode.equals("limits")) ((com.fasterxml.jackson.databind.node.ObjectNode) hello.path("limits")).put("maxFrames", 900);
emit(hello);
if (mode.equals("descendant")) {
@@ -12,7 +12,7 @@ import static org.junit.jupiter.api.Assertions.*;
class HeadlessProcessSessionTest {
@TempDir Path root;
static final HeadlessLimits LIMITS = new HeadlessLimits(600, 4096, 4096, 1000, 500, 150);
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();
@@ -0,0 +1,176 @@
package p.studio.app.runtime;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.*;
import org.junit.jupiter.api.io.TempDir;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.ConfigurableApplicationContext;
import p.studio.api.automation.*;
import p.studio.api.project.*;
import p.studio.api.session.*;
import p.studio.api.shipper.Shipper;
import p.studio.app.StudioApplicationConfiguration;
import p.studio.core.project.ProjectLocalStudioSetupStore;
import java.nio.file.*;
import java.util.*;
import java.util.concurrent.TimeUnit;
import static org.junit.jupiter.api.Assertions.*;
/** Actual app composition and saved-source services; no runtime/build/LSP doubles. */
class HeadlessTaskIntegrationTest {
@TempDir Path root;
ConfigurableApplicationContext app;
ProjectSession project;
TaskTools tasks;
LanguageQueries language;
ObjectMapper mapper;
Path source;
String task, code;
final Set<ProcessHandle> ownedProcesses = new HashSet<>();
@BeforeEach void open() throws Exception {
root = root.toRealPath();
String installation = System.getProperty("studio.test.runtimeInstall", "");
assertFalse(installation.isBlank(), "Supply -PstudioRuntimeInstall=<runtime distribution>");
app = new SpringApplicationBuilder(StudioApplicationConfiguration.class).web(WebApplicationType.NONE).headless(true).run();
mapper = app.getBean(ObjectMapper.class);
for (var ref : p.studio.compiler.FrontendRegistryService.require("pbs").documentation().orElseThrow().references(1, p.studio.AppMode.Game)) {
if (!ref.id().startsWith("pbs:example:game:1:")) continue;
Path file = root.resolve(ref.id().substring("pbs:example:game:1:".length()));
Files.createDirectories(file.getParent()); Files.writeString(file, ref.text());
}
source = root.resolve("src/main.pbs"); code = Files.readString(source);
var reference = app.getBean(ProjectCatalog.class).openProject(root);
app.getBean(ProjectLocalStudioSetupStore.class).save(reference, new ProjectLocalStudioSetup(installation, null));
project = app.getBean(ProjectSessionFactory.class).open(reference);
tasks = app.getBean(TaskTools.class); language = app.getBean(LanguageQueries.class);
assertTrue(project.automation().grant(false).toCompletableFuture().get(5, TimeUnit.SECONDS).success());
task = tasks.acquire(root).task().value();
}
@AfterEach void close() {
try { if (project != null) project.close(); }
finally { if (app != null) app.close(); }
assertTrue(ownedProcesses.stream().noneMatch(ProcessHandle::isAlive), "Managed runtime processes must stop on project closure");
}
TrackedOperation finished(String request) throws Exception {
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(30);
do {
var result = tasks.operation(root, task, new OperationLookup(null, request));
if (result.workerTerminated()) return result;
Thread.sleep(5);
} while (System.nanoTime() < deadline);
throw new AssertionError("Operation did not finish: " + request);
}
TrackedOperation build(String request) throws Exception {
tasks.build(root, task, request); return finished(request);
}
String successfulBuild(String request) throws Exception {
var result = build(request); assertNull(result.failure());
assertNotNull(result.buildResult()); assertTrue(result.buildResult().success(), result.buildResult().diagnostics().toString());
assertNotNull(result.buildId()); return result.buildId();
}
TaskTools.HeadlessReply call(TaskTools.HeadlessAction action, String build) {
var reply = tasks.headless(root, task, action, build, Map.of());
if (action == TaskTools.HeadlessAction.BOOT) {
String installation = Path.of(System.getProperty("studio.test.runtimeInstall")).toAbsolutePath().toString();
ProcessHandle.current().descendants().filter(process -> process.info().command().orElse("").startsWith(installation + "/"))
.forEach(ownedProcesses::add);
assertFalse(ownedProcesses.isEmpty(), "Observe the actual packaged runtime process");
}
return reply;
}
AutomationOutcome advance(String request) throws Exception {
tasks.advance(root, task, request, 3);
var result = finished(request); assertNull(result.failure(), String.valueOf(result.failure()));
assertNotNull(result.runtimeResult()); return result.runtimeResult();
}
com.fasterxml.jackson.databind.JsonNode diagnostics() {
return mapper.valueToTree(language.query(root, task, "diagnostics", Map.of("uri", source.toUri().toString()))).path("result");
}
void authorityRetained() { assertEquals(ControlState.AGENT_WORKING, project.automation().snapshot().state()); }
@Test void savedEditsRebuildRealArtifactsAndCorrelateDevWithoutSnapshots() throws Exception {
assertTrue(diagnostics().isEmpty());
assertThrows(ControlDeniedException.class, () -> app.getBean(Shipper.class).prepare(project.projectReference(), ignored -> {}));
String first = successfulBuild("first");
String session = (String) call(TaskTools.HeadlessAction.BOOT, first).values().get("sessionId");
var initial = advance("initial");
assertEquals(AutomationOutcome.Kind.SUCCEEDED, initial.kind());
assertEquals(first, initial.capture().buildId());
assertArrayEquals(initial.capture().png(), project.automation().snapshot().capture().png());
call(TaskTools.HeadlessAction.RESET, null);
assertTrue(project.automation().snapshot().stale());
assertEquals(AutomationFailure.Code.NO_FRAME_AVAILABLE, assertThrows(AutomationException.class,
() -> call(TaskTools.HeadlessAction.CAPTURE, null)).failure().code());
assertEquals(session, call(TaskTools.HeadlessAction.BOOT, first).values().get("sessionId"));
assertArrayEquals(initial.capture().png(), advance("rebooted").capture().png());
// Native agent-style edit: same project files, no clean-tree or apply step.
Files.writeString(source, code.replace("Color.rgb(16, 20, 28)", "Color.rgb(80, 40, 20)"));
assertTrue(diagnostics().isEmpty());
String second = successfulBuild("second");
assertNotEquals(first, second);
assertTrue(project.automation().snapshot().stale());
assertTrue(finished("initial").captureStale());
assertEquals(AutomationFailure.Code.SESSION_NOT_FOUND, assertThrows(AutomationException.class,
() -> call(TaskTools.HeadlessAction.STATE, null)).failure().code());
assertEquals(AutomationFailure.Code.BUILD_NOT_FOUND, assertThrows(AutomationException.class,
() -> call(TaskTools.HeadlessAction.BOOT, first)).failure().code());
assertTrue(ownedProcesses.stream().noneMatch(ProcessHandle::isAlive), "Rebuild must stop the previous runtime");
assertNotEquals(session, call(TaskTools.HeadlessAction.BOOT, second).values().get("sessionId"));
var changed = advance("changed");
assertFalse(Arrays.equals(initial.capture().png(), changed.capture().png()));
assertEquals(second, project.automation().snapshot().capture().buildId());
assertFalse(project.automation().snapshot().stale());
authorityRetained();
assertTrue(tasks.release(root, task).toCompletableFuture().get(7, TimeUnit.SECONDS).success());
assertTrue(project.automation().snapshot().manualAllowed());
assertTrue(ownedProcesses.stream().noneMatch(ProcessHandle::isAlive), "Release must stop the runtime before returning control");
assertTrue(Files.readString(source).contains("Color.rgb(80, 40, 20)"));
}
@Test void compileAndGuestFailuresKeepAuthorityForCorrectiveBuilds() throws Exception {
String original = successfulBuild("original");
call(TaskTools.HeadlessAction.BOOT, original); advance("before-error");
Files.writeString(source, "fn frame( {");
assertFalse(diagnostics().isEmpty());
var failed = build("compile-error");
assertFalse(failed.buildResult().success()); assertNull(failed.buildId());
assertFalse(failed.buildResult().diagnostics().isEmpty());
assertFalse(project.automation().snapshot().diagnostics().isEmpty());
assertTrue(project.automation().snapshot().stale()); authorityRetained();
assertEquals(AutomationFailure.Code.BUILD_NOT_FOUND, assertThrows(AutomationException.class,
() -> call(TaskTools.HeadlessAction.BOOT, original)).failure().code());
Files.writeString(source, code.replace("x = x + 1;", "x = x / (x - x);"));
assertTrue(diagnostics().isEmpty());
call(TaskTools.HeadlessAction.BOOT, successfulBuild("guest-error"));
var fault = advance("fault");
assertEquals(AutomationOutcome.Kind.GUEST_FAULT, fault.kind());
assertFalse(fault.diagnostics().isEmpty());
assertNotNull(call(TaskTools.HeadlessAction.FAULT, null).values().get("fault"));
authorityRetained();
Files.writeString(source, code);
assertTrue(diagnostics().isEmpty());
call(TaskTools.HeadlessAction.BOOT, successfulBuild("corrected"));
assertEquals(AutomationOutcome.Kind.SUCCEEDED, advance("working-again").kind());
authorityRetained();
}
@Test void unavailableRuntimeIsExplicitAndCanBeConfiguredWithinTheSameTask() throws Exception {
String build = successfulBuild("build");
var setup = app.getBean(ProjectLocalStudioSetupStore.class);
setup.save(project.projectReference(), ProjectLocalStudioSetup.defaults());
assertEquals(AutomationFailure.Code.RUNTIME_UNAVAILABLE, assertThrows(AutomationException.class,
() -> call(TaskTools.HeadlessAction.BOOT, build)).failure().code());
authorityRetained();
setup.save(project.projectReference(), new ProjectLocalStudioSetup(System.getProperty("studio.test.runtimeInstall"), null));
call(TaskTools.HeadlessAction.BOOT, build);
assertEquals(AutomationOutcome.Kind.SUCCEEDED, advance("configured").kind());
authorityRetained();
}
}