From bc76f08bbdeeca80c5352e9273a37f44e5e9fe39 Mon Sep 17 00:00:00 2001 From: bQUARKz Date: Tue, 29 Sep 2026 11:02:21 +0100 Subject: [PATCH] implement real headless process gateway and supervision --- README.md | 11 + .../10. DEV and Automation Specification.md | 19 ++ prometeu-app/build.gradle.kts | 12 +- .../p/studio/app/runtime/HeadlessLimits.java | 20 ++ .../app/runtime/HeadlessProcessGateway.java | 41 +++ .../app/runtime/HeadlessProcessSession.java | 306 ++++++++++++++++++ .../p/studio/app/runtime/HeadlessWire.java | 103 ++++++ .../p/studio/app/mcp/McpTaskToolsTest.java | 2 +- .../p/studio/app/runtime/HeadlessFixture.java | 74 +++++ .../runtime/HeadlessInstalledRuntimeTest.java | 79 +++++ .../runtime/HeadlessProcessSessionTest.java | 97 ++++++ .../api/automation/CanonicalCapture.java | 10 +- .../studio/core/session/DefaultTaskTools.java | 2 +- 13 files changed, 771 insertions(+), 5 deletions(-) create mode 100644 prometeu-app/src/main/java/p/studio/app/runtime/HeadlessLimits.java create mode 100644 prometeu-app/src/main/java/p/studio/app/runtime/HeadlessProcessGateway.java create mode 100644 prometeu-app/src/main/java/p/studio/app/runtime/HeadlessProcessSession.java create mode 100644 prometeu-app/src/main/java/p/studio/app/runtime/HeadlessWire.java create mode 100644 prometeu-app/src/test/java/p/studio/app/runtime/HeadlessFixture.java create mode 100644 prometeu-app/src/test/java/p/studio/app/runtime/HeadlessInstalledRuntimeTest.java create mode 100644 prometeu-app/src/test/java/p/studio/app/runtime/HeadlessProcessSessionTest.java diff --git a/README.md b/README.md index 65a6da41..25c0b8e3 100644 --- a/README.md +++ b/README.md @@ -62,6 +62,17 @@ remain the developer's responsibility. See the [MCP contract](docs/specs/studio/11.%20MCP%20Tools%20and%20Project%20Knowledge%20Contract.md) for schemas, authorization, limits and delivery boundaries. +The real headless process adapter can be verified independently of its pending +task-service composition, using an extracted runtime distribution: + +```bash +./gradlew :prometeu-app:headlessProcessTest -PstudioRuntimeInstall=/absolute/path/to/runtime +``` + +This gate builds an installed PBS example, launches the actual runtime, checks +canonical PNGs and explicit reset/reboot, cancels an advance and verifies process +cleanup. It does not download a runtime or substitute a protocol fixture. + ## Requirements - JDK 21 or newer recommended for local development diff --git a/docs/specs/studio/10. DEV and Automation Specification.md b/docs/specs/studio/10. DEV and Automation Specification.md index bf1dcfef..b35972a6 100644 --- a/docs/specs/studio/10. DEV and Automation Specification.md +++ b/docs/specs/studio/10. DEV and Automation Specification.md @@ -203,6 +203,14 @@ mandatory capability MUST block the session; compatible minor additions are permitted. It MUST obey complete UTF-8 JSONL framing and separate protocol stdout from stderr diagnostics. Invalid input/schema MUST not disappear silently. +The application adapter resolves the executable from `ProjectLocalStudioSetup`, +launches it without a shell in the project root, and passes all six effective +limits explicitly. Hello and initialize share one handshake deadline. Required +hello limits must match the launch configuration; request IDs and session IDs +are checked on every subsequent response. Partial lines, invalid UTF-8, +duplicate JSON keys, uncorrelated replies and non-monotonic progress invalidate +the process. Stderr is drained independently into bounded diagnostics. + The runtime-owned surface covers boot/reset, set/clear normalized input, advance, capture, state/fault, cancel and shutdown. Conflicting execution work MUST NOT execute concurrently or be silently queued. Advance MUST preserve @@ -210,6 +218,10 @@ requested/completed counts and stop reasons. Cancellation is observed between frames; the current frame retains its deterministic watchdog, not a wall-clock guest deadline. No background realtime game loop is introduced for automation. +Reset leaves the runtime unbooted and clears its capture. It does not implicitly +boot the cartridge again. A subsequent explicit boot may reuse the session's +known build cartridge; an invalidated process requires an explicit new session. + | Configurable, handshake-advertised limit | Default | | --- | --- | | Frames per advance | 600 | @@ -229,9 +241,16 @@ Screenshot means the runtime's canonical **RGBA8888 framebuffer bitmap**. Capture MUST use lossless PNG/base64 with dimensions, original stride/layout, runtime session, `logical_frame_index` and `FrameId`. These two frame identities MUST NOT be assumed numerically equal. Studio MUST attach build correlation. +Both identities retain the full unsigned 64-bit range: Java uses `BigInteger`, +and MCP serializes integer JSON values without conversion through floating point. Hashes MAY supplement but MUST NOT replace pixels. No desktop/window screenshot, temporary-image-file transport or continuous video is permitted. +The adapter validates base64, PNG signature, RGBA8 header, dimensions and decoded +image consistency in memory, then forwards the original PNG bytes unchanged. +Its decoder currently guards allocations at 16,777,216 pixels; exceeding this +bound fails explicitly rather than resizing or substituting the image. + Agent and DEV MUST receive the same capture and correlation for requested advances. DEV MUST identify images from an older build/session as stale during edits/rebuilds. The previous execution MUST stop before rebuilding artifacts diff --git a/prometeu-app/build.gradle.kts b/prometeu-app/build.gradle.kts index 1e2ad67e..273cb769 100644 --- a/prometeu-app/build.gradle.kts +++ b/prometeu-app/build.gradle.kts @@ -32,7 +32,7 @@ javafx { } // Opt-in desktop gate: real JavaFX toolkit and windows, no display required by normal unit tests. -tasks.named("test") { exclude("**/DevDesktopTest.class", "**/InstalledKnowledgeTest.class") } +tasks.named("test") { exclude("**/DevDesktopTest.class", "**/InstalledKnowledgeTest.class", "**/HeadlessInstalledRuntimeTest.class") } tasks.register("devDesktopTest") { group = "verification" description = "Runs the DEV/Debug desktop lifecycle and handoff smoke tests (requires a display)." @@ -55,3 +55,13 @@ tasks.register("installedKnowledgeTest") { inputs.dir(distribution) systemProperty("studio.test.distribution", distribution.get().asFile.absolutePath) } + +tasks.register("headlessProcessTest") { + group = "verification" + description = "Exercises the configured packaged headless runtime (requires -PstudioRuntimeInstall)." + testClassesDirs = sourceSets["test"].output.classesDirs + classpath = sourceSets["test"].runtimeClasspath + useJUnitPlatform() + include("**/HeadlessInstalledRuntimeTest.class") + systemProperty("studio.test.runtimeInstall", providers.gradleProperty("studioRuntimeInstall").getOrElse("")) +} diff --git a/prometeu-app/src/main/java/p/studio/app/runtime/HeadlessLimits.java b/prometeu-app/src/main/java/p/studio/app/runtime/HeadlessLimits.java new file mode 100644 index 00000000..8a6f077a --- /dev/null +++ b/prometeu-app/src/main/java/p/studio/app/runtime/HeadlessLimits.java @@ -0,0 +1,20 @@ +package p.studio.app.runtime; + +import java.util.List; + +/** Configured before launch, then verified against the runtime's effective handshake. */ +public record HeadlessLimits(long maxFrames, int maxCommandBytes, int maxResponseBytes, + long handshakeTimeoutMs, long callTimeoutMs, long shutdownTimeoutMs) { + public HeadlessLimits { + if (maxFrames < 1 || maxCommandBytes < 4096 || maxResponseBytes < 4096 + || handshakeTimeoutMs < 1 || callTimeoutMs < 1 || shutdownTimeoutMs < 1) + throw new IllegalArgumentException("Invalid headless limits"); + } + public static HeadlessLimits defaults() { return new HeadlessLimits(600, 65536, 33554432, 5000, 60000, 5000); } + List arguments() { + return List.of("headless", "--stdio", "--max-frames", Long.toString(maxFrames), + "--max-command-bytes", Integer.toString(maxCommandBytes), "--max-response-bytes", Integer.toString(maxResponseBytes), + "--handshake-timeout-ms", Long.toString(handshakeTimeoutMs), "--call-timeout-ms", Long.toString(callTimeoutMs), + "--shutdown-timeout-ms", Long.toString(shutdownTimeoutMs)); + } +} diff --git a/prometeu-app/src/main/java/p/studio/app/runtime/HeadlessProcessGateway.java b/prometeu-app/src/main/java/p/studio/app/runtime/HeadlessProcessGateway.java new file mode 100644 index 00000000..137c661f --- /dev/null +++ b/prometeu-app/src/main/java/p/studio/app/runtime/HeadlessProcessGateway.java @@ -0,0 +1,41 @@ +package p.studio.app.runtime; + +import com.fasterxml.jackson.databind.ObjectMapper; +import p.studio.api.automation.*; +import p.studio.api.project.*; +import p.studio.api.shipper.ShipperPrepareResult; +import p.studio.core.runtime.HeadlessGateway; +import java.nio.file.*; +import java.util.*; +import java.util.function.Function; + +/** Configured-installation-only headless launcher; independent of desktop Debug. */ +public final class HeadlessProcessGateway implements HeadlessGateway { + private final ObjectMapper mapper; + private final Function setup; + private final HeadlessLimits limits; + public HeadlessProcessGateway(ObjectMapper mapper, Function setup) { + this(mapper, setup, HeadlessLimits.defaults()); + } + public HeadlessProcessGateway(ObjectMapper mapper, Function setup, HeadlessLimits limits) { + this.mapper = mapper; this.setup = setup; this.limits = limits; + } + @Override public Session boot(ProjectReference project, String buildId, ShipperPrepareResult build) throws Exception { + String installation = setup.apply(project).prometeuRuntimePath(); + if (installation == null) throw new AutomationException(AutomationFailure.Code.RUNTIME_UNAVAILABLE, "Configure the project runtime installation first"); + Path executable = Path.of(installation).resolve(System.getProperty("os.name").startsWith("Windows") ? "prometeu.exe" : "prometeu").toAbsolutePath().normalize(); + if (!Files.isRegularFile(executable) || !Files.isExecutable(executable)) + throw new AutomationException(AutomationFailure.Code.RUNTIME_UNAVAILABLE, "Configured runtime executable is unavailable"); + if (!build.success() || build.manifestPath() == null || !Files.isRegularFile(build.manifestPath())) + throw new AutomationException(AutomationFailure.Code.BUILD_NOT_FOUND, "Successful build manifest is unavailable"); + Path root = project.rootPath().toRealPath(), manifest = build.manifestPath().toRealPath(); + if (!manifest.startsWith(root)) throw new AutomationException(AutomationFailure.Code.OUTSIDE_PROJECT_SCOPE, "Build manifest is outside the project"); + var command = new ArrayList(); command.add(executable.toString()); command.addAll(limits.arguments()); + final Process process; + try { process = new ProcessBuilder(command).directory(root.toFile()).start(); } + catch (java.io.IOException unavailable) { throw new AutomationException(AutomationFailure.Code.RUNTIME_UNAVAILABLE, "Cannot launch the configured runtime"); } + var session = new HeadlessProcessSession(process, mapper, limits, buildId); + try { session.initializeAndBoot(manifest.getParent()); return session; } + catch (Exception failure) { session.abort("Headless startup failed"); throw failure; } + } +} diff --git a/prometeu-app/src/main/java/p/studio/app/runtime/HeadlessProcessSession.java b/prometeu-app/src/main/java/p/studio/app/runtime/HeadlessProcessSession.java new file mode 100644 index 00000000..ded75db0 --- /dev/null +++ b/prometeu-app/src/main/java/p/studio/app/runtime/HeadlessProcessSession.java @@ -0,0 +1,306 @@ +package p.studio.app.runtime; + +import com.fasterxml.jackson.core.*; +import com.fasterxml.jackson.databind.*; +import p.studio.api.automation.*; +import p.studio.core.runtime.HeadlessGateway; +import java.io.*; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.util.*; +import java.util.concurrent.*; +import java.util.concurrent.atomic.*; +import java.util.concurrent.locks.ReentrantLock; +import java.util.function.Consumer; +import static p.studio.app.runtime.HeadlessWire.*; + +/** One supervised process, bounded JSONL, no retry/replay and no simulated-time clock. */ +final class HeadlessProcessSession implements HeadlessGateway.Session { + private final Process process; + private final ObjectMapper mapper; + private final HeadlessLimits limits; + private final String buildId; + private volatile String sessionId; + private volatile JsonNode hello; + private Path cartridge; + private final CompletableFuture greeting = new CompletableFuture<>(); + private final Map pending = new ConcurrentHashMap<>(); + private final Set descendants = ConcurrentHashMap.newKeySet(); + private final ExecutorService io = Executors.newVirtualThreadPerTaskExecutor(); + private final ExecutorService writer = Executors.newSingleThreadExecutor(Thread.ofPlatform().daemon().name("headless-writer").factory()); + private final ScheduledExecutorService timer = Executors.newSingleThreadScheduledExecutor(Thread.ofPlatform().daemon().name("headless-supervisor").factory()); + private final ReentrantLock work = new ReentrantLock(); + private final AtomicBoolean dead = new AtomicBoolean(); + private final AtomicReference advance = new AtomicReference<>(); + private final Deque stderr = new ArrayDeque<>(); + private volatile boolean closing; + private CompletableFuture shutdown; + + HeadlessProcessSession(Process process, ObjectMapper source, HeadlessLimits limits, String buildId) { + this.process = process; this.limits = limits; this.buildId = buildId; + mapper = source.copy().enable(JsonParser.Feature.STRICT_DUPLICATE_DETECTION).enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS); + mapper.getFactory().setStreamReadConstraints(StreamReadConstraints.builder().maxStringLength(limits.maxResponseBytes()).build()); + timer.scheduleAtFixedRate(() -> { if (process.isAlive()) process.descendants().forEach(descendants::add); }, 0, 20, TimeUnit.MILLISECONDS); + io.execute(this::readOutput); io.execute(this::readErrors); + process.onExit().thenRun(() -> { if (!closing) abort("Headless process exited"); }); + } + + void initializeAndBoot(Path cartridge) throws Exception { + this.cartridge = cartridge; + long deadline = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(limits.handshakeTimeoutMs()); + hello = await(greeting, limits.handshakeTimeoutMs()); + version(hello.path("protocolVersion")); text(hello, "runtimeVersion"); capabilities(hello.path("capabilities")); + var expected = mapper.valueToTree(limits); + for (var fields = expected.fieldNames(); fields.hasNext();) { + String field = fields.next(); + if (count(hello.path("limits"), field) != expected.path(field).longValue()) + throw new AutomationException(AutomationFailure.Code.RUNTIME_INCOMPATIBLE, "Runtime limits do not match launch configuration"); + } + var init = mapper.createObjectNode(); init.putObject("protocolVersion").put("major", 1).put("minor", 0); + init.set("requiredCapabilities", mapper.valueToTree(CAPABILITIES)); + var negotiated = request("initialize", init, null, remaining(deadline)); + version(negotiated.path("protocolVersion")); capabilities(negotiated.path("capabilities")); + state(request("boot", mapper.createObjectNode().put("path", cartridge.toString()), null, limits.callTimeoutMs())); + } + @Override public String sessionId() { return sessionId; } + @Override public long maxFramesPerAdvance() { return limits.maxFrames(); } + long pid() { return process.pid(); } + boolean alive() { return process.isAlive() || descendants.stream().anyMatch(ProcessHandle::isAlive); } + + @Override public TaskTools.HeadlessReply call(TaskTools.HeadlessAction action, Map input) throws Exception { + if (!work.tryLock()) throw new AutomationException(AutomationFailure.Code.BUSY, "Headless operation active"); + try { + String command = switch (action) { + case BOOT -> "boot"; + case RESET -> "reset"; case SET_INPUT -> "set_input"; case CLEAR_INPUT -> "clear_input"; + case CAPTURE -> "capture"; case STATE -> "get_state"; case FAULT -> "get_fault"; + default -> throw new IllegalArgumentException("Use lifecycle methods for boot/shutdown"); + }; + var params = action == TaskTools.HeadlessAction.BOOT ? mapper.createObjectNode().put("path", cartridge.toString()) : mapper.valueToTree(input); + var result = request(command, params, null, limits.callTimeoutMs()); + var values = new LinkedHashMap(); values.put("sessionId", sessionId); values.put("buildId", buildId); + CanonicalCapture capture = null; + switch (action) { + case CAPTURE -> capture = capture(result, sessionId, buildId); + case STATE, RESET, BOOT -> { + state(result); values.put("state", mapper.convertValue(result, Object.class)); + values.put("runtimeVersion", text(hello, "runtimeVersion")); + values.put("limits", mapper.convertValue(hello.path("limits"), Object.class)); + values.put("capabilities", mapper.convertValue(hello.path("capabilities"), Object.class)); + } + case FAULT -> { fault(result); values.put("fault", mapper.convertValue(result, Object.class)); } + default -> { if (!result.isObject()) throw invalid("Invalid acknowledgement"); } + } + return new TaskTools.HeadlessReply(values, capture); + } catch (AutomationException failure) { invalidateMalformed(failure); throw failure; } + finally { work.unlock(); } + } + + @Override public AutomationOutcome advance(long frames, Consumer progress) throws Exception { + if (frames < 0 || frames > limits.maxFrames()) throw new AutomationException(AutomationFailure.Code.LIMIT_EXCEEDED, "Requested frames exceed effective limit"); + if (!work.tryLock()) throw new AutomationException(AutomationFailure.Code.BUSY, "Headless operation active"); + boolean interrupted = false; + try { + var item = new Pending("advance", frames, progress); advance.set(item); + send(item, mapper.createObjectNode().put("frames", frames)); + JsonNode result; + try { result = await(item.result, limits.callTimeoutMs()); } + catch (InterruptedException cancelled) { + interrupted = true; cancel(); + result = awaitUninterruptibly(item.result, limits.shutdownTimeoutMs()); + } catch (TimeoutException timedOut) { + cancel(); + try { awaitUninterruptibly(item.result, limits.shutdownTimeoutMs()); } catch (Exception ignored) { } + abort("Headless advance deadline exceeded"); throw infrastructure("Headless advance deadline exceeded"); + } + long requested = count(result, "requested"), completed = count(result, "completed"); + if (requested != frames || completed > frames || completed < item.completed) throw invalid("Inconsistent final progress"); + progress.accept(new TrackedOperation.Progress(frames, completed)); + var diagnostics = new ArrayList(); + var kind = switch (text(result, "stop")) { + case "completed" -> { if (completed != frames) throw invalid("Incomplete completed result"); yield AutomationOutcome.Kind.SUCCEEDED; } + case "canceled" -> AutomationOutcome.Kind.CANCELLED; + case "terminated" -> AutomationOutcome.Kind.TERMINATED; + case "faulted" -> { fault(result.path("fault")); if (result.path("fault").isNull()) throw invalid("Missing fault"); diagnostics.add(result.path("fault").toString()); yield AutomationOutcome.Kind.GUEST_FAULT; } + case "host_error" -> { error(result.path("error")); diagnostics.add(result.path("error").toString()); yield AutomationOutcome.Kind.INFRASTRUCTURE_FAILURE; } + default -> throw invalid("Unknown advance stop"); + }; + CanonicalCapture captured = null; + if (!closing) { + try { captured = capture(request("capture", mapper.createObjectNode(), null, limits.callTimeoutMs()), sessionId, buildId); } + catch (AutomationException noFrame) { if (noFrame.failure().code() != AutomationFailure.Code.NO_FRAME_AVAILABLE) throw noFrame; } + } + synchronized (stderr) { diagnostics.addAll(stderr); stderr.clear(); } + return new AutomationOutcome(kind, requested, completed, diagnostics, captured); + } catch (TimeoutException timeout) { abort("Cancellation deadline exceeded"); throw infrastructure("Cancellation deadline exceeded"); } + catch (AutomationException failure) { invalidateMalformed(failure); throw failure; } + finally { advance.set(null); work.unlock(); if (interrupted) Thread.currentThread().interrupt(); } + } + + @Override public void cancel() { + var target = advance.get(); + if (target == null || target.result.isDone() || !target.cancelled.compareAndSet(false, true) || dead.get()) return; + var cancel = new Pending("cancel", null, null); + send(cancel, mapper.createObjectNode().put("targetRequestId", target.id)); + timer.schedule(() -> { if (!target.result.isDone() || !cancel.result.isDone()) abort("Runtime did not stop after cancellation"); }, limits.shutdownTimeoutMs(), TimeUnit.MILLISECONDS); + } + @Override public synchronized CompletionStage shutdown() { + if (shutdown != null) return shutdown; + closing = true; + shutdown = CompletableFuture.runAsync(() -> { + long deadline = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(limits.shutdownTimeoutMs()); + try { + if (!dead.get()) { + var response = request("shutdown", mapper.createObjectNode(), null, remaining(deadline)); + if (!response.path("closed").isBoolean() || !response.path("closed").booleanValue()) throw invalid("Missing shutdown acknowledgement"); + if (!process.waitFor(remaining(deadline), TimeUnit.MILLISECONDS)) throw new TimeoutException(); + } + } catch (Exception failure) { + abort("Headless shutdown failed"); throw infrastructure("Headless shutdown failed; owned process tree terminated"); + } finally { terminate(); if (alive()) throw infrastructure("Owned runtime process tree did not terminate"); } + }); + return shutdown; + } + private JsonNode request(String command, JsonNode params, Consumer observer, long timeout) throws Exception { + var item = new Pending(command, null, observer); send(item, params); + try { return await(item.result, timeout); } + catch (InterruptedException interrupted) { abort("Headless request interrupted"); Thread.currentThread().interrupt(); throw infrastructure("Headless request interrupted"); } + catch (TimeoutException exceeded) { + if (!command.equals("shutdown") && !command.equals("initialize") && !dead.get()) { + closing = true; + try { + var stop = new Pending("shutdown", null, null); send(stop, mapper.createObjectNode()); + awaitUninterruptibly(stop.result, limits.shutdownTimeoutMs()); + } catch (Exception ignored) { /* Deadline escalation below always invalidates this process. */ } + } + abort("Headless request deadline exceeded"); throw infrastructure("Headless request deadline exceeded"); + } + } + private void send(Pending item, JsonNode params) { + if (dead.get()) throw infrastructure("Headless session lost; create a new session explicitly"); + var envelope = mapper.createObjectNode().put("requestId", item.id).put("command", item.command); envelope.set("params", params); + final byte[] bytes; + try { bytes = mapper.writeValueAsBytes(envelope); } catch (IOException invalid) { throw new IllegalArgumentException(invalid); } + if (bytes.length > limits.maxCommandBytes()) throw new AutomationException(AutomationFailure.Code.LIMIT_EXCEEDED, "Command exceeds runtime message limit"); + item.params = params; pending.put(item.id, item); + try { writer.execute(() -> { + try { process.getOutputStream().write(bytes); process.getOutputStream().write('\n'); process.getOutputStream().flush(); } + catch (IOException failed) { abort("Headless stdin closed"); } + }); } catch (RejectedExecutionException closed) { abort("Headless writer closed"); throw infrastructure("Headless writer closed"); } + } + + private void readOutput() { + try (var input = new BufferedInputStream(process.getInputStream())) { + var bytes = new ByteArrayOutputStream(); int next; + while ((next = input.read()) != -1) { + if (next == '\n') { + byte[] line = bytes.toByteArray(); bytes.reset(); + String json = StandardCharsets.UTF_8.newDecoder().decode(java.nio.ByteBuffer.wrap(line)).toString(); + receive(mapper.readTree(json)); + } else { + if (bytes.size() >= limits.maxResponseBytes()) throw invalid("Response exceeds limit"); + bytes.write(next); + } + } + if (bytes.size() != 0) throw invalid("Truncated JSONL response"); + if (!closing || !pending.isEmpty()) abort("Headless stdout closed"); + } catch (Exception failure) { abort("Malformed or lost headless output"); } + } + private void receive(JsonNode message) { + process.descendants().forEach(descendants::add); + if (message == null || !message.isObject()) throw invalid("Expected object"); + if (sessionId == null) { + if (!text(message, "type").equals("hello")) throw invalid("Expected hello"); + sessionId = text(message, "sessionId"); greeting.complete(message); return; + } + if (!text(message, "sessionId").equals(sessionId)) throw invalid("Wrong session identity"); + var item = pending.get(text(message, "requestId")); + if (item == null) throw invalid("Uncorrelated response"); + if (text(message, "type").equals("progress")) { + long requested = count(message, "requested"), completed = count(message, "completed"); + if (item.frames == null || requested != item.frames || completed < item.completed || completed > requested) throw invalid("Invalid progress"); + item.completed = completed; item.observer.accept(new TrackedOperation.Progress(requested, completed)); return; + } + if (!text(message, "type").equals("response") || message.has("result") == message.has("error")) throw invalid("Invalid response envelope"); + if (message.has("error")) { + var error = message.path("error"); error(error); + var code = switch (text(error, "code")) { + case "no_frame_available" -> AutomationFailure.Code.NO_FRAME_AVAILABLE; + case "busy", "already_booted" -> AutomationFailure.Code.BUSY; + case "not_cancelable" -> AutomationFailure.Code.NOT_CANCELABLE; + case "incompatible_version", "unsupported_capability" -> AutomationFailure.Code.RUNTIME_INCOMPATIBLE; + case "limit_exceeded", "response_too_large" -> AutomationFailure.Code.LIMIT_EXCEEDED; + default -> AutomationFailure.Code.INFRASTRUCTURE_FAILURE; + }; + pending.remove(item.id); + item.result.completeExceptionally(new AutomationException(code, "Runtime " + error.path("code").asText() + ": " + error.path("message").asText())); + } else { + var result = message.get("result"); + if (item.command.equals("cancel") && (!result.path("requested").isBoolean() || !result.path("requested").booleanValue() + || !result.path("targetRequestId").equals(item.params.path("targetRequestId")))) throw invalid("Invalid cancellation acknowledgement"); + pending.remove(item.id); item.result.complete(result); + } + } + private void readErrors() { + try (var input = process.getErrorStream()) { + byte[] bytes = new byte[1024]; int read; + while ((read = input.read(bytes)) != -1) synchronized (stderr) { + stderr.addLast(new String(bytes, 0, read, StandardCharsets.UTF_8)); + while (stderr.size() > 32) stderr.removeFirst(); + } + } catch (IOException ignored) { } + } + void abort(String message) { + if (dead.compareAndSet(false, true)) { + terminate(); + greeting.completeExceptionally(infrastructure(message)); + pending.values().forEach(item -> item.result.completeExceptionally(infrastructure(message))); pending.clear(); + } else terminate(); + } + private void terminate() { + dead.set(true); + process.descendants().forEach(descendants::add); + descendants.forEach(ProcessHandle::destroyForcibly); process.destroyForcibly(); + writer.shutdownNow(); timer.shutdownNow(); io.shutdown(); + // Killing first unblocks pipe IO; closing a writer before kill can wait on its blocked monitor. + try { process.waitFor(1000, TimeUnit.MILLISECONDS); } catch (InterruptedException interrupted) { Thread.currentThread().interrupt(); } + descendants.forEach(handle -> { if (handle.isAlive()) handle.destroyForcibly(); }); + for (var handle : descendants) { + try { handle.onExit().get(1000, TimeUnit.MILLISECONDS); } + catch (Exception ignored) { /* A failed cleanup is surfaced by shutdown below. */ } + } + if (!process.isAlive()) { + try { process.getOutputStream().close(); } catch (IOException ignored) { } + } + } + private void invalidateMalformed(AutomationException failure) { + if (failure.getMessage().startsWith("Invalid headless response:")) abort("Invalid headless response"); + } + private static AutomationException infrastructure(String message) { return new AutomationException(AutomationFailure.Code.INFRASTRUCTURE_FAILURE, message); } + private static T await(CompletableFuture future, long timeout) throws Exception { + try { return future.get(timeout, TimeUnit.MILLISECONDS); } + catch (ExecutionException error) { if (error.getCause() instanceof Exception cause) throw cause; throw error; } + } + private static long remaining(long deadline) throws TimeoutException { + long nanos = deadline - System.nanoTime(); + if (nanos <= 0) throw new TimeoutException(); + return Math.max(1, TimeUnit.NANOSECONDS.toMillis(nanos)); + } + private static T awaitUninterruptibly(CompletableFuture future, long timeout) throws Exception { + long deadline = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(timeout); + while (true) { + try { return await(future, Math.max(1, TimeUnit.NANOSECONDS.toMillis(deadline - System.nanoTime()))); } + catch (InterruptedException ignored) { if (System.nanoTime() >= deadline) throw new TimeoutException(); } + } + } + private static final class Pending { + final String id = UUID.randomUUID().toString(), command; + final Long frames; + final Consumer observer; + final CompletableFuture result = new CompletableFuture<>(); + final AtomicBoolean cancelled = new AtomicBoolean(); + volatile long completed; + JsonNode params; + Pending(String command, Long frames, Consumer observer) { this.command = command; this.frames = frames; this.observer = observer; } + } +} diff --git a/prometeu-app/src/main/java/p/studio/app/runtime/HeadlessWire.java b/prometeu-app/src/main/java/p/studio/app/runtime/HeadlessWire.java new file mode 100644 index 00000000..1e7ae406 --- /dev/null +++ b/prometeu-app/src/main/java/p/studio/app/runtime/HeadlessWire.java @@ -0,0 +1,103 @@ +package p.studio.app.runtime; + +import com.fasterxml.jackson.databind.JsonNode; +import p.studio.api.automation.*; +import java.math.BigInteger; +import java.nio.ByteBuffer; +import java.util.*; + +/** Validates required v1 fields while permitting compatible minor additions. */ +final class HeadlessWire { + static final Set CAPABILITIES = Set.of("boot", "reset", "set_input", "clear_input", "advance", "capture", "get_state", "get_fault", "cancel", "shutdown"); + static String text(JsonNode node, String key) { + var value = node.path(key); + if (!value.isTextual() || value.textValue().isBlank()) throw invalid("Missing " + key); + return value.textValue(); + } + static BigInteger uint(JsonNode value) { + if (!value.isIntegralNumber() || value.bigIntegerValue().signum() < 0 || value.bigIntegerValue().bitLength() > 64) throw invalid("Invalid uint64"); + return value.bigIntegerValue(); + } + static long count(JsonNode node, String key) { + try { return uint(node.path(key)).longValueExact(); } + catch (ArithmeticException overflow) { throw invalid("Counter exceeds requested operation range"); } + } + static void version(JsonNode value) { + if (!value.path("major").isIntegralNumber() || !value.path("major").bigIntegerValue().equals(BigInteger.ONE)) + throw new AutomationException(AutomationFailure.Code.RUNTIME_INCOMPATIBLE, "Unsupported headless protocol major"); + uint(value.path("minor")); + } + static void capabilities(JsonNode value) { + if (!value.isArray()) throw invalid("Missing capabilities"); + var actual = new HashSet(); + for (var item : value) { if (!item.isTextual()) throw invalid("Invalid capability"); actual.add(item.textValue()); } + if (!actual.containsAll(CAPABILITIES)) throw new AutomationException(AutomationFailure.Code.RUNTIME_INCOMPATIBLE, "Required headless capability unavailable"); + } + static void state(JsonNode value) { + for (var key : List.of("pc", "logicalFrameIndex", "tickIndex", "appId")) uint(value.path(key)); + if (!Set.of("running", "paused", "terminated", "faulted").contains(text(value, "status")) || !value.path("stackTop").isArray()) throw invalid("Invalid state"); + for (var item : value.path("stackTop")) { + var data = item.path("value"); + boolean valid = switch (text(item, "kind")) { + case "int32" -> data.isIntegralNumber() && data.canConvertToInt(); + case "int64" -> data.isTextual() && signed64(data.textValue()); + case "float64", "string" -> data.isTextual(); + case "boolean" -> data.isBoolean(); + case "null" -> data.isNull(); + case "heap_ref" -> { uint(data); yield true; } + default -> false; + }; + if (!valid) throw invalid("Invalid typed stack value"); + } + } + private static boolean signed64(String text) { try { Long.parseLong(text); return true; } catch (NumberFormatException invalid) { return false; } } + static void error(JsonNode value) { + text(value, "code"); + if (!value.path("message").isTextual() || !value.path("details").isObject()) throw invalid("Invalid structured error"); + } + static void fault(JsonNode value) { + if (value.isNull()) return; + if (!value.path("pc").isNull()) uint(value.path("pc")); + if (!value.path("summary").isTextual()) throw invalid("Invalid fault summary"); + switch (text(value, "kind")) { + case "vm_trap" -> { + var trap = value.path("trap"); + for (var key : List.of("pc", "code", "opcode")) uint(trap.path(key)); + if (!trap.path("message").isTextual() || !(trap.path("span").isObject() || trap.path("span").isNull())) throw invalid("Invalid trap"); + } + case "vm_panic" -> { if (!value.path("message").isTextual()) throw invalid("Invalid panic"); } + case "vm_init" -> { text(value.path("initError"), "code"); text(value.path("initError"), "message"); } + default -> throw invalid("Invalid fault kind"); + } + } + static CanonicalCapture capture(JsonNode value, String session, String build) { + if (!text(value, "mimeType").equals("image/png") || !text(value, "encoding").equals("base64") || !text(value, "pixelFormat").equals("RGBA8888")) throw invalid("Invalid capture encoding"); + int width = dimension(value, "width"), height = dimension(value, "height"), stride = dimension(value, "stridePixels"); + if (stride < width || (long) width * height > 16_777_216) throw invalid("Invalid or oversized framebuffer layout"); + final byte[] png; + try { png = Base64.getDecoder().decode(text(value, "data")); } + catch (IllegalArgumentException malformed) { throw invalid("Invalid capture base64"); } + byte[] signature = {(byte)137,80,78,71,13,10,26,10}; + if (png.length < 33 || !Arrays.equals(signature, Arrays.copyOf(png, 8))) throw invalid("Invalid PNG"); + var header = ByteBuffer.wrap(png); + if (header.getInt(8) != 13 || header.getInt(12) != 0x49484452 || header.getInt(16) != width || header.getInt(20) != height + || png[24] != 8 || png[25] != 6) throw invalid("PNG does not match RGBA8888 metadata"); + try (var encoded = new javax.imageio.stream.MemoryCacheImageInputStream(new java.io.ByteArrayInputStream(png))) { + var readers = javax.imageio.ImageIO.getImageReaders(encoded); + if (!readers.hasNext()) throw invalid("Undecodable PNG"); + var reader = readers.next(); + try { + reader.setInput(encoded); + var decoded = reader.read(0); + if (decoded == null || decoded.getWidth() != width || decoded.getHeight() != height) throw invalid("Undecodable PNG"); + } finally { reader.dispose(); } + } catch (java.io.IOException malformed) { throw invalid("Undecodable PNG"); } + return new CanonicalCapture(session, build, uint(value.path("logicalFrameIndex")), uint(value.path("frameId")), width, height, stride, png); + } + private static int dimension(JsonNode value, String key) { + long number = count(value, key); + if (number < 1 || number > Integer.MAX_VALUE) throw invalid("Invalid dimension"); + return (int) number; + } + static AutomationException invalid(String message) { return new AutomationException(AutomationFailure.Code.INFRASTRUCTURE_FAILURE, "Invalid headless response: " + message); } +} diff --git a/prometeu-app/src/test/java/p/studio/app/mcp/McpTaskToolsTest.java b/prometeu-app/src/test/java/p/studio/app/mcp/McpTaskToolsTest.java index bebead92..d3b775ba 100644 --- a/prometeu-app/src/test/java/p/studio/app/mcp/McpTaskToolsTest.java +++ b/prometeu-app/src/test/java/p/studio/app/mcp/McpTaskToolsTest.java @@ -198,7 +198,7 @@ class McpTaskToolsTest { assertEquals("CANCELLED", result.path("result").path("status").asText()); assertEquals(2, result.path("progress").path("completedFrames").asInt()); assertFalse(result.path("capture").path("stale").asBoolean()); - assertEquals(2, session.snapshot().capture().logicalFrameIndex()); + assertEquals(java.math.BigInteger.valueOf(2), session.snapshot().capture().logicalFrameIndex()); assertEquals(ControlState.AGENT_WORKING, session.snapshot().state()); assertFalse(value(call("studio_operation_cancel", args().put("operationId", operation))).path("cancellationRequested").asBoolean()); } diff --git a/prometeu-app/src/test/java/p/studio/app/runtime/HeadlessFixture.java b/prometeu-app/src/test/java/p/studio/app/runtime/HeadlessFixture.java new file mode 100644 index 00000000..56850efb --- /dev/null +++ b/prometeu-app/src/test/java/p/studio/app/runtime/HeadlessFixture.java @@ -0,0 +1,74 @@ +package p.studio.app.runtime; + +import com.fasterxml.jackson.databind.*; +import java.io.*; +import java.math.BigInteger; +import java.nio.file.*; +import java.util.*; + +/** Deliberately adversarial child process. Never packaged into production. */ +public final class HeadlessFixture { + static final ObjectMapper MAPPER = new ObjectMapper(); + static String mode; + static void emit(JsonNode value) throws Exception { + byte[] bytes = (value.toString() + "\r\n").getBytes(java.nio.charset.StandardCharsets.UTF_8); + for (int at = 0; at < bytes.length; at += 7) { System.out.write(bytes, at, Math.min(7, bytes.length - at)); System.out.flush(); } + } + static JsonNode state() { return MAPPER.createObjectNode().put("pc", 0).put("logicalFrameIndex", new BigInteger("18446744073709551615")) + .put("tickIndex", new BigInteger("18446744073709551615")).put("appId", 1).put("status", "paused").set("stackTop", MAPPER.createArrayNode()); } + static void response(String id, JsonNode result) throws Exception { + emit(MAPPER.createObjectNode().put("type", "response").put("sessionId", mode.equals("wrong-session") ? "alien" : "fixture").put("requestId", id).set("result", result)); + } + public static void main(String[] args) throws Exception { + mode = args[0]; + if (mode.equals("child") || mode.equals("no-hello")) { Thread.sleep(60000); return; } + if (mode.equals("malformed")) { System.out.println("not json"); Thread.sleep(60000); return; } + if (mode.equals("oversized")) { System.out.print("x".repeat(5000)); System.out.flush(); Thread.sleep(60000); return; } + if (mode.equals("utf8")) { System.out.write(new byte[]{(byte)0xff, 10}); System.out.flush(); Thread.sleep(60000); return; } + 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))); + if (mode.equals("limits")) ((com.fasterxml.jackson.databind.node.ObjectNode) hello.path("limits")).put("maxFrames", 900); + emit(hello); + if (mode.equals("descendant")) { + var child = new ProcessBuilder(java(), "-cp", System.getProperty("java.class.path"), HeadlessFixture.class.getName(), "child").start(); + Files.writeString(Path.of("descendant.pid"), Long.toString(child.pid())); + } + System.err.println("fixture stderr is not JSONL"); + String active = null; long frames = 0; + var reader = new BufferedReader(new InputStreamReader(System.in)); + for (String line; (line = reader.readLine()) != null;) { + var request = MAPPER.readTree(line); String id = request.path("requestId").asText(), command = request.path("command").asText(); + switch (command) { + case "initialize" -> response(id, MAPPER.createObjectNode().setAll(Map.of("protocolVersion", hello.path("protocolVersion"), "capabilities", hello.path("capabilities")))); + case "boot", "reset" -> response(id, state()); + case "get_state" -> { if (!mode.equals("hang-call")) response(id, state()); } + case "get_fault" -> response(id, MAPPER.nullNode()); + case "advance" -> { + active = id; frames = request.path("params").path("frames").longValue(); + emit(MAPPER.createObjectNode().put("type", "progress").put("sessionId", "fixture").put("requestId", id) + .put("requested", frames).put("completed", mode.equals("bad-progress") ? frames + 1 : 2)); + if (mode.equals("crash")) System.exit(23); + if (mode.equals("hang-cancel") || mode.equals("cooperative") || mode.equals("descendant")) continue; + response(id, MAPPER.createObjectNode().put("requested", frames).put("completed", frames).put("stop", "completed")); + } + case "cancel" -> { + if (mode.equals("hang-cancel") || mode.equals("descendant")) continue; + response(id, MAPPER.createObjectNode().put("requested", true).put("targetRequestId", active)); + response(active, MAPPER.createObjectNode().put("requested", frames).put("completed", 2).put("stop", "canceled")); + } + case "capture" -> { + var image = new java.awt.image.BufferedImage(1, 1, java.awt.image.BufferedImage.TYPE_INT_ARGB); + image.setRGB(0, 0, 0xff123456); var bytes = new ByteArrayOutputStream(); javax.imageio.ImageIO.write(image, "png", bytes); + response(id, MAPPER.createObjectNode().put("mimeType", "image/png").put("encoding", "base64").put("pixelFormat", "RGBA8888") + .put("width", 1).put("height", 1).put("stridePixels", 3).put("logicalFrameIndex", new BigInteger("18446744073709551615")) + .put("frameId", new BigInteger("9223372036854775808")).put("data", mode.equals("bad-png") ? "broken" : Base64.getEncoder().encodeToString(bytes.toByteArray()))); + } + case "shutdown" -> { if (mode.equals("descendant")) continue; response(id, MAPPER.createObjectNode().put("closed", true)); return; } + default -> response(id, MAPPER.createObjectNode()); + } + } + } + static String java() { return Path.of(System.getProperty("java.home"), "bin", "java").toString(); } +} diff --git a/prometeu-app/src/test/java/p/studio/app/runtime/HeadlessInstalledRuntimeTest.java b/prometeu-app/src/test/java/p/studio/app/runtime/HeadlessInstalledRuntimeTest.java new file mode 100644 index 00000000..4810539f --- /dev/null +++ b/prometeu-app/src/test/java/p/studio/app/runtime/HeadlessInstalledRuntimeTest.java @@ -0,0 +1,79 @@ +package p.studio.app.runtime; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.jupiter.api.*; +import org.junit.jupiter.api.io.TempDir; +import p.studio.api.automation.*; +import p.studio.api.project.*; +import p.studio.app.compiler.CompilerBuildGatewayAdapter; +import p.studio.app.operation.ExecutorOperationExecutor; +import p.studio.core.project.*; +import p.studio.core.shipper.StudioShipperService; +import java.nio.file.*; +import java.util.*; +import java.util.concurrent.*; +import static org.junit.jupiter.api.Assertions.*; + +/** Explicit packaged-process gate, not satisfied by protocol fixtures. */ +class HeadlessInstalledRuntimeTest { + @TempDir Path root; + @Test void configuredDistributionBootsSavedBuildAndReturnsDeterministicCanonicalPixels() throws Exception { + String install = System.getProperty("studio.test.runtimeInstall"); + assertNotNull(install, "Supply -PstudioRuntimeInstall="); + assertTrue(Files.isRegularFile(Path.of(install, "prometeu-headless"))); + var mapper = new ObjectMapper(); + for (var doc : p.studio.compiler.FrontendRegistryService.require("pbs").documentation().orElseThrow().references(1, p.studio.AppMode.Game)) + if (doc.id().startsWith("pbs:example:game:1:")) { + Path file = root.resolve(doc.id().substring("pbs:example:game:1:".length())); + Files.createDirectories(file.getParent()); Files.writeString(file, doc.text()); + } + var setup = new ProjectLocalStudioSetupStore(mapper); + var project = new ProjectCatalogService(root, mapper, setup).openProject(root); + setup.save(project, new ProjectLocalStudioSetup(install, null)); + try (var workers = Executors.newSingleThreadExecutor(); var packer = p.packer.Packer.bootstrap(mapper, ignored -> {})) { + var build = new StudioShipperService(new CompilerBuildGatewayAdapter(), packer.workspaceService(), mapper, new ExecutorOperationExecutor(workers)) + .prepare(project, ignored -> {}).completion().toCompletableFuture().get(15, TimeUnit.SECONDS); + assertTrue(build.success(), build.diagnostics().toString()); + var gateway = new HeadlessProcessGateway(mapper, setup::load); + var session = (HeadlessProcessSession) gateway.boot(project, "real-build", build); + try { + assertEquals(600, session.maxFramesPerAdvance()); + assertEquals(AutomationFailure.Code.NO_FRAME_AVAILABLE, assertThrows(AutomationException.class, + () -> session.call(TaskTools.HeadlessAction.CAPTURE, Map.of())).failure().code()); + var observed = new ArrayList(); + var outcome = session.advance(3, observed::add); + assertEquals(AutomationOutcome.Kind.SUCCEEDED, outcome.kind()); assertEquals(3, outcome.completedFrames()); + assertNotNull(outcome.capture()); assertEquals("real-build", outcome.capture().buildId()); + assertEquals(session.sessionId(), outcome.capture().sessionId()); + var image = javax.imageio.ImageIO.read(new java.io.ByteArrayInputStream(outcome.capture().png())); + assertEquals(outcome.capture().width(), image.getWidth()); assertEquals(outcome.capture().height(), image.getHeight()); + assertEquals(3L, observed.getLast().completedFrames()); + var state = session.call(TaskTools.HeadlessAction.STATE, Map.of()); + assertEquals("0.1.0", state.values().get("runtimeVersion")); + assertNull(session.call(TaskTools.HeadlessAction.FAULT, Map.of()).values().get("fault")); + session.call(TaskTools.HeadlessAction.SET_INPUT, Map.of("a", true)); + session.call(TaskTools.HeadlessAction.CLEAR_INPUT, Map.of()); + session.call(TaskTools.HeadlessAction.RESET, Map.of()); + assertEquals(AutomationFailure.Code.NO_FRAME_AVAILABLE, assertThrows(AutomationException.class, + () -> session.call(TaskTools.HeadlessAction.CAPTURE, Map.of())).failure().code()); + session.call(TaskTools.HeadlessAction.BOOT, Map.of()); + var repeated = session.advance(3, ignored -> {}); + assertArrayEquals(outcome.capture().png(), repeated.capture().png()); + assertEquals(0, session.advance(0, ignored -> {}).completedFrames()); + assertEquals(AutomationFailure.Code.LIMIT_EXCEEDED, assertThrows(AutomationException.class, + () -> session.advance(601, ignored -> {})).failure().code()); + } finally { session.shutdown().toCompletableFuture().get(7, TimeUnit.SECONDS); } + assertFalse(session.alive()); + var cancellable = (HeadlessProcessSession) new HeadlessProcessGateway(mapper, setup::load, + new HeadlessLimits(20000, 65536, 33554432, 5000, 60000, 5000)).boot(project, "cancel-build", build); + try { + assertEquals(20000, cancellable.maxFramesPerAdvance()); + var cancelled = cancellable.advance(20000, progress -> { if (progress.completedFrames() == 1) cancellable.cancel(); }); + assertEquals(AutomationOutcome.Kind.CANCELLED, cancelled.kind()); + assertTrue(cancelled.completedFrames() >= 1 && cancelled.completedFrames() < 20000); + assertNotNull(cancelled.capture()); + } finally { cancellable.shutdown().toCompletableFuture().get(7, TimeUnit.SECONDS); } + assertFalse(cancellable.alive()); + } + } +} diff --git a/prometeu-app/src/test/java/p/studio/app/runtime/HeadlessProcessSessionTest.java b/prometeu-app/src/test/java/p/studio/app/runtime/HeadlessProcessSessionTest.java new file mode 100644 index 00000000..9fce1164 --- /dev/null +++ b/prometeu-app/src/test/java/p/studio/app/runtime/HeadlessProcessSessionTest.java @@ -0,0 +1,97 @@ +package p.studio.app.runtime; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.jupiter.api.*; +import org.junit.jupiter.api.io.TempDir; +import p.studio.api.automation.*; +import java.nio.file.*; +import java.util.*; +import java.util.concurrent.*; +import java.util.concurrent.atomic.AtomicReference; +import static org.junit.jupiter.api.Assertions.*; + +class HeadlessProcessSessionTest { + @TempDir Path root; + static final HeadlessLimits LIMITS = new HeadlessLimits(600, 4096, 4096, 1000, 500, 150); + final List 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; + } + @AfterEach void cleanup() { sessions.forEach(session -> session.abort("test cleanup")); } + @Test void fragmentedProtocolPreservesUnsignedFrameIdentityLayoutAndSeparateStderr() throws Exception { + var session = start("normal"); session.initializeAndBoot(root); + var outcome = session.advance(3, ignored -> {}); + assertEquals(AutomationOutcome.Kind.SUCCEEDED, outcome.kind()); + assertEquals("18446744073709551615", outcome.capture().logicalFrameIndex().toString()); + assertEquals("9223372036854775808", outcome.capture().frameId().toString()); + assertEquals(3, outcome.capture().stridePixels()); + assertTrue(outcome.diagnostics().stream().anyMatch(s -> s.contains("fixture stderr"))); + var wire = p.studio.app.mcp.McpToolResult.capture(new ObjectMapper(), outcome.capture(), false).wire(); + assertEquals(outcome.capture().frameId(), wire.path("structuredContent").path("value").path("frameId").bigIntegerValue()); + session.shutdown().toCompletableFuture().get(3, TimeUnit.SECONDS); assertFalse(session.alive()); + } + @Test void rejectsBadHandshakeMalformedOversizedAndNonUtf8OutputAndCleansUp() throws Exception { + for (var mode : List.of("major", "capabilities", "limits", "malformed", "oversized", "utf8", "wrong-session", "no-hello")) { + var session = start(mode); + assertThrows(Exception.class, () -> session.initializeAndBoot(root), mode); + session.abort("startup rejection"); assertFalse(session.alive(), mode); + } + } + @Test void crashRetainsOnlyObservedProgressAndNeverRestartsOrReplays() throws Exception { + var session = start("crash"); session.initializeAndBoot(root); + var known = new AtomicReference(); + assertThrows(AutomationException.class, () -> session.advance(30, known::set)); + assertEquals(2L, known.get().completedFrames()); assertFalse(session.alive()); + assertThrows(AutomationException.class, () -> session.call(TaskTools.HeadlessAction.STATE, Map.of())); + } + @Test void deadlinesStopHungCallsAndCancellationPreservesKnownPartialProgress() throws Exception { + var call = start("hang-call"); call.initializeAndBoot(root); + assertThrows(AutomationException.class, () -> call.call(TaskTools.HeadlessAction.STATE, Map.of())); assertFalse(call.alive()); + var session = start("hang-cancel"); session.initializeAndBoot(root); + var known = new AtomicReference(); + assertThrows(AutomationException.class, () -> session.advance(30, known::set)); + assertEquals(2L, known.get().completedFrames()); assertFalse(session.alive()); + } + @Test void cooperativeCancelReturnsFinalImageAndRejectsConcurrentWork() throws Exception { + var session = start("cooperative"); session.initializeAndBoot(root); + 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)); + 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); + assertEquals(AutomationOutcome.Kind.CANCELLED, outcome.kind()); assertEquals(2, outcome.completedFrames()); assertNotNull(outcome.capture()); + } + session.shutdown().toCompletableFuture().get(3, TimeUnit.SECONDS); assertFalse(session.alive()); + } + @Test void malformedProgressAndCaptureInvalidateSession() throws Exception { + for (var mode : List.of("bad-progress", "bad-png")) { + var session = start(mode); session.initializeAndBoot(root); + assertThrows(AutomationException.class, () -> session.advance(3, ignored -> {})); assertFalse(session.alive()); + } + } + @Test void shutdownEscalatesAndKillsOwnedDescendantsWithoutTouchingUnrelatedProcesses() throws Exception { + var unrelated = new ProcessBuilder(HeadlessFixture.java(), "-cp", System.getProperty("java.class.path"), HeadlessFixture.class.getName(), "child").start(); + try { + var session = start("descendant"); session.initializeAndBoot(root); + long child = Long.parseLong(Files.readString(root.resolve("descendant.pid"))); + assertTrue(ProcessHandle.of(child).orElseThrow().isAlive()); + assertThrows(ExecutionException.class, () -> session.shutdown().toCompletableFuture().get(4, TimeUnit.SECONDS)); + assertFalse(session.alive()); assertFalse(ProcessHandle.of(child).map(ProcessHandle::isAlive).orElse(false)); + assertTrue(unrelated.isAlive()); + } finally { unrelated.destroyForcibly(); unrelated.waitFor(2, TimeUnit.SECONDS); } + } + @Test void missingConfiguredInstallationIsExplicitAndNeverDiscoversAnotherRuntime() throws Exception { + var project = new p.studio.api.project.ProjectReference("game", "1", "pbs", 1, p.studio.api.project.ProjectTarget.Game, root); + var build = p.studio.api.shipper.ShipperPrepareResult.failed(List.of(), List.of()); + var missing = new HeadlessProcessGateway(new ObjectMapper(), ignored -> p.studio.api.project.ProjectLocalStudioSetup.defaults()); + assertEquals(AutomationFailure.Code.RUNTIME_UNAVAILABLE, assertThrows(AutomationException.class, + () -> missing.boot(project, "build", build)).failure().code()); + var unavailable = new HeadlessProcessGateway(new ObjectMapper(), ignored -> new p.studio.api.project.ProjectLocalStudioSetup(root.toString(), null)); + assertEquals(AutomationFailure.Code.RUNTIME_UNAVAILABLE, assertThrows(AutomationException.class, + () -> unavailable.boot(project, "build", build)).failure().code()); + } +} diff --git a/prometeu-studio-api/src/main/java/p/studio/api/automation/CanonicalCapture.java b/prometeu-studio-api/src/main/java/p/studio/api/automation/CanonicalCapture.java index 582bdf0c..8d88ebee 100644 --- a/prometeu-studio-api/src/main/java/p/studio/api/automation/CanonicalCapture.java +++ b/prometeu-studio-api/src/main/java/p/studio/api/automation/CanonicalCapture.java @@ -1,10 +1,16 @@ package p.studio.api.automation; import java.util.Objects; /** Lossless PNG bytes; stride describes the original RGBA8888 buffer, not PNG padding. */ -public record CanonicalCapture(String sessionId, String buildId, long logicalFrameIndex, - long frameId, int width, int height, int stridePixels, byte[] png) { +public record CanonicalCapture(String sessionId, String buildId, java.math.BigInteger logicalFrameIndex, + java.math.BigInteger frameId, int width, int height, int stridePixels, byte[] png) { + public CanonicalCapture(String sessionId, String buildId, long logicalFrameIndex, long frameId, + int width, int height, int stridePixels, byte[] png) { + this(sessionId, buildId, java.math.BigInteger.valueOf(logicalFrameIndex), java.math.BigInteger.valueOf(frameId), width, height, stridePixels, png); + } public CanonicalCapture { Objects.requireNonNull(sessionId); Objects.requireNonNull(buildId); Objects.requireNonNull(png); + if (logicalFrameIndex.signum() < 0 || logicalFrameIndex.bitLength() > 64 || frameId.signum() < 0 || frameId.bitLength() > 64) + throw new IllegalArgumentException("Frame identity must be uint64"); if (width <= 0 || height <= 0 || stridePixels < width) throw new IllegalArgumentException("invalid frame layout"); png = png.clone(); } diff --git a/prometeu-studio-core/src/main/java/p/studio/core/session/DefaultTaskTools.java b/prometeu-studio-core/src/main/java/p/studio/core/session/DefaultTaskTools.java index 9ed4d4bf..8a36632e 100644 --- a/prometeu-studio-core/src/main/java/p/studio/core/session/DefaultTaskTools.java +++ b/prometeu-studio-core/src/main/java/p/studio/core/session/DefaultTaskTools.java @@ -201,7 +201,7 @@ public final class DefaultTaskTools implements TaskTools { var captured = record.runtime == null ? null : record.runtime.capture(); boolean stale = captured != null && (current.stale() || current.capture() == null || !captured.sessionId().equals(current.capture().sessionId()) || !captured.buildId().equals(current.capture().buildId()) - || captured.logicalFrameIndex() != current.capture().logicalFrameIndex() || captured.frameId() != current.capture().frameId()); + || !captured.logicalFrameIndex().equals(current.capture().logicalFrameIndex()) || !captured.frameId().equals(current.capture().frameId())); return new TrackedOperation(snapshot, record.request, record.progress, done ? record.buildId : null, done ? record.build : null, done ? record.runtime : null, done ? record.failure : null, done, stale);