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