feat(studio): show executed source diagnostics in UI2
Test / Tests and coverage
Intrepid/Prometeu/Studio/pipeline/head This commit looks good

Capture bounded compiler inputs by revision and PBX identity, consume Play v2 faults and retain static diagnostic excerpts across failed preparation. Integrate the UI2 panel, qualification evidence and regression tests without adding an editor.
This commit is contained in:
2026-11-26 08:55:33 +00:00
parent 481c479427
commit 601997d163
47 changed files with 2811 additions and 58 deletions
@@ -168,6 +168,33 @@ instruction nor a function's first line supplies an exact fallback. The complete
diagnostic and public-failure contract is defined in
[Compiler 19, sections 12–13](19.%20Verification%20and%20Safety%20Checks%20Specification.md).
### 7.2 Consumed input for interactive execution diagnostics
The compiler adapter MUST capture the exact UTF-8 bytes already consumed by the
compilation, including project files, dependencies, SDK interfaces and generated
PBS/barrels. Synthetic loaders parsing in-memory text MUST also record those same
bytes on their registered source handles. Capture MUST NOT reread working files
or regenerate text after compilation. Mixed revisions, missing observations and
malformed UTF-8 MUST fail capture explicitly.
The neutral execution capture binds compilation/build ID, emitted PBX SHA-256 and
compilation-local file IDs to immutable source text, source SHA-256, project
identity, logical origin and source kind. Dependency origins MUST identify their
owning project; generated and SDK origins MUST remain recognizable. A path or
file ID alone does not establish revision identity. Full text MUST NOT enter
generic diagnostic maps, logs or the runtime wire protocol.
The initial capture policy is 4 MiB UTF-8 per file, 1,024 files and 16 MiB per
capture. Accounting includes UTF-8 content, canonical/logical paths and reserved
metadata for each source plus capture identity. Exceeding a budget MUST fail
preparation explicitly; sources MUST NOT be silently dropped. These are retained
capture storage budgets, not a bound on total compiler or JVM heap.
These values are consumed by the current UI2 diagnostic excerpt. They do not add
PBX sections, change guest ABI or establish an editor/full-document API. Admission,
retention, source availability and presentation are specified by
[Integrated Play](../studio/14.%20Integrated%20Play%20Specification.md#execution-diagnostics).
## 8. Deterministic Emitter Rejection
Emitter-side rejection must be deterministic for malformed or inconsistent artifact candidates, including at minimum:
@@ -26,8 +26,8 @@ close MUST flush pending snapshots. Transient native show/maximization events MU
NOT overwrite the saved normal geometry. Legacy geometry remains readable.
This slice exposes a global Play/Stop button, a separate Pause/Resume toggle, a
Gameplay tab with the game viewport, and bounded logs. Execution belongs to the
project session, independently of tab selection or lifetime. The global toolbar
Gameplay tab with the game viewport, bounded logs and static execution diagnostics.
Execution belongs to the project session, independently of tab selection or lifetime. The global toolbar
MUST remain above the tabs. Starting Play selects Gameplay. Pause selection,
accessible names and command availability MUST follow observed execution state,
including automatic pauses and failures. Stop MUST remain Stop until execution
@@ -307,6 +307,57 @@ Scale and scroll operate in JavaFX logical coordinates, with scene
transforms accounting for host display scaling. These frontend changes apply to
the new UI only; the old UI is outside the current graphics migration scope.
## Execution diagnostics
UI2 MUST present execution failures in the Gameplay diagnostic panel: category,
message, available logical source/line/column, executed revision and a static
excerpt. Preparation, connection, loading, host, watchdog and VM failures MUST
remain distinguishable. PC, code, opcode, resource and source span are preserved
when supplied by the producer; absent facts MUST NOT be invented. The first
structured fault remains primary across subsequent EOF/process teardown.
Play requires a coordinated [protocol v2](../../../../runtime/docs/specs/runtime/11b-studio-play-protocol.md)
pair and exact native bundle qualification. Runtime readiness confirms the digest
of the PBX actually initialized. Studio MUST compare it with the captured build
before START. A mismatch or incompatible protocol fails explicitly. Studio MUST
NOT silently launch a lower-capability Play path. Existing asset/qualification
guards and save/owned-process teardown contracts remain effective.
The compilation capture follows
[Compiler 15 section 7.2](../compiler/15.%20Bytecode%20and%20PBX%20Mapping%20Specification.md#72-consumed-input-for-interactive-execution-diagnostics).
The open project retains the last admitted execution and at most one candidate.
The candidate replaces the last capture only after identity confirmation and
immediately before execution starts. Failed/cancelled compilation, capture, boot
or connection MUST preserve the previous admitted diagnostic. A new failed attempt
may be shown alongside it, with its own execution identity. Late callbacks cannot
overwrite the current attempt. Successful project close releases both captures
after teardown; a refused save/close retains the current session. There is no
persistent source history or full-file viewer.
Retained captures are limited to 16 MiB each, hence 32 MiB per project for last
plus candidate, including accounted source metadata. This does not bound total
compiler/JVM heap or caller-owned copies. The service resolves a diagnostic once
against its immutable capture, off the FX thread, without filesystem reads.
Resolution requires a matching PBX digest, captured file ID, valid half-open UTF-8
byte boundaries and a range within the captured bytes. Missing identity, source,
span or invalid offsets MUST yield an explicit availability explanation instead
of a guessed location. Display positions are one-based lines and UTF-16 columns;
CRLF and supplementary Unicode characters MUST be handled consistently.
The displayed excerpt contains at most seven lines and 8 KiB UTF-8, including the
fault location when valid; long lines may be shortened at Unicode boundaries.
Any shortened source or fault MUST be indicated explicitly. Editing or deleting
the working file after compilation MUST NOT change the displayed executed text.
Generated sources show the captured PBS and their generated origin. Dependency
origins identify their owning project. Hash/build/execution identities remain
available for attribution, with concise visual forms permitted.
The UI uses static presentation controls with existing themes, text scale,
English/Portuguese localization and accessible labels. It MUST NOT instantiate
an editor, full-document view, edit/save actions, editorial LSP or unused future
editor infrastructure. The legacy JavaFX frontend is not modified by this feature;
neutral API constructors remain compatible with its compilation.
## Verification and limits
The product baseline is Java 25, retaining JavaFX 23.0.2. The bundled image uses an
@@ -43,8 +43,23 @@ public final class CompilerBuildGatewayAdapter implements CompilerBuildGateway {
var root = context.rootProjectPathCanon == null ? project.rootPath() : context.rootProjectPathCanon;
var issues = CompilerDiagnosticProjection.issues(result.diagnostics(), sources,
CompilerDiagnosticProjection.capturedText(context.fileTable), root, analysisId).stream().map(StudioDiagnostic::fromMap).toList();
var captured = new java.util.LinkedHashMap<Integer, p.studio.api.execution.ExecutionSources.Source>();
for (var source : p.studio.compiler.source.diagnostics.ConsumedSources.capture(context.fileTable,
p.studio.api.execution.ExecutionSources.MAX_FILE_BYTES, p.studio.api.execution.ExecutionSources.MAX_FILES,
p.studio.api.execution.ExecutionSources.MAX_CAPTURE_BYTES)) {
var projectId=new p.studio.compiler.source.identifiers.ProjectId(source.projectId());
boolean dependency=!projectId.equals(context.resolvedWorkspace.mainProjectId());
String logical=dependency?"@"+context.resolvedWorkspace.graph().projectDescriptor(projectId).getName()+":"+source.logicalPath():source.logicalPath();
String kind=dependency&&source.kind().equals("source")?"dependency":source.kind();
captured.put(source.fileId(), new p.studio.api.execution.ExecutionSources.Source(source.fileId(), source.projectId(),
source.path(), logical, kind, source.sha256(), source.text()));
}
var executionSources = new p.studio.api.execution.ExecutionSources(analysisId,
p.studio.api.execution.ExecutionSources.digest(java.nio.file.Files.readAllBytes(result.bytecodeArtifactPath())), captured);
return new CompilerBuildOutput(result.bytecodeArtifactPath(), capabilities.stream().toList(), issues,
inputContext(context, root, analysisId, sources));
inputContext(context, root, analysisId, sources), executionSources);
} catch (java.io.IOException failure) {
throw new IllegalStateException("Cannot identify prepared program", failure);
} catch (BuildException failure) {
var root = context.rootProjectPathCanon == null ? project.rootPath() : context.rootProjectPathCanon;
var issues = CompilerDiagnosticProjection.issues(failure.getDiagnostics(), failure.getSourceReferences(),
@@ -0,0 +1,80 @@
package p.studio.app.runtime.studio;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.StreamReadConstraints;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.*;
import p.studio.api.execution.RuntimeDiagnostic;
import java.io.IOException;
import java.util.*;
/** Validates the bounded fault envelope before publishing neutral values. */
final class StudioFaults {
private static final ObjectMapper JSON = new ObjectMapper(JsonFactory.builder().streamReadConstraints(
StreamReadConstraints.builder().maxNestingDepth(32).maxStringLength(8192).maxNumberLength(20).build()).build());
private StudioFaults() { }
static RuntimeDiagnostic decode(byte[] bytes, byte[] session, String program) throws IOException {
return decode(bytes,session,program,false);
}
static RuntimeDiagnostic decodeHost(byte[] bytes, byte[] session, String program) throws IOException {
return decode(bytes,session,program,true);
}
private static RuntimeDiagnostic decode(byte[] bytes, byte[] session, String program, boolean host) throws IOException {
if (bytes.length > StudioWire.CONTROL_LIMIT) throw invalid("Fault exceeds control limit");
try {
JsonNode root;
try(var parser=JSON.createParser(bytes)) {
root=JSON.readTree(parser);
if(parser.nextToken()!=null)throw invalid("Trailing fault content");
}
if(root==null||!root.isObject()||!root.path("schemaVersion").isIntegralNumber()||!root.path("schemaVersion").canConvertToInt()||root.path("schemaVersion").intValue()!=1
||!root.path("sessionId").isTextual()||!root.path("sessionId").textValue().equals(HexFormat.of().formatHex(session))
||!root.path("truncated").isBoolean())throw invalid("Invalid fault envelope/session");
validateStrings(root);
var digestNode=root.get("programSha256");
if(digestNode==null||!(digestNode.isNull()||digestNode.isTextual()))throw invalid("Invalid fault program identity");
String digest=digestNode.isNull()?"":digestNode.textValue();
if(!digestNode.isNull()&&(!digest.matches("[0-9a-f]{64}")||!digest.equals(program)))throw invalid("Fault belongs to another program");
var tick=root.path("tick");if(!tick.isIntegralNumber()||tick.bigIntegerValue().signum()<0||tick.bigIntegerValue().bitLength()>64)
throw invalid("Invalid fault tick");
JsonNode fault=root.path("fault");String kind=string(fault,"kind"), message=string(fault,"summary");
if(!(host?Set.of("load","host","transport","watchdog"):Set.of("vm_trap","vm_panic","vm_init")).contains(kind))throw invalid("Invalid fault kind");
if(!fault.has("pc"))throw invalid("Missing fault PC field");
Long pc=nullableUnsigned(fault.get("pc"),32), code=null,opcode=null;
RuntimeDiagnostic.Span span=null;
if(kind.equals("vm_trap")) {
var trap=fault.path("trap");code=unsigned(trap.path("code"),32);opcode=unsigned(trap.path("opcode"),16);
if(!Objects.equals(pc,unsigned(trap.path("pc"),32)))throw invalid("Inconsistent fault PC");
string(trap,"message");var location=trap.get("span");
if(location==null||!(location.isObject()||location.isNull()))throw invalid("Invalid fault span");
if(!location.isNull())span=new RuntimeDiagnostic.Span(unsigned(location.path("file_id"),32),
unsigned(location.path("start"),32),unsigned(location.path("end"),32));
if(digest.isEmpty())throw invalid("Executed trap has no program identity");
} else if(kind.equals("vm_init")) {
if(pc!=null||!fault.path("initError").isObject())throw invalid("Invalid initialization fault");
} else if(kind.equals("vm_panic")) string(fault,"message");
else if(pc!=null||!digest.isEmpty())throw invalid("Host error cannot claim VM execution identity/location");
Map<String,Object> facts=JSON.convertValue(fault,new TypeReference<Map<String,Object>>(){});
facts.put("tick",tick.bigIntegerValue().toString());
return new RuntimeDiagnostic(HexFormat.of().formatHex(session),digest,kind,message,pc,code,opcode,span,
root.path("truncated").booleanValue(),facts);
} catch(IllegalArgumentException failure) {throw new IOException("Invalid Studio fault facts",failure);}
}
private static void validateStrings(JsonNode node)throws IOException {
if(node.isTextual()&&node.textValue().getBytes(java.nio.charset.StandardCharsets.UTF_8).length>8192)
throw invalid("Oversized diagnostic string");
for(var child:node)validateStrings(child);
}
private static String string(JsonNode node,String key)throws IOException {
var v=node.get(key);if(v==null||!v.isTextual()||v.textValue().isBlank())throw invalid("Invalid fault "+key);
if(v.textValue().getBytes(java.nio.charset.StandardCharsets.UTF_8).length>8192)throw invalid("Oversized fault "+key);
return v.textValue();
}
private static long unsigned(JsonNode v,int bits)throws IOException {
if(v==null||!v.isIntegralNumber()||!v.canConvertToLong()||v.longValue()<0||v.bigIntegerValue().bitLength()>bits)
throw invalid("Invalid unsigned fault field");return v.longValue();
}
private static Long nullableUnsigned(JsonNode v,int bits)throws IOException {return v==null||v.isNull()?null:unsigned(v,bits);}
private static IOException invalid(String message){return new IOException(message);}
}
@@ -20,6 +20,9 @@ final class StudioRuntimeConnection implements RuntimeConnection {
private final Reader controlReader,videoReader;
private final Writer writer;
private final byte[] session;
private final String programSha256;
private final Consumer<RuntimeDiagnostic> diagnostics;
private final CompletableFuture<Void> terminalControl=new CompletableFuture<>();
private final int width,height;
private final LatestFramePool frames;
private final Consumer<RuntimeLogEntry> logs;
@@ -45,10 +48,11 @@ final class StudioRuntimeConnection implements RuntimeConnection {
private record Pending(int kind,long deadline,CompletableFuture<Void> result) { }
StudioRuntimeConnection(Process process,Socket control,Socket video,Reader controlReader,Reader videoReader,
byte[] session,int width,int height,Consumer<RuntimeLogEntry> logs,Executor executor,
byte[] session,int width,int height,String programSha256,Consumer<RuntimeDiagnostic> diagnostics,Consumer<RuntimeLogEntry> logs,Executor executor,
CompletableFuture<Void> stdout,CompletableFuture<Void> stderr)throws IOException {
this.process=process;this.control=control;this.video=video;this.controlReader=controlReader;this.videoReader=videoReader;
this.session=session.clone();this.width=width;this.height=height;this.logs=logs;this.executor=executor;
this.programSha256=programSha256;this.diagnostics=diagnostics;
writer=new Writer(control.getOutputStream());frames=new LatestFramePool(width,height);
workers.add(CompletableFuture.runAsync(this::writeLoop,executor));
workers.add(CompletableFuture.runAsync(this::controlLoop,executor));
@@ -61,6 +65,8 @@ final class StudioRuntimeConnection implements RuntimeConnection {
// TCP ordering is per channel; video EOF can race STOPPED on control.
if(code==0&&stopRequest!=0&&!failed.get()){
try{stopped.get(2,TimeUnit.SECONDS);}catch(Exception missing){fail(new IOException("Runtime exited without STOPPED",missing));}
}else if(!failed.get()){
try{terminalControl.get(2,TimeUnit.SECONDS);}catch(Exception missing){fail(new IOException("Runtime exited without terminal diagnostic",missing));}
}
closing.set(true);state.set(4);timer.shutdownNow();closeSockets();frames.close();
for(Pending p:pending.values())p.result().completeExceptionally(new IOException("Runtime exited"));pending.clear();
@@ -73,6 +79,7 @@ final class StudioRuntimeConnection implements RuntimeConnection {
});
}
@Override public CompletableFuture<Integer> completion(){return completion;}
@Override public String verifiedProgramSha256(){return programSha256;}
@Override public CompletableFuture<Void> startExecution(){return command(START);}
@Override public CompletableFuture<Void> pause(){return command(PAUSE);}
@Override public CompletableFuture<Void> resume(){return command(RESUME);}
@@ -127,12 +134,23 @@ final class StudioRuntimeConnection implements RuntimeConnection {
long e=p.getLong();p.getLong();int s=p.getInt();
if(e==0||s<0||s>2)throw new IOException("Invalid PONG state");
}
case ERROR->{String text=text(m.payload(),0);logs.accept(RuntimeLogEntry.error(text));fail(new IOException(text));return;}
case ERROR->{
if(m.header().request()!=0)throw new IOException("Unsolicited error has request correlation");
var diagnostic=StudioFaults.decodeHost(m.payload(),session,programSha256);
diagnostics.accept(diagnostic);logs.accept(RuntimeLogEntry.error(diagnostic.message()));
fail(new IOException(diagnostic.message()));terminalControl.complete(null);return;
}
case FAULT->{
if(m.header().request()!=0)throw new IOException("Unsolicited fault has request correlation");
var diagnostic=StudioFaults.decode(m.payload(),session,programSha256);
diagnostics.accept(diagnostic);logs.accept(RuntimeLogEntry.error(diagnostic.message()));
fail(new IOException(diagnostic.message()));terminalControl.complete(null);return;
}
case STOPPED->{if(m.payload().length!=0||m.header().request()!=stopRequest||stopRequest==0)
throw new IOException("Unexpected STOPPED");expectedEnd=true;stopped.complete(null);return;}
throw new IOException("Unexpected STOPPED");expectedEnd=true;stopped.complete(null);terminalControl.complete(null);return;}
default->throw new IOException("Unexpected runtime control message");
}
}}catch(IOException|RuntimeException e){if(!closing.get()&&!expectedEnd)fail(e);}
}}catch(IOException|RuntimeException e){if(!closing.get()&&!expectedEnd)fail(e);terminalControl.complete(null);}
}
private void result(Message message)throws IOException {
byte[] p=message.payload();if(p.length<20)throw new IOException("Invalid command result");
@@ -173,19 +191,26 @@ final class StudioRuntimeConnection implements RuntimeConnection {
if(!closing.get()&&!expectedEnd){
if(stopRequest!=0){
try{stopped.get(2,TimeUnit.SECONDS);}catch(Exception incomplete){if(!closing.get()&&!expectedEnd)fail(e);}
}else fail(e);
}else {
try{terminalControl.get(2,TimeUnit.SECONDS);}catch(Exception incomplete){if(!closing.get()&&!failed.get())fail(e);}
}
}
}
}
private void heartbeat(){
if(closing.get()||failed.get())return;
long now=System.nanoTime();
if(now-lastControl>TimeUnit.SECONDS.toNanos(5)){fail(new IOException("Runtime control heartbeat expired"));return;}
for(Pending p:pending.values())if(now-p.deadline()>0){fail(new IOException("Runtime command timed out"));return;}
if(now-lastControl>TimeUnit.SECONDS.toNanos(5)){fail(new IOException("Runtime control heartbeat expired"),"watchdog");return;}
for(Pending p:pending.values())if(now-p.deadline()>0){fail(new IOException("Runtime command timed out"),"watchdog");return;}
enqueue(new Packet(PING,0,new byte[0]));
}
private void fail(Throwable why){
fail(why,"transport");
}
private void fail(Throwable why,String kind){
if(closing.get()||!failed.compareAndSet(false,true))return;
diagnostics.accept(RuntimeDiagnostic.failure(HexFormat.of().formatHex(session),kind,
why.getMessage()==null?why.getClass().getSimpleName():why.getMessage()));
failure=why;state.set(4);logs.accept(RuntimeLogEntry.error("Runtime connection failed: "+why.getMessage()));
for(Pending p:pending.values())p.result().completeExceptionally(why);pending.clear();
stopped.completeExceptionally(why);closeSockets();frames.close();timer.shutdownNow();
@@ -27,7 +27,17 @@ public final class StudioRuntimeGateway implements RuntimeGateway {
}
@Override public RuntimeConnection start(ProjectReference project,ProjectLocalStudioSetup setup,
Consumer<RuntimeLogEntry> logs,PlayOptions options)throws Exception {
return start(project,setup,logs,options,UUID.randomUUID().toString().replace("-",""),
p.studio.api.execution.ExecutionSources.EMPTY,ignored->{});
}
@Override public RuntimeConnection start(ProjectReference project,ProjectLocalStudioSetup setup,
Consumer<RuntimeLogEntry> logs,PlayOptions options,String runId,
p.studio.api.execution.ExecutionSources sources,Consumer<p.studio.api.execution.RuntimeDiagnostic> diagnostics)throws Exception {
new p.studio.app.assets.ManagedAssetGuard(mapper).require(project.rootPath(),project.rootPath().resolve("build"),setup);
String expected=p.studio.api.execution.ExecutionSources.digest(Files.readAllBytes(project.rootPath().resolve("build/program.pbx")));
if(!sources.programSha256().isEmpty()&&!expected.equals(sources.programSha256()))
throw new IOException("Prepared program changed after source capture");
if(!runId.matches("[0-9a-f]{32}"))throw new IllegalArgumentException("Invalid Play session identity");
Path executable=executable(setup);
List<String> command=new ArrayList<>(List.of(executable.toString(),"--studio","--run",project.rootPath().resolve("build").toString()));
if(project.memcardSlots()!=null&&!options.disposableSave()){
@@ -36,30 +46,41 @@ public final class StudioRuntimeGateway implements RuntimeGateway {
command.add("--memcard");command.add(image.toString());
}
InetAddress loopback=InetAddress.getByName("127.0.0.1");
byte[] session=new byte[16],token=new byte[32];SecureRandom random=new SecureRandom();random.nextBytes(session);random.nextBytes(token);
byte[] session=HexFormat.of().parseHex(runId),token=new byte[32];SecureRandom random=new SecureRandom();random.nextBytes(token);
Process process=null;Socket control=null,video=null;
ExecutorService io=Executors.newThreadPerTaskExecutor(Thread.ofVirtual().name("studio-play-io-",0).factory());
try(ServerSocket controls=new ServerSocket(0,4,loopback);ServerSocket videos=new ServerSocket(0,4,loopback)){
process=new ProcessBuilder(command).directory(project.rootPath().toFile()).start();
CompletableFuture<Void> stdout=drain(process.getInputStream(),false,logs,io);
CompletableFuture<Void> stderr=drain(process.getErrorStream(),true,logs,io);
byte[] bootstrap=little(53).put(session).put(token).putShort((short)controls.getLocalPort())
.putShort((short)videos.getLocalPort()).put((byte)(options.disposableSave()?1:0)).array();
byte[] bootstrap=little(85).put(session).put(token).putShort((short)controls.getLocalPort())
.putShort((short)videos.getLocalPort()).put((byte)(options.disposableSave()?1:0)).put(HexFormat.of().parseHex(expected)).array();
try(OutputStream input=process.getOutputStream()){new Writer(input).send(BOOTSTRAP,0,bootstrap);}
long deadline=System.nanoTime()+TimeUnit.SECONDS.toNanos(10);
Accepted c=accept(controls,session,token,1,process,deadline);control=c.socket();
Accepted v=accept(videos,session,token,2,process,deadline);video=v.socket();
control.setSoTimeout(remaining(deadline));
Message ready=c.reader().receive();
if(ready.header().kind()!=READY||ready.header().request()!=0||ready.payload().length<16)throw new IOException("Interactive runtime did not become ready");
if(ready.header().kind()==FAULT&&ready.header().request()==0){
var fault=StudioFaults.decode(ready.payload(),session,expected);diagnostics.accept(fault);
throw new IOException(fault.message());
}
if(ready.header().kind()==ERROR&&ready.header().request()==0){
var fault=StudioFaults.decodeHost(ready.payload(),session,expected);diagnostics.accept(fault);
throw new IOException(fault.message());
}
if(ready.header().kind()!=READY||ready.header().request()!=0||ready.payload().length<48)throw new IOException("Interactive runtime did not become ready with Play 2.0 identity");
var fields=java.nio.ByteBuffer.wrap(ready.payload()).order(java.nio.ByteOrder.LITTLE_ENDIAN);
int width=fields.getInt(),height=fields.getInt(),fps=fields.getInt(),format=fields.getInt();
byte[] loaded=new byte[32];fields.get(loaded);
if(!java.security.MessageDigest.isEqual(loaded,HexFormat.of().parseHex(expected)))
throw new IOException("Loaded program does not match prepared compilation");
frameBytes(width,height,width);
if(fps!=60||format!=RGBA8)throw new IOException("Unsupported interactive display format");
String version=text(ready.payload(),16);
logs.accept(RuntimeLogEntry.info("Studio Play protocol 1.0; runtime "+version));
String version=text(ready.payload(),48);
logs.accept(RuntimeLogEntry.info("Studio Play protocol 2.0; runtime "+version));
control.setSoTimeout(0);video.setSoTimeout(0);
var connection=new StudioRuntimeConnection(process,control,video,c.reader(),v.reader(),session,width,height,logs,io,stdout,stderr);
var connection=new StudioRuntimeConnection(process,control,video,c.reader(),v.reader(),session,width,height,expected,diagnostics,logs,io,stdout,stderr);
connection.completion().whenComplete((code,failure)->io.shutdown());
return connection;
}catch(Throwable failure){
@@ -81,7 +102,7 @@ public final class StudioRuntimeGateway implements RuntimeGateway {
listener.setSoTimeout(100);
while(System.nanoTime()<deadline){
if(Thread.currentThread().isInterrupted())throw new InterruptedIOException("Runtime startup cancelled");
if(!process.isAlive())throw new IOException("Runtime exited during startup with code "+process.exitValue());
if(!process.isAlive())throw new IOException("Studio requires Play 2.0; runtime exited during startup with code "+process.exitValue()+". Verify the selected installation.");
Socket socket;
try{socket=listener.accept();}catch(SocketTimeoutException wait){continue;}
boolean admitted=false;
@@ -96,11 +117,11 @@ public final class StudioRuntimeGateway implements RuntimeGateway {
}catch(IOException invalid){/* Reject an unrelated/malformed peer within the startup deadline. */}
finally{if(!admitted)close(socket);}
}
throw new SocketTimeoutException("Interactive runtime handshake timed out");
throw new SocketTimeoutException("Studio requires Play 2.0; runtime handshake timed out");
}
private static int remaining(long deadline)throws SocketTimeoutException {
long ms=TimeUnit.NANOSECONDS.toMillis(deadline-System.nanoTime());
if(ms<=0)throw new SocketTimeoutException("Interactive runtime handshake timed out");return (int)Math.min(ms,Integer.MAX_VALUE);
if(ms<=0)throw new SocketTimeoutException("Studio requires Play 2.0; runtime handshake timed out");return (int)Math.min(ms,Integer.MAX_VALUE);
}
static void close(Socket socket){if(socket!=null)try{socket.close();}catch(IOException ignored){}}
static CompletableFuture<Void> drain(InputStream source,boolean error,Consumer<RuntimeLogEntry> logs,Executor executor){
@@ -4,29 +4,29 @@ import java.io.*;
import java.nio.*;
import java.nio.charset.*;
/** Studio Play v1. No JavaFX, object serialization or platform-native transport. */
/** Studio Play v2. No JavaFX, object serialization or platform-native transport. */
public final class StudioWire {
private StudioWire() { }
public static final int HEADER_BYTES = 32, CONTROL_LIMIT = 65536, FRAME_LIMIT = 16 * 1024 * 1024;
public static final int FRAME_METADATA_BYTES = 48, RGBA8 = 1;
public static final int HELLO=1, READY=2, START=3, PAUSE=4, RESUME=5, STOP=6, RESULT=7,
INPUT=8, FRAME=9, FRAME_RECEIVED=10, PING=11, PONG=12, ERROR=13, STOPPED=14, BOOTSTRAP=15;
INPUT=8, FRAME=9, FRAME_RECEIVED=10, PING=11, PONG=12, ERROR=13, STOPPED=14, BOOTSTRAP=15, FAULT=16;
public static ByteBuffer little(int length) { return ByteBuffer.allocate(length).order(ByteOrder.LITTLE_ENDIAN); }
public record Header(int kind, int length, long sequence, long request) {
public Header {
if (kind < HELLO || kind > BOOTSTRAP || sequence == 0 || length < 0
if (kind < HELLO || kind > FAULT || sequence == 0 || length < 0
|| length > (kind == FRAME ? FRAME_LIMIT : CONTROL_LIMIT))
throw new IllegalArgumentException("Invalid Studio message type, sequence or payload length");
}
public byte[] encode() {
return little(HEADER_BYTES).putInt(0x31545350).putShort((short)1).putShort((short)0)
return little(HEADER_BYTES).putInt(0x31545350).putShort((short)2).putShort((short)0)
.putShort((short)kind).putShort((short)0).putInt(length).putLong(sequence).putLong(request).array();
}
public static Header decode(byte[] bytes) throws IOException {
if (bytes.length != HEADER_BYTES) throw new IOException("Truncated Studio header");
var b = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN);
if (b.getInt()!=0x31545350 || b.getShort()!=1 || b.getShort()!=0)
throw new IOException("Incompatible Studio protocol magic/version");
if (b.getInt()!=0x31545350 || b.getShort()!=2 || b.getShort()!=0)
throw new IOException("Incompatible Studio Play protocol: required 2.0, or invalid magic");
int kind = Short.toUnsignedInt(b.getShort());
if (b.getShort()!=0) throw new IOException("Unknown Studio protocol flags");
long length = Integer.toUnsignedLong(b.getInt()), seq=b.getLong(), request=b.getLong();
@@ -264,6 +264,39 @@
"prometeu-headless": "5107d2d0fc30149cb2ece3124b0622654bd991871d6a3c2b26f22e97dd2645f9",
"prometeu-runtime": "a29e75597ffb7110854452c9ce4802167a78e62f6b19526bc12b83584a52996f"
}
},
{
"profile": {
"contractVersion": 1,
"profileId": "native-bundle-ebd67587b36384c6902d5e39072779da1ff59da500da6575b249866b2f4d6ad3",
"runtimeVersion": "0.1.0",
"executableSha256": "f05056dfc67e6e8b8b2f9c1f22b9a98d670bcf32c8077b1a4d738e7e0e754137",
"limits": {
"glyph": 16,
"scene": 16
},
"evidence": [
{
"bankType": "glyph",
"acceptedPreloads": 16,
"rejectedPreloads": 17,
"evidencePath": "asset-capacity/evidence/native-bundle-ebd67587b36384c6902d5e39072779da1ff59da500da6575b249866b2f4d6ad3.json",
"evidenceSha256": "dbbc4ac4026ec9b8ee5323e5f263f809e966b6ad2de69c3209012ae97b773f52"
},
{
"bankType": "scene",
"acceptedPreloads": 16,
"rejectedPreloads": 17,
"evidencePath": "asset-capacity/evidence/native-bundle-ebd67587b36384c6902d5e39072779da1ff59da500da6575b249866b2f4d6ad3.json",
"evidenceSha256": "dbbc4ac4026ec9b8ee5323e5f263f809e966b6ad2de69c3209012ae97b773f52"
}
]
},
"executables": {
"prometeu": "f05056dfc67e6e8b8b2f9c1f22b9a98d670bcf32c8077b1a4d738e7e0e754137",
"prometeu-headless": "7234a19c2aa8c311a8cac6e7718c4a368c1406ef8d4e3cb32cca49d332a5d239",
"prometeu-runtime": "a1e89fc04d7976b739fddd008f1984ae6758dff9c5b9fb3685165a5d7180ba65"
}
}
]
}
@@ -35,6 +35,56 @@ class StudioPlayDesktopTest {
var ready=new CompletableFuture<Void>();Platform.startup(()->{Platform.setImplicitExit(false);ready.complete(null);});ready.get(15,TimeUnit.SECONDS);
}
@AfterAll static void stopToolkit(){Platform.exit();}
@Test void realTrapShowsExecutedSourceAfterEditDeletionAndFailedPreparation() throws Exception {
Path root=Files.createDirectories(temporary.resolve("diagnostic-project"));Files.createDirectories(root.resolve("src"));
Files.writeString(root.resolve("prometeu.json"),"""
{"name":"diagnostic-project","version":"1","language":"pbs","stdlib":"1","target":"Game","dependencies":[]}
""");
Files.writeString(root.resolve("src/mod.barrel"),"pub fn frame() -> void;");
String original="// execução 😀\r\n[Frame] fn frame() -> void { let zero = 0; let value = 123 / zero; }\r\n";
Path source=root.resolve("src/main.pbs");Files.writeString(source,original);
var initial=p.studio.ui.javafx2.appearance.PresentationSettings.defaults(Locale.ENGLISH);
var resources=new WindowResources(initial,new p.studio.ui.javafx2.preferences.SettingsStore(){
public p.studio.ui.javafx2.appearance.PresentationSettings load(){return initial;}
public void save(p.studio.ui.javafx2.appearance.PresentationSettings value){}
});
try(var app=new SpringApplicationBuilder(StudioApplicationConfiguration.class).web(WebApplicationType.NONE).headless(false).run()) {
var catalog=app.getBean(ProjectCatalog.class);var setups=app.getBean(ProjectLocalStudioSetupStore.class);
var ref=catalog.openProject(root);setups.save(ref,new ProjectLocalStudioSetup(System.getProperty("studio.test.runtimeInstall"),null));
var access=app.getBean(ProjectAccessRegistry.class);
var factory=new DefaultExecutionControllerFactory(app.getBean(p.studio.api.shipper.Shipper.class),
new StudioRuntimeGateway(app.getBean(ObjectMapper.class)),app.getBean(p.studio.api.operation.OperationExecutor.class),access);
var known=new KnownProjects(){public List<ProjectReference> listKnownProjects(){return List.of(ref);}public void remember(ProjectReference r){}public void forget(ProjectReference r){}};
Stage stage=fx(Stage::new);
var window=fx(()->new StudioWindowCoordinator2(stage,catalog,known,app.getBean(ProjectSessionFactory.class),factory,
setups::save,app.getBean("studioExecutor",ExecutorService.class),resources));
try {
fx(()->{window.showLauncher();window.openProject(root);return null;});
await(()->{try{return fx(()->window.projectSession()!=null);}catch(Exception e){throw new RuntimeException(e);}},()->"Diagnostic project did not open");
focus(stage);fire(stage,"play");
Supplier<String> facts=()->{try{return fx(()->window.projectSession().executionSession().snapshot().toString());}catch(Exception e){return e.toString();}};
await(()->{try{return fx(()->window.projectSession().executionSession().snapshot().state()==ExecutionState.RUNTIME_FAILED);}catch(Exception e){throw new RuntimeException(e);}},facts);
var diagnostic=fx(()->window.projectSession().executionSession().snapshot().diagnostics().getFirst());
assertEquals("vm_trap",diagnostic.fault().kind());assertNotNull(diagnostic.fault().pc());
assertEquals("available",diagnostic.excerpt().availability());assertEquals(2,diagnostic.excerpt().line());
assertEquals(ExecutionSources.digest(original.getBytes(java.nio.charset.StandardCharsets.UTF_8)),diagnostic.excerpt().revision());
Files.writeString(source,"// edited after execution\n");Files.delete(source);
await(()->{try{return fx(()->stage.getScene().lookup("#runtime-diagnostic-source")!=null);}catch(Exception e){throw new RuntimeException(e);}},facts);
fx(()->{assertTrue(((Label)stage.getScene().lookup("#runtime-diagnostic-source")).getText().contains("123 / zero"));
assertTrue(((Label)stage.getScene().lookup("#runtime-diagnostic-location")).getText().contains(":2:"));
assertNull(stage.getScene().lookup("#code-editor"));return null;});
dragGameplayDivider(stage,.4);capture(stage,"diagnostic-executed-source.png");
// A later build fails; its message is shown alongside the retained execution.
focus(stage);fire(stage,"play");
await(()->{try{return fx(()->window.projectSession().executionSession().snapshot().state()==ExecutionState.PREPARE_FAILED);}catch(Exception e){throw new RuntimeException(e);}},facts);
var after=fx(()->window.projectSession().executionSession().snapshot().diagnostics());
assertEquals(2,after.size());assertEquals("preparation",after.getFirst().fault().kind());assertEquals(diagnostic,after.getLast());
fx(()->{var tabs=(TabPane)stage.getScene().lookup("#project-tabs");tabs.getSelectionModel().select(0);return null;});
capture(stage,"diagnostic-retained-after-prepare-failure.png");
} finally {fx(window::closeAsync).toCompletableFuture().get(15,TimeUnit.SECONDS);}
}
}
private static void await(BooleanSupplier condition,Supplier<String> failure)throws Exception{
long deadline=System.nanoTime()+TimeUnit.SECONDS.toNanos(20);
while(System.nanoTime()<deadline){if(condition.getAsBoolean())return;Thread.sleep(25);}fail(failure.get());
@@ -58,8 +108,12 @@ class StudioPlayDesktopTest {
public boolean interactive(){return true;}
public p.studio.core.runtime.RuntimeConnection start(ProjectReference p,ProjectLocalStudioSetup s,Consumer<p.studio.api.runtime.RuntimeLogEntry> logs)throws Exception{return start(p,s,logs,PlayOptions.PERSISTENT);}
public p.studio.core.runtime.RuntimeConnection start(ProjectReference p,ProjectLocalStudioSetup s,Consumer<p.studio.api.runtime.RuntimeLogEntry> logs,PlayOptions options)throws Exception{
var actual=nativeGateway.start(p,s,logs,options);
return start(p,s,logs,options,UUID.randomUUID().toString().replace("-",""),ExecutionSources.EMPTY,d->{});
}
public p.studio.core.runtime.RuntimeConnection start(ProjectReference p,ProjectLocalStudioSetup s,Consumer<p.studio.api.runtime.RuntimeLogEntry> logs,PlayOptions options,String runId,ExecutionSources sources,Consumer<RuntimeDiagnostic> diagnostics)throws Exception{
var actual=nativeGateway.start(p,s,logs,options,runId,sources,diagnostics);
return new p.studio.core.runtime.RuntimeConnection(){
public String verifiedProgramSha256(){return actual.verifiedProgramSha256();}
public CompletableFuture<Integer> completion(){return actual.completion();}
public CompletableFuture<Void> startExecution(){return actual.startExecution();}
public CompletableFuture<Void> pause(){
@@ -64,6 +64,9 @@ class AnimationIntegrationTest {
var result=p.studio.compiler.workspaces.BuilderPipelineService.INSTANCE.compile(build,p.studio.utilities.logs.LogAggregator.stdout());assertTrue(result.bytecodeBytes().length>0);
var source=new p.studio.compiler.workspaces.AssetSurfaceContextLoader(layouts).load(root).animations().getFirst();
Path generatedPath=null;String generatedText=null;
var captured=p.studio.compiler.source.diagnostics.ConsumedSources.capture(build.fileTable,4*1024*1024,1024,16*1024*1024);
assertEquals(2,captured.stream().filter(s->s.kind().equals("generated")).count());
assertTrue(captured.stream().anyMatch(s->s.kind().equals("sdk")));
for(var id:build.fileTable.identifiers()){var handle=build.fileTable.get(id);if(handle.getCanonPath().startsWith(Path.of("/virtual/generated/animations"))&&handle.getFilename().equals("main.pbs")){generatedPath=handle.getCanonPath();generatedText=handle.readUtf8().orElseThrow();}}
assertNotNull(generatedPath);assertFalse(generatedText.contains(root.toString()));
var bridge=new p.studio.lsp.services.compiler.CompilerLanguageServiceBridge(layouts);
@@ -0,0 +1,42 @@
package p.studio.app.compiler;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import p.studio.api.execution.ExecutionSources;
import p.studio.api.project.*;
import java.nio.file.*;
import java.nio.charset.StandardCharsets;
import static org.junit.jupiter.api.Assertions.*;
class ExecutionSourceBuildTest {
@TempDir Path root;
@Test void capturesProjectDependencyAndSdkWithDistinctLogicalOriginsAndRejectsOversizedInput() throws Exception {
Files.createDirectories(root.resolve("src"));
Path dependency=Files.createDirectories(root.resolve(".workspace/repos/lib/src/probe")).getParent().getParent();
Files.writeString(root.resolve(".workspace/repos/registry.json"),"{}");
Files.writeString(root.resolve("prometeu.json"),"""
{"name":"app","version":"1","language":"pbs","stdlib":"1","target":"Game","dependencies":[{"path":".workspace/repos/lib"}]}
""");
Files.writeString(dependency.resolve("prometeu.json"),"""
{"name":"lib","version":"1","language":"pbs","stdlib":"1","target":"Game","dependencies":[]}
""");
Files.writeString(dependency.resolve("src/probe/main.pbs"),"fn value() -> int { return 42; }");
Files.writeString(dependency.resolve("src/probe/mod.barrel"),"pub fn value() -> int;");
Files.writeString(root.resolve("src/mod.barrel"),"pub fn frame() -> void;");
String text="import { value } from @lib:probe;\nimport { math } from @sdk:math;\n[Frame] fn frame() -> void { let number = math.abs(value()); }\n";
Path main=root.resolve("src/main.pbs");Files.writeString(main,text);
var project=new ProjectReference("app","1","pbs",1,ProjectTarget.Game,root);
var adapter=new CompilerBuildGatewayAdapter();var build=adapter.compile(project,ignored->{});
var capture=build.executionSources();
assertEquals(ExecutionSources.digest(Files.readAllBytes(build.bytecodeArtifact())),capture.programSha256());
assertTrue(capture.sources().values().stream().anyMatch(s->s.kind().equals("dependency")&&s.logicalPath().startsWith("@lib:")));
assertTrue(capture.sources().values().stream().anyMatch(s->s.kind().equals("sdk")));
Files.delete(main);
assertTrue(capture.sources().values().stream().anyMatch(s->s.text().equals(text)));
assertFalse(build.context().toString().contains("let number"));
Files.writeString(main,"[Frame] fn frame() -> void {}\n//"+"x".repeat(ExecutionSources.MAX_FILE_BYTES));
var failure=assertThrows(IllegalStateException.class,()->adapter.compile(project,ignored->{}));
assertTrue(failure.getMessage().contains("source byte limit"),failure.toString());
assertTrue(capture.sources().values().stream().anyMatch(s->s.sha256().equals(ExecutionSources.digest(text.getBytes(StandardCharsets.UTF_8)))));
}
}
@@ -71,6 +71,7 @@ class HeadlessTaskIntegrationTest {
String successfulBuild(String request) throws Exception {
var result = build(request); assertNull(result.failure());
assertNotNull(result.buildResult()); assertTrue(result.buildResult().success(), result.buildResult().diagnostics().toString());
assertTrue(result.buildResult().executionSources().sources().isEmpty(),"Managed task history must not retain interactive source captures");
assertNotNull(result.buildId()); return result.buildId();
}
TaskTools.HeadlessReply call(TaskTools.HeadlessAction action, String build) {
@@ -47,7 +47,7 @@ class StudioPlayInstalledRuntimeTest {
finally{formatting.shutdown().toCompletableFuture().get(7,TimeUnit.SECONDS);}
assertTrue(Files.isRegularFile(image));
var gateway=new StudioRuntimeGateway(json);
var persistent=gateway.start(project,setup,logs::add,PlayOptions.PERSISTENT);
var persistent=assertDoesNotThrow(()->gateway.start(project,setup,logs::add,PlayOptions.PERSISTENT),logs::toString);
try{
persistent.startExecution().get(5,TimeUnit.SECONDS);awaitColor(persistent,0,0,255,logs); // BGRA red
var refusal=assertThrows(ExecutionException.class,()->persistent.stopAsync().get(5,TimeUnit.SECONDS));
@@ -0,0 +1,75 @@
package p.studio.app.runtime.studio;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.junit.jupiter.api.Test;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.*;
import static org.junit.jupiter.api.Assertions.*;
class StudioFaultsTest {
private static final ObjectMapper JSON = new ObjectMapper();
private static final byte[] SESSION = HexFormat.of().parseHex("03".repeat(16));
private static final String PROGRAM = "ab".repeat(32);
private static byte[] fixture() throws IOException {
try(var in=StudioFaultsTest.class.getResourceAsStream("/studio-protocol/fixtures/fault.hex")) {
assertNotNull(in);
var bytes=HexFormat.of().parseHex(new String(in.readAllBytes(),StandardCharsets.US_ASCII).replaceAll("\\s+",""));
var message=new StudioWire.Reader(new ByteArrayInputStream(bytes)).receive();
assertEquals(StudioWire.FAULT,message.header().kind());
return message.payload();
}
}
@Test void sharedRustFixtureKeepsUnsignedPcSpanAndUnicode() throws Exception {
var fault=StudioFaults.decode(fixture(),SESSION,PROGRAM);
assertEquals(4294967295L,fault.pc());assertEquals(7,fault.span().fileId());
assertEquals(18,fault.span().start());assertTrue(fault.message().contains("ação"));
assertEquals(PROGRAM,fault.programSha256());assertFalse(fault.truncated());
}
@Test void rejectsInvalidIdentityNumericFieldsAndEnvelope() throws Exception {
for(String field:List.of("sessionId","programSha256","schemaVersion","tick","truncated")) {
var root=(ObjectNode)JSON.readTree(fixture());root.put(field,"invalid");
assertThrows(IOException.class,()->StudioFaults.decode(JSON.writeValueAsBytes(root),SESSION,PROGRAM),field);
}
for(String field:List.of("pc","code","opcode")) {
var root=(ObjectNode)JSON.readTree(fixture());((ObjectNode)root.path("fault").path("trap")).put(field,-1);
assertThrows(IOException.class,()->StudioFaults.decode(JSON.writeValueAsBytes(root),SESSION,PROGRAM),field);
}
var root=(ObjectNode)JSON.readTree(fixture());
((ObjectNode)root.path("fault").path("trap").path("span")).put("end",1);
assertThrows(IOException.class,()->StudioFaults.decode(JSON.writeValueAsBytes(root),SESSION,PROGRAM));
assertThrows(IOException.class,()->StudioFaults.decode(new byte[65537],SESSION,PROGRAM));
assertThrows(IOException.class,()->StudioFaults.decode((new String(fixture(),StandardCharsets.UTF_8)+" {}").getBytes(StandardCharsets.UTF_8),SESSION,PROGRAM));
assertThrows(IOException.class,()->StudioFaults.decode(new byte[]{(byte)0xff},SESSION,PROGRAM));
}
@Test void initFailureHasNoFabricatedPcOrProgramAndLimitsAreEnforced() throws Exception {
var root=(ObjectNode)JSON.readTree(fixture());root.putNull("programSha256");root.put("truncated",true);
root.set("fault",JSON.readTree("{\"kind\":\"vm_init\",\"pc\":null,\"summary\":\"invalid PBX\",\"initError\":{\"code\":\"malformed\"}}"));
var result=StudioFaults.decode(JSON.writeValueAsBytes(root),SESSION,PROGRAM);
assertNull(result.pc());assertNull(result.span());assertEquals("",result.programSha256());assertTrue(result.truncated());
((ObjectNode)root.get("fault")).put("summary","😀".repeat(2049));
assertThrows(IOException.class,()->StudioFaults.decode(JSON.writeValueAsBytes(root),SESSION,PROGRAM));
((ObjectNode)root.get("fault")).put("summary","invalid PBX");
((ObjectNode)root.get("fault")).put("pc",1);
assertThrows(IOException.class,()->StudioFaults.decode(JSON.writeValueAsBytes(root),SESSION,PROGRAM));
}
@Test void hostCategoriesAreStructuredAndCannotClaimAVmPc() throws Exception {
for(String kind:List.of("load","host","transport","watchdog")) {
var root=(ObjectNode)JSON.readTree(fixture());root.putNull("programSha256");
root.set("fault",JSON.createObjectNode().put("kind",kind).put("summary","host failure").putNull("pc"));
var fault=StudioFaults.decodeHost(JSON.writeValueAsBytes(root),SESSION,PROGRAM);
assertEquals(kind,fault.kind());assertNull(fault.pc());assertNull(fault.span());
((ObjectNode)root.get("fault")).put("pc",5);
assertThrows(IOException.class,()->StudioFaults.decodeHost(JSON.writeValueAsBytes(root),SESSION,PROGRAM));
}
}
@Test void unsignedSpanFactsArePreservedAndSchemaNumbersCannotWrap() throws Exception {
var root=(ObjectNode)JSON.readTree(fixture());
((ObjectNode)root.path("fault").path("trap").path("span")).put("file_id",4294967295L).put("start",4294967294L).put("end",4294967295L);
var fault=StudioFaults.decode(JSON.writeValueAsBytes(root),SESSION,PROGRAM);
assertEquals(4294967295L,fault.span().fileId());assertEquals(4294967295L,fault.span().end());
root.put("schemaVersion",4294967297L);
assertThrows(IOException.class,()->StudioFaults.decode(JSON.writeValueAsBytes(root),SESSION,PROGRAM));
}
}
@@ -19,25 +19,33 @@ class StudioPlayProcessTest {
static final class Native implements AutoCloseable {
final ExecutorService io=Executors.newVirtualThreadPerTaskExecutor();
final List<String> logs=new CopyOnWriteArrayList<>();
final List<p.studio.api.execution.RuntimeDiagnostic> faults=new CopyOnWriteArrayList<>();
Message startup;
Process process;Socket control,video;StudioRuntimeConnection connection;
Native()throws Exception {
Native()throws Exception {this(java.nio.file.Path.of(System.getProperty("studio.test.studioCartridge")),null);assertNotNull(connection);}
Native(java.nio.file.Path cartridge,String expectedDigest)throws Exception {
try(ServerSocket c=new ServerSocket(0,4,InetAddress.getByName("127.0.0.1"));
ServerSocket v=new ServerSocket(0,4,InetAddress.getByName("127.0.0.1"))){
process=new ProcessBuilder(System.getProperty("studio.test.studioHost"),"--studio","--run",
System.getProperty("studio.test.studioCartridge")).start();
cartridge.toString()).start();
var stdout=StudioRuntimeGateway.drain(process.getInputStream(),false,e->logs.add(e.message()),io);
var stderr=StudioRuntimeGateway.drain(process.getErrorStream(),true,e->logs.add(e.message()),io);
String digest=expectedDigest==null?p.studio.api.execution.ExecutionSources.digest(java.nio.file.Files.readAllBytes(cartridge.resolve("program.pbx"))):expectedDigest;
byte[] session=new byte[16],token=new byte[32];Arrays.fill(session,(byte)3);Arrays.fill(token,(byte)7);
try(var input=process.getOutputStream()){new Writer(input).send(BOOTSTRAP,0,little(53)
.put(session).put(token).putShort((short)c.getLocalPort()).putShort((short)v.getLocalPort()).put((byte)1).array());}
try(var input=process.getOutputStream()){new Writer(input).send(BOOTSTRAP,0,little(85)
.put(session).put(token).putShort((short)c.getLocalPort()).putShort((short)v.getLocalPort()).put((byte)1).put(HexFormat.of().parseHex(digest)).array());}
c.setSoTimeout(10000);v.setSoTimeout(10000);control=c.accept();video=v.accept();
control.setSoTimeout(10000);video.setSoTimeout(10000);
Reader cr=new Reader(control.getInputStream()),vr=new Reader(video.getInputStream());
assertEquals(HELLO,cr.receive().header().kind());assertEquals(HELLO,vr.receive().header().kind());
var ready=cr.receive();assertEquals(READY,ready.header().kind());
var ready=cr.receive();startup=ready;
if(ready.header().kind()==FAULT){faults.add(StudioFaults.decode(ready.payload(),session,digest));return;}
if(ready.header().kind()==ERROR){faults.add(StudioFaults.decodeHost(ready.payload(),session,digest));return;}
assertEquals(READY,ready.header().kind());
var b=ByteBuffer.wrap(ready.payload()).order(ByteOrder.LITTLE_ENDIAN);int width=b.getInt(),height=b.getInt();
control.setSoTimeout(0);video.setSoTimeout(0);
connection=new StudioRuntimeConnection(process,control,video,cr,vr,session,width,height,e->logs.add(e.message()),io,stdout,stderr);
assertArrayEquals(HexFormat.of().parseHex(digest),Arrays.copyOfRange(ready.payload(),16,48));
connection=new StudioRuntimeConnection(process,control,video,cr,vr,session,width,height,digest,faults::add,e->logs.add(e.message()),io,stdout,stderr);
}catch(Throwable failure){close();throw failure;}
}
ExecutionFrame image()throws Exception {
@@ -53,6 +61,53 @@ class StudioPlayProcessTest {
io.shutdownNow();
}
}
@Test void differentLoadedProgramIsRejectedBeforeReadyOrStart() throws Exception {
try(var nativeRun=new Native(java.nio.file.Path.of(System.getProperty("studio.test.studioCartridge")),"ab".repeat(32))) {
assertNull(nativeRun.connection);assertEquals(ERROR,nativeRun.startup.header().kind());
assertTrue(nativeRun.faults.getFirst().message().contains("differs from prepared compilation"));
assertNull(nativeRun.faults.getFirst().pc());
}
}
@Test void invalidPbxProducesAnInitializationFaultBeforeReadyWithoutInventingPc(@org.junit.jupiter.api.io.TempDir java.nio.file.Path root) throws Exception {
var original=java.nio.file.Path.of(System.getProperty("studio.test.studioCartridge"));
try(var files=java.nio.file.Files.walk(original)) {
for(var file:files.toList()) {
var target=root.resolve(original.relativize(file));
if(java.nio.file.Files.isDirectory(file))java.nio.file.Files.createDirectories(target);
else java.nio.file.Files.copy(file,target);
}
}
java.nio.file.Files.write(root.resolve("program.pbx"),new byte[]{1,2,3});
try(var nativeRun=new Native(root,null)) {
assertEquals(FAULT,nativeRun.startup.header().kind(),nativeRun.logs.toString());
var fault=nativeRun.faults.getFirst();assertEquals("vm_init",fault.kind());assertNull(fault.pc());assertNull(fault.span());
assertTrue(fault.facts().containsKey("initError"));assertNull(nativeRun.connection);
}
}
@Test void realCompiledTrapArrivesBeforeEofAndKeepsItsSourceSpan(@org.junit.jupiter.api.io.TempDir java.nio.file.Path root) throws Exception {
java.nio.file.Files.createDirectories(root.resolve("src"));
java.nio.file.Files.writeString(root.resolve("prometeu.json"),"{\"name\":\"fault-probe\",\"version\":\"1\",\"language\":\"pbs\",\"stdlib\":\"1\",\"target\":\"Game\",\"dependencies\":[]}");
java.nio.file.Files.writeString(root.resolve("src/mod.barrel"),"pub fn frame() -> void;");
java.nio.file.Files.writeString(root.resolve("src/main.pbs"),"// ação 😀\r\n[Frame] fn frame() -> void { let zero = 0; let value = 123 / zero; }\r\n");
var mapper=new com.fasterxml.jackson.databind.ObjectMapper();
var project=new p.studio.core.project.ProjectCatalogService(root,mapper,new p.studio.core.project.ProjectLocalStudioSetupStore(mapper)).openProject(root);
try(var workers=Executors.newFixedThreadPool(2);var packer=p.packer.Packer.bootstrap(mapper,e->{})) {
var shipper=new p.studio.core.shipper.StudioShipperService(new p.studio.app.compiler.CompilerBuildGatewayAdapter(),packer.workspaceService(),mapper,new p.studio.app.operation.ExecutorOperationExecutor(workers));
var build=shipper.prepare(project,e->{}).completion().toCompletableFuture().get(30,TimeUnit.SECONDS);
assertTrue(build.success(),build.diagnostics().toString());
try(var nativeRun=new Native(root.resolve("build"),null)) {
assertNotNull(nativeRun.connection,nativeRun.faults.toString());
java.nio.file.Files.delete(root.resolve("src/main.pbs"));
nativeRun.connection.startExecution().get(3,TimeUnit.SECONDS);
assertThrows(ExecutionException.class,()->nativeRun.connection.completion().get(5,TimeUnit.SECONDS));
var fault=nativeRun.faults.getFirst();assertEquals("vm_trap",fault.kind(),()->nativeRun.faults+"\n"+nativeRun.logs);assertNotNull(fault.pc());assertNotNull(fault.span());
var source=build.executionSources().sources().get(Math.toIntExact(fault.span().fileId()));
assertNotNull(source);assertTrue(source.text().contains("123 / zero"));
assertEquals(build.executionSources().programSha256(),fault.programSha256());
assertFalse(nativeRun.process.isAlive());
}
}
}
@Test void liveFramesRemainStableDuringSlowPresentationAndStopIsConfirmed()throws Exception {
try(var s=new Native()){
long pid=s.process.pid();s.connection.startExecution().get(3,TimeUnit.SECONDS);
@@ -27,6 +27,11 @@ class StudioWireTest {
assertArrayEquals(fixture("pause.hex"),new Header(PAUSE,0,1,42).encode());
assertEquals(42,Header.decode(fixture("pause.hex")).request());
}
@Test void v1IsRejectedWithTheRequiredVersionBeforeAnyCommand() throws Exception {
byte[] header=fixture("pause.hex");header[4]=1;
var failure=assertThrows(IOException.class,()->Header.decode(header));
assertTrue(failure.getMessage().contains("required 2.0"));
}
@Test void fragmentedReadsWorkButTruncationAndReplayFail() throws Exception {
byte[] bytes=fixture("pause.hex");
InputStream fragmented=new FilterInputStream(new ByteArrayInputStream(bytes)) {
@@ -0,0 +1,27 @@
50 53 54 31 02 00 00 00 10 00 00 00 82 01 00 00
01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
7b 22 73 63 68 65 6d 61 56 65 72 73 69 6f 6e 22
3a 31 2c 22 73 65 73 73 69 6f 6e 49 64 22 3a 22
30 33 30 33 30 33 30 33 30 33 30 33 30 33 30 33
30 33 30 33 30 33 30 33 30 33 30 33 30 33 30 33
22 2c 22 70 72 6f 67 72 61 6d 53 68 61 32 35 36
22 3a 22 61 62 61 62 61 62 61 62 61 62 61 62 61
62 61 62 61 62 61 62 61 62 61 62 61 62 61 62 61
62 61 62 61 62 61 62 61 62 61 62 61 62 61 62 61
62 61 62 61 62 61 62 61 62 61 62 61 62 61 62 61
62 61 62 22 2c 22 74 69 63 6b 22 3a 37 2c 22 74
72 75 6e 63 61 74 65 64 22 3a 66 61 6c 73 65 2c
22 66 61 75 6c 74 22 3a 7b 22 6b 69 6e 64 22 3a
22 76 6d 5f 74 72 61 70 22 2c 22 70 63 22 3a 34
32 39 34 39 36 37 32 39 35 2c 22 73 75 6d 6d 61
72 79 22 3a 22 64 69 76 69 73 69 6f 6e 20 62 79
20 7a 65 72 6f 20 e2 80 94 20 61 c3 a7 c3 a3 6f
22 2c 22 74 72 61 70 22 3a 7b 22 70 63 22 3a 34
32 39 34 39 36 37 32 39 35 2c 22 63 6f 64 65 22
3a 32 2c 22 6f 70 63 6f 64 65 22 3a 31 34 2c 22
73 70 61 6e 22 3a 7b 22 66 69 6c 65 5f 69 64 22
3a 37 2c 22 73 74 61 72 74 22 3a 31 38 2c 22 65
6e 64 22 3a 32 33 7d 2c 22 6d 65 73 73 61 67 65
22 3a 22 64 69 76 69 73 69 6f 6e 20 62 79 20 7a
65 72 6f 20 e2 80 94 20 61 c3 a7 c3 a3 6f 22 7d
7d 7d
@@ -1,2 +1 @@
50 53 54 31 01 00 00 00 04 00 00 00 00 00 00 00
01 00 00 00 00 00 00 00 2a 00 00 00 00 00 00 00
50 53 54 31 02 00 00 00 04 00 00 00 00 00 00 00 01 00 00 00 00 00 00 00 2a 00 00 00 00 00 00 00
@@ -1,6 +1 @@
50 53 54 31 01 00 00 00 09 00 00 00 38 00 00 00
01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f
01 00 00 00 00 00 00 00 07 00 00 00 00 00 00 00
02 00 00 00 01 00 00 00 02 00 00 00 01 00 00 00
ff 00 00 ff 00 00 ff 80
50 53 54 31 02 00 00 00 09 00 00 00 38 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 01 00 00 00 00 00 00 00 07 00 00 00 00 00 00 00 02 00 00 00 01 00 00 00 02 00 00 00 01 00 00 00 ff 00 00 ff 00 00 ff 80
@@ -83,6 +83,9 @@ public final class InterfaceModuleLoader {
utf8.length,
0,
ignored -> () -> utf8);
// Synthetic inputs are consumed directly by the parser, so record the
// same immutable provider bytes before publishing their file identity.
sourceHandle.readBytes().orElseThrow();
return fileTable.register(sourceHandle);
}
@@ -226,11 +226,13 @@ final class PbsModuleAssemblyService {
var unit=new MutableModuleUnit();var module=moduleId(table,coordinates);
byte[] utf8=generated.source().getBytes(StandardCharsets.UTF_8);
var file=files.register(new SourceHandle(owner,Path.of("@generated/animations").resolve(generated.moduleName()).resolve("main.pbs"),generated.path(),utf8.length,0,ignored->()->utf8));
files.get(file).readBytes().orElseThrow();
var ast=parseSourceFile(file,generated.source(),diagnostics,SourceKind.PROJECT);
unit.sources.add(new PbsModuleVisibilityValidator.SourceFile(file,ast));moduleByFile.put(file,module);
parsed.add(new PbsParsedSourceFile(file,ast,module,SourceKind.PROJECT));
byte[] barrel=generated.barrel().getBytes(StandardCharsets.UTF_8);
var barrelId=files.register(new SourceHandle(owner,Path.of("@generated/animations").resolve(generated.moduleName()).resolve("mod.barrel"),generated.path().resolveSibling("mod.barrel"),barrel.length,0,ignored->()->barrel));
files.get(barrelId).readBytes().orElseThrow();
unit.barrels.add(new PbsModuleVisibilityValidator.BarrelFile(barrelId,parseBarrelFile(barrelId,generated.barrel(),diagnostics)));
moduleByFile.put(barrelId,module);modules.put(coordinates,unit);
}
@@ -39,6 +39,10 @@ class InterfaceModuleLoaderTest {
assertEquals(1, module.barrelFiles().size());
assertFalse(module.sourceFiles().getFirst().fileId().isNone());
assertFalse(module.barrelFiles().getFirst().fileId().isNone());
// Capture must already exist after parsing; these assertions precede any test read.
var consumed=p.studio.compiler.source.diagnostics.ConsumedSources.capture(fileTable,4096,10,16384);
assertEquals(2,consumed.size());assertTrue(consumed.stream().allMatch(s->s.kind().equals("sdk")));
assertTrue(consumed.stream().anyMatch(s->s.text().equals("declare host Gfx { fn draw() -> void; }")));
assertTrue(fileTable.get(module.sourceFiles().getFirst().fileId()).readUtf8().isPresent());
assertTrue(fileTable.get(module.barrelFiles().getFirst().fileId()).readUtf8().isPresent());
assertEquals(
@@ -75,6 +75,18 @@ public class SourceHandle {
public String observedSha256() { return observedSha256; }
public boolean mixedRevisions() { return mixedRevisions; }
/** A coherent copy of already consumed input; never invokes the provider. */
public synchronized Optional<Observation> observation(int maxBytes) {
if (observedBytes != null && observedBytes.length > maxBytes)
throw new IllegalStateException("Execution source capture unavailable: source byte limit: " + relativePath);
return observedBytes == null ? Optional.empty()
: Optional.of(new Observation(observedSha256, mixedRevisions, observedBytes));
}
public record Observation(String sha256, boolean mixedRevisions, byte[] bytes) {
public Observation { bytes = bytes.clone(); }
@Override public byte[] bytes() { return bytes.clone(); }
}
/** Already consumed bytes only; this accessor never invokes the provider. */
public Optional<String> observedText() {
var bytes = observedBytes;
@@ -0,0 +1,41 @@
package p.studio.compiler.source.diagnostics;
import p.studio.compiler.source.tables.FileTableReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
/** Compilation-owned capture. Callers supply their retention policy, not live paths. */
public final class ConsumedSources {
private ConsumedSources() { }
public record Source(int fileId, int projectId, String path, String logicalPath,
String kind, String sha256, String text) { }
public static List<Source> capture(FileTableReader files, int maxFileBytes, int maxFiles, long maxBytes) {
var result = new ArrayList<Source>();
long total = 128; // Capture identity/header metadata, in addition to each source record.
for (var id : files.identifiers()) {
if (result.size() >= maxFiles) throw unavailable("source count limit");
var file = files.get(id);
var observation = file.observation(maxFileBytes).orElseThrow(() -> unavailable("input was not captured: " + file.getRelativePath()));
if (observation.mixedRevisions()) throw unavailable("mixed input revisions: " + file.getRelativePath());
byte[] bytes = observation.bytes();
if (bytes.length > maxFileBytes) throw unavailable("source byte limit: " + file.getRelativePath());
String path = file.getCanonPath().toString(), logical = file.getRelativePath().toString();
String kind = logical.startsWith("@stdlib") ? "sdk" : logical.startsWith("@generated") ? "generated" : "source";
// Fixed fields, both paths, hash and origin are included in the budget.
total += bytes.length + path.getBytes(StandardCharsets.UTF_8).length
+ logical.getBytes(StandardCharsets.UTF_8).length + 128L;
if (total > maxBytes) throw unavailable("capture byte limit");
final String text;
try { text = StandardCharsets.UTF_8.newDecoder().decode(java.nio.ByteBuffer.wrap(bytes)).toString(); }
catch (java.nio.charset.CharacterCodingException invalid) { throw unavailable("invalid UTF-8: " + logical); }
result.add(new Source(id.getId(), file.getProjectId().getIndex(), path, logical, kind, observation.sha256(), text));
}
return List.copyOf(result);
}
private static IllegalStateException unavailable(String reason) {
return new IllegalStateException("Execution source capture unavailable: " + reason);
}
}
@@ -0,0 +1,42 @@
package p.studio.compiler.source.diagnostics;
import org.junit.jupiter.api.Test;
import p.studio.compiler.models.SourceHandle;
import p.studio.compiler.source.identifiers.ProjectId;
import p.studio.compiler.source.tables.FileTable;
import java.nio.file.Path;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.jupiter.api.Assertions.*;
class ConsumedSourcesTest {
@Test void capturesConsumedBytesWithoutRereadingAndPreservesVirtualOrigins() {
var reads = new AtomicInteger(); var files = new FileTable(1);
var source = new SourceHandle(new ProjectId(0), Path.of("@stdlib/core/sample/main.pbs"),
Path.of("/virtual/stdlib/core/sample/main.pbs"), 0, 0,
path -> () -> { reads.incrementAndGet(); return "// á 😀\r\nfn x(){}".getBytes(StandardCharsets.UTF_8); });
files.register(source); source.readBytes();
var capture = ConsumedSources.capture(files, 1024, 10, 4096);
assertEquals(1, reads.get()); assertEquals("sdk", capture.getFirst().kind());
assertEquals("// á 😀\r\nfn x(){}", capture.getFirst().text());
assertThrows(UnsupportedOperationException.class, () -> capture.clear());
}
@Test void refusesUncapturedMixedMalformedAndOverBudgetInputs() {
var files = new FileTable(1); var read = new AtomicInteger();
var source = new SourceHandle(new ProjectId(0), Path.of("main.pbs"), Path.of("/fixture/main.pbs"), 0, 0,
path -> () -> (read.incrementAndGet() == 1 ? "first" : "other").getBytes(StandardCharsets.UTF_8));
files.register(source);
assertThrows(IllegalStateException.class, () -> ConsumedSources.capture(files, 100, 1, 1000));
source.readBytes();
assertThrows(IllegalStateException.class, () -> ConsumedSources.capture(files, 4, 1, 1000));
assertThrows(IllegalStateException.class, () -> ConsumedSources.capture(files, 100, 0, 1000));
assertThrows(IllegalStateException.class, () -> ConsumedSources.capture(files, 100, 1, 1));
source.readBytes();
assertThrows(IllegalStateException.class, () -> ConsumedSources.capture(files, 100, 1, 1000));
var invalid = new FileTable(1);
var malformed = new SourceHandle(new ProjectId(0), Path.of("bad.pbs"), Path.of("/fixture/bad.pbs"), 1, 0, path -> () -> new byte[]{(byte)255});
invalid.register(malformed); malformed.readBytes();
assertThrows(IllegalStateException.class, () -> ConsumedSources.capture(invalid, 100, 1, 1000));
}
}
@@ -0,0 +1,10 @@
package p.studio.api.execution;
import java.util.Objects;
/** Static presentation values: no editor document, live path or source-opening port. */
public record ExecutionDiagnostic(RuntimeDiagnostic fault, Excerpt excerpt) {
public record Excerpt(String buildId, String logicalPath, String sourceKind, String revision,
int line, int column, String text, boolean truncated, String availability) { }
public ExecutionDiagnostic { Objects.requireNonNull(fault); Objects.requireNonNull(excerpt); }
}
@@ -13,6 +13,11 @@ public interface ExecutionSession extends AutoCloseable {
void beginPreparationCycle();
default void prepareSources(String runId, ExecutionSources sources) { }
default void admitSources(String runId, String programSha256) { }
default void discardCandidate(String runId) { }
default void recordDiagnostic(RuntimeDiagnostic diagnostic) { }
void transitionToPrepareFailed();
void transitionToConnecting();
@@ -3,9 +3,11 @@ package p.studio.api.execution;
import java.util.List;
import java.util.Objects;
public record ExecutionSnapshot(ExecutionState state, List<ExecutionLogEntry> logs) {
public record ExecutionSnapshot(ExecutionState state, List<ExecutionLogEntry> logs, List<ExecutionDiagnostic> diagnostics) {
public ExecutionSnapshot(ExecutionState state, List<ExecutionLogEntry> logs) { this(state, logs, List.of()); }
public ExecutionSnapshot {
Objects.requireNonNull(state, "state");
logs = List.copyOf(Objects.requireNonNull(logs, "logs"));
diagnostics = List.copyOf(Objects.requireNonNull(diagnostics, "diagnostics"));
}
}
@@ -0,0 +1,49 @@
package p.studio.api.execution;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.*;
/** Bounded immutable input of one compilation, consumed by interactive execution. */
public record ExecutionSources(String buildId, String programSha256, Map<Integer, Source> sources) {
public static final int MAX_FILE_BYTES = 4 * 1024 * 1024;
public static final int MAX_FILES = 1024;
public static final int MAX_CAPTURE_BYTES = 16 * 1024 * 1024;
public static final ExecutionSources EMPTY = new ExecutionSources("", "", Map.of());
public record Source(int fileId, int projectId, String path, String logicalPath,
String kind, String sha256, String text) {
public Source {
if (fileId < 0 || projectId < 0) throw new IllegalArgumentException("Invalid source identity");
Objects.requireNonNull(path); Objects.requireNonNull(logicalPath); Objects.requireNonNull(kind);
Objects.requireNonNull(sha256); Objects.requireNonNull(text);
if (!Set.of("source","dependency","sdk","generated").contains(kind))
throw new IllegalArgumentException("Invalid execution source kind");
byte[] bytes = text.getBytes(StandardCharsets.UTF_8);
if (bytes.length > MAX_FILE_BYTES || !digest(bytes).equals(sha256))
throw new IllegalArgumentException("Invalid execution source size/revision");
}
}
public ExecutionSources {
Objects.requireNonNull(buildId); Objects.requireNonNull(programSha256); Objects.requireNonNull(sources);
if (!programSha256.isEmpty() && !programSha256.matches("[0-9a-f]{64}"))
throw new IllegalArgumentException("Invalid program identity");
if (sources.size() > MAX_FILES) throw new IllegalArgumentException("Execution source count limit");
long bytes = buildId.getBytes(StandardCharsets.UTF_8).length + programSha256.length() + 16L;
if (bytes > MAX_CAPTURE_BYTES) throw new IllegalArgumentException("Execution source capture metadata limit");
for (var e : sources.entrySet()) {
var s = Objects.requireNonNull(e.getValue());
if (e.getKey() != s.fileId()) throw new IllegalArgumentException("Mismatched source ID");
bytes += s.text().getBytes(StandardCharsets.UTF_8).length + s.path().getBytes(StandardCharsets.UTF_8).length
+ s.logicalPath().getBytes(StandardCharsets.UTF_8).length + 128L;
if (bytes > MAX_CAPTURE_BYTES) throw new IllegalArgumentException("Execution source capture byte limit");
}
sources = Map.copyOf(sources);
}
public static String digest(byte[] bytes) {
try { return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); }
catch (java.security.NoSuchAlgorithmException impossible) { throw new IllegalStateException(impossible); }
}
}
@@ -0,0 +1,32 @@
package p.studio.api.execution;
import java.util.Map;
import java.util.Objects;
import p.studio.api.values.ValueMaps;
/** Machine facts of a single authenticated Play execution, independent of JavaFX. */
public record RuntimeDiagnostic(String runId, String programSha256, String kind, String message,
Long pc, Long code, Long opcode, Span span, boolean truncated,
Map<String, Object> facts) {
public static RuntimeDiagnostic failure(String runId, String kind, String message) {
byte[] bytes=message.getBytes(java.nio.charset.StandardCharsets.UTF_8);
boolean truncated=bytes.length>8192;
if(truncated) {
int end=8192;
while((bytes[end]&0xc0)==0x80)end--;
message=new String(bytes,0,end,java.nio.charset.StandardCharsets.UTF_8);
}
return new RuntimeDiagnostic(runId,"",kind,message,null,null,null,null,truncated,Map.of());
}
public record Span(long fileId, long start, long end) {
public Span { if (fileId < 0 || fileId > 0xffff_ffffL || start < 0 || end < start || end > 0xffff_ffffL)
throw new IllegalArgumentException("Invalid source span"); }
}
public RuntimeDiagnostic {
Objects.requireNonNull(runId); Objects.requireNonNull(programSha256); Objects.requireNonNull(kind); Objects.requireNonNull(message);
if (!runId.matches("[0-9a-f]{32}") || (!programSha256.isEmpty() && !programSha256.matches("[0-9a-f]{64}")))
throw new IllegalArgumentException("Invalid execution identity");
if (pc != null && (pc < 0 || pc > 0xffff_ffffL)) throw new IllegalArgumentException("Invalid PC");
facts = ValueMaps.object(facts == null ? Map.of() : facts);
}
}
@@ -16,7 +16,14 @@ public record ShipperPrepareResult(
List<String> diagnostics,
List<StudioDiagnostic> issues,
Map<String, Object> summary,
Map<String, Object> context) {
Map<String, Object> context,
p.studio.api.execution.ExecutionSources executionSources) {
public ShipperPrepareResult(ShipperPreparationStatus status, List<ShipperLogEntry> logs, Path manifestPath,
List<Path> emittedArtifacts, List<String> diagnostics, List<StudioDiagnostic> issues,
Map<String, Object> summary, Map<String, Object> context) {
this(status, logs, manifestPath, emittedArtifacts, diagnostics, issues, summary, context,
p.studio.api.execution.ExecutionSources.EMPTY);
}
public ShipperPrepareResult(ShipperPreparationStatus status, List<ShipperLogEntry> logs, Path manifestPath,
List<Path> emittedArtifacts, List<String> diagnostics) {
this(status, logs, manifestPath, emittedArtifacts, diagnostics, List.of(), DiagnosticValues.legacySummary("build"), Map.of());
@@ -28,6 +35,7 @@ public record ShipperPrepareResult(
emittedArtifacts = List.copyOf(Objects.requireNonNull(emittedArtifacts, "emittedArtifacts"));
diagnostics = List.copyOf(Objects.requireNonNull(diagnostics, "diagnostics"));
issues = List.copyOf(issues); summary = ValueMaps.object(summary); context = ValueMaps.object(context);
Objects.requireNonNull(executionSources);
}
public Map<String, Object> diagnosticView() {
@@ -36,7 +44,11 @@ public record ShipperPrepareResult(
public ShipperPrepareResult withContext(Map<String, Object> additions) {
var merged = new java.util.LinkedHashMap<>(context); merged.putAll(additions);
return new ShipperPrepareResult(status, logs, manifestPath, emittedArtifacts, diagnostics, issues, summary, merged);
return new ShipperPrepareResult(status, logs, manifestPath, emittedArtifacts, diagnostics, issues, summary, merged, executionSources);
}
public ShipperPrepareResult withExecutionSources(p.studio.api.execution.ExecutionSources sources) {
return new ShipperPrepareResult(status, logs, manifestPath, emittedArtifacts, diagnostics, issues, summary, context, sources);
}
public ShipperPrepareResult asCancelled() {
@@ -22,6 +22,11 @@ public final class DefaultExecutionSession implements ExecutionSession {
private final CopyOnWriteArrayList<Consumer<ExecutionSnapshot>> listeners = new CopyOnWriteArrayList<>();
private ExecutionState state = ExecutionState.IDLE;
private long nextSequence = 1L;
private p.studio.api.execution.ExecutionSources retained = p.studio.api.execution.ExecutionSources.EMPTY;
private p.studio.api.execution.ExecutionSources candidate = p.studio.api.execution.ExecutionSources.EMPTY;
private String retainedRun = "", candidateRun = "";
private boolean closed, retainedAcceptsDiagnostics;
private p.studio.api.execution.ExecutionDiagnostic lastDiagnostic, attemptDiagnostic;
@Override
public ExecutionSnapshot snapshot() {
@@ -39,7 +44,56 @@ public final class DefaultExecutionSession implements ExecutionSession {
}
@Override
public void beginPreparationCycle() { publish(transitionLocked(ExecutionState.PREPARING, true)); }
public void beginPreparationCycle() {
synchronized (monitor) {
if (closed) throw new IllegalStateException("Execution session is closed");
retainedAcceptsDiagnostics = false;
candidate = p.studio.api.execution.ExecutionSources.EMPTY; candidateRun = ""; attemptDiagnostic = null;
}
publish(transitionLocked(ExecutionState.PREPARING, true));
}
@Override public void prepareSources(String runId, p.studio.api.execution.ExecutionSources sources) {
synchronized (monitor) { if (closed) return; candidateRun = runId; candidate = Objects.requireNonNull(sources); }
}
@Override public void admitSources(String runId, String programSha256) {
synchronized (monitor) {
if (closed) throw new IllegalStateException("Execution session is closed");
if (!candidateRun.equals(runId)) throw new IllegalStateException("Stale execution source admission");
if (!candidate.programSha256().isEmpty() && !candidate.programSha256().equals(programSha256))
throw new IllegalStateException("Loaded program does not match captured compilation");
retained = candidate; retainedRun = runId; candidate = p.studio.api.execution.ExecutionSources.EMPTY;
candidateRun = ""; lastDiagnostic = null; attemptDiagnostic = null;
retainedAcceptsDiagnostics = true;
}
}
@Override public void discardCandidate(String runId) {
synchronized (monitor) {
if (candidateRun.equals(runId)) { candidateRun = ""; candidate = p.studio.api.execution.ExecutionSources.EMPTY; }
}
}
@Override public void recordDiagnostic(p.studio.api.execution.RuntimeDiagnostic diagnostic) {
final p.studio.api.execution.ExecutionSources source;
synchronized (monitor) {
if (retainedAcceptsDiagnostics && diagnostic.runId().equals(retainedRun)) source = retained;
else if (diagnostic.runId().equals(candidateRun)) source = candidate;
else return;
}
var resolved = ExecutionExcerpts.resolve(diagnostic, source);
final ExecutionSnapshot snapshot;
synchronized (monitor) {
if (retainedAcceptsDiagnostics && diagnostic.runId().equals(retainedRun)) {
if (lastDiagnostic == null) lastDiagnostic = resolved;
} else if (diagnostic.runId().equals(candidateRun)) {
if (attemptDiagnostic == null) attemptDiagnostic = resolved;
} else return;
snapshot = snapshotLocked();
}
publish(snapshot);
}
@Override
public void transitionToPrepareFailed() { publish(transitionLocked(ExecutionState.PREPARE_FAILED, false)); }
@@ -102,6 +156,11 @@ public final class DefaultExecutionSession implements ExecutionSession {
transitionToStopped();
}
listeners.clear();
synchronized (monitor) {
closed = true; retainedAcceptsDiagnostics = false;
retained = candidate = p.studio.api.execution.ExecutionSources.EMPTY;
retainedRun = candidateRun = ""; lastDiagnostic = attemptDiagnostic = null;
}
}
private void appendLog(ExecutionLogSource source, ExecutionLogSeverity severity, String message, Instant timestamp) {
@@ -130,7 +189,10 @@ public final class DefaultExecutionSession implements ExecutionSession {
}
private ExecutionSnapshot snapshotLocked() {
return new ExecutionSnapshot(state, List.copyOf(logs));
var diagnostics = new ArrayList<p.studio.api.execution.ExecutionDiagnostic>(2);
if (attemptDiagnostic != null) diagnostics.add(attemptDiagnostic);
if (lastDiagnostic != null) diagnostics.add(lastDiagnostic);
return new ExecutionSnapshot(state, List.copyOf(logs), diagnostics);
}
private static void ensureTransitionAllowed(ExecutionState current, ExecutionState next) {
@@ -0,0 +1,56 @@
package p.studio.core.execution;
import p.studio.api.execution.*;
import java.nio.charset.StandardCharsets;
/** Resolves immutable consumed input on the service thread, never the FX thread. */
final class ExecutionExcerpts {
private ExecutionExcerpts() { }
static ExecutionDiagnostic resolve(RuntimeDiagnostic fault, ExecutionSources capture) {
var unavailable = new ExecutionDiagnostic.Excerpt(capture.buildId(), "", "", "", 0, 0, "", false, "no-span");
if (fault.span() == null) return new ExecutionDiagnostic(fault, unavailable);
String reason = "program-not-confirmed";
if (!capture.programSha256().isEmpty() && capture.programSha256().equals(fault.programSha256())) {
var source = fault.span().fileId() > Integer.MAX_VALUE ? null : capture.sources().get((int)fault.span().fileId());
reason = "source-not-captured";
if (source != null) {
reason = "invalid-span";
byte[] bytes = source.text().getBytes(StandardCharsets.UTF_8);
if (fault.span().end() <= bytes.length) {
try {
String prefix = decode(bytes, 0, (int)fault.span().start());
decode(bytes, (int)fault.span().start(), (int)(fault.span().end() - fault.span().start()));
String text = source.text(); int focus = prefix.length();
int line = 1 + (int) prefix.chars().filter(c -> c == '\n').count();
int column = focus - prefix.lastIndexOf('\n');
int lo = focus;
for (int i = 0; i < 4 && lo > 0; i++) {
int newline = text.lastIndexOf('\n', lo - 1);
lo = newline < 0 ? 0 : newline;
}
if (lo > 0 && text.charAt(lo) == '\n') lo++;
int hi = focus;
for (int i = 0; i < 4 && hi < text.length(); i++) {
int newline = text.indexOf('\n', hi);
hi = newline < 0 ? text.length() : newline + 1;
}
int boundedLo = Math.max(lo, focus - 1024), boundedHi = Math.min(hi, focus + 3072);
if (boundedLo > 0 && boundedLo < text.length() && Character.isLowSurrogate(text.charAt(boundedLo))) boundedLo--;
if (boundedHi < text.length() && boundedHi > 0 && Character.isLowSurrogate(text.charAt(boundedHi))) boundedHi--;
String excerpt = text.substring(boundedLo, boundedHi);
while (excerpt.getBytes(StandardCharsets.UTF_8).length > 8192)
excerpt = excerpt.substring(0, excerpt.offsetByCodePoints(excerpt.length(), -1));
boolean truncated = boundedLo != lo || boundedHi != hi || excerpt.length() != boundedHi - boundedLo;
return new ExecutionDiagnostic(fault, new ExecutionDiagnostic.Excerpt(capture.buildId(), source.logicalPath(),
source.kind(), source.sha256(), line, column, excerpt, truncated, "available"));
} catch (java.nio.charset.CharacterCodingException invalidBoundary) { /* Do not fabricate a location. */ }
}
}
}
return new ExecutionDiagnostic(fault, new ExecutionDiagnostic.Excerpt(capture.buildId(), "", "", "", 0, 0, "", false, reason));
}
private static String decode(byte[] bytes, int offset, int count) throws java.nio.charset.CharacterCodingException {
return StandardCharsets.UTF_8.newDecoder().decode(java.nio.ByteBuffer.wrap(bytes, offset, count)).toString();
}
}
@@ -22,6 +22,7 @@ final class InteractiveExecutionController implements ExecutionController {
private Attempt attempt;
private boolean closed;
private static final class Attempt {
final String runId=java.util.UUID.randomUUID().toString().replace("-","");
final ManualLease lease;
volatile RuntimeConnection connection;
volatile OperationHandle<ExecutionSnapshot> play;
@@ -45,6 +46,7 @@ final class InteractiveExecutionController implements ExecutionController {
}
Attempt a=new Attempt(access.enterExecution(project.rootPath()));attempt=a;
a.lease.onProjectClose(()->stopAttempt(a));session.beginPreparationCycle();
session.prepareSources(a.runId,ExecutionSources.EMPTY);
try{a.play=operations.submit("Play "+project.name(),()->start(a));
a.play.termination().whenComplete((v,f)->{synchronized(monitor){
if(a.connection==null){if(a.stopping)stoppedWithoutProcess(a);release(a);}
@@ -61,13 +63,21 @@ final class InteractiveExecutionController implements ExecutionController {
ShipperPrepareResult prepared=a.preparation.completion().toCompletableFuture().join();
a.preparation.termination().toCompletableFuture().join();
if(a.stopping)return session.snapshot();
if(!prepared.success()){session.transitionToPrepareFailed();return session.snapshot();}
if(!prepared.success()){
session.recordDiagnostic(RuntimeDiagnostic.failure(a.runId,"preparation",prepared.diagnostics().isEmpty()?"Preparation failed":prepared.diagnostics().toString()));
session.transitionToPrepareFailed();return session.snapshot();
}
session.prepareSources(a.runId, prepared.executionSources());
session.transitionToConnecting();
RuntimeConnection connection=runtime.start(project,setup,
log->session.appendRuntimeLog(log.severity(),log.message(),log.timestamp()),options);
log->{synchronized(monitor){if(attempt==a&&!closed)session.appendRuntimeLog(log.severity(),log.message(),log.timestamp());}},
options,a.runId,prepared.executionSources(),diagnostic->{synchronized(monitor){
if(attempt==a&&!closed)session.recordDiagnostic(diagnostic);
}});
synchronized(monitor){a.connection=connection;}
connection.completion().whenComplete((code,failure)->exited(a,connection,code,failure));
if(a.stopping){connection.stopAsync().join();return session.snapshot();}
session.admitSources(a.runId,connection.verifiedProgramSha256());
boolean paused=a.pauseOnReady;
if(paused)connection.pause().join();
connection.startExecution().join();
@@ -80,6 +90,8 @@ final class InteractiveExecutionController implements ExecutionController {
} catch(Throwable failure){
Throwable cause=cause(failure);
synchronized(monitor){
if(attempt==a&&!closed&&!a.stopping)session.recordDiagnostic(RuntimeDiagnostic.failure(a.runId,
session.snapshot().state()==ExecutionState.PREPARING?"preparation":"connection",message(cause)));
if(attempt==a&&a.connection==null){
if(a.stopping){/* Actual worker termination owns the final state and lease. */}
else {log("Play failed: "+message(cause));
@@ -91,6 +103,7 @@ final class InteractiveExecutionController implements ExecutionController {
OperationHandle<ShipperPrepareResult> preparation=a.preparation;
if(preparation!=null)try{preparation.termination().toCompletableFuture().join();}catch(CompletionException|CancellationException ignored){}
a.preparation=null;
session.discardCandidate(a.runId);
}
return session.snapshot();
}
@@ -153,7 +166,11 @@ final class InteractiveExecutionController implements ExecutionController {
if(a.connection!=connection)return;a.connection=null;
if(attempt==a){
if(failure==null&&code!=null&&code==0)session.transitionToStopped();
else {log("Runtime ended: "+(failure==null?"exit "+code:message(cause(failure))));session.transitionToRuntimeFailed();}
else {
String detail=failure==null?"exit "+code:message(cause(failure));
session.recordDiagnostic(RuntimeDiagnostic.failure(a.runId,"connection",detail));
log("Runtime ended: "+detail);session.transitionToRuntimeFailed();
}
}
if(a.play==null||a.play.termination().toCompletableFuture().isDone())release(a);
else a.play.termination().whenComplete((v,f)->release(a));
@@ -4,6 +4,7 @@ import java.util.concurrent.CompletableFuture;
public interface RuntimeConnection extends AutoCloseable {
CompletableFuture<Integer> completion();
default String verifiedProgramSha256() { return ""; }
default CompletableFuture<Void> startExecution() { return CompletableFuture.completedFuture(null); }
default CompletableFuture<Void> pause() { return CompletableFuture.failedFuture(new UnsupportedOperationException("Pause unavailable")); }
@@ -11,6 +11,11 @@ public interface RuntimeGateway {
Consumer<RuntimeLogEntry> logs) throws Exception;
default boolean interactive() {return false;}
default RuntimeConnection start(ProjectReference project, ProjectLocalStudioSetup setup,
Consumer<RuntimeLogEntry> logs, p.studio.api.execution.PlayOptions options, String runId,
p.studio.api.execution.ExecutionSources sources, Consumer<p.studio.api.execution.RuntimeDiagnostic> diagnostics) throws Exception {
return start(project, setup, logs, options);
}
default RuntimeConnection start(ProjectReference project, ProjectLocalStudioSetup setup,
Consumer<RuntimeLogEntry> logs,p.studio.api.execution.PlayOptions options) throws Exception {
if(options.disposableSave())throw new UnsupportedOperationException("Disposable Play unavailable");
@@ -44,6 +44,7 @@ public final class DefaultTaskTools implements TaskTools {
GuestTests.PRODUCTION.equals(entry.getValue().context().getOrDefault("targetId", GuestTests.PRODUCTION)));
String candidateId = UUID.randomUUID().toString();
var result = shipper.prepareNow(catalog.openProject(data.task.projectRoot()), new BuildSelection(selected, candidateId), ignored -> {})
.withExecutionSources(p.studio.api.execution.ExecutionSources.EMPTY)
.withContext(Map.of("targetId", selected));
if (Thread.currentThread().isInterrupted() || record.handle != null && record.handle.snapshot().state() == OperationState.CANCELLED) result = result.asCancelled();
if (result.success() && !Thread.currentThread().isInterrupted()) {
@@ -19,7 +19,12 @@ public interface CompilerBuildGateway {
}
record CompilerBuildOutput(Path bytecodeArtifact, List<String> requiredCapabilities,
List<StudioDiagnostic> issues, Map<String, Object> context,
p.studio.api.execution.ExecutionSources executionSources) {
public CompilerBuildOutput(Path bytecodeArtifact, List<String> requiredCapabilities,
List<StudioDiagnostic> issues, Map<String, Object> context) {
this(bytecodeArtifact, requiredCapabilities, issues, context, p.studio.api.execution.ExecutionSources.EMPTY);
}
public CompilerBuildOutput(Path bytecodeArtifact, List<String> requiredCapabilities) {
this(bytecodeArtifact, requiredCapabilities, List.of(), Map.of());
}
@@ -27,6 +32,7 @@ public interface CompilerBuildGateway {
bytecodeArtifact = bytecodeArtifact == null ? null : bytecodeArtifact.toAbsolutePath().normalize();
requiredCapabilities = List.copyOf(requiredCapabilities);
issues = List.copyOf(issues); context = p.studio.api.values.ValueMaps.object(context);
executionSources = java.util.Objects.requireNonNull(executionSources);
}
}
}
@@ -104,7 +104,7 @@ public final class StudioShipperService implements Shipper, SavedProjectPreparat
final Path stagedRoot = stage;
return new ShipperPrepareResult(result.status(), result.logs(), destination.resolve(stagedRoot.relativize(result.manifestPath())),
result.emittedArtifacts().stream().map(p -> destination.resolve(stagedRoot.relativize(p))).toList(),
result.diagnostics(), result.issues(), result.summary(), result.context()).withContext(java.util.Map.of("buildProvenance", provenance));
result.diagnostics(), result.issues(), result.summary(), result.context(), result.executionSources()).withContext(java.util.Map.of("buildProvenance", provenance));
} catch (java.util.concurrent.CancellationException cancelled) {
return ShipperPrepareResult.failed(List.of(), List.of("Test build cancelled before publication")).asCancelled();
} catch (IOException | RuntimeException failure) {
@@ -145,7 +145,7 @@ public final class StudioShipperService implements Shipper, SavedProjectPreparat
}}
checkCancelled();packer.publishWorkspaceFiles(new p.packer.messages.PublishWorkspaceFilesRequest(new PackerProjectContext(project.name(),project.rootPath()),java.util.UUID.randomUUID().toString(),edits));
Path build=project.rootPath().resolve("build");return new ShipperPrepareResult(result.status(),result.logs(),build.resolve("manifest.json"),
result.emittedArtifacts().stream().map(p->build.resolve(candidate.relativize(p))).toList(),result.diagnostics(),result.issues(),result.summary(),result.context());
result.emittedArtifacts().stream().map(p->build.resolve(candidate.relativize(p))).toList(),result.diagnostics(),result.issues(),result.summary(),result.context(),result.executionSources());
});
}catch(Exception failure) {
if(Thread.currentThread().isInterrupted()||failure instanceof java.util.concurrent.CancellationException)return ShipperPrepareResult.failed(List.of(),List.of("Production build cancelled before publication")).asCancelled();
@@ -225,7 +225,8 @@ public final class StudioShipperService implements Shipper, SavedProjectPreparat
current = "manifest"; stages.put(current, "running"); checkCancelled();
var manifest = writeManifest(project, build, outputRoot, logs, sink); checkCancelled(); stages.put(current, "passed");
AssetBuildQualification.write(mapper,outputRoot,capacity);
return finish(ShipperPreparationStatus.SUCCESS, logs, manifest, artifacts, issues, stages, inputs, "passed");
return finish(ShipperPreparationStatus.SUCCESS, logs, manifest, artifacts, issues, stages, inputs, "passed")
.withExecutionSources(build.executionSources());
} catch (java.util.concurrent.CancellationException cancelled) {
stages.put(current, "cancelled");
return finish(ShipperPreparationStatus.CANCELLED, logs, null, List.of(), issues, stages, inputs, "cancelled");
@@ -0,0 +1,56 @@
package p.studio.core.execution;
import org.junit.jupiter.api.Test;
import p.studio.api.execution.*;
import java.util.Map;
import java.nio.charset.StandardCharsets;
import static org.junit.jupiter.api.Assertions.*;
class ExecutionDiagnosticsTest {
private static final String RUN = "1".repeat(32), NEXT = "2".repeat(32), SHA = "a".repeat(64);
private static final String TEXT = "// á 😀\r\nfn crash() { let value = 1 / 0; }\n";
private static ExecutionSources sources() {
return new ExecutionSources("build", SHA, Map.of(7, new ExecutionSources.Source(7, 0, "/virtual/source.pbs", "@generated/main.pbs", "generated",
ExecutionSources.digest(TEXT.getBytes(StandardCharsets.UTF_8)), TEXT)));
}
private static RuntimeDiagnostic fault(String run, String sha, int start, int end) {
return new RuntimeDiagnostic(run, sha, "vm_trap", "division by zero", 1L, 2L, 3L,
new RuntimeDiagnostic.Span(7, start, end), false, Map.of());
}
@Test void retainedExecutionSurvivesFailedPreparationAndLateCallbacksCannotReplaceIt() {
var session = new DefaultExecutionSession();session.beginPreparationCycle();
session.prepareSources(RUN, sources()); session.admitSources(RUN, SHA);
session.transitionToConnecting();session.transitionToRunning();
int offset = TEXT.substring(0,TEXT.indexOf("1 / 0")).getBytes(StandardCharsets.UTF_8).length;
session.recordDiagnostic(fault(RUN,SHA,offset,offset+5));session.transitionToRuntimeFailed();
var first = session.snapshot().diagnostics().getFirst();
assertEquals(2, first.excerpt().line());assertTrue(first.excerpt().text().contains("1 / 0"));
assertEquals("available",first.excerpt().availability());
session.beginPreparationCycle();session.prepareSources(NEXT, sources());session.discardCandidate(NEXT);session.transitionToPrepareFailed();
assertEquals(first,session.snapshot().diagnostics().getFirst());
session.recordDiagnostic(fault(NEXT,SHA,0,1));assertEquals(1,session.snapshot().diagnostics().size());
session.beginPreparationCycle();session.prepareSources(NEXT,sources());session.admitSources(NEXT,SHA);
assertTrue(session.snapshot().diagnostics().isEmpty());
session.recordDiagnostic(fault(RUN,SHA,offset,offset+5));assertTrue(session.snapshot().diagnostics().isEmpty());
session.close();session.recordDiagnostic(fault(NEXT,SHA,0,1));assertTrue(session.snapshot().diagnostics().isEmpty());
}
@Test void digestAndUtf8BoundariesMustMatchBeforeShowingLocation() {
var session=new DefaultExecutionSession();session.prepareSources(RUN,sources());
assertThrows(IllegalStateException.class,()->session.admitSources(RUN,"b".repeat(64)));
assertEquals("program-not-confirmed",ExecutionExcerpts.resolve(fault(RUN,"b".repeat(64),0,1),sources()).excerpt().availability());
int inside = TEXT.indexOf('á');
assertEquals("invalid-span",ExecutionExcerpts.resolve(fault(RUN,SHA,inside+1,inside+2),sources()).excerpt().availability());
assertThrows(IllegalArgumentException.class,()->new ExecutionSources.Source(0,0,"x","x","source",SHA,TEXT));
}
@Test void excerptsStayWithinSevenLinesAndEightKiBAndKeepTheFaultInView() {
String text="before\n".repeat(8)+"😀".repeat(4000)+"1 / 0"+"é".repeat(10000)+"\r\n"+"after\n".repeat(8);
var sources=new ExecutionSources("build",SHA,Map.of(7,new ExecutionSources.Source(7,0,"/virtual/x","@generated/x","generated",
ExecutionSources.digest(text.getBytes(StandardCharsets.UTF_8)),text)));
int offset=text.substring(0,text.indexOf("1 / 0")).getBytes(StandardCharsets.UTF_8).length;
var resolved=ExecutionExcerpts.resolve(fault(RUN,SHA,offset,offset+5),sources).excerpt();
assertEquals("available",resolved.availability());assertEquals(9,resolved.line());assertEquals(8001,resolved.column());
assertTrue(resolved.text().contains("1 / 0"));assertTrue(resolved.truncated());
assertTrue(resolved.text().lines().count()<=7);assertTrue(resolved.text().getBytes(StandardCharsets.UTF_8).length<=8192);
assertFalse(resolved.text().contains("\ufffd"));
}
}
@@ -37,6 +37,24 @@ class InteractiveExecutionControllerTest {
private RuntimeGateway gateway(Connection connection){return (p,s,l)->connection;}
private ProjectReference project(){return new ProjectReference("Game","1","pbs",1,ProjectTarget.Game,root);}
@Test void failedCaptureCannotLaunchAnotherRuntimeOrEraseThePreviousDiagnostic() {
var ops=new ControlledOperations();var state=new DefaultExecutionSession();var connection=new Connection();
var launches=new java.util.concurrent.atomic.AtomicInteger();var builds=new java.util.concurrent.atomic.AtomicInteger();
Shipper preparation=(p,l)->{
if(builds.incrementAndGet()>1)throw new IllegalStateException("Execution source capture unavailable: capture byte limit");
return done(new ShipperPrepareResult(ShipperPreparationStatus.SUCCESS,List.of(),root.resolve("manifest.json"),List.of(),List.of()));
};
RuntimeGateway runtime=(p,s,l)->{launches.incrementAndGet();return connection;};
var controller=new InteractiveExecutionController(project(),ProjectLocalStudioSetup.defaults(),state,preparation,runtime,ops,new ProjectAccessRegistry(),PlayOptions.PERSISTENT);
controller.play();ops.last.finish();connection.exit.completeExceptionally(new java.io.IOException("previous execution fault"));
var previous=state.snapshot().diagnostics().getFirst();
controller.play();ops.last.finish();
assertEquals(1,launches.get());assertEquals(ExecutionState.PREPARE_FAILED,state.snapshot().state());
assertEquals("preparation",state.snapshot().diagnostics().getFirst().fault().kind());
assertTrue(state.snapshot().diagnostics().getFirst().fault().message().contains("capture byte limit"));
assertEquals(previous,state.snapshot().diagnostics().getLast());assertFalse(controller.ownsExecution());
}
@Test void buildAndLaunchReceiveTheSameFrozenEffectiveRuntime(){
var ops=new ControlledOperations();var state=new DefaultExecutionSession();var connection=new Connection();
var effective=new ProjectLocalStudioSetup("global-runtime",null);
@@ -0,0 +1,57 @@
package p.studio.ui.javafx2.play;
import javafx.geometry.Insets;
import javafx.scene.control.Label;
import javafx.scene.control.ScrollPane;
import javafx.scene.layout.VBox;
import p.studio.api.execution.ExecutionDiagnostic;
import p.studio.ui.javafx2.appearance.AppearanceContext;
import java.util.List;
/** Static values resolved by the execution service; no document or filesystem access. */
public final class RuntimeDiagnosticsPane extends VBox {
private final AppearanceContext context;
private final VBox content=new VBox(10);
private List<ExecutionDiagnostic> displayed=List.of();
public RuntimeDiagnosticsPane(AppearanceContext context) {
this.context=context;setId("runtime-diagnostics");getStyleClass().add("runtime-diagnostics");
var scroll=new ScrollPane(content);scroll.setFitToWidth(true);scroll.setMinHeight(0);scroll.setPrefHeight(240);
getChildren().add(scroll);setMinHeight(0);setMaxHeight(USE_PREF_SIZE);
context.observe(this::render);
}
public void show(List<ExecutionDiagnostic> diagnostics) {
if(displayed.equals(diagnostics))return;
displayed=List.copyOf(diagnostics);render();
}
private void render() {
boolean present=!displayed.isEmpty();setVisible(present);setManaged(present);content.getChildren().clear();
if(!present)return;
content.setPadding(new Insets(10));
for(int index=0;index<displayed.size();index++) {
var value=displayed.get(index);var fault=value.fault();var excerpt=value.excerpt();
String suffix=index==0?"":"-"+index;
var category=label(context.text("diagnostic.kind."+fault.kind()),"runtime-diagnostic-category"+suffix);
category.getStyleClass().add("runtime-diagnostic-category");
var message=label(fault.message(),"runtime-diagnostic-message"+suffix);
var location=label(excerpt.availability().equals("available")
?context.text("diagnostic.location",excerpt.logicalPath(),Integer.toString(excerpt.line()),Integer.toString(excerpt.column()),context.text("diagnostic.source."+excerpt.sourceKind()))
:context.text("diagnostic.unavailable."+excerpt.availability()),"runtime-diagnostic-location"+suffix);
var card=new VBox(5,category,message,location);
if(!excerpt.revision().isEmpty()) {
var revision=label(context.text("diagnostic.revision",excerpt.revision().substring(0,12),shortIdentity(excerpt.buildId()),shortIdentity(fault.runId())),"runtime-diagnostic-revision"+suffix);
revision.setAccessibleText(context.text("diagnostic.revision",excerpt.revision(),excerpt.buildId(),fault.runId()));
var source=label(excerpt.text(),"runtime-diagnostic-source"+suffix);source.setWrapText(false);
var sourceScroll=new ScrollPane(source);sourceScroll.setFitToHeight(true);sourceScroll.setMinHeight(0);
card.getChildren().addAll(revision,sourceScroll);
}
if(fault.truncated()||excerpt.truncated())card.getChildren().add(label(context.text("diagnostic.truncated"),"runtime-diagnostic-truncated"+suffix));
content.getChildren().add(card);
}
}
private static String shortIdentity(String value){return value.substring(0,Math.min(8,value.length()));}
private static Label label(String text,String id) {
var label=new Label(text);label.setId(id);label.setWrapText(true);label.setMinWidth(0);label.setMaxWidth(Double.MAX_VALUE);
label.setAccessibleText(text);return label;
}
}
@@ -18,6 +18,7 @@ import p.studio.ui.javafx2.appearance.AppearanceContext;
import p.studio.ui.javafx2.ai.AiWorkspace;
import p.studio.ui.javafx2.components.*;
import p.studio.ui.javafx2.play.PlaybackViewport;
import p.studio.ui.javafx2.play.RuntimeDiagnosticsPane;
import p.studio.ui.javafx2.shell.MinimalShell;
import p.studio.ui.javafx2.shell.ExecutionBar;
import p.studio.ui.javafx2.shell.TabStatusFooter;
@@ -97,6 +98,7 @@ public final class StudioWindowCoordinator2 implements AutoCloseable {
}
private Label stateLabel;
private TextArea logs;
private RuntimeDiagnosticsPane diagnostics;
private long lastLog=-1;
private long operationSequence;
private ExecutionState displayedState;
@@ -150,7 +152,7 @@ public final class StudioWindowCoordinator2 implements AutoCloseable {
public void resolved(ProjectReference reference){loadingProject.setText(reference.name());}
public void prepare(ProjectSession session,WindowGeometry geometry){project=session;showProject();restoreGeometry(geometry);}
public void present(){stage.setTitle(project.projectReference().name()+" · "+context.text("brand"));stage.show();stage.toFront();hideLoading();createdProject=null;refresh();connectAgent();}
public void discard(){if(projectGeometry!=null){projectGeometry.close();projectGeometry=null;}stage.hide();project=null;play=null;if(viewport!=null){viewport.close();viewport=null;}if(viewContext!=null){viewContext.close();viewContext=null;}shell.workspace().getChildren().clear();}
public void discard(){if(projectGeometry!=null){projectGeometry.close();projectGeometry=null;}stage.hide();project=null;play=null;clearDiagnostics();if(viewport!=null){viewport.close();viewport=null;}if(viewContext!=null){viewContext.close();viewContext=null;}shell.workspace().getChildren().clear();}
public void failed(Throwable failure,boolean cleanupRequired){hideLoading();showChooser();
String detail=diagnostic(failure);
chooser.feedback(cleanupRequired?"projects.cleanupFailed":createdProject==null?"projects.openFailed":"projects.createdOpenFailed",cleanupRequired,detail);
@@ -359,7 +361,9 @@ public final class StudioWindowCoordinator2 implements AutoCloseable {
var game=new BorderPane(viewport,localControls,null,null,null);game.setId("project-play");
viewport.setMinHeight(64);
logs=new TextArea();logs.setId("execution-logs");logs.setEditable(false);logs.setPrefRowCount(4);logs.setWrapText(true);logs.setMinHeight(64);
var split=new SplitPane(game,logs);split.setId("gameplay-split");split.getStyleClass().add("studio-gameplay-split");
diagnostics=new RuntimeDiagnosticsPane(c);
var executionDetails=new VBox(diagnostics,logs);executionDetails.setMinHeight(64);VBox.setVgrow(logs,Priority.ALWAYS);
var split=new SplitPane(game,executionDetails);split.setId("gameplay-split");split.getStyleClass().add("studio-gameplay-split");
split.getStyleClass().add("studio-workspace-split");
split.setOrientation(javafx.geometry.Orientation.VERTICAL);split.setDividerPositions(.8);
// Apply the initial ratio after the native window has received its actual size.
@@ -439,6 +443,7 @@ public final class StudioWindowCoordinator2 implements AutoCloseable {
private void refresh(){
if(project==null||play==null||closed)return;
var snapshot=project.executionSession().snapshot();var state=snapshot.state();boolean owned=controller!=null&&controller.ownsExecution();
if(diagnostics!=null)diagnostics.show(snapshot.diagnostics());
play.setText(context.text(owned?"play.stop":"play.start"));play.setAccessibleText(play.getText());
play.setDisable(busy||closing||state==ExecutionState.STOPPING);
pause.setDisable(busy||closing||state!=ExecutionState.RUNNING&&state!=ExecutionState.PAUSED);
@@ -484,11 +489,13 @@ public final class StudioWindowCoordinator2 implements AutoCloseable {
background(()->closeOwned(oldProject,oldController),(warning,failure)->{
if(failure!=null){closing=false;exitRequested=false;projectCloseRequested=false;error(failure);refresh();return;}
project=null;controller=null;agent=null;closing=false;projectCloseRequested=false;play=null;notice.setText("");
clearDiagnostics();
if(viewport!=null){viewport.close();viewport=null;}if(viewContext!=null){viewContext.close();viewContext=null;}shell.workspace().getChildren().clear();
if(exitRequested)finishExit();else {showChooser();if(warning!=null)error(warning);}
});
}));
}
private void clearDiagnostics(){if(diagnostics!=null){diagnostics.show(List.of());diagnostics=null;}}
private Throwable closeOwned(ProjectSession session,ExecutionController execution){
RuntimeException warning=null,failure=null;
try{if(execution!=null)execution.close();}catch(RuntimeException error){failure=error;}
@@ -72,7 +72,7 @@ state.PAUSING=Pausing…
state.PAUSED=Paused · Resume to continue
state.RESUMING=Resuming…
state.STOPPING=Stopping…
state.RUNTIME_FAILED=Runtime failed · see logs
state.RUNTIME_FAILED=Runtime failed · see diagnostics
state.STOPPED=Stopped
theme.label=Theme
theme.dark=Bananodore · dark
@@ -222,3 +222,24 @@ conversation.sample.intro=# Project inspection\n\nI found the **source** and the
conversation.sample.tool=Run project checks
conversation.sample.failure=The fixture found a missing configuration value.
conversation.sample.after=The check reported a configuration issue. The details above explain what needs to be adjusted.
diagnostic.kind.vm_trap=Application trap
diagnostic.kind.vm_panic=Application failure
diagnostic.kind.vm_init=Program initialization failed
diagnostic.kind.preparation=Preparation failed
diagnostic.kind.connection=Connection failed
diagnostic.kind.load=Cartridge loading failed
diagnostic.kind.host=Runtime host failure
diagnostic.kind.transport=Runtime connection interrupted
diagnostic.kind.watchdog=Runtime timed out
diagnostic.location={0}:{1}:{2} · {3}
diagnostic.revision=Executed source {0} · build {1} · execution {2}
diagnostic.truncated=Diagnostic or source excerpt was shortened.
diagnostic.unavailable.no-span=Source location unavailable for this failure.
diagnostic.unavailable.program-not-confirmed=Executed program identity was not confirmed.
diagnostic.unavailable.source-not-captured=Source for this location was not captured.
diagnostic.unavailable.invalid-span=Source location does not match the captured text.
diagnostic.source.sdk=SDK
diagnostic.source.generated=generated source
diagnostic.source.source=source
diagnostic.source.dependency=dependency source
@@ -72,7 +72,7 @@ state.PAUSING=Pausando…
state.PAUSED=Pausado · Resume para continuar
state.RESUMING=Retomando…
state.STOPPING=Encerrando…
state.RUNTIME_FAILED=Falha no runtime · consulte os logs
state.RUNTIME_FAILED=Falha no runtime · consulte o diagnóstico
state.STOPPED=Encerrado
theme.label=Tema
theme.dark=Bananodore · escuro
@@ -222,3 +222,24 @@ conversation.sample.intro=# Inspeção do projeto\n\nEncontrei o **código** e a
conversation.sample.tool=Executar verificações do projeto
conversation.sample.failure=O exemplo encontrou um valor ausente na configuração.
conversation.sample.after=A verificação apontou um problema na configuração. Os detalhes acima explicam o que precisa ser ajustado.
diagnostic.kind.vm_trap=Trap da aplicação
diagnostic.kind.vm_panic=Falha da aplicação
diagnostic.kind.vm_init=Falha na inicialização do programa
diagnostic.kind.preparation=Falha na preparação
diagnostic.kind.connection=Falha na conexão
diagnostic.kind.load=Falha no carregamento do cartucho
diagnostic.kind.host=Falha do host do runtime
diagnostic.kind.transport=Conexão com o runtime interrompida
diagnostic.kind.watchdog=Tempo de resposta do runtime excedido
diagnostic.location={0}:{1}:{2} · {3}
diagnostic.revision=Fonte executado {0} · build {1} · execução {2}
diagnostic.truncated=O diagnóstico ou trecho do fonte foi abreviado.
diagnostic.unavailable.no-span=Localização no fonte indisponível para esta falha.
diagnostic.unavailable.program-not-confirmed=A identidade do programa executado não foi confirmada.
diagnostic.unavailable.source-not-captured=O fonte desta localização não foi capturado.
diagnostic.unavailable.invalid-span=A localização não corresponde ao texto capturado.
diagnostic.source.sdk=SDK
diagnostic.source.generated=fonte gerado
diagnostic.source.source=fonte
diagnostic.source.dependency=fonte de dependência
@@ -40,6 +40,33 @@ class FoundationDesktopTest {
captures=Path.of(System.getProperty("studio.ui2.captureDir")); Files.createDirectories(captures);
}
@AfterAll static void stopToolkit() { Platform.exit(); }
@Test void staticRuntimeDiagnosticsFollowLanguageThemeScaleAndAvailability() throws Exception {
var context=fx(()->new AppearanceContext(PresentationSettings.defaults(Locale.ENGLISH),messages,fonts,value->{}));
var panel=fx(()->new p.studio.ui.javafx2.play.RuntimeDiagnosticsPane(context));
var fault=new p.studio.api.execution.RuntimeDiagnostic("1".repeat(32),"a".repeat(64),"vm_trap","Division by zero · ação 😀",42L,10L,35L,
new p.studio.api.execution.RuntimeDiagnostic.Span(7,0,5),false,Map.of());
var excerpt=new p.studio.api.execution.ExecutionDiagnostic.Excerpt("build-123","@generated/animation/main.pbs","generated","b".repeat(64),5,12,
"fn frame() {\n let value = 123 / zero;\n}",false,"available");
var value=new p.studio.api.execution.ExecutionDiagnostic(fault,excerpt);
var window=fx(()->{var stage=new Stage();var root=new VBox(panel);context.attach(root);stage.setScene(new Scene(root,800,440));
stage.setOnHidden(e->context.close());stage.show();panel.show(List.of(value));return new Window(stage,context,null,null);});
try {
for(Theme theme:Theme.values())for(StudioLanguage language:StudioLanguage.values()) {
fx(()->{context.update(context.settings().withTheme(theme).withLanguage(language).withScale(1.25));
window.stage.getScene().getRoot().applyCss();window.stage.getScene().getRoot().layout();
assertTrue(((Label)panel.lookup("#runtime-diagnostic-location")).getText().contains("@generated/animation/main.pbs:5:12"));
assertTrue(((Label)panel.lookup("#runtime-diagnostic-source")).getText().contains("123 / zero"));
assertTrue(panel.lookupAll(".text-input").isEmpty());
assertEquals(language==StudioLanguage.ENGLISH?"Application trap":"Trap da aplicação",((Label)panel.lookup("#runtime-diagnostic-category")).getText());return null;});
capture(window,"runtime-diagnostic-"+theme+"-"+language);
}
fx(()->{panel.show(List.of(new p.studio.api.execution.ExecutionDiagnostic(
p.studio.api.execution.RuntimeDiagnostic.failure("2".repeat(32),"connection","Connection interrupted"),
new p.studio.api.execution.ExecutionDiagnostic.Excerpt("","","","",0,0,"",false,"no-span"))));
assertNull(panel.lookup("#runtime-diagnostic-source"));assertTrue(panel.isVisible());
panel.show(List.of());assertFalse(panel.isVisible());assertFalse(panel.isManaged());return null;});
} finally {fx(()->{window.stage.close();return null;});}
}
@Test void shellGalleryStateThemesLocalesFontsAndLifecycle() throws Exception {
Window window=fx(() -> open(true));
try {