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
@@ -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();