feat(studio): ship JavaFX 2 Play and delegate integration tooling
Launch the JavaFX 2 project shell on Java 25 with an interactive viewport, managed Play lifecycle and project mutation guards. Preserve headless/MCP and save compatibility, and qualify exact runtime executable bundles. Separate unit JaCoCo gates from opt-in integration suites and use the internal Pong fixture for the headless visual pilot. Move maintenance and native conformance tools into tooling; retain the VS Code extension and update current navigation links. Validation: tooling make verify passed, including 1064 Studio unit tests, JaCoCo thresholds and 22 headless integration tests.
This commit is contained in:
@@ -1,103 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Check repository Markdown navigation without fetching or modifying sources.
|
||||
|
||||
Runtime mirrors keep provider-relative links and exact bytes. Pass --runtime to
|
||||
also check provider links against a local read-only checkout; otherwise those
|
||||
references are reported separately and do not make ordinary builds depend on it.
|
||||
"""
|
||||
import argparse
|
||||
import re
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
from urllib.parse import unquote
|
||||
|
||||
|
||||
def prose(text):
|
||||
"""Exclude fenced examples; their sample links are not document navigation."""
|
||||
lines = []
|
||||
fence = None
|
||||
for line in text.splitlines():
|
||||
match = re.match(r"^\s{0,3}(`{3,}|~{3,})", line)
|
||||
if match:
|
||||
marker = match.group(1)
|
||||
if fence is None:
|
||||
fence = marker
|
||||
elif marker[0] == fence[0] and len(marker) >= len(fence):
|
||||
fence = None
|
||||
lines.append("")
|
||||
else:
|
||||
lines.append(line if fence is None else "")
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def anchors(text):
|
||||
found = set(re.findall(r'(?:id|name)=["\']([^"\']+)["\']', text))
|
||||
counts = {}
|
||||
for heading in re.findall(r"^ {0,3}#{1,6}\s+(.+?)\s*#*\s*$", prose(text), re.M):
|
||||
heading = re.sub(r"\[([^\]]+)\]\([^)]+\)", r"\1", heading)
|
||||
heading = re.sub(r"<[^>]+>", "", heading).lower()
|
||||
slug = re.sub(r"[^\w\-\s]", "", heading).replace(" ", "-")
|
||||
count = counts.get(slug, 0)
|
||||
counts[slug] = count + 1
|
||||
found.add(slug + (f"-{count}" if count else ""))
|
||||
return found
|
||||
|
||||
|
||||
def verify(root, runtime):
|
||||
tracked = subprocess.check_output(
|
||||
["git", "ls-files", "--cached", "--others", "--exclude-standard", "-z"],
|
||||
cwd=root, text=True).split("\0")
|
||||
files = {root / name for name in tracked if name.endswith(".md")}
|
||||
files.add(root / "AGENTS.md")
|
||||
files = sorted(path for path in files if path.is_file())
|
||||
mirror_names = {"docs/vm-arch/ARCHITECTURE.md", "docs/vm-arch/ISA_CORE.md"}
|
||||
failures = []
|
||||
local_count = provider_count = 0
|
||||
anchor_cache = {}
|
||||
for source in files:
|
||||
relative = source.relative_to(root).as_posix()
|
||||
content = prose(source.read_text())
|
||||
links = re.findall(r"\]\(([^)\n]+)\)", content)
|
||||
links += re.findall(r"^\s*\[[^\]]+\]:\s*(\S+)", content, re.M)
|
||||
for link in links:
|
||||
link = link.strip().strip("<>")
|
||||
if re.match(r"[a-zA-Z][a-zA-Z\d+.-]*:", link) or link.startswith("//"):
|
||||
continue
|
||||
path, _, fragment = link.partition("#")
|
||||
target = (source.parent / unquote(path)).resolve() if path else source
|
||||
provider = False
|
||||
if relative in mirror_names:
|
||||
provider = True
|
||||
if runtime:
|
||||
target = ((runtime / relative).parent / unquote(path)).resolve() if path else runtime / relative
|
||||
elif target.is_relative_to(root.parent / "runtime"):
|
||||
provider = True
|
||||
if runtime:
|
||||
target = runtime / target.relative_to(root.parent / "runtime")
|
||||
if provider:
|
||||
provider_count += 1
|
||||
if runtime is None:
|
||||
continue
|
||||
else:
|
||||
local_count += 1
|
||||
if not target.exists():
|
||||
failures.append(f"{relative}: missing target {link}")
|
||||
elif fragment and target.suffix == ".md":
|
||||
if target not in anchor_cache:
|
||||
anchor_cache[target] = anchors(target.read_text())
|
||||
if unquote(fragment) not in anchor_cache[target]:
|
||||
failures.append(f"{relative}: missing anchor {link}")
|
||||
for failure in failures:
|
||||
print(failure)
|
||||
mode = "checked" if runtime else "classified; use --runtime to check"
|
||||
print(f"Markdown: {len(files)} files; {local_count} local links; "
|
||||
f"{provider_count} provider links ({mode}); {len(failures)} failures")
|
||||
return bool(failures)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--root", type=Path, default=Path(__file__).resolve().parents[2])
|
||||
parser.add_argument("--runtime", type=Path)
|
||||
args = parser.parse_args()
|
||||
raise SystemExit(verify(args.root.resolve(), args.runtime.resolve() if args.runtime else None))
|
||||
@@ -1,138 +0,0 @@
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import p.studio.compiler.FrontendRegistryService;
|
||||
import p.studio.compiler.messages.BuildingIssue;
|
||||
import p.studio.compiler.messages.BuilderPipelineConfig;
|
||||
import p.studio.compiler.models.BuilderPipelineContext;
|
||||
import p.studio.compiler.source.identifiers.FileId;
|
||||
import p.studio.compiler.workspaces.BuilderPipelineService;
|
||||
import p.studio.compiler.workspaces.PipelineStage;
|
||||
import p.studio.compiler.workspaces.stages.*;
|
||||
import p.studio.utilities.logs.LogAggregator;
|
||||
|
||||
import java.nio.file.*;
|
||||
import java.security.MessageDigest;
|
||||
import java.util.*;
|
||||
|
||||
/** Research-only probe: production stages, isolated source projects, no compiler changes. */
|
||||
public final class PbsProductionCorpusProbe {
|
||||
static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
static final String ANALYSIS_ID = UUID.randomUUID().toString();
|
||||
static int issueIndex;
|
||||
static final List<String> LOG = new ArrayList<>();
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
Path root = Path.of(args[0]).toRealPath();
|
||||
boolean optimize = args[1].equals("optimized");
|
||||
boolean publicEntry = args.length > 3 && args[3].equals("public");
|
||||
var result = new LinkedHashMap<String, Object>();
|
||||
result.put("projectRoot", root.toString());
|
||||
result.put("optimization", optimize ? "optimized" : "unoptimized");
|
||||
result.put("entrypoint", publicEntry ? "BuilderPipelineService.compile" : "public analysis + production compile stages");
|
||||
result.put("frontendOrigin", FrontendRegistryService.require("pbs").getClass().getProtectionDomain().getCodeSource().getLocation().toString());
|
||||
result.put("sdkOrigin", p.studio.compiler.pbs.stdlib.StdlibEnvironmentResolver.class.getProtectionDomain().getCodeSource().getLocation().toString());
|
||||
result.put("javaVersion", System.getProperty("java.version"));
|
||||
result.put("pipelineOrigin", BuilderPipelineService.class.getProtectionDomain().getCodeSource().getLocation().toString());
|
||||
var ctx = BuilderPipelineContext.fromConfig(new BuilderPipelineConfig(false, root.toString()));
|
||||
var logs = LogAggregator.with(LOG::add);
|
||||
var phases = new ArrayList<Map<String, Object>>();
|
||||
result.put("phases", phases);
|
||||
result.put("status", "infrastructure_failure");
|
||||
try {
|
||||
if (publicEntry) {
|
||||
var compiled = BuilderPipelineService.INSTANCE.compile(ctx, logs);
|
||||
result.put("diagnostics", compiled.diagnostics().stream().map(i -> issue(i, ctx)).toList());
|
||||
result.put("status", "compiled");
|
||||
} else {
|
||||
var analyzed = BuilderPipelineService.INSTANCE.analyze(ctx, logs);
|
||||
var phase = new LinkedHashMap<String, Object>();
|
||||
phase.put("phase", "analysis");
|
||||
phase.put("diagnostics", analyzed.diagnostics().stream().map(i -> issue(i, ctx)).toList());
|
||||
boolean failed = analyzed.diagnostics().stream().anyMatch(BuildingIssue::isError);
|
||||
phase.put("status", failed ? "failed" : "passed");
|
||||
phases.add(phase);
|
||||
if (failed) result.put("status", "analysis_failed");
|
||||
else {
|
||||
var stages = new ArrayList<PipelineStage>();
|
||||
stages.add(new LowerToIRVMPipelineStage());
|
||||
if (optimize) stages.add(new OptimizeIRVMPipelineStage());
|
||||
stages.add(new EmitBytecodePipelineStage());
|
||||
stages.add(new LinkBytecodePipelineStage());
|
||||
stages.add(new VerifyBytecodePipelineStage());
|
||||
result.put("status", "compiled");
|
||||
for (var stage : stages) {
|
||||
if (!optimize && stage instanceof EmitBytecodePipelineStage) ctx.optimizedIrvm = ctx.irvm;
|
||||
var issues = stage.run(ctx, logs).asCollection();
|
||||
var item = new LinkedHashMap<String, Object>();
|
||||
item.put("phase", stage.getClass().getSimpleName());
|
||||
item.put("diagnostics", issues.stream().map(i -> issue(i, ctx)).toList());
|
||||
boolean errors = issues.stream().anyMatch(BuildingIssue::isError);
|
||||
item.put("status", errors ? "failed" : "passed");
|
||||
phases.add(item);
|
||||
if (errors) { result.put("status", "compile_failed"); break; }
|
||||
}
|
||||
}
|
||||
}
|
||||
if (result.get("status").equals("compiled")) {
|
||||
Path cartridge = root.resolve("cartridge");
|
||||
Files.createDirectories(cartridge);
|
||||
Files.write(cartridge.resolve("program.pbx"), ctx.bytecodeBytes);
|
||||
var manifest = new LinkedHashMap<String, Object>();
|
||||
manifest.put("magic", "PMTU"); manifest.put("cartridge_version", 1);
|
||||
manifest.put("app_id", 113); manifest.put("title", "PBS production assertion fixture");
|
||||
manifest.put("app_version", "1.0.0"); manifest.put("app_mode", "Game");
|
||||
manifest.put("capabilities", List.of()); manifest.put("asset_table", List.of()); manifest.put("preload", List.of());
|
||||
MAPPER.writerWithDefaultPrettyPrinter().writeValue(cartridge.resolve("manifest.json").toFile(), manifest);
|
||||
result.put("cartridge", cartridge.toString());
|
||||
result.put("bytecodeBytes", ctx.bytecodeBytes.length);
|
||||
result.put("bytecodeSha256", HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(ctx.bytecodeBytes)));
|
||||
}
|
||||
} catch (Throwable failure) {
|
||||
result.put("status", failure instanceof p.studio.compiler.exceptions.BuildException
|
||||
? "public_compile_rejected" : "pipeline_exception");
|
||||
result.put("exception", causes(failure));
|
||||
if (failure instanceof p.studio.compiler.exceptions.BuildException buildFailure)
|
||||
result.put("diagnostics", buildFailure.getDiagnostics().stream().map(i -> issue(i,ctx)).toList());
|
||||
}
|
||||
if (ctx.fileTable != null) {
|
||||
var files = new LinkedHashMap<String, Object>();
|
||||
for (int i = 0; i < ctx.fileTable.size(); i++) {
|
||||
var f = ctx.fileTable.get(new FileId(i));
|
||||
files.put(Integer.toString(i), f.getCanonPath().toString());
|
||||
}
|
||||
result.put("files", files);
|
||||
}
|
||||
if (ctx.irBackend != null) {
|
||||
var functions = new ArrayList<Map<String, Object>>();
|
||||
for (var fn : ctx.irBackend.getExecutableFunctions()) {
|
||||
var file = ctx.fileTable.get(fn.fileId()).getCanonPath();
|
||||
if (!file.startsWith(root)) continue;
|
||||
var f = new LinkedHashMap<String, Object>();
|
||||
f.put("callableId", fn.callableId().toString()); f.put("name", fn.callableName());
|
||||
f.put("file", root.relativize(file).toString());
|
||||
f.put("instructions", fn.instructions().stream().map(Object::toString).toList());
|
||||
functions.add(f);
|
||||
}
|
||||
result.put("projectFunctions", functions);
|
||||
}
|
||||
result.put("inputs", p.studio.compiler.source.diagnostics.CompilerDiagnosticProjection.inputs(
|
||||
p.studio.compiler.source.diagnostics.SourceReference.snapshot(ctx.fileTable), root));
|
||||
result.put("logs", LOG);
|
||||
Path report = Path.of(args[2]); Files.createDirectories(report.getParent());
|
||||
MAPPER.writerWithDefaultPrettyPrinter().writeValue(report.toFile(), result);
|
||||
System.out.println(result.get("status") + " " + root.getFileName());
|
||||
}
|
||||
|
||||
static Map<String, Object> issue(BuildingIssue i, BuilderPipelineContext ctx) {
|
||||
var sources = p.studio.compiler.source.diagnostics.SourceReference.snapshot(ctx.fileTable);
|
||||
return p.studio.compiler.source.diagnostics.CompilerDiagnosticProjection.issue(i, sources,
|
||||
p.studio.compiler.source.diagnostics.CompilerDiagnosticProjection.capturedText(ctx.fileTable),
|
||||
ctx.rootProjectPathCanon, ANALYSIS_ID + ":" + issueIndex++);
|
||||
}
|
||||
|
||||
static List<Map<String, String>> causes(Throwable t) {
|
||||
var result = new ArrayList<Map<String, String>>();
|
||||
for (int n = 0; t != null && n < 8; n++, t = t.getCause())
|
||||
result.add(Map.of("class", t.getClass().getName(), "message", String.valueOf(t.getMessage())));
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -1,44 +0,0 @@
|
||||
# PBS production corpus qualification
|
||||
|
||||
Owner: compiler/pbs. This maintained runner preserves the frozen 28-case input and writes each run to a new directory. It never rebuilds or writes the runtime provider and does not modify a game workspace or memcard.
|
||||
|
||||
Build the candidate with the required regression gate, then run the corpus:
|
||||
|
||||
```bash
|
||||
./gradlew :prometeu-compiler:frontends:prometeu-frontend-pbs:test :prometeu-compiler:prometeu-build-pipeline:test :prometeu-lsp:prometeu-lsp-v1:test :prometeu-app:test :prometeu-app:installedKnowledgeTest --console=plain
|
||||
```
|
||||
|
||||
```bash
|
||||
python3 tools/pbs-production-corpus/run.py --corpus prometeu-compiler/frontends/prometeu-frontend-pbs/src/test/resources/production-regressions/cases.json --distribution prometeu-app/build/install/prometeu-app --runtime-headless /absolute/existing/prometeu-headless --output build/pbs-production-corpus/new-run
|
||||
```
|
||||
|
||||
Each case is compiled in a fresh JVM/project outside the checkout. Checkout mode puts current classes/resources first; installed mode includes only candidate JARs and runs outside the checkout. The runner verifies candidate product class freshness and records Java, SDK/compiler origins, JAR/source/PBX/manifest/runtime hashes, Git/worktree state, diagnostic phases and protocol transcripts.
|
||||
|
||||
The required corpus produces 168 observations: 28 cases × checkout/installed × optimized production stages, investigation-only unoptimized stages, and the public optimized facade. Unoptimized means omitting OptimizeIRVMPipelineStage and emitting original IRVM; it is not a public compiler flag. The expected runtime matrix is 108 executions: 27 compiled cases × checkout/installed × two optimization configurations, with 104 normal three-frame successes and four deliberately faulting controls. The file-private case must remain a structured source rejection in all six compile configurations.
|
||||
|
||||
Use --select id1,id2 or --origins checkout/installed for focused investigation. Without those restrictions, exit zero requires the complete expected matrix and classifications. Output directories cannot be reused or target published lessons and their evidence. Runtime processes are terminated and waited for on every path. Logs are local evidence, while summary.json and per-case JSON preserve structured results.
|
||||
|
||||
The focused-cases.json resource is an additional matrix for contextual overloads, noncommutative receiver/argument order, original global storage, service singleton identity and privacy. It does not replace or alter the frozen corpus. Successful compiler proof does not imply qualification of an installed runtime distribution or a live Studio session. The Studio tests independently preserve MCP/LSP diagnostic contracts.
|
||||
|
||||
The completed production corrections, original baseline and separate post-fix reports are consolidated in [LSN-0106](../../discussion/lessons/DSC-0111-pbs-production-reproductions-and-fixes/LSN-0106-pbs-production-binding-and-lowering-corrections.md).
|
||||
|
||||
## Installed authoring contracts
|
||||
|
||||
The existing installed reference corpus includes `production/GUIDE.md` and 21
|
||||
complete positive/negative projects covering eight authoring scenarios. Run
|
||||
`:prometeu-app:installedKnowledgeTest` first; it compiles their actual installed
|
||||
resources outside the checkout and emits artifacts and source/JAR/catalog hashes
|
||||
under `prometeu-compiler/prometeu-build-pipeline/build/registry-conformance/production-contracts`.
|
||||
Then qualify their behavioral assertions and exact bounds faults using the same
|
||||
headless protocol harness as the original corpus:
|
||||
|
||||
```bash
|
||||
python3 tools/pbs-production-corpus/qualify-installed-contracts.py --artifacts prometeu-compiler/prometeu-build-pipeline/build/registry-conformance/production-contracts --distribution prometeu-app/build/install/prometeu-app --runtime-headless /absolute/existing/prometeu-headless --output build/pbs-installed-contracts/new-run
|
||||
```
|
||||
|
||||
The qualifier rejects a distribution whose JAR hashes differ from the compilation
|
||||
record. It preserves separate discovery/compilation/rejection/execution results,
|
||||
checks fault code 3 rather than accepting any trap, and verifies worker termination.
|
||||
Gfx is qualified for installed API compilation; graphical execution and pixel
|
||||
output are not claimed. Existing runtime binaries are executed without writing
|
||||
their repository. The original frozen corpus and its matrix remain unchanged.
|
||||
@@ -1,74 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Qualify artifacts compiled from installed PBS references using the existing runtime harness."""
|
||||
import argparse
|
||||
import importlib.util
|
||||
import json
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--artifacts', type=Path, required=True)
|
||||
parser.add_argument('--distribution', type=Path, required=True)
|
||||
parser.add_argument('--runtime-headless', type=Path, required=True)
|
||||
parser.add_argument('--output', type=Path, required=True)
|
||||
args = parser.parse_args()
|
||||
sys.dont_write_bytecode = True
|
||||
spec = importlib.util.spec_from_file_location('pbs_corpus', Path(__file__).with_name('run.py'))
|
||||
harness = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(harness)
|
||||
artifacts = args.artifacts.resolve(strict=True)
|
||||
distribution = args.distribution.resolve(strict=True)
|
||||
binary = args.runtime_headless.resolve(strict=True)
|
||||
output = args.output.resolve()
|
||||
if output.exists():
|
||||
parser.error('Output must be a new directory; evidence is never overwritten')
|
||||
output.mkdir(parents=True)
|
||||
compilation = json.loads((artifacts / 'compilation.json').read_text())
|
||||
assert compilation['passed']
|
||||
jars = {p.name: harness.sha(p) for p in (distribution / 'lib').glob('*.jar')}
|
||||
assert jars == compilation['provenance']['installedJarSha256'], 'Compiled artifacts must match this distribution'
|
||||
scratch = Path(tempfile.mkdtemp(prefix='pbs-installed-contracts-'))
|
||||
observations = []
|
||||
for case in compilation['cases']:
|
||||
expected = case['expectation']['expectedRuntime']
|
||||
if expected == 'not-run':
|
||||
continue
|
||||
assert case['compileStatus'] == 'compiled' and case['matchesExpectation'] and case['sourceUnchanged']
|
||||
cartridge = artifacts / case['id']
|
||||
assert harness.sha(cartridge / 'program.pbx') == case['bytecodeSha256']
|
||||
assert harness.sha(cartridge / 'manifest.json') == case['manifestSha256']
|
||||
saved = output / 'artifacts' / case['id']
|
||||
shutil.copytree(cartridge, saved)
|
||||
result = harness.execute(binary, str(saved), scratch / case['id'])
|
||||
fault = result.get('fault')
|
||||
if isinstance(fault, dict) and 'fault' in fault:
|
||||
fault = fault['fault']
|
||||
code = (fault or {}).get('trap', {}).get('code')
|
||||
matched = result['observedRuntime'] == expected and result['workerTerminated']
|
||||
if expected == 'fault':
|
||||
matched &= code == case['expectation']['faultCode']
|
||||
result.update(id=case['id'], expectedRuntime=expected, expectedFaultCode=case['expectation'].get('faultCode'),
|
||||
observedFaultCode=code, matchesExpectation=matched)
|
||||
harness.write(output / 'execution' / (case['id'] + '.json'), result)
|
||||
observations.append({k: result[k] for k in ['id', 'expectedRuntime', 'observedRuntime', 'observedFaultCode', 'matchesExpectation', 'workerTerminated']})
|
||||
print(case['id'], result['observedRuntime'], code, matched, flush=True)
|
||||
shutil.copy2(artifacts / 'compilation.json', output / 'compilation.json')
|
||||
provenance = {'installed': compilation['provenance'], 'distribution': str(distribution),
|
||||
'runtime': str(binary), 'runtimeSha256': harness.sha(binary), 'runnerSha256': harness.sha(__file__),
|
||||
'harnessSha256': harness.sha(Path(__file__).with_name('run.py')), 'scratch': str(scratch),
|
||||
'runtimeWrites': False, 'gfxExecution': 'not-run; installed API compilation only'}
|
||||
harness.write(output / 'provenance.json', provenance)
|
||||
summary = {'compileClassifications': len(compilation['cases']), 'executions': observations,
|
||||
'passed': bool(observations) and all(x['matchesExpectation'] for x in observations)}
|
||||
harness.write(output / 'summary.json', summary)
|
||||
harness.write(output / 'checksums.json', {str(p.relative_to(output)): harness.sha(p) for p in output.rglob('*') if p.is_file()})
|
||||
print(json.dumps({'compileClassifications': summary['compileClassifications'], 'executionCount': len(observations), 'passed': summary['passed']}))
|
||||
return 0 if summary['passed'] else 1
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
raise SystemExit(main())
|
||||
@@ -1,223 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Isolated production PBS regression matrix. Never writes the received baseline or runtime checkout."""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import platform
|
||||
import selectors
|
||||
import signal
|
||||
import subprocess
|
||||
import tempfile
|
||||
import time
|
||||
import zipfile
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
MODULES = ["prometeu-infra", "prometeu-animation", "prometeu-compiler/prometeu-compiler-core",
|
||||
"prometeu-compiler/prometeu-frontend-api", "prometeu-compiler/frontends/prometeu-frontend-pbs",
|
||||
"prometeu-compiler/prometeu-frontend-registry", "prometeu-compiler/prometeu-deps",
|
||||
"prometeu-compiler/prometeu-build-pipeline"]
|
||||
|
||||
|
||||
def sha(path):
|
||||
return hashlib.sha256(Path(path).read_bytes()).hexdigest()
|
||||
|
||||
|
||||
def write(path, data):
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(json.dumps(data, indent=2, ensure_ascii=False) + "\n")
|
||||
|
||||
|
||||
class Session:
|
||||
def __init__(self, binary, directory):
|
||||
self.stderr_path = directory / "runtime.stderr"
|
||||
self.stderr = self.stderr_path.open("wb")
|
||||
self.process = subprocess.Popen([str(binary), "--stdio"], stdin=subprocess.PIPE, stdout=subprocess.PIPE,
|
||||
stderr=self.stderr, cwd=directory, start_new_session=True)
|
||||
self.selector = selectors.DefaultSelector()
|
||||
self.selector.register(self.process.stdout, selectors.EVENT_READ)
|
||||
self.buffer = bytearray()
|
||||
self.transcript = []
|
||||
self.request = 0
|
||||
|
||||
def event(self):
|
||||
deadline = time.monotonic() + 12
|
||||
while b"\n" not in self.buffer:
|
||||
remaining = deadline - time.monotonic()
|
||||
if remaining <= 0 or not self.selector.select(remaining):
|
||||
raise TimeoutError("Runtime reply deadline")
|
||||
data = os.read(self.process.stdout.fileno(), 65536)
|
||||
if not data:
|
||||
raise EOFError("Runtime closed stdout")
|
||||
self.buffer.extend(data)
|
||||
line, _, self.buffer = self.buffer.partition(b"\n")
|
||||
value = json.loads(line)
|
||||
self.transcript.append({"direction": "received", "message": value})
|
||||
return value
|
||||
|
||||
def call(self, command, params=None):
|
||||
self.request += 1
|
||||
request = {"requestId": f"pbs-corpus-{self.request}", "command": command, "params": params or {}}
|
||||
self.transcript.append({"direction": "sent", "message": request})
|
||||
self.process.stdin.write(json.dumps(request).encode() + b"\n")
|
||||
self.process.stdin.flush()
|
||||
while True:
|
||||
response = self.event()
|
||||
if response.get("requestId") != request["requestId"]:
|
||||
raise AssertionError("Unexpected response correlation")
|
||||
if response.get("type") == "progress":
|
||||
continue
|
||||
if "error" in response:
|
||||
raise RuntimeError(json.dumps(response["error"]))
|
||||
return response.get("result")
|
||||
|
||||
def close(self):
|
||||
try:
|
||||
if self.process.poll() is None:
|
||||
try:
|
||||
self.call("shutdown")
|
||||
self.process.wait(timeout=5)
|
||||
except Exception:
|
||||
os.killpg(self.process.pid, signal.SIGKILL)
|
||||
self.process.wait(timeout=5)
|
||||
finally:
|
||||
self.selector.close()
|
||||
self.stderr.close()
|
||||
self.process.stdin.close()
|
||||
self.process.stdout.close()
|
||||
|
||||
|
||||
def execute(binary, cartridge, work):
|
||||
work.mkdir(parents=True)
|
||||
result = {"observedRuntime": "infrastructure_failure"}
|
||||
session = Session(binary, work)
|
||||
try:
|
||||
hello = session.event()
|
||||
assert hello["type"] == "hello" and hello["protocolVersion"]["major"] == 1
|
||||
required = ["boot", "advance", "get_state", "get_fault", "shutdown"]
|
||||
assert set(required) <= set(hello["capabilities"])
|
||||
result["hello"] = hello
|
||||
session.call("initialize", {"protocolVersion": {"major": 1, "minor": min(1, hello["protocolVersion"]["minor"])},
|
||||
"requiredCapabilities": required})
|
||||
result["boot"] = session.call("boot", {"path": cartridge})
|
||||
result["advance"] = advance = session.call("advance", {"frames": 3})
|
||||
result["fault"] = fault = session.call("get_fault")
|
||||
result["state"] = session.call("get_state")
|
||||
fault = fault.get("fault") if isinstance(fault, dict) and "fault" in fault else fault
|
||||
result["observedRuntime"] = "fault" if fault is not None else "passed" if advance.get("completed") == 3 else "incomplete"
|
||||
except Exception as failure:
|
||||
result["exception"] = {"class": type(failure).__name__, "message": str(failure)}
|
||||
finally:
|
||||
session.close()
|
||||
result.update(workerTerminated=session.process.poll() is not None, processExitCode=session.process.returncode,
|
||||
transcript=session.transcript, stderr=session.stderr_path.read_text(errors="replace"))
|
||||
return result
|
||||
|
||||
|
||||
def source_rejection(report):
|
||||
issues = report.get("diagnostics", []) + [i for p in report.get("phases", []) for i in p.get("diagnostics", [])]
|
||||
return report.get("status") in ("analysis_failed", "public_compile_rejected") and any(i.get("severity") == "ERROR" and (i.get("failureKind") == "program-rejection" or str(i.get("code", "")).startswith("E_")) for i in issues) \
|
||||
and not any(i.get("failureKind") in ("internal-failure", "infrastructure-failure", "verification-limit") for i in issues)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--corpus", type=Path, required=True)
|
||||
parser.add_argument("--distribution", type=Path, required=True)
|
||||
parser.add_argument("--runtime-headless", type=Path, required=True)
|
||||
parser.add_argument("--output", type=Path, required=True)
|
||||
parser.add_argument("--select", help="Comma-separated IDs; omitted for the complete 168/108 gate")
|
||||
parser.add_argument("--origins", choices=["checkout", "installed", "both"], default="both")
|
||||
args = parser.parse_args()
|
||||
corpus, distribution, binary, output = args.corpus.resolve(strict=True), args.distribution.resolve(strict=True), args.runtime_headless.resolve(strict=True), args.output.resolve()
|
||||
if output.exists():
|
||||
parser.error("Output must be a new directory; evidence is never overwritten")
|
||||
lessons = ROOT / "discussion/lessons"
|
||||
if output == lessons or lessons in output.parents:
|
||||
parser.error("Published lessons and their evidence are read-only")
|
||||
output.mkdir(parents=True)
|
||||
cases = json.loads(corpus.read_text())["cases"]
|
||||
if args.select:
|
||||
selected = set(args.select.split(",")); assert selected <= {c["id"] for c in cases}
|
||||
cases = [c for c in cases if c["id"] in selected]
|
||||
scratch = Path(tempfile.mkdtemp(prefix="pbs-production-corpus-"))
|
||||
assert not scratch.is_relative_to(ROOT)
|
||||
java, javac = distribution / "runtime/bin/java", distribution / "runtime/bin/javac"
|
||||
jars = sorted((distribution / "lib").glob("*.jar")); assert jars
|
||||
# Verify candidate product classes before mixing checkout classes with third-party dependencies.
|
||||
freshness = []
|
||||
for module in MODULES:
|
||||
jar = next(p for p in jars if p.name == Path(module).name + ".jar" or p.name.startswith(Path(module).name + "-"))
|
||||
with zipfile.ZipFile(jar) as archive:
|
||||
classes = ROOT / module / "build/classes/java/main"
|
||||
compared = list(classes.rglob("*.class")); assert compared
|
||||
different = [str(p.relative_to(classes)) for p in compared if archive.read(str(p.relative_to(classes))) != p.read_bytes()]
|
||||
assert not different, (module, different)
|
||||
freshness.append({"module": module, "jarSha256": sha(jar), "matchingClasses": len(compared)})
|
||||
provenance = {"schemaVersion": 1, "corpusSha256": sha(corpus), "runtime": str(binary), "runtimeSha256": sha(binary),
|
||||
"platform": platform.platform(), "gitHead": subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=ROOT, text=True).strip(),
|
||||
"worktreeStatus": subprocess.check_output(["git", "status", "--short"], cwd=ROOT, text=True).splitlines(),
|
||||
"java": subprocess.run([str(java), "-version"], capture_output=True, text=True, check=True).stderr,
|
||||
"distribution": str(distribution), "jars": {p.name: sha(p) for p in jars}, "candidateFreshness": freshness,
|
||||
"probeSha256": sha(Path(__file__).resolve().with_name("PbsProductionCorpusProbe.java")), "runnerSha256": sha(__file__),
|
||||
"scratch": str(scratch), "unoptimizedVariant": "Investigation-only: omit OptimizeIRVMPipelineStage and emit original IRVM; not a public compiler flag"}
|
||||
write(output / "provenance.json", provenance)
|
||||
observations, executions = [], []
|
||||
origins = ["checkout", "installed"] if args.origins == "both" else [args.origins]
|
||||
for origin in origins:
|
||||
installed = os.pathsep.join(map(str, jars))
|
||||
entries = [ROOT / m / suffix for m in MODULES for suffix in ["build/classes/java/main", "build/resources/main"] if (ROOT / m / suffix).exists()]
|
||||
cp = os.pathsep.join(map(str, entries)) + os.pathsep + installed if origin == "checkout" else installed
|
||||
classes = scratch / origin / "classes"; classes.mkdir(parents=True)
|
||||
subprocess.run([str(javac), "-proc:none", "-cp", cp, "-d", str(classes), str(Path(__file__).resolve().with_name("PbsProductionCorpusProbe.java"))], cwd=scratch, check=True)
|
||||
for case in cases:
|
||||
for variant in ["optimized", "unoptimized", "optimized-public"]:
|
||||
project = scratch / origin / case["id"] / variant
|
||||
for name, source in case["files"].items():
|
||||
path = project / name; path.parent.mkdir(parents=True, exist_ok=True); path.write_text(source)
|
||||
report_path = output / "compilation" / origin / f"{case['id']}-{variant}.json"
|
||||
cmd = [str(java), "-cp", str(classes) + os.pathsep + cp, "PbsProductionCorpusProbe", str(project), "unoptimized" if variant == "unoptimized" else "optimized", str(report_path)]
|
||||
if variant == "optimized-public": cmd.append("public")
|
||||
try:
|
||||
completed = subprocess.run(cmd, cwd=scratch, capture_output=True, text=True, timeout=50, check=True)
|
||||
report = json.loads(report_path.read_text()); report["stderr"] = completed.stderr
|
||||
except Exception as failure:
|
||||
report = {"status": "infrastructure_failure", "exception": {"class": type(failure).__name__, "message": str(failure)}}
|
||||
expected = case["expectedCompile"]
|
||||
matched = report["status"] == "compiled" if expected == "compiled" else source_rejection(report)
|
||||
if origin == "installed" and report.get("frontendOrigin"):
|
||||
assert all(str(distribution) in report.get(key, "") for key in ["frontendOrigin", "pipelineOrigin", "sdkOrigin"])
|
||||
sources_unchanged = all((project / name).read_text() == source for name, source in case["files"].items())
|
||||
assert sources_unchanged
|
||||
identity = {"caseId": case["id"], "origin": origin, "variant": variant, "sourceSha256": case["sourceSha256"]}
|
||||
report.update(identity, expectedCompile=expected, matchesExpectation=matched, sourcesUnchanged=sources_unchanged)
|
||||
if report["status"] == "compiled":
|
||||
cartridge = Path(report["cartridge"])
|
||||
for name in ["manifest.json", "program.pbx"]:
|
||||
target = output / "artifacts" / origin / case["id"] / variant / name
|
||||
target.parent.mkdir(parents=True, exist_ok=True); target.write_bytes((cartridge / name).read_bytes())
|
||||
report["manifestSha256"] = sha(cartridge / "manifest.json")
|
||||
write(report_path, report); observations.append({**identity, "status": report["status"], "matchesExpectation": matched, "report": str(report_path.relative_to(output))})
|
||||
print(origin, case["id"], variant, report["status"], matched, flush=True)
|
||||
if report["status"] == "compiled" and variant != "optimized-public":
|
||||
result = execute(binary, report["cartridge"], project / "execution")
|
||||
result.update(identity, bytecodeSha256=report["bytecodeSha256"], expectedRuntime=case["expectedRuntime"])
|
||||
result["matchesExpectation"] = result["observedRuntime"] == case["expectedRuntime"] and result["workerTerminated"]
|
||||
path = output / "execution" / origin / f"{case['id']}-{variant}.json"; write(path, result)
|
||||
executions.append({**identity, "observedRuntime": result["observedRuntime"], "matchesExpectation": result["matchesExpectation"], "report": str(path.relative_to(output))})
|
||||
write(output / "summary.json", {"compilation": observations, "execution": executions})
|
||||
failures = [x for x in observations + executions if not x["matchesExpectation"]]
|
||||
expected_runs = sum(c["expectedCompile"] == "compiled" for c in cases) * len(origins) * 2
|
||||
complete = len(observations) == len(cases)*len(origins)*3 and len(executions) == expected_runs
|
||||
summary = {"compilation": observations, "execution": executions, "compileCount": len(observations), "executionCount": len(executions),
|
||||
"normalSuccesses": sum(x["observedRuntime"] == "passed" for x in executions), "deliberateFaults": sum(x["observedRuntime"] == "fault" and x["caseId"] == "runtime-trap-control" for x in executions),
|
||||
"complete": complete, "failures": failures, "passed": complete and not failures}
|
||||
write(output / "summary.json", summary)
|
||||
write(output / "checksums.json", {str(p.relative_to(output)): sha(p) for p in output.rglob("*") if p.is_file()})
|
||||
print(json.dumps({k:v for k,v in summary.items() if k not in ("compilation", "execution", "failures")}))
|
||||
return 0 if summary["passed"] else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -1,545 +0,0 @@
|
||||
# Studio PBX producer conformance
|
||||
|
||||
Owner: compiler/general. This harness uses the production runtime loader and VM;
|
||||
it does not implement a Java approximation of runtime admission.
|
||||
|
||||
## PBS memcard and MemcardBuffer qualification
|
||||
|
||||
Generate the production PBS corpus and the actual installed-JAR example, then run
|
||||
both runtime profiles without modifying the runtime checkout:
|
||||
|
||||
```sh
|
||||
./gradlew test :prometeu-app:installedKnowledgeTest --console=plain
|
||||
CARGO_TARGET_DIR=/tmp/studio-pbx-memcard-target python3 tools/pbx-conformance/run.py --runtime ../runtime --memcard-only
|
||||
CARGO_TARGET_DIR=/tmp/studio-pbx-memcard-target python3 tools/pbx-conformance/run.py --runtime ../runtime --memcard-only --release
|
||||
```
|
||||
|
||||
The dedicated carrier has concrete Array<Int32> storage, capacity 0..4096, zero
|
||||
initialization, checked byte access and reference aliasing. Ordinary PBS arrays
|
||||
keep vacancy/optional semantics. The corpus checks all 14 native imports, both
|
||||
producer optimizer variants, typed source boundaries and origin protection;
|
||||
source aliases and canonical imported/reexported hooks; named evaluation order;
|
||||
exact four-byte save/remount and no resave; 4096-byte transfers; 64-slot admission;
|
||||
clear/commit; retained requests and BUSY; memory-only/pause/resume; public title,
|
||||
format-version and 32x32 icon publication; absent/read-only/corrupt media; controlled
|
||||
FAILURE/INDETERMINATE; hook refusal/trap/fuel; capacity/index/value/transfer traps.
|
||||
The status-first facade forwards native calls without an intermediate typed RET,
|
||||
so failed-domain Null payloads reach the caller's status check unchanged.
|
||||
|
||||
`memcard.rs` executes the production Firmware/SystemOS, VM, FileMemcard and its
|
||||
shared worker. Fault storage distinguishes pre-publication failure from uncertain
|
||||
metadata publication. The installed-JAR source fixture is also executed natively.
|
||||
This is **native production-host evidence**. Multiple Firmware instances and a
|
||||
file remount in this process do not establish save/reopen through the configured
|
||||
installed runtime CLI/JSONL protocol. The separate process gate below consumes
|
||||
the now-published provider surface for storage and explicit choices.
|
||||
No alternative process protocol or physical power-cut qualification is claimed.
|
||||
|
||||
The separate Studio process gate now consumes the published protocol 1.1 memcard
|
||||
extension through HeadlessProcessGateway and the configured installation:
|
||||
|
||||
```sh
|
||||
./gradlew :prometeu-app:memcardProcessTest -PstudioRuntimeInstall=/absolute/extracted/installation
|
||||
```
|
||||
|
||||
It builds actual PBS through the compiler and Studio shipper, requires a native
|
||||
terminal commit SUCCESS, terminates the writer, then starts separate readers for
|
||||
versions 1 and 2 with identical uint32 app_id. Both optimizer variants are required.
|
||||
The reader's reachable entry/role graph contains no saving or presentation calls;
|
||||
it validates exactly 00 7f 80 ff before rendering its observed oracle. Each read
|
||||
leaves the complete image byte-identical and no native request submitted. A second
|
||||
case proves missing-file open does not create, memory-only is explicit and dirty
|
||||
shutdown refusal preserves the channel until explicit discard. Runtime dev/release
|
||||
binary layouts and an extracted distribution are identified separately in evidence.
|
||||
|
||||
## PBS Map and Keyval qualification
|
||||
|
||||
Generate the mandatory Map corpus and actual installed-JAR example, then execute
|
||||
the dedicated verifier in both runtime profiles:
|
||||
|
||||
```sh
|
||||
./gradlew :prometeu-architecture-tests:test --tests '*PbsMapKeyvalTest' :prometeu-app:installedKnowledgeTest --console=plain
|
||||
CARGO_TARGET_DIR=/tmp/studio-pbx-map-target python3 tools/pbx-conformance/run.py --runtime ../runtime --map-only
|
||||
CARGO_TARGET_DIR=/tmp/studio-pbx-map-target python3 tools/pbx-conformance/run.py --runtime ../runtime --map-only --release
|
||||
```
|
||||
|
||||
Each non-GC source case has ordinary/optimized PBS producer variants, independent
|
||||
of the Rust dev/release profile. The manifest names every required success/fault,
|
||||
resource, injection, GC, import and installed fixture; missing files fail. The
|
||||
full harness includes Map separately from its historical catch-all PBS verifier.
|
||||
|
||||
The corpus covers typed non-positional keys; default/explicit Identity; optional
|
||||
V and previous-value presence; original-key retention under content policies;
|
||||
read-only Keyval instance identity; collisions/negative full hashes; rehash and
|
||||
capture callback counters; complete tuple/native/contract groups; evaluation order;
|
||||
alias reentrancy and permitted callback reads; and the shared snapshot state table.
|
||||
|
||||
Resource fixtures compare attempted instruction prefixes with successful
|
||||
instruction prefixes under lowered production quotas. They separate installed
|
||||
guard writes from structural mutation and measure old/candidate table/node and
|
||||
snapshot/keyval peaks. A named test-only allocation after the real candidate-table
|
||||
store qualifies permitted post-write incomplete invariants; production SDK has no
|
||||
injected probe. Natural quota refusal counts are reported separately.
|
||||
|
||||
Real safepoints check independent key/value roots, obsolete-value release after
|
||||
replacement, removed-key/value reclamation, Map-node reclamation, captured Keyvals,
|
||||
consumed Cursor prefixes, retained final current and release after all owners exit.
|
||||
Imported/reexported and installed examples execute through the production loader
|
||||
and VM and actually construct the shared entry Cursor. This is local semantic and
|
||||
resource qualification, not a performance benchmark or a new provider contract.
|
||||
|
||||
From the Studio root:
|
||||
|
||||
```sh
|
||||
./gradlew :prometeu-compiler:prometeu-build-pipeline:test --tests '*LinkedRegistryTest' --tests '*PbxRegistryConformanceTest' --tests '*TypedCommonPipelineTest' --tests '*RuntimeCatalogPipelineTest'
|
||||
./gradlew :prometeu-architecture-tests:test --tests '*PbsRuntimeAlignmentTest' --tests '*PbsStructuredValuesTest' --tests '*PbsClosuresTest' --tests '*PbsGenericContractsTest'
|
||||
python3 tools/pbx-conformance/run.py --runtime ../runtime
|
||||
```
|
||||
|
||||
The Java tests generate PBX in the build-pipeline module's
|
||||
`build/registry-conformance`. `run.py` creates a temporary Cargo project, copies
|
||||
the runtime lockfile and references its bytecode/hal/vm/system crates by path.
|
||||
It never modifies the runtime checkout. Add `--online` for an uncached machine;
|
||||
by default Cargo uses only cached dependencies. Java 21, Rust and the runtime
|
||||
checkout's dependencies are required.
|
||||
|
||||
The output identifies runtime revision, OS/architecture and load configuration.
|
||||
Positive fixtures distinguish loading from execution. The vec2 signature fixture
|
||||
is deliberately load-only because its entry requires arguments. Native binding
|
||||
uses SYSTEM for the positive case and NONE for missing-capability rejection;
|
||||
all other cases use NONE. Resource tests explicitly lower default limits.
|
||||
|
||||
## PBS controlled guest lifecycle qualification
|
||||
|
||||
Generate the source corpus and installed example, then run both runtime profiles:
|
||||
|
||||
```sh
|
||||
./gradlew :prometeu-architecture-tests:test --tests '*PbsGuestLifecycleTest' :prometeu-app:installedKnowledgeTest
|
||||
python3 tools/pbx-conformance/run.py --runtime ../runtime --lifecycle-only
|
||||
python3 tools/pbx-conformance/run.py --runtime ../runtime --lifecycle-only --release
|
||||
```
|
||||
|
||||
`PbsGuestLifecycleTest` emits ordinary/optimized production PBX for both hooks,
|
||||
each independently and neither, ordinary direct calls, fatal traps, total fuel
|
||||
exhaustion and successful calls spanning slices. Arbitrary function names and
|
||||
unmarked functions named BeforePause/BeforeResume distinguish role metadata from
|
||||
name conventions. An actual workspace import/reexport case selects one original
|
||||
declaration without requiring colocation with Frame. A conflicting declaration
|
||||
must fail project analysis. Synthetic binary fixtures explicitly cover direct
|
||||
and transitive FRAME_SYNC rejection; they do not add PBS sync syntax.
|
||||
|
||||
`lifecycle.rs` loads these images with the production VM and runs the production
|
||||
Firmware/SystemOS foreground path using the standard TestPlatform hardware.
|
||||
Home/resume asserts exact ordered guest effects, unchanged continuation PC and
|
||||
game-session ticks/frames during hooks, preserved heap/global state and a single
|
||||
Init execution. Direct suspension and Shell foreground handoff must not add a
|
||||
reaction tick. A partial frame retains its existing operand and call frame while
|
||||
controlled hooks run. Ordinary direct calls do not acquire a controlled context.
|
||||
|
||||
The independent 1,500,000-cycle fuel budget survives slices and debugger stops;
|
||||
single stepping uses the same accounting. Fatal trap/fuel/sync cases cannot run
|
||||
subsequent gameplay or publish a logical frame. After a crash, counters are read
|
||||
from the retained game session rather than the newly active crash UI. Probe
|
||||
functions run only as terminal observations after continuation/frame assertions.
|
||||
|
||||
The runner adds production firmware/driver dependencies to its temporary Cargo
|
||||
project. Sources, manifests, lockfiles and build outputs in the runtime checkout
|
||||
remain untouched. This is local lifecycle conformance; installed runtime/game
|
||||
qualification and MemcardBoot/persistence remain separate scopes.
|
||||
|
||||
Negative fixtures mutate Java-produced bytes independently of the writer to
|
||||
exercise malformed input that the writer correctly refuses to construct.
|
||||
Initialization JSON comes from `prometeu_system::CrashReport`, and is checked
|
||||
against the runtime's published headless schema. Saved JSON files remain under
|
||||
the generated fixture directory. Studio process tests replay selected observed
|
||||
payloads from `prometeu-app/src/test/resources/runtime` and assert unchanged MCP
|
||||
projection, including null executed PC and nested verifier context.
|
||||
|
||||
## Known upstream schema defect
|
||||
|
||||
At runtime `f7d7c167531bb662a1af9d73fc326bb476bf8aa7`, the LoadReason Rust enum
|
||||
includes LifecycleRole, LifecycleSignature, DuplicateLifecycleRole and
|
||||
NonFiniteValue, absent from the published JSON schema enum. This corpus
|
||||
observes LifecycleRole and NonFiniteValue. The harness prints an explicit
|
||||
`UPSTREAM SCHEMA GAP` for those two reasons and verifies that adding exactly
|
||||
the missing enum value makes the original payload valid. It never alters the
|
||||
payload or reports those cases as conforming to the unmodified schema. Any
|
||||
other schema failure remains fatal. Track the runtime correction in AGD75;
|
||||
remove the exception once the schema is corrected.
|
||||
|
||||
The original registry/catalog fixtures qualify common backend production. The
|
||||
PBS fixtures below additionally qualify source lowering; this harness does not
|
||||
claim installed-runtime deployment or memcard persistence.
|
||||
|
||||
## Runtime catalog consumer fixtures
|
||||
|
||||
The catalog corpus adds common-IR Random calls with an aliased handle, a discarded
|
||||
first result, mixed next/nextf/range calls and a subsequent next. The VM checks the
|
||||
independent seed-42 handoff vector and identical charged work before/after
|
||||
optimization. Constants are compared slot-by-slot against runtime materialization,
|
||||
including exact Float bits and both slots of `vec2.zero`. Pool deduplication may
|
||||
share a value but cannot omit a group component.
|
||||
|
||||
A known zero-argument touch query loads and traps `TRAP_UNAVAILABLE` without a
|
||||
hardware context. A removed endpoint ID is rejected even after an unreachable
|
||||
HALT. `color.html_rgba` executes with a String value and rejects a proven null
|
||||
at load time, matching the runtime verifier's stricter rule despite the
|
||||
dispatcher's nullable String carrier. These are distinct outcomes. Run the separate provider-export check with
|
||||
`python3 tools/runtime-catalog/verify.py --runtime ../runtime` to compare the
|
||||
selected source revision, imported CSV bytes and exporter output as well.
|
||||
|
||||
|
||||
## PBS source and input qualification
|
||||
|
||||
`PbsRuntimeAlignmentTest` compiles actual SDK declarations and source programs
|
||||
through the PBS frontend, production common IR, typed Registry and PBX writer.
|
||||
Its 114 fixtures execute on the selected runtime: all 48 Pad combinations with
|
||||
both literal Button arguments and enum locals passed through a typed function,
|
||||
six Touch queries, numeric boundaries/conversions/faults, builtin groups,
|
||||
String, fixed multiple returns and named application with observable Y,X effects.
|
||||
|
||||
The controlled input platform asserts the exact button/coordinate reader and
|
||||
one read per public query. Each query is also executed without a platform to
|
||||
prove TRAP_UNAVAILABLE. The loaded PBS registries are checked for the defaults
|
||||
of all eight existing value types, including null String, positive Float zero
|
||||
and complete vec2/pixel groups. No source constructors or new collection API
|
||||
are introduced to test storage defaults.
|
||||
|
||||
The harness requires the complete fixture count. It must not pass by skipping
|
||||
missing PBS fixtures. Integer arithmetic wrapping is distinct from checked
|
||||
Int64-to-Int32 narrowing and Float numeric-range faults. The full installed
|
||||
knowledge gate remains separate and mandatory for SDK resource/producer
|
||||
integration.
|
||||
|
||||
## PBS typed arrays, optional and Struct/contract execution
|
||||
|
||||
`PbsStructuredValuesTest` generates 27 mandatory `pbs-structured-*` fixtures.
|
||||
They cover contextual arrays, nested levels, vacancy/zero, clear/length, aliasing,
|
||||
int/long bounds, single evaluation, lazy optional fallback, inferred/explicit
|
||||
optional tuples, native vec2 groups, fields and constructors, overloads and Self,
|
||||
contract elements/dispatch, imported services/structs/contracts, global file-init,
|
||||
and the installed example. The runtime harness names every required fixture;
|
||||
a missing file is an error.
|
||||
|
||||
Eighteen additional runs lower GuestBytes or HandleSlots to 0, 1 or 2. They assert
|
||||
resource faults, bounded accounting, no object publication at zero quota, and
|
||||
release of session ownership. The integer-storage fixture succeeds with one
|
||||
handle total, proving that its three integers do not allocate individual boxes.
|
||||
String session accounting is checked after each structured execution.
|
||||
|
||||
The GC fixture compiles all allocations, roots and post-collection reads from PBS.
|
||||
A test-only driver hook replaces one isolated marker assignment with FRAME_SYNC
|
||||
and NOPs without changing code offsets; it does not add PBS sync syntax. At the
|
||||
real runtime safepoint, at least 1,100 discarded objects are reclaimed while
|
||||
nested references, tuples and strings remain readable. `resource-diagnostics`
|
||||
is enabled solely for observation. Default production ceilings and GC threshold
|
||||
are unchanged outside the explicitly lowered quota runs. This is semantic and
|
||||
resource conformance, not a performance benchmark or installed game qualification.
|
||||
|
||||
## PBS first-class functions and closure lifetime
|
||||
|
||||
`PbsClosuresTest` adds nine mandatory source/load/execute fixtures: named and
|
||||
anonymous functions, snapshots, shared objects/arrays, nested function captures,
|
||||
complete tuple groups and contract receivers, independent environments, Fn fields
|
||||
and overload selection, imported functions, and the installed example. Each
|
||||
returns 42. Six additional GuestBytes/HandleSlots runs at limits 0, 1 and 2 check
|
||||
closure allocation faults and session ownership, bringing structured quota runs
|
||||
to 24.
|
||||
|
||||
The tenth fixture, `closure-frame-lifecycle.pbx`, uses the existing production
|
||||
lifecycle assembler without bytecode patching. Its first frame stores a closure
|
||||
capturing an object; the next frame invokes it twice (41, then 42) and drops the
|
||||
reference. Each of three frames also discards 1,200 closures. The harness asserts
|
||||
threshold collections, retained closure/object reachability after frame one,
|
||||
and reclamation after release. The remaining root is the global array.
|
||||
PBS publishes FRAME_ROOT and the existing guarded wrapper returns normally.
|
||||
No sync syntax, new frame integration, suspension or coroutine is introduced.
|
||||
|
||||
## PBS service constants and runtime math
|
||||
|
||||
`PbsRuntimeMathTest` produces 261 independent numeric cases in both ordinary and
|
||||
optimized bytecode (522 mandatory executions per runtime profile), covering all
|
||||
26 math/mathf signatures. The checked-in corpus preserves 240 provider scalar
|
||||
fixture rows and exact contract examples (duplicates removed); provenance is in
|
||||
`prometeu-architecture-tests/src/test/resources/math/provenance.txt`.
|
||||
|
||||
The harness verifies exact bits/faults, selected intrinsic identity and one
|
||||
retained call per case. Single-step charging is compared with the provider's
|
||||
opcode costs and independent fixture call cost; full-budget charging must equal
|
||||
their sum, and optimization must preserve total cycles. Additional cases exercise
|
||||
pi/tau, literal sin, ordinary int/long service constants, constant dependencies,
|
||||
and real module imports with service aliases. The installed example also imports
|
||||
both SDK services, so installedKnowledgeTest covers their packaged resources.
|
||||
|
||||
```sh
|
||||
./gradlew :prometeu-architecture-tests:test --tests '*PbsRuntimeMathTest'
|
||||
python3 tools/pbx-conformance/run.py --runtime ../runtime --math-only
|
||||
python3 tools/pbx-conformance/run.py --runtime ../runtime --math-only --release
|
||||
```
|
||||
|
||||
Omit `--math-only` for the full existing corpus. `--release` selects the optimized
|
||||
Rust runtime harness; it is independent of the PBS optimizer variants included in
|
||||
every run. Optional `CARGO_TARGET_DIR` can retain build artifacts outside the
|
||||
runtime checkout. Each invocation prints runtime revision, platform, profile,
|
||||
features, lockfile and provider catalog/oracle hashes. Local evidence qualifies
|
||||
macOS/arm64 only; macOS/x86_64 and Linux/x86_64 remain pending.
|
||||
|
||||
## PBS explicit Random integration
|
||||
|
||||
`PbsRuntimeRandomTest` adds 226 source fixtures plus one real SDK import/alias
|
||||
fixture. The 48 unchanged provider oracle rows produce 192 exact integer/Float
|
||||
cases (six seeds, eight draws, two output kinds and two optimizer variants).
|
||||
The remaining paired fixtures cover mixed/discarded draws, independent objects,
|
||||
locals/globals/fields/arrays/parameters/results/captures, named/positional effects,
|
||||
unit/extreme ranges, invalid limits, null and typed-null Dynamic storage, real
|
||||
rejection followed by acceptance, and collection roots.
|
||||
|
||||
Each paired fixture runs with single-instruction budgets and twice with full
|
||||
budgets, comparing exact result bits or faults, intrinsic charges and total
|
||||
cycles. Explicit source `as long` conversions are charged separately. The GC
|
||||
fixture reuses the existing test-only FRAME_SYNC marker hook; all allocations,
|
||||
roots and post-collection draws are compiled PBS. At least 1,100 discarded Random
|
||||
objects are reclaimed while array, field and closure references preserve the
|
||||
same generator. The import fixture uses the production workspace builder and
|
||||
lifecycle assembler. The focused driver calls file initializers before Probe.main;
|
||||
it does not claim a new lifecycle API.
|
||||
|
||||
```sh
|
||||
./gradlew :prometeu-architecture-tests:test --tests '*PbsRuntimeRandomTest'
|
||||
python3 tools/pbx-conformance/run.py --runtime ../runtime --random-only
|
||||
python3 tools/pbx-conformance/run.py --runtime ../runtime --random-only --release
|
||||
```
|
||||
|
||||
The driver rejects an oracle copy that differs from the selected provider and
|
||||
prints source/oracle/catalog/lockfile fingerprints and toolchain/profile details.
|
||||
A complete run includes the Random corpus and keeps it separate from the older
|
||||
114 input/type fixtures. Rare synthetic 64-attempt acceptance/cap/rollback,
|
||||
malformed carriers and native provenance are provider tests, not PBS-produced
|
||||
claims. Qualify those separately with the provider's `random_contract` suite and
|
||||
`cargo test -p prometeu-vm --lib random` in debug/release. No alternate RNG or
|
||||
public injection hook is used. Installed knowledge validation remains a separate
|
||||
gate for packaged SDK/spec/example resources.
|
||||
|
||||
## PBS generic contracts
|
||||
|
||||
`PbsGenericContractsTest` generates fourteen mandatory source fixtures:
|
||||
`identity`, `manual`, `multiple`, `tuple`, `optional`, `function`, `contract`,
|
||||
`native`, `recursive`, `phantom`, `receiver`, `gc`, `installed` and `imports`.
|
||||
The corpus uses ordinary concrete Trait descriptors on the existing runtime.
|
||||
It checks several applications on one owner, ordered substitution, composed
|
||||
multi-slot values, finite recursion, canonical aliases/reexports and distinct
|
||||
same-named argument declarations. The imported program uses the production
|
||||
workspace builder and lifecycle assembler.
|
||||
|
||||
The generic and handwritten concrete identity fixtures both execute with one
|
||||
heap handle, establishing that contract adaptation needs no generic wrapper.
|
||||
Typed absence and implementation index zero are valid. A mismatched Trait call
|
||||
must be rejected by the verifier or trap with the runtime type check. The GC
|
||||
fixture retains a contract receiver through a closure while at least 1,100
|
||||
discarded objects are reclaimed. Reduced GuestBytes, HandleSlots and loader
|
||||
implementation limits verify refusal and ownership release. Descriptor counts
|
||||
and PBX byte sizes are printed as evidence, without a performance threshold.
|
||||
|
||||
```sh
|
||||
./gradlew :prometeu-architecture-tests:test --tests '*PbsGenericContractsTest'
|
||||
python3 tools/pbx-conformance/run.py --runtime ../runtime --generic-contracts-only
|
||||
```
|
||||
|
||||
The full harness also requires these fixtures. The driver uses an external
|
||||
runtime checkout without editing its sources or changing PBX, ISA or quotas.
|
||||
|
||||
|
||||
## Minimal storage ISA, SDK collections and phase-aware refusals
|
||||
|
||||
Generate common/source fixtures and the real installed-JAR examples, then run:
|
||||
|
||||
```sh
|
||||
./gradlew :prometeu-compiler:prometeu-build-pipeline:test :prometeu-architecture-tests:test :prometeu-app:installedKnowledgeTest
|
||||
CARGO_TARGET_DIR=/tmp/studio-pbx-conformance python3 tools/pbx-conformance/run.py --runtime ../runtime
|
||||
CARGO_TARGET_DIR=/tmp/studio-pbx-conformance python3 tools/pbx-conformance/run.py --runtime ../runtime --release
|
||||
```
|
||||
|
||||
Focused `--list-cursor-only` and `--linked-only` modes include mandatory neutral
|
||||
storage/copy/terminal/admission fixtures as well as their collection corpus. The
|
||||
complete run requires both. No runtime source, manifest, lockfile or target
|
||||
artifact is modified: the Cargo harness and target live outside that checkout.
|
||||
|
||||
The selected provider supports ARRAY_LEN and ARRAY_COPY, ordinary typed stores
|
||||
and terminal TRAP. Four dead-code fixtures prove that 0xA7/0xA8/0xAA/0xAB reject
|
||||
at real instruction positions; corresponding Int32-immediate fixtures must load.
|
||||
All producer-opcode checks decode instruction boundaries rather than scanning
|
||||
raw PBX bytes. Neutral ordinary/optimized programs qualify stores and copy without
|
||||
PBS types. A store followed by TRAP_EXPLICIT proves that terminal failure retains
|
||||
previous effects and source spans survive lowering/optimization.
|
||||
|
||||
Eleven paired neutral copy cases independently check scalar/vec2/String groups,
|
||||
snapshot overlap, empty ranges, bad ranges/receivers, negative/above-u32 counts
|
||||
and fault precedence. At the actual copy PC, zero budget executes nothing;
|
||||
positive budget admits a complete attempt with overshoot. N=10/W=1 costs 24,
|
||||
including receiver/range/scratch refusal; W=2 costs 44. Invalid or empty counts
|
||||
cost base 4 as defined by the provider. Refusals preserve the five operands and
|
||||
previous storage, release scratch and do not count a successful step. Native
|
||||
String owners release with the session. Checked cost-overflow defenses requiring
|
||||
synthetic internal widths are provider evidence, not an assertion that admitted
|
||||
consumer layouts can attain those widths.
|
||||
|
||||
List source fixtures cover every mutator, exact growth, logical versus physical
|
||||
bounds, int/long and named evaluation, holes, aliases and complete native/tuple/
|
||||
Fn/contract/reference groups. Linked fixtures cover empty/single/multiple states,
|
||||
reciprocal links, nearest-end lookup, complete values and both snapshot orders.
|
||||
Logical SDK refusals now produce TRAP_EXPLICIT; physical instructions retain
|
||||
their own faults. No missing ordinary or optimized fixture is silently skipped.
|
||||
|
||||
Four List and ten Linked source-generated mutation boundaries have normal and
|
||||
optimized variants. GuestBytes, HandleSlots, AuxiliaryBytes and TemporaryBytes
|
||||
ceilings are lowered from measured setup/success peaks. Non-owning diagnostic
|
||||
observations inspect the original collection objects independently of guest code.
|
||||
Every instruction prefix is compared with the corresponding successful prefix.
|
||||
A refused instruction preserves its own observable entry state. Before visible
|
||||
mutation the entire old collection must remain unchanged; after mutation the
|
||||
previous successful writes remain, without a whole-method rollback or safe-reuse
|
||||
claim. Successful single-instruction-budget traversal also qualifies suspension
|
||||
and resumption in the middle of a source method. Snapshot capture failures must
|
||||
always preserve their source and expose no partial result.
|
||||
|
||||
No-growth insertion prepares a one-slot private array before shifting and copies
|
||||
that complete stored group into place; candidate/optional/result and operand/
|
||||
frame preparation remain charged. ARRAY_COPY scratch remains a mandatory observed
|
||||
refusal. Linked prepares nodes/results before its sequential link updates. The
|
||||
corpus retains explicit coverage requirements for these resource refusal paths;
|
||||
it does not rename old publication guarantees as new evidence.
|
||||
|
||||
Normal GC safepoints qualify removed nodes and payloads, collection clear,
|
||||
snapshot independence, consumed-prefix reclamation and sticky final values.
|
||||
The Cursor fixture requires 1,200 -> 1 -> 1 -> 0 snapshot nodes/payloads, with no
|
||||
live source/snapshot array. Linked captures must not retain editable source nodes.
|
||||
The actual installed SDK/spec/example is compiled outside the checkout and its
|
||||
PBX is loaded/executed by the production VM; import/reexport fixtures also run.
|
||||
|
||||
Catalog schema 2 is imported with all 25 fields, per-entry nullable masks,
|
||||
explicit invocation/scratch/context profiles and cost parameters. Ordinary parity
|
||||
and rejection tests need no runtime checkout. Explicit exporter verification uses
|
||||
`tools/runtime-catalog/verify.py` and the selected clean SHA/digests. Nullable
|
||||
hash.string metadata is qualified independently of older non-nullable String
|
||||
entries; importing it does not deliver PBS hashing facades or Set/Map.
|
||||
|
||||
Evidence prints consumer/provider source hashes, selected revision and clean state,
|
||||
toolchain/platform/profile, lockfile/catalog hashes, capabilities, default ceilings
|
||||
and lowered refusal limits. Keep new qualification separate from historical List/
|
||||
Linked evidence; prior successful providers are not relabeled as the new target.
|
||||
|
||||
## PBS hashing, Identity and Set
|
||||
|
||||
`IdentityHashingPipelineTest` qualifies neutral 0x97/0x98 production, complete
|
||||
concrete/Trait groups and both optimizer paths. It also emits malformed-category,
|
||||
right-TypeId, unknown-TypeId, dead-code, partial-group and truncated fixtures.
|
||||
Unknown global inputs in two neutral cases reach production runtime validation:
|
||||
an absent/different left cannot hide the invalid complete right view. Refusal
|
||||
retains all three input slots, charges seven cycles and executes zero successful
|
||||
query steps; zero budget executes nothing.
|
||||
|
||||
`PbsIdentityHashingTest` selects all 30 scalar/String rows from the unchanged
|
||||
118-row independent provider C XXH64 oracle. Both producer paths preserve exact
|
||||
signed digest bits and attempted costs. Separate source fixtures qualify Struct,
|
||||
Array, Fn, Random, complete contracts, mutation, aliases and discarded scalar and
|
||||
reference results. The reference-query source gate ran before Set algorithm work.
|
||||
The consumer oracle copy is checked against the selected provider on every
|
||||
explicit harness invocation. Ordinary Gradle compilation uses local resources.
|
||||
|
||||
`PbsSetTest` exercises the complete source API, contextual/default/explicit
|
||||
construction, optional/default diagnostics, nominal origin, shared complete values,
|
||||
content opt-in, collisions, exact growth arithmetic, callbacks, aliases and Cursor.
|
||||
Counter strategies demonstrate that rehash and capture do not call hash/equals.
|
||||
SDK aliases, generic-function reexports and installed examples compile through
|
||||
actual workspace builders; installed compilation uses only installDist JARs in an
|
||||
external directory and writes mandatory PBX fixtures for runtime execution.
|
||||
|
||||
```sh
|
||||
./gradlew :prometeu-compiler:prometeu-build-pipeline:test --tests '*IdentityHashingPipelineTest'
|
||||
./gradlew :prometeu-architecture-tests:test --tests '*PbsIdentityHashingTest' --tests '*PbsSetTest'
|
||||
./gradlew :prometeu-app:installedKnowledgeTest
|
||||
CARGO_TARGET_DIR=/tmp/studio-pbx-target python3 tools/pbx-conformance/run.py --runtime ../runtime --identity-hashing-only
|
||||
CARGO_TARGET_DIR=/tmp/studio-pbx-target python3 tools/pbx-conformance/run.py --runtime ../runtime --set-only
|
||||
```
|
||||
|
||||
The Set quota corpus measures old/candidate coexistence and compares every
|
||||
original-object instruction prefix with a successful run. It treats guard writes
|
||||
separately from structural writes. Natural quota cases cover insertion, growth,
|
||||
duplicate inclusion, removal, clear and capture with no claim that all failures
|
||||
preserve the entire Set or that every theoretical failure boundary occurs at the
|
||||
sampled limits. Current natural runs refuse before structural mutation; this is
|
||||
reported explicitly by their summaries.
|
||||
|
||||
A **separate test-only instrumented source fixture** inserts a controlled Array
|
||||
allocation after the real candidate-table store and before size assignment. A
|
||||
lowered guest quota refuses that probe. The old size six, new table capacity 16,
|
||||
seven reachable nodes and active guard remain, while the refused instruction
|
||||
preserves its own entry state. This demonstrates the post-publication failure
|
||||
boundary; it is not a production SDK allocation, callback, algorithm or claim about
|
||||
natural refusal frequency. Its ordinary/optimized fixtures are named
|
||||
`pbs-set-injected-refusal-growth*` and are generated from an in-memory SDK copy.
|
||||
|
||||
Real safepoints qualify source Set node/candidate release, removal/clear, snapshot
|
||||
prefix reclamation and sticky final retention. Set GC tests do not assume an
|
||||
iteration order. Add `--release` to qualify the Rust release profile independently
|
||||
of the two producer variants; omit focused flags for the complete mandatory corpus.
|
||||
All harness builds remain outside the runtime checkout, which is consumed unchanged.
|
||||
|
||||
## PBS Stack and Queue qualification
|
||||
|
||||
The mandatory Stack/Queue corpus is included in every complete run. A focused
|
||||
run uses `python3 tools/pbx-conformance/run.py --runtime ../runtime --stack-queue-only`;
|
||||
add `--release` for the optimized runtime profile. Both source producer paths are
|
||||
mandatory in each profile. Generate fixtures with the architecture tests and
|
||||
`:prometeu-app:installedKnowledgeTest` before executing the runner.
|
||||
|
||||
`stack_queue.rs` validates dense/circular storage, inactive-slot cleanup, exact
|
||||
capacity/growth, wrapped growth, complete payloads, once/named evaluation, snapshot
|
||||
orders/states, imports and actual installed-JAR examples. Lowered quota runs compare
|
||||
complete original-object instruction prefixes to a successful run and distinguish
|
||||
preservation before mutation from retained writes afterward. Separate test-only
|
||||
growth probes demonstrate an installed candidate with old size after a later fault;
|
||||
these probes are not shipped or counted as natural refusal frequencies.
|
||||
|
||||
GC fixtures require actual advancing collection counters. Snapshots release source
|
||||
backings and observe 1,200 → 1 → 1 → 0 nodes/payloads. Collection fixtures observe
|
||||
64 → 61 → 0 → 1 → 0 payloads and only one retained backing until its final owner
|
||||
is dropped. Temporary Cargo projects/targets stay outside the runtime checkout.
|
||||
|
||||
|
||||
## PBS Result, Sprite and Animation qualification
|
||||
|
||||
Generate the source corpora with `:prometeu-architecture-tests:test` and
|
||||
`:prometeu-app:installedKnowledgeTest`. Focused native gates are `--result-only`
|
||||
and `--animation-only`; add `--release` for the runtime release profile. Before
|
||||
animation qualification, generate the Composer pixel corpus with
|
||||
`:prometeu-app:headlessProcessTest --tests '*AnimationInstalledRuntimeTest'`
|
||||
and `-PstudioRuntimeInstall=<extracted-runtime-installation>`. The desktop gate
|
||||
is `:prometeu-app:animationDesktopTest`. Each native gate
|
||||
requires both ordinary and optimized producer variants and fails on missing fixtures.
|
||||
|
||||
Result executes status plus complete payload groups, once-only propagation and
|
||||
handling, error remapping, reference/Fn/trait/builtin payloads and uncaught traps.
|
||||
Animation executes the public core, reusable independent backing, state/reset/time
|
||||
boundaries, every domain error, exact long limits and a test-only near-limit state.
|
||||
The isolated count/phase setup is never shipped as a public mutation hook.
|
||||
|
||||
`animation.rs` single-steps actual instructions between post-construction markers.
|
||||
Sprite and successful, negative and overflow advance paths must execute zero
|
||||
StructNew/ArrayNew/MakeClosure instructions. Large jumps must remain below the
|
||||
bounded instruction gate. Zero guest/handle quotas trap during construction and
|
||||
are distinct from recoverable domain errors. A test-only safepoint marker observes
|
||||
live private rings followed by complete reclamation after their last owner clears.
|
||||
|
||||
The installed-JAR producer saves a real Packer-bound canonical sidecar, compiles
|
||||
virtual factories with read-only JSON origins and supplies both producer variants
|
||||
for production firmware execution. `AnimationInstalledRuntimeTest` separately boots
|
||||
the configured extracted runtime and compares every pixel of direct/generated
|
||||
Composer sprites with the shared preview across tick boundaries and alternating
|
||||
palettes. That saved-project corpus is replayed by production firmware in native
|
||||
dev/release with both producers, comparing the exact same canonical pixels. The public Composer
|
||||
facade retains int status and nine arguments; its private host carrier is narrowed
|
||||
from the existing native Int64 status. No runtime source write is required.
|
||||
|
||||
Keep Cargo targets in `/tmp` and retain source hashes, provider revision, profiles,
|
||||
allocation counts and GC observations with the completed discussion's evidence.
|
||||
@@ -1,118 +0,0 @@
|
||||
//! Real core playback and executed allocation evidence, including error paths.
|
||||
use super::*;
|
||||
use prometeu_vm::LogicalFrameEndingReason as End;
|
||||
use prometeu_bytecode::{decode_next, isa::core::CoreOpCode as Op};
|
||||
|
||||
pub fn verify(root: &std::path::Path) {
|
||||
let manifest = std::fs::read_to_string(root.join("pbs-animation-manifest.txt")).expect("mandatory animation manifest");
|
||||
let names: Vec<_> = manifest.lines().collect();
|
||||
assert_eq!(names, ["basic", "loop", "once", "negative", "overflow", "draft", "limits", "matrix", "errors"]);
|
||||
for name in names { for suffix in ["", "-optimized"] {
|
||||
let bytes = std::fs::read(root.join(format!("pbs-animation-{name}{suffix}.pbx"))).expect("mandatory animation fixture");
|
||||
let image = ValidatedProgramImage::load(&bytes, &mut LoadBudget::new(LoadLimits::default()), caps::NONE)
|
||||
.unwrap_or_else(|e| panic!("animation/{name}{suffix}: load {e:?}"));
|
||||
let mut vm = VirtualMachine::from_image(image.clone(), Default::default());
|
||||
vm.prepare_boot_call().unwrap();
|
||||
let mut watching = false; let mut started = 0; let mut ended = 0; let mut allocations = 0; let mut measured_steps=0;
|
||||
for step in 0..2_000_000 {
|
||||
let instruction = decode_next(vm.pc(), image.code()).unwrap();
|
||||
if instruction.opcode == Op::PushI32 {
|
||||
if instruction.imm_i32().unwrap() == 162000001 { watching = true; started += 1; }
|
||||
if instruction.imm_i32().unwrap() == 162000002 { watching = false; ended += 1; }
|
||||
}
|
||||
if watching { measured_steps+=1; }
|
||||
if watching && matches!(instruction.opcode, Op::StructNew | Op::ArrayNew | Op::MakeClosure) { allocations += 1; }
|
||||
let report = vm.run_budget(1, &mut NoNative, &mut HostContext::new(None))
|
||||
.unwrap_or_else(|e| panic!("animation/{name}{suffix}: run {e:?}"));
|
||||
if matches!(report.reason, End::Halted | End::EndOfRom) { break; }
|
||||
assert!(matches!(report.reason, End::BudgetExhausted), "animation/{name}{suffix}: {report:?}");
|
||||
assert!(step < 1_999_999, "animation failed to terminate");
|
||||
}
|
||||
assert_eq!(vm.operand_stack_top(2), vec![Value::Int32(42), Value::Int32(0)], "animation/{name}{suffix}");
|
||||
if !matches!(name, "basic" | "draft" | "limits" | "matrix") { assert_eq!((started, ended), (1, 1)); }
|
||||
assert!(measured_steps<50000,"bounded frame traversal: {measured_steps}");
|
||||
assert_eq!(allocations, 0, "animation/{name}{suffix}: executed advance/sprite heap allocations");
|
||||
if name=="basic" {
|
||||
use prometeu_vm::resource_budget::{RuntimeLimits,RuntimeResource};
|
||||
for resource in [RuntimeResource::GuestBytes,RuntimeResource::HandleSlots] {
|
||||
let mut refused=VirtualMachine::from_image(image.clone(),RuntimeLimits::default().lowered(resource,0).unwrap());
|
||||
refused.prepare_boot_call().unwrap();let report=refused.run_budget(100_000,&mut NoNative,&mut HostContext::new(None)).unwrap();
|
||||
assert!(matches!(report.reason,End::Trap(ref fault) if fault.code==prometeu_bytecode::TRAP_RESOURCE_LIMIT));
|
||||
assert_eq!(refused.heap().len(),0);println!("ANIMATION QUOTA TRAP PASS {suffix} {resource:?}");
|
||||
}
|
||||
}
|
||||
println!("ANIMATION PASS {name}{suffix} watched={started} executed_allocations={allocations}");
|
||||
} }
|
||||
verify_gc(root);
|
||||
verify_installed(root);
|
||||
verify_composer(root);
|
||||
}
|
||||
|
||||
fn verify_gc(root: &std::path::Path) {
|
||||
for suffix in ["", "-optimized"] {
|
||||
let bytes=std::fs::read(root.join(format!("pbs-animation-gc{suffix}.pbx"))).unwrap();
|
||||
let image=ValidatedProgramImage::load(&bytes,&mut LoadBudget::new(LoadLimits::default()),caps::NONE).unwrap();
|
||||
let mut vm=VirtualMachine::from_image(image.clone(),Default::default());vm.prepare_boot_call().unwrap();
|
||||
for round in 0..2 {
|
||||
let report=vm.run_budget(30_000_000,&mut NoNative,&mut HostContext::new(None)).unwrap();
|
||||
assert!(matches!(report.reason,End::FrameSync),"animation GC: {report:?}");
|
||||
let objects=vm.heap().diagnostic_typed_storage();
|
||||
for name in ["Animator","_AnimationClip","_AnimationFrame"] {
|
||||
let count=objects.iter().filter(|o|image.registry().declarations().types[o.type_id.0 as usize].name.as_deref()==Some(name)).count();
|
||||
if round==0 {assert!(count>0,"live animation root {name}");} else {assert_eq!(count,0,"unowned cycle {name}");}
|
||||
}
|
||||
assert!(vm.resource_snapshot().gc.reclaimed>1000);
|
||||
println!("ANIMATION GC PASS {suffix} round={round} collections={} reclaimed={}",vm.resource_snapshot().gc.collections,vm.resource_snapshot().gc.reclaimed);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn verify_installed(root: &std::path::Path) {
|
||||
use prometeu_drivers::TestPlatform;
|
||||
use prometeu_firmware::firmware::Firmware;
|
||||
use prometeu_hal::{InputSignals,app_mode::AppMode,cartridge::{Cartridge,AssetsPayloadSource}};
|
||||
for suffix in ["", "-optimized"] {
|
||||
let name=format!("pbs-animation-installed{suffix}");
|
||||
let mut fw=Firmware::new(None);let mut platform=TestPlatform::new();
|
||||
fw.load_cartridge(Cartridge{app_id:84,title:"Studio animation".into(),app_version:"1.0.0".into(),app_mode:AppMode::Game,capabilities:caps::NONE,memcard_slots:None,program:std::fs::read(root.join(format!("{name}.pbx"))).unwrap(),assets:AssetsPayloadSource::empty(),asset_table:vec![],preload:vec![]});
|
||||
for _ in 0..5 {fw.tick(&InputSignals::default(),&mut platform);assert!(fw.os.vm().last_crash_report().is_none());}
|
||||
let task=fw.os.lifecycle().resident_game_task().unwrap();let mut sessions=fw.os.sessions();let session=sessions.vm_session_for_task_mut(task).unwrap();
|
||||
let id=std::fs::read_to_string(root.join(format!("{name}.probe"))).unwrap();session.vm.prepare_call(id.trim()).unwrap();
|
||||
let report=session.vm.run_budget(100_000,&mut NoNative,&mut HostContext::new(None)).unwrap();assert!(matches!(report.reason,End::Halted|End::EndOfRom));assert_eq!(session.vm.operand_stack_top(1),vec![Value::Int32(42)]);
|
||||
println!("ANIMATION INSTALLED GENERATED/FIRMWARE PASS {suffix}");
|
||||
}
|
||||
}
|
||||
|
||||
fn verify_composer(root: &std::path::Path) {
|
||||
use prometeu_drivers::TestPlatform;
|
||||
use prometeu_firmware::firmware::Firmware;
|
||||
use prometeu_hal::{InputSignals,app_mode::AppMode,cartridge::{Cartridge,AssetsPayloadSource,AssetsPackPrelude}};
|
||||
for suffix in ["", "-optimized"] {
|
||||
let prefix=format!("pbs-animation-composer{suffix}");
|
||||
let manifest:serde_json::Value=serde_json::from_slice(&std::fs::read(root.join(format!("{prefix}.manifest.json"))).unwrap()).unwrap();
|
||||
let oracle:serde_json::Value=serde_json::from_slice(&std::fs::read(root.join(format!("{prefix}.oracle.json"))).unwrap()).unwrap();
|
||||
let packed=std::fs::read(root.join(format!("{prefix}.assets.pa"))).unwrap();let prelude=AssetsPackPrelude::from_bytes(&packed).unwrap();
|
||||
let mut fw=Firmware::new(None);let mut platform=TestPlatform::new();
|
||||
fw.load_cartridge(Cartridge{app_id:84,title:"Studio animation Composer".into(),app_version:"1.0.0".into(),app_mode:AppMode::Game,
|
||||
capabilities:caps::COMPOSER,memcard_slots:None,
|
||||
program:std::fs::read(root.join(format!("{prefix}.pbx"))).unwrap(),assets:AssetsPayloadSource::from_bytes(packed[prelude.payload_offset as usize..].to_vec()),
|
||||
asset_table:serde_json::from_value(manifest["asset_table"].clone()).unwrap(),preload:serde_json::from_value(manifest["preload"].clone()).unwrap()});
|
||||
let mut observed=0;
|
||||
for _ in 0..50000 {
|
||||
fw.tick(&InputSignals::default(),&mut platform);
|
||||
assert!(fw.os.vm().last_crash_report().is_none(),"Composer {suffix}: {:?}",fw.os.vm().last_crash_report());
|
||||
if let Some(task)=fw.os.lifecycle().resident_game_task() {
|
||||
let completed={let sessions=fw.os.sessions();sessions.vm_session_for_task(task).map(|s|s.runtime.atomic_telemetry.completed_logical_frames.load(std::sync::atomic::Ordering::Relaxed)).unwrap_or(0)};
|
||||
if completed>observed {
|
||||
assert_eq!(completed,observed+1,"one native frame per observation");
|
||||
let sample=&oracle[observed as usize];let pixels=sample["rgba"].as_array().unwrap();let front=platform.local_hardware().gfx.front_buffer();let width=platform.local_hardware().gfx.size().0;
|
||||
for x in [32,64] {for y in 0..16 {for dx in 0..16 {assert_eq!(front[(32+y)*width+x+dx],pixels[y*16+dx].as_u64().unwrap() as u32,"{prefix} tick={observed} x={x} pixel={dx},{y}");}}}
|
||||
println!("ANIMATION COMPOSER PIXELS PASS {suffix} tick={observed} glyph={} palette={}",sample["glyph"],sample["palette"]);
|
||||
observed=completed;if observed==8 {break;}
|
||||
}
|
||||
}
|
||||
std::thread::yield_now();
|
||||
}
|
||||
assert_eq!(observed,8,"native Composer did not produce all frames");
|
||||
}
|
||||
}
|
||||
@@ -1,219 +0,0 @@
|
||||
//! Studio-produced PBS images through the production VM and foreground firmware.
|
||||
use prometeu_bytecode::{Value, registry::LifecycleRole};
|
||||
use prometeu_drivers::TestPlatform;
|
||||
use prometeu_firmware::firmware::{Firmware, FirmwareState};
|
||||
use prometeu_hal::{InputSignals, app_mode::AppMode, cartridge::{Cartridge, AssetsPayloadSource}};
|
||||
use prometeu_system::task::{TaskId, TaskState};
|
||||
use prometeu_vm::{HostContext, LogicalFrameEndingReason as Reason, ValidatedProgramImage, VirtualMachine};
|
||||
use std::path::Path;
|
||||
|
||||
fn bytes(root: &Path, name: &str) -> Vec<u8> {
|
||||
std::fs::read(root.join(format!("{name}.pbx"))).unwrap_or_else(|e| panic!("{name}: {e}"))
|
||||
}
|
||||
fn load(root: &Path, name: &str) -> VirtualMachine {
|
||||
let image = ValidatedProgramImage::load(&bytes(root, name), &mut super::LoadBudget::new(Default::default()), super::caps::NONE).unwrap();
|
||||
for role in [LifecycleRole::BeforePause, LifecycleRole::BeforeResume] {
|
||||
if let Some(id) = image.registry().lifecycle_hook(role) { assert_ne!(id.0, 0); }
|
||||
}
|
||||
let mut vm = VirtualMachine::from_image(image, Default::default());
|
||||
vm.prepare_boot_call().unwrap();
|
||||
let report = vm.run_budget(100_000, &mut super::NoNative, &mut HostContext::new(None)).unwrap();
|
||||
assert!(matches!(report.reason, Reason::EndOfRom | Reason::Halted), "{name}: {report:?}");
|
||||
vm
|
||||
}
|
||||
fn query(root: &Path, name: &str, vm: &mut VirtualMachine) -> i32 {
|
||||
let id = std::fs::read_to_string(root.join(format!("{name}.probe"))).unwrap();
|
||||
vm.prepare_call(id.trim()).unwrap();
|
||||
let report = vm.run_budget(100_000, &mut super::NoNative, &mut HostContext::new(None)).unwrap();
|
||||
assert!(matches!(report.reason, Reason::EndOfRom | Reason::Halted), "{name}: {report:?}");
|
||||
match vm.operand_stack_top(1)[0] { Value::Int32(value) => value, ref other => panic!("{other:?}") }
|
||||
}
|
||||
fn finish_hook(vm: &mut VirtualMachine, expected: Reason) -> usize {
|
||||
let mut previous = vm.lifecycle_remaining_cycles().unwrap();
|
||||
let mut slices = 0;
|
||||
loop {
|
||||
slices += 1; assert!(slices < 16);
|
||||
let report = vm.run_budget(u64::MAX, &mut super::NoNative, &mut HostContext::new(None)).unwrap();
|
||||
// Includes the specified whole-instruction overshoot; this corpus uses scalar instructions.
|
||||
assert!(report.cycles_used <= VirtualMachine::LIFECYCLE_SLICE + 100);
|
||||
if report.reason != Reason::BudgetExhausted {
|
||||
assert_eq!(report.reason, expected); break;
|
||||
}
|
||||
let remaining = vm.lifecycle_remaining_cycles().unwrap();
|
||||
assert!(remaining < previous);
|
||||
assert_eq!(previous.saturating_sub(report.cycles_used), remaining);
|
||||
previous = remaining;
|
||||
}
|
||||
slices
|
||||
}
|
||||
|
||||
fn snapshot(fw: &mut Firmware, task: TaskId) -> (usize, u64, u64) {
|
||||
// The active foreground facade switches to the crash UI after failure.
|
||||
// Observe the retained game session so a foreground change cannot reset the oracle.
|
||||
let sessions = fw.os.sessions();
|
||||
let session = sessions.vm_session_for_task(task).unwrap();
|
||||
(session.vm.pc(), session.runtime.tick_index,
|
||||
session.runtime.atomic_telemetry.completed_logical_frames.load(std::sync::atomic::Ordering::Relaxed) as u64)
|
||||
}
|
||||
fn firmware(root: &Path, name: &str) -> (Firmware, TestPlatform, TaskId) {
|
||||
let mut fw = Firmware::new(None); let mut platform = TestPlatform::new();
|
||||
fw.load_cartridge(Cartridge {
|
||||
app_id: 86, title: "Studio PBS lifecycle".into(), app_version: "1.0.0".into(),
|
||||
app_mode: AppMode::Game, capabilities: super::caps::NONE, memcard_slots: None,
|
||||
program: bytes(root, name), assets: AssetsPayloadSource::empty(), asset_table: vec![], preload: vec![],
|
||||
});
|
||||
fw.tick(&InputSignals::default(), &mut platform);
|
||||
let task = fw.os.lifecycle().resident_game_task().unwrap();
|
||||
fw.tick(&InputSignals::default(), &mut platform);
|
||||
assert!(fw.os.vm().last_crash_report().is_none());
|
||||
(fw, platform, task)
|
||||
}
|
||||
fn foreground_case(root: &Path, name: &str, expected: i32, resume: bool) {
|
||||
let (mut fw, mut platform, task) = firmware(root, name);
|
||||
let signals = InputSignals::default();
|
||||
fw.request_home_from_host();
|
||||
fw.tick(&signals, &mut platform); // Existing Home handoff, including its gameplay reaction.
|
||||
let suspended = snapshot(&mut fw, task);
|
||||
fw.tick(&signals, &mut platform); // Hook only, or already-suspended case without a hook.
|
||||
assert_eq!(fw.os.lifecycle().task_state(task), Some(TaskState::Suspended), "{name}");
|
||||
assert_eq!(snapshot(&mut fw, task), suspended, "pause changed gameplay state: {name}");
|
||||
assert!(fw.resume_resident_game_from_home());
|
||||
if resume {
|
||||
fw.tick(&signals, &mut platform); // BeforeResume only.
|
||||
assert_eq!(snapshot(&mut fw, task), suspended, "resume changed gameplay state: {name}");
|
||||
}
|
||||
fw.tick(&signals, &mut platform); // First eligible gameplay frame validates guest stage/init/heap.
|
||||
assert!(fw.os.vm().last_crash_report().is_none(), "{name}");
|
||||
assert_eq!(snapshot(&mut fw, task).1, suspended.1 + 1);
|
||||
let actual = {
|
||||
let mut sessions = fw.os.sessions();
|
||||
let session = sessions.vm_session_for_task_mut(task).unwrap();
|
||||
// Terminal observation only, after all continuation/frame assertions; no later host tick.
|
||||
query(root, name, &mut session.vm)
|
||||
};
|
||||
assert_eq!(actual, expected, "ordered guest effects/init/heap: {name}");
|
||||
println!("FIRMWARE HOME/RESUME PASS {name}: pc={}, gameplayTicks={}, frames={}, guest={actual}", suspended.0, suspended.1, suspended.2);
|
||||
}
|
||||
|
||||
fn other_foreground_paths(root: &Path, name: &str) {
|
||||
for shell in [false, true] {
|
||||
let (mut fw, mut platform, task) = firmware(root, name);
|
||||
let before = snapshot(&mut fw, task);
|
||||
if shell { fw.os.sessions().try_create_native_shell_task(99, "Tools").unwrap(); }
|
||||
else { fw.os.lifecycle().suspend_task(task).unwrap(); }
|
||||
fw.tick(&InputSignals::default(), &mut platform);
|
||||
assert_eq!(fw.os.lifecycle().task_state(task), Some(TaskState::Suspended));
|
||||
assert_eq!(snapshot(&mut fw, task), before);
|
||||
println!("DIRECT/SHELL SUSPEND PASS {name}: shell={shell}, no reaction tick");
|
||||
}
|
||||
let mut vm = load(root, name);
|
||||
vm.prepare_boot_call().unwrap();
|
||||
let partial = vm.run_budget(1, &mut super::NoNative, &mut HostContext::new(None)).unwrap();
|
||||
assert_eq!(partial.reason, Reason::BudgetExhausted);
|
||||
assert!(!vm.call_stack_is_empty());
|
||||
let pc = vm.pc(); let stack = vm.operand_stack_top(1000).to_vec();
|
||||
assert!(!stack.is_empty(), "suspended wrapper must retain an operand");
|
||||
for role in [LifecycleRole::BeforePause, LifecycleRole::BeforeResume] {
|
||||
assert!(vm.begin_lifecycle(role).unwrap());
|
||||
finish_hook(&mut vm, Reason::LifecycleComplete);
|
||||
assert_eq!(vm.pc(), pc); assert_eq!(vm.operand_stack_top(1000).to_vec(), stack);
|
||||
assert!(!vm.call_stack_is_empty());
|
||||
}
|
||||
let resumed = vm.run_budget(100_000, &mut super::NoNative, &mut HostContext::new(None)).unwrap();
|
||||
assert!(matches!(resumed.reason, Reason::EndOfRom | Reason::Halted));
|
||||
assert_eq!(query(root, name, &mut vm), 230112);
|
||||
println!("SUSPENDED STACK/CONTINUATION PASS {name}: retained operand, frame and heap");
|
||||
}
|
||||
|
||||
pub fn verify(root: &Path) {
|
||||
for suffix in ["", "-optimized"] {
|
||||
for (case, expected, resume) in [("both", 230112, true), ("pause", 20109, false), ("resume", 30110, true), ("none", 107, false)] {
|
||||
let name = format!("pbs-lifecycle-{case}{suffix}");
|
||||
let mut vm = load(root, &name);
|
||||
for (role, present) in [(LifecycleRole::BeforePause, case == "both" || case == "pause"), (LifecycleRole::BeforeResume, resume)] {
|
||||
let pc = vm.pc(); let stack = vm.operand_stack_top(1000).to_vec();
|
||||
assert_eq!(vm.begin_lifecycle(role).unwrap(), present);
|
||||
if present {
|
||||
assert!(vm.begin_lifecycle(role).is_err(), "controlled calls cannot reenter");
|
||||
finish_hook(&mut vm, Reason::LifecycleComplete);
|
||||
}
|
||||
assert_eq!(vm.pc(), pc); assert_eq!(vm.operand_stack_top(1000).to_vec(), stack);
|
||||
}
|
||||
vm.prepare_boot_call().unwrap();
|
||||
let next = vm.run_budget(100_000, &mut super::NoNative, &mut HostContext::new(None)).unwrap();
|
||||
assert!(matches!(next.reason, Reason::Halted | Reason::EndOfRom));
|
||||
assert_eq!(query(root, &name, &mut vm), expected);
|
||||
foreground_case(root, &name, expected, resume);
|
||||
}
|
||||
other_foreground_paths(root, &format!("pbs-lifecycle-both{suffix}"));
|
||||
let name = format!("pbs-lifecycle-direct{suffix}");
|
||||
let mut vm = load(root, &name);
|
||||
assert!(!vm.lifecycle_active()); assert_eq!(query(root, &name, &mut vm), 230112);
|
||||
println!("ORDINARY CALL PASS {name}: no controlled invocation");
|
||||
|
||||
let name = format!("pbs-lifecycle-slices{suffix}");
|
||||
let mut vm = load(root, &name);
|
||||
vm.begin_lifecycle(LifecycleRole::BeforePause).unwrap();
|
||||
let hook_pc = vm.pc(); vm.insert_breakpoint(hook_pc);
|
||||
let remaining = vm.lifecycle_remaining_cycles();
|
||||
let stopped = vm.run_budget(250_000, &mut super::NoNative, &mut HostContext::new(None)).unwrap();
|
||||
assert_eq!(stopped.reason, Reason::Breakpoint); assert_eq!(stopped.cycles_used, 0);
|
||||
assert_eq!(vm.lifecycle_remaining_cycles(), remaining);
|
||||
vm.remove_breakpoint(hook_pc);
|
||||
vm.step(&mut super::NoNative, &mut HostContext::new(None)).unwrap();
|
||||
assert!(vm.lifecycle_remaining_cycles().unwrap() < remaining.unwrap());
|
||||
assert!(finish_hook(&mut vm, Reason::LifecycleComplete) > 1);
|
||||
println!("SLICES + DEBUGGER PASS {name}: one retained total fuel budget");
|
||||
|
||||
for case in ["trap", "fuel"] {
|
||||
let name = format!("pbs-lifecycle-{case}{suffix}");
|
||||
let mut vm = load(root, &name);
|
||||
vm.begin_lifecycle(LifecycleRole::BeforePause).unwrap();
|
||||
let mut slices = 0;
|
||||
let terminal = loop {
|
||||
slices += 1; assert!(slices < 16);
|
||||
let report = vm.run_budget(u64::MAX, &mut super::NoNative, &mut HostContext::new(None)).unwrap();
|
||||
if report.reason != Reason::BudgetExhausted { break report.reason; }
|
||||
};
|
||||
if case == "trap" { assert!(matches!(terminal, Reason::Trap(_))); }
|
||||
else { assert!(matches!(&terminal, Reason::Panic(text) if text.contains("lifecycle total cycle budget exhausted"))); assert!(slices > 1); }
|
||||
let blocked = vm.run_budget(1000, &mut super::NoNative, &mut HostContext::new(None)).unwrap();
|
||||
assert_eq!(blocked.reason, terminal); assert_eq!(blocked.steps_executed, 0);
|
||||
assert!(vm.prepare_boot_call().is_err());
|
||||
let (mut fw, mut platform, task) = firmware(root, &name);
|
||||
fw.request_home_from_host(); fw.tick(&InputSignals::default(), &mut platform);
|
||||
let before = snapshot(&mut fw, task);
|
||||
for _ in 0..16 {
|
||||
fw.tick(&InputSignals::default(), &mut platform);
|
||||
if matches!(fw.state, FirmwareState::AppCrashes(_)) { break; }
|
||||
}
|
||||
assert!(matches!(fw.state, FirmwareState::AppCrashes(_)), "{name}");
|
||||
assert_eq!(snapshot(&mut fw, task).1, before.1);
|
||||
assert_eq!(snapshot(&mut fw, task).2, before.2);
|
||||
println!("FATAL + GAMEPLAY BLOCK PASS {name}: {terminal:?}, slices={slices}");
|
||||
}
|
||||
}
|
||||
// These binaries are explicitly synthetic; no PBS sync surface is claimed.
|
||||
for case in ["direct", "transitive"] {
|
||||
let name = format!("synthetic-lifecycle-sync-{case}");
|
||||
let mut vm = load(root, &name);
|
||||
vm.begin_lifecycle(LifecycleRole::BeforePause).unwrap();
|
||||
let report = vm.run_budget(100_000, &mut super::NoNative, &mut HostContext::new(None)).unwrap();
|
||||
assert!(matches!(report.reason, Reason::Trap(_)), "{report:?}");
|
||||
let again = vm.run_budget(1000, &mut super::NoNative, &mut HostContext::new(None)).unwrap();
|
||||
assert_eq!(again.steps_executed, 0); assert_eq!(again.reason, report.reason);
|
||||
let (mut fw, mut platform, task) = firmware(root, &name);
|
||||
fw.request_home_from_host(); fw.tick(&InputSignals::default(), &mut platform);
|
||||
let before = snapshot(&mut fw, task);
|
||||
fw.tick(&InputSignals::default(), &mut platform);
|
||||
assert!(matches!(fw.state, FirmwareState::AppCrashes(_)));
|
||||
assert_eq!(snapshot(&mut fw, task).1, before.1); assert_eq!(snapshot(&mut fw, task).2, before.2);
|
||||
println!("SYNTHETIC SYNC REJECTION PASS {case}: no gameplay/frame publication");
|
||||
}
|
||||
let name = "pbs-lifecycle-imports";
|
||||
let mut vm = load(root, name);
|
||||
assert!(vm.begin_lifecycle(LifecycleRole::BeforePause).unwrap());
|
||||
finish_hook(&mut vm, Reason::LifecycleComplete);
|
||||
assert!(!vm.has_lifecycle_hook(LifecycleRole::BeforeResume));
|
||||
println!("PRODUCTION PIPELINE IMPORTS PASS: alias/reexport selected one original hook");
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,533 +0,0 @@
|
||||
//! Native production Firmware/SystemOS evidence; never a claim about the installed process protocol.
|
||||
use prometeu_drivers::{TestPlatform, memcard::FileMemcard};
|
||||
use prometeu_firmware::firmware::{Firmware, FirmwareState};
|
||||
use prometeu_hal::{
|
||||
InputSignals,
|
||||
app_mode::AppMode,
|
||||
cartridge::{AssetsPayloadSource, Cartridge},
|
||||
memcard::{MemcardIoError, MemcardStorage},
|
||||
};
|
||||
use prometeu_system::memcard::{
|
||||
admission::PreparationState,
|
||||
image::IMAGE_BYTES,
|
||||
session::{Mode, RequestState},
|
||||
transaction::Card,
|
||||
};
|
||||
use std::{
|
||||
path::Path,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
const APP: u32 = 1296387395;
|
||||
const PAYLOAD: [u8; 4] = [0, 127, 128, 255];
|
||||
fn fresh(path: &Path) -> FileMemcard {
|
||||
FileMemcard::create(path, IMAGE_BYTES, |io, id| {
|
||||
Card::format(io, id).map_err(|_| MemcardIoError::IoError)
|
||||
})
|
||||
.unwrap()
|
||||
}
|
||||
fn start(
|
||||
root: &Path,
|
||||
name: &str,
|
||||
storage: Option<Box<dyn MemcardStorage>>,
|
||||
choice: InputSignals,
|
||||
) -> (Firmware, TestPlatform) {
|
||||
start_slots(root, name, storage, choice, 1)
|
||||
}
|
||||
fn start_slots(
|
||||
root: &Path,
|
||||
name: &str,
|
||||
storage: Option<Box<dyn MemcardStorage>>,
|
||||
choice: InputSignals,
|
||||
slots: u8,
|
||||
) -> (Firmware, TestPlatform) {
|
||||
let mut fw = Firmware::new(None);
|
||||
let mut platform = TestPlatform::new();
|
||||
fw.os.poll_background_io(&mut platform);
|
||||
if let Some(storage) = storage {
|
||||
fw.os.memcard().mount_card(storage).unwrap();
|
||||
let deadline = Instant::now() + Duration::from_secs(5);
|
||||
while !fw.os.memcard().card_installed() {
|
||||
fw.os.poll_background_io(&mut platform);
|
||||
assert!(
|
||||
!matches!(fw.os.memcard().admission.state, PreparationState::Failed(_)),
|
||||
"mount failed: {:?}",
|
||||
fw.os.memcard().admission.state
|
||||
);
|
||||
assert!(Instant::now() < deadline);
|
||||
std::thread::sleep(Duration::from_millis(1));
|
||||
}
|
||||
}
|
||||
fw.load_cartridge(Cartridge {
|
||||
app_id: APP,
|
||||
title: "Studio memcard".into(),
|
||||
app_version: "1".into(),
|
||||
app_mode: AppMode::Game,
|
||||
capabilities: super::caps::MEMCARD,
|
||||
memcard_slots: Some(slots),
|
||||
program: std::fs::read(root.join(format!("{name}.pbx"))).unwrap(),
|
||||
assets: AssetsPayloadSource::empty(),
|
||||
asset_table: vec![],
|
||||
preload: vec![],
|
||||
});
|
||||
fw.tick(&InputSignals::default(), &mut platform);
|
||||
fw.tick(&choice, &mut platform);
|
||||
(fw, platform)
|
||||
}
|
||||
fn run(fw: &mut Firmware, platform: &mut TestPlatform, frames: usize) {
|
||||
for _ in 0..frames {
|
||||
fw.tick(&InputSignals::default(), platform);
|
||||
assert!(
|
||||
!matches!(fw.state, FirmwareState::AppCrashes(_)),
|
||||
"guest crashed: {:?}",
|
||||
fw.state
|
||||
);
|
||||
std::thread::sleep(Duration::from_millis(1));
|
||||
}
|
||||
let deadline = Instant::now() + Duration::from_secs(2);
|
||||
while worker_pending(fw) {
|
||||
assert!(Instant::now() < deadline, "native worker did not settle");
|
||||
fw.tick(&InputSignals::default(), platform);
|
||||
assert!(
|
||||
!matches!(fw.state, FirmwareState::AppCrashes(_)),
|
||||
"guest crashed: {:?}",
|
||||
fw.state
|
||||
);
|
||||
std::thread::sleep(Duration::from_millis(1));
|
||||
}
|
||||
}
|
||||
fn worker_pending(fw: &mut Firmware) -> bool {
|
||||
let mem = fw.os.memcard();
|
||||
let telemetry = mem.lane.telemetry();
|
||||
let context = mem.session.context();
|
||||
mem.admission.state == PreparationState::Pending
|
||||
|| telemetry.active_job_id.is_some()
|
||||
|| telemetry.pending_depth != 0
|
||||
|| (1..=8).any(|id| {
|
||||
mem.session
|
||||
.query(context, id)
|
||||
.is_ok_and(|r| r.state == RequestState::Pending)
|
||||
})
|
||||
}
|
||||
fn assert_ram(fw: &mut Firmware, dirty: bool) {
|
||||
let session = &mut fw.os.memcard().session;
|
||||
let context = session.context();
|
||||
let mut bytes = [0; 4];
|
||||
assert_eq!(session.read(context, 0, 0, &mut bytes).unwrap(), 4);
|
||||
assert_eq!(bytes, PAYLOAD);
|
||||
assert_eq!(session.descriptor(context, 0).unwrap().2, dirty);
|
||||
}
|
||||
struct Fault {
|
||||
inner: FileMemcard,
|
||||
kind: u8,
|
||||
payload: bool,
|
||||
}
|
||||
impl MemcardStorage for Fault {
|
||||
fn len(&self) -> Result<u64, MemcardIoError> {
|
||||
self.inner.len()
|
||||
}
|
||||
fn read_only(&self) -> bool {
|
||||
self.inner.read_only()
|
||||
}
|
||||
fn read_at(&mut self, o: u64, b: &mut [u8]) -> Result<(), MemcardIoError> {
|
||||
self.inner.read_at(o, b)
|
||||
}
|
||||
fn write_at(&mut self, o: u64, b: &[u8]) -> Result<(), MemcardIoError> {
|
||||
if o >= 802816 {
|
||||
self.payload = true;
|
||||
if self.kind == 1 {
|
||||
return Err(MemcardIoError::IoError);
|
||||
}
|
||||
}
|
||||
self.inner.write_at(o, b)?;
|
||||
if self.kind == 2 && self.payload && (o == 8192 || o == 12288) {
|
||||
self.inner.sync()?;
|
||||
return Err(MemcardIoError::IoError);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn sync(&mut self) -> Result<(), MemcardIoError> {
|
||||
self.inner.sync()
|
||||
}
|
||||
}
|
||||
pub fn verify(root: &Path) {
|
||||
let work = std::env::temp_dir().join(format!("studio-memcard-native-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&work).unwrap();
|
||||
let abi = std::fs::read(root.join("pbs-memcard-abi.pbx")).unwrap();
|
||||
super::ValidatedProgramImage::load(
|
||||
&abi,
|
||||
&mut super::LoadBudget::new(Default::default()),
|
||||
super::caps::MEMCARD,
|
||||
)
|
||||
.unwrap();
|
||||
println!("NATIVE LOAD PASS all 14 mem imports against the production loader");
|
||||
for suffix in ["", "-optimized"] {
|
||||
let name = format!("pbs-memcard-example{suffix}");
|
||||
let path = work.join(format!("save{suffix}.pmc"));
|
||||
let (mut fw, mut p) = start(
|
||||
root,
|
||||
&name,
|
||||
Some(Box::new(fresh(&path))),
|
||||
InputSignals {
|
||||
a_signal: true,
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
run(&mut fw, &mut p, 100);
|
||||
assert_ram(&mut fw, false);
|
||||
assert_eq!(fw.os.memcard().session.mode(), Some(Mode::Persistent));
|
||||
drop(fw);
|
||||
let mut card = Card::mount(Box::new(FileMemcard::open(&path, false).unwrap())).unwrap();
|
||||
let slot = card
|
||||
.catalog
|
||||
.games
|
||||
.iter()
|
||||
.find(|g| g.app_id == APP)
|
||||
.unwrap()
|
||||
.slots[0] as usize;
|
||||
let generation = card.current().slots[slot].generation;
|
||||
let mut bytes = [0; 4];
|
||||
assert_eq!(card.read_slot(slot, &mut bytes).unwrap(), 4);
|
||||
assert_eq!(bytes, PAYLOAD);
|
||||
drop(card);
|
||||
let (mut reopened, mut p) = start(
|
||||
root,
|
||||
&name,
|
||||
Some(Box::new(FileMemcard::open(&path, false).unwrap())),
|
||||
InputSignals {
|
||||
a_signal: true,
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
run(&mut reopened, &mut p, 100);
|
||||
assert_ram(&mut reopened, false);
|
||||
drop(reopened);
|
||||
let card = Card::mount(Box::new(FileMemcard::open(&path, false).unwrap())).unwrap();
|
||||
assert_eq!(
|
||||
card.current().slots[slot].generation,
|
||||
generation,
|
||||
"reopen must read, not resave"
|
||||
);
|
||||
drop(card);
|
||||
let (mut memory, mut p) = start(
|
||||
root,
|
||||
&name,
|
||||
None,
|
||||
InputSignals {
|
||||
x_signal: true,
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
run(&mut memory, &mut p, 100);
|
||||
assert_ram(&mut memory, true);
|
||||
assert_eq!(memory.os.memcard().session.mode(), Some(Mode::MemoryOnly));
|
||||
memory.request_home_from_host();
|
||||
run(&mut memory, &mut p, 4);
|
||||
assert!(memory.resume_resident_game_from_home());
|
||||
run(&mut memory, &mut p, 4);
|
||||
assert_ram(&mut memory, true);
|
||||
println!(
|
||||
"NATIVE PASS {name}: exact save/reopen, no resave, memory-only; not installed-process evidence"
|
||||
);
|
||||
let name = format!("pbs-memcard-contract{suffix}");
|
||||
let path = work.join(format!("contract{suffix}.pmc"));
|
||||
let (mut contract, mut p) = start(
|
||||
root,
|
||||
&name,
|
||||
Some(Box::new(fresh(&path))),
|
||||
InputSignals {
|
||||
a_signal: true,
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
run(&mut contract, &mut p, 100);
|
||||
assert_ram(&mut contract, false);
|
||||
println!(
|
||||
"NATIVE PASS {name}: zero initialization, aliases, ordinary-array vacancy, domain errors/status-first Null payloads"
|
||||
);
|
||||
let name = format!("pbs-memcard-alias{suffix}");
|
||||
let (mut alias, mut p) = start(
|
||||
root,
|
||||
&name,
|
||||
None,
|
||||
InputSignals {
|
||||
x_signal: true,
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
run(&mut alias, &mut p, 100);
|
||||
assert_ram(&mut alias, true);
|
||||
println!(
|
||||
"NATIVE PASS {name}: imported type/service aliases retain native carrier and forwarding"
|
||||
);
|
||||
let name = format!("pbs-memcard-imports{suffix}");
|
||||
let (mut imports, mut p) = start(
|
||||
root,
|
||||
&name,
|
||||
None,
|
||||
InputSignals {
|
||||
x_signal: true,
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
run(&mut imports, &mut p, 100);
|
||||
let context = imports.os.memcard().session.context();
|
||||
assert_eq!(
|
||||
imports
|
||||
.os
|
||||
.memcard()
|
||||
.session
|
||||
.presentation(context)
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.title,
|
||||
"Imported hook"
|
||||
);
|
||||
println!(
|
||||
"NATIVE PASS {name}: one canonical imported role, initialized dependencies, retained target"
|
||||
);
|
||||
let name = format!("pbs-memcard-busy{suffix}");
|
||||
let path = work.join(format!("busy{suffix}.pmc"));
|
||||
let (mut busy, mut p) = start(
|
||||
root,
|
||||
&name,
|
||||
Some(Box::new(fresh(&path))),
|
||||
InputSignals {
|
||||
a_signal: true,
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
run(&mut busy, &mut p, 100);
|
||||
assert_ram(&mut busy, false);
|
||||
println!("NATIVE PASS {name}: committing source rejects write/clear/second commit");
|
||||
let name = format!("pbs-memcard-clear{suffix}");
|
||||
let path = work.join(format!("clear{suffix}.pmc"));
|
||||
let (mut clear, mut p) = start(
|
||||
root,
|
||||
&name,
|
||||
Some(Box::new(fresh(&path))),
|
||||
InputSignals {
|
||||
a_signal: true,
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
run(&mut clear, &mut p, 100);
|
||||
let context = clear.os.memcard().session.context();
|
||||
let (descriptor, used, dirty) = clear.os.memcard().session.descriptor(context, 0).unwrap();
|
||||
assert_eq!(used, 0);
|
||||
assert_eq!(descriptor.generation, 2);
|
||||
assert!(!dirty);
|
||||
drop(clear);
|
||||
let mut card = Card::mount(Box::new(FileMemcard::open(&path, false).unwrap())).unwrap();
|
||||
let slot = card
|
||||
.catalog
|
||||
.games
|
||||
.iter()
|
||||
.find(|g| g.app_id == APP)
|
||||
.unwrap()
|
||||
.slots[0] as usize;
|
||||
assert_eq!(card.read_slot(slot, &mut [0; 4]).unwrap(), 0);
|
||||
println!("NATIVE PASS {name}: explicit clear commit survives remount");
|
||||
let name = format!("pbs-memcard-publish{suffix}");
|
||||
let path = work.join(format!("publish{suffix}.pmc"));
|
||||
let (mut public, mut p) = start(
|
||||
root,
|
||||
&name,
|
||||
Some(Box::new(fresh(&path))),
|
||||
InputSignals {
|
||||
a_signal: true,
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
run(&mut public, &mut p, 100);
|
||||
assert_ram(&mut public, false);
|
||||
let context = public.os.memcard().session.context();
|
||||
let result = (1..=8)
|
||||
.find_map(|id| public.os.memcard().session.query(context, id).ok())
|
||||
.unwrap();
|
||||
assert_eq!(result.state, RequestState::Success);
|
||||
drop(public);
|
||||
let mut card = Card::mount(Box::new(FileMemcard::open(&path, false).unwrap())).unwrap();
|
||||
let game = card.catalog.games.iter().find(|g| g.app_id == APP).unwrap();
|
||||
assert_eq!(game.title, "Updated presentation");
|
||||
assert_eq!(game.data_format_version, 2);
|
||||
assert_eq!(card.read_icon(APP).unwrap(), vec![0; 560]);
|
||||
println!("NATIVE PASS {name}: public title/format/icon publication and retained request");
|
||||
let name = format!("pbs-memcard-transfer-limit{suffix}");
|
||||
let (mut transfer, mut p) = start(
|
||||
root,
|
||||
&name,
|
||||
None,
|
||||
InputSignals {
|
||||
x_signal: true,
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
run(&mut transfer, &mut p, 100);
|
||||
let session = &mut transfer.os.memcard().session;
|
||||
let context = session.context();
|
||||
assert_eq!(session.descriptor(context, 0).unwrap().1, 4096);
|
||||
let mut last = [0];
|
||||
assert_eq!(session.read(context, 0, 4095, &mut last).unwrap(), 1);
|
||||
assert_eq!(last, [255]);
|
||||
println!("NATIVE PASS {name}: exact 4096-byte transfer and byte 255");
|
||||
let name = format!("pbs-memcard-example{suffix}");
|
||||
let (mut full, mut p) = start_slots(
|
||||
root,
|
||||
&name,
|
||||
None,
|
||||
InputSignals {
|
||||
x_signal: true,
|
||||
..Default::default()
|
||||
},
|
||||
64,
|
||||
);
|
||||
run(&mut full, &mut p, 100);
|
||||
assert_eq!(full.os.memcard().session.count(), 64);
|
||||
assert_ram(&mut full, true);
|
||||
println!("NATIVE PASS {name}: 64-slot admission");
|
||||
}
|
||||
for (kind, expected) in [(1, RequestState::Failure), (2, RequestState::Indeterminate)] {
|
||||
for suffix in ["", "-optimized"] {
|
||||
let path = work.join(format!("fault-{kind}{suffix}.pmc"));
|
||||
let fault = Fault {
|
||||
inner: fresh(&path),
|
||||
kind,
|
||||
payload: false,
|
||||
};
|
||||
let (mut fw, mut p) = start(
|
||||
root,
|
||||
&format!("pbs-memcard-retained{suffix}"),
|
||||
Some(Box::new(fault)),
|
||||
InputSignals {
|
||||
a_signal: true,
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
run(&mut fw, &mut p, 100);
|
||||
let session = &mut fw.os.memcard().session;
|
||||
let context = session.context();
|
||||
let result = (1..=8)
|
||||
.find_map(|id| session.query(context, id).ok())
|
||||
.expect("one retained guest request");
|
||||
assert_eq!(result.state, expected);
|
||||
assert!(session.descriptor(context, 0).unwrap().2);
|
||||
println!(
|
||||
"NATIVE PASS PBS facade query{suffix}: {expected:?}, request {}, dirty RAM preserved",
|
||||
result.id
|
||||
);
|
||||
}
|
||||
}
|
||||
for name in [
|
||||
"pbs-memcard-inconsistent",
|
||||
"pbs-memcard-trap",
|
||||
"pbs-memcard-fuel",
|
||||
"pbs-memcard-capacity-negative",
|
||||
"pbs-memcard-capacity-overflow",
|
||||
"pbs-memcard-read-bounds",
|
||||
"pbs-memcard-write-bounds",
|
||||
"pbs-memcard-byte-negative",
|
||||
"pbs-memcard-byte-overflow",
|
||||
"pbs-memcard-transfer-overflow",
|
||||
] {
|
||||
for suffix in ["", "-optimized"] {
|
||||
let name = format!("{name}{suffix}");
|
||||
let (mut fw, mut p) = start(
|
||||
root,
|
||||
&name,
|
||||
None,
|
||||
InputSignals {
|
||||
x_signal: true,
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
for _ in 0..150 {
|
||||
fw.tick(&InputSignals::default(), &mut p);
|
||||
if matches!(fw.state, FirmwareState::AppCrashes(_)) {
|
||||
break;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(1));
|
||||
}
|
||||
assert!(
|
||||
matches!(fw.state, FirmwareState::AppCrashes(_)),
|
||||
"{name} must block admission"
|
||||
);
|
||||
if let Some(task) = fw.os.lifecycle().resident_game_task() {
|
||||
let sessions = fw.os.sessions();
|
||||
let session = sessions.vm_session_for_task(task).unwrap();
|
||||
assert_eq!(
|
||||
session
|
||||
.runtime
|
||||
.atomic_telemetry
|
||||
.completed_logical_frames
|
||||
.load(std::sync::atomic::Ordering::Relaxed),
|
||||
0
|
||||
);
|
||||
}
|
||||
println!("NATIVE PASS {name}: trap/failure, no completed gameplay frame");
|
||||
}
|
||||
}
|
||||
let path = work.join("readonly.pmc");
|
||||
drop(fresh(&path));
|
||||
for storage in [
|
||||
None,
|
||||
Some(Box::new(FileMemcard::open(&path, true).unwrap()) as Box<dyn MemcardStorage>),
|
||||
] {
|
||||
let (mut fw, mut p) = start(
|
||||
root,
|
||||
"pbs-memcard-example",
|
||||
storage,
|
||||
InputSignals {
|
||||
a_signal: true,
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
run(&mut fw, &mut p, 20);
|
||||
assert!(matches!(fw.state, FirmwareState::LoadCartridge(_)));
|
||||
assert_eq!(
|
||||
fw.os.memcard().session.mode(),
|
||||
None,
|
||||
"must not silently fall back to RAM"
|
||||
);
|
||||
}
|
||||
println!("NATIVE PASS absent/read-only: explicit choice retained; no memory fallback");
|
||||
let corrupt = work.join("corrupt.pmc");
|
||||
drop(fresh(&corrupt));
|
||||
let mut bytes = std::fs::read(&corrupt).unwrap();
|
||||
bytes[8192..16384].fill(0);
|
||||
std::fs::write(&corrupt, &bytes).unwrap();
|
||||
let mut fw = Firmware::new(None);
|
||||
let mut p = TestPlatform::new();
|
||||
fw.os.poll_background_io(&mut p);
|
||||
fw.os
|
||||
.memcard()
|
||||
.mount_card(Box::new(FileMemcard::open(&corrupt, false).unwrap()))
|
||||
.unwrap();
|
||||
let deadline = Instant::now() + Duration::from_secs(2);
|
||||
while fw.os.memcard().admission.state == PreparationState::Pending {
|
||||
fw.os.poll_background_io(&mut p);
|
||||
assert!(Instant::now() < deadline);
|
||||
std::thread::sleep(Duration::from_millis(1));
|
||||
}
|
||||
assert_eq!(
|
||||
fw.os.memcard().admission.state,
|
||||
PreparationState::Failed(prometeu_system::memcard::image::Error::Corrupt)
|
||||
);
|
||||
assert_eq!(std::fs::read(&corrupt).unwrap(), bytes);
|
||||
println!("NATIVE PASS corrupt media: rejected without replacing with empty data");
|
||||
let (mut installed, mut p) = start(
|
||||
root,
|
||||
"pbs-memcard-installed",
|
||||
None,
|
||||
InputSignals {
|
||||
x_signal: true,
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
run(&mut installed, &mut p, 100);
|
||||
assert_ram(&mut installed, true);
|
||||
println!(
|
||||
"NATIVE PASS installed-JAR PBS example: native Firmware/SystemOS execution, not installed runtime process"
|
||||
);
|
||||
std::fs::remove_dir_all(work).unwrap();
|
||||
}
|
||||
@@ -1,56 +0,0 @@
|
||||
//! PBS result groups execute on the unchanged production loader and VM.
|
||||
use super::*;
|
||||
use prometeu_vm::LogicalFrameEndingReason as End;
|
||||
use prometeu_bytecode::{decode_next, isa::core::CoreOpCode as Op};
|
||||
|
||||
pub fn verify(root: &std::path::Path) {
|
||||
let cases = [
|
||||
("unit-ok", vec![Value::Int32(0)]),
|
||||
("unit-err", vec![Value::Int32(2)]),
|
||||
("scalar", vec![Value::Int32(0), Value::Int32(42)]),
|
||||
("error", vec![Value::Int32(1), Value::Int64(0)]),
|
||||
("tuple", vec![Value::Int32(0), Value::Int64(9_007_199_254_740_993), Value::Int32(42)]),
|
||||
("reference", vec![Value::Int32(2), Value::Null]),
|
||||
("propagate", vec![Value::Int32(2), Value::Int64(0), Value::Null]),
|
||||
("nested", vec![Value::Int32(2), Value::Int32(0)]),
|
||||
("recover", vec![Value::Int32(0), Value::Int32(42)]),
|
||||
("remap", vec![Value::Int32(2), Value::Int32(0)]),
|
||||
("success", vec![Value::Int32(0), Value::Int32(42)]),
|
||||
("trait", vec![Value::Int32(1), Value::Null, Value::Null]),
|
||||
("fn", vec![Value::Int32(1), Value::Null]),
|
||||
("once", vec![Value::Int32(0), Value::Int32(42)]),
|
||||
("block-remap", vec![Value::Int32(2), Value::Int32(0)]),
|
||||
("reference-ok", vec![Value::Int32(0), Value::Int32(42)]),
|
||||
("fn-ok", vec![Value::Int32(0), Value::Int32(42)]),
|
||||
("trait-ok", vec![Value::Int32(0), Value::Int32(42)]),
|
||||
("color-ok", vec![Value::Int32(0), Value::Int64(42)]),
|
||||
("color-err", vec![Value::Int32(1), Value::Int64(0)]),
|
||||
("trap", vec![]),
|
||||
];
|
||||
let manifest = std::fs::read_to_string(root.join("pbs-result-manifest.txt")).expect("mandatory result manifest");
|
||||
assert_eq!(manifest.lines().count(), cases.len() * 2);
|
||||
for (name, expected) in cases { for suffix in ["", "-optimized"] {
|
||||
let bytes = std::fs::read(root.join(format!("pbs-result-{name}{suffix}.pbx"))).expect("mandatory result fixture");
|
||||
let image = ValidatedProgramImage::load(&bytes, &mut LoadBudget::new(LoadLimits::default()), caps::NONE)
|
||||
.unwrap_or_else(|e| panic!("result/{name}{suffix}: load {e:?}"));
|
||||
let mut vm = VirtualMachine::from_image(image.clone(), Default::default());
|
||||
vm.prepare_boot_call().unwrap();
|
||||
let mut allocations = 0;
|
||||
let mut trapped=false;
|
||||
for step in 0..100_000 {
|
||||
let instruction = decode_next(vm.pc(), image.code()).unwrap();
|
||||
if matches!(instruction.opcode, Op::StructNew | Op::ArrayNew | Op::MakeClosure) { allocations += 1; }
|
||||
let report = vm.run_budget(1, &mut NoNative, &mut HostContext::new(None))
|
||||
.unwrap_or_else(|e| panic!("result/{name}{suffix}: run {e:?}"));
|
||||
if matches!(report.reason, End::Trap(_)) && name=="trap" { trapped=true;break; }
|
||||
if matches!(report.reason, End::Halted | End::EndOfRom) { break; }
|
||||
assert!(matches!(report.reason, End::BudgetExhausted), "result/{name}{suffix}: {report:?}");
|
||||
assert!(step < 99_999, "result failed to terminate");
|
||||
}
|
||||
if name=="trap" { assert!(trapped,"handle must not recover a VM trap");println!("RESULT TRAP PASS {suffix}");continue; }
|
||||
assert_eq!(vm.operand_stack_top(expected.len()).iter().rev().cloned().collect::<Vec<_>>(), expected, "result/{name}{suffix}");
|
||||
if matches!(name,"reference-ok"|"fn-ok"|"trait-ok") { assert!(allocations>0,"successful payload is constructed"); }
|
||||
else { assert_eq!(allocations, 0, "result/{name}{suffix}: no holder or inactive payload allocations"); }
|
||||
println!("RESULT PASS {name}{suffix} group={expected:?} executed_allocations={allocations}");
|
||||
} }
|
||||
}
|
||||
@@ -1,80 +0,0 @@
|
||||
"""Build a production-loader harness without writing into the runtime checkout."""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import pathlib
|
||||
import platform
|
||||
import subprocess
|
||||
import tempfile
|
||||
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--runtime", type=pathlib.Path, default=pathlib.Path("../runtime"))
|
||||
parser.add_argument("--fixtures", type=pathlib.Path, default=pathlib.Path("prometeu-compiler/prometeu-build-pipeline/build/registry-conformance"))
|
||||
parser.add_argument("--online", action="store_true", help="Allow Cargo to fetch uncached dependencies")
|
||||
parser.add_argument("--animation-only", action="store_true", help="Run mandatory PBS core animation corpus")
|
||||
parser.add_argument("--result-only", action="store_true", help="Run mandatory PBS result return-group corpus")
|
||||
parser.add_argument("--memcard-only", action="store_true", help="Run PBS memcard through production Firmware/SystemOS (native, not installed process)")
|
||||
parser.add_argument("--lifecycle-only", action="store_true", help="Run PBS guest lifecycle VM and production firmware corpus")
|
||||
parser.add_argument("--release", action="store_true", help="Execute an optimized runtime harness")
|
||||
parser.add_argument("--set-only", action="store_true", help="Run mandatory PBS Set corpus")
|
||||
parser.add_argument("--map-only", action="store_true", help="Run mandatory PBS Map/Keyval corpus")
|
||||
parser.add_argument("--stack-queue-only", action="store_true", help="Run mandatory PBS Stack/Queue corpus")
|
||||
parser.add_argument("--identity-hashing-only", action="store_true", help="Run mandatory neutral and PBS identity/hash corpus")
|
||||
parser.add_argument("--math-only", action="store_true", help="Run the complete PBS math corpus only")
|
||||
parser.add_argument("--random-only", action="store_true", help="Run the complete PBS Random corpus only")
|
||||
parser.add_argument("--generic-contracts-only", action="store_true", help="Run the mandatory generic-contract source corpus only")
|
||||
parser.add_argument("--linked-only", action="store_true", help="Run mandatory SDK Linked corpus only")
|
||||
parser.add_argument("--list-cursor-only", action="store_true", help="Run the mandatory SDK List/Cursor corpus only")
|
||||
parser.add_argument("--generic-structs-only", action="store_true", help="Run the mandatory generic-struct/function source corpus only")
|
||||
args = parser.parse_args()
|
||||
runtime = args.runtime.resolve()
|
||||
if not args.math_only:
|
||||
provider_vectors = runtime / "crates/console/prometeu-vm/tests/fixtures/random-conformance.tsv"
|
||||
consumer_vectors = pathlib.Path("prometeu-architecture-tests/src/test/resources/random/random-conformance.tsv")
|
||||
if provider_vectors.read_bytes() != consumer_vectors.read_bytes():
|
||||
raise SystemExit("Random oracle differs from the selected provider; update provenance and requalify")
|
||||
provider_hash_vectors = runtime / "crates/console/prometeu-vm/tests/fixtures/hash-conformance.tsv"
|
||||
consumer_hash_vectors = pathlib.Path("prometeu-architecture-tests/src/test/resources/hash/hash-conformance.tsv")
|
||||
if provider_hash_vectors.read_bytes() != consumer_hash_vectors.read_bytes():
|
||||
raise SystemExit("Hash oracle differs from selected provider")
|
||||
print(subprocess.check_output(["rustc", "-Vv"], text=True).strip(), flush=True)
|
||||
for source in [pathlib.Path(__file__), pathlib.Path(__file__).with_name("main.rs"),
|
||||
pathlib.Path(__file__).with_name("stack_queue.rs"),
|
||||
pathlib.Path(__file__).with_name("lifecycle.rs"),
|
||||
pathlib.Path(__file__).with_name("memcard.rs"),
|
||||
pathlib.Path("prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsMemcardTest.java"),
|
||||
pathlib.Path("prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/game/stdlib/1/sdk/mem/main.pbs"),
|
||||
pathlib.Path("prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsGuestLifecycleTest.java"),
|
||||
pathlib.Path("prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsStackQueueTest.java"),
|
||||
pathlib.Path("prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsRuntimeRandomTest.java"),
|
||||
pathlib.Path("prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/game/stdlib/1/sdk/random/main.pbs")]:
|
||||
print("sha256", source, hashlib.sha256(source.read_bytes()).hexdigest(), flush=True)
|
||||
print("studio", subprocess.check_output(["git", "rev-parse", "HEAD"], text=True).strip(), flush=True)
|
||||
print("runtime", subprocess.check_output(["git", "-C", str(runtime), "rev-parse", "HEAD"], text=True).strip(), flush=True)
|
||||
print("runtime working tree", subprocess.check_output(["git","-C",str(runtime),"status","--short"],text=True).strip() or "clean",flush=True)
|
||||
for source in [pathlib.Path("prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsListCursorTest.java"),
|
||||
pathlib.Path("prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsLinkedTest.java"),
|
||||
pathlib.Path("prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/game/stdlib/1/sdk/collections/main.pbs"),
|
||||
runtime / "crates/console/prometeu-vm/src/virtual_machine/array_copy.rs"]:
|
||||
print("sha256",source,hashlib.sha256(source.read_bytes()).hexdigest(),flush=True)
|
||||
print("platform", platform.platform(), "limits=default", "capabilities=MEMCARD" if args.memcard_only else "capabilities=NONE", flush=True)
|
||||
print("profile", "release" if args.release else "dev", "features=resource-diagnostics", flush=True)
|
||||
for relative in ["Cargo.lock", "docs/vm-arch/INTRINSICS.csv", "docs/vm-arch/BUILTIN_CONSTANTS.csv", "crates/console/prometeu-vm/tests/fixtures/numeric-conformance.tsv", "crates/console/prometeu-vm/tests/fixtures/random-conformance.tsv"]:
|
||||
print("sha256", relative, hashlib.sha256((runtime / relative).read_bytes()).hexdigest(), flush=True)
|
||||
with tempfile.TemporaryDirectory(prefix="pbx-conformance-") as directory:
|
||||
root = pathlib.Path(directory)
|
||||
manifest = '[package]\nname="studio-pbx-conformance"\nversion="0.1.0"\nedition="2024"\n[dependencies]\n'
|
||||
for crate in ["prometeu-bytecode", "prometeu-hal", "prometeu-vm", "prometeu-system", "prometeu-firmware", "prometeu-drivers"]:
|
||||
features = ',features=["resource-diagnostics"]' if crate == "prometeu-vm" else ''
|
||||
manifest += f'{crate}={{path={json.dumps(str(runtime / "crates/console" / crate))}{features}}}\n'
|
||||
manifest += 'serde_json="1.0.149"\njsonschema={version="0.33",default-features=false}\n'
|
||||
(root / "Cargo.toml").write_text(manifest)
|
||||
(root / "Cargo.lock").write_text((runtime / "Cargo.lock").read_text())
|
||||
(root / "src").mkdir()
|
||||
(root / "src/main.rs").write_text(pathlib.Path(__file__).with_name("main.rs").read_text())
|
||||
(root / "src/stack_queue.rs").write_text(pathlib.Path(__file__).with_name("stack_queue.rs").read_text())
|
||||
(root / "src/animation.rs").write_text(pathlib.Path(__file__).with_name("animation.rs").read_text())
|
||||
(root / "src/result.rs").write_text(pathlib.Path(__file__).with_name("result.rs").read_text())
|
||||
(root / "src/memcard.rs").write_text(pathlib.Path(__file__).with_name("memcard.rs").read_text())
|
||||
(root / "src/lifecycle.rs").write_text(pathlib.Path(__file__).with_name("lifecycle.rs").read_text())
|
||||
subprocess.run(["cargo", "run", *(["--release"] if args.release else []), *([] if args.online else ["--offline"]), "--manifest-path", str(root / "Cargo.toml"), "--", str(args.fixtures.resolve()), str(runtime / "devtools/headless-protocol/response.schema.json"), *(["--animation-only"] if args.animation_only else []), *(["--result-only"] if args.result_only else []), *(["--memcard-only"] if args.memcard_only else []), *(["--lifecycle-only"] if args.lifecycle_only else []), *(["--stack-queue-only"] if args.stack_queue_only else []), *(["--map-only"] if args.map_only else []), *(["--set-only"] if args.set_only else []), *(["--identity-hashing-only"] if args.identity_hashing_only else []), *(["--math-only"] if args.math_only else []), *(["--random-only"] if args.random_only else []), *(["--generic-contracts-only"] if args.generic_contracts_only else []), *(["--generic-structs-only"] if args.generic_structs_only else []), *(["--list-cursor-only"] if args.list_cursor_only else []), *(["--linked-only"] if args.linked_only else [])], check=True)
|
||||
@@ -1,570 +0,0 @@
|
||||
//! Real PBS Stack/Queue qualification against the unchanged production provider.
|
||||
use super::*;
|
||||
use prometeu_bytecode::{TRAP_RESOURCE_LIMIT, decode_next, isa::core::CoreOpCode as Op};
|
||||
use prometeu_vm::{
|
||||
LogicalFrameEndingReason as End,
|
||||
resource_budget::{RuntimeLimits, RuntimeResource as Q},
|
||||
resource_diagnostics::{StorageObject, StorageValue as V},
|
||||
};
|
||||
|
||||
fn load(
|
||||
root: &std::path::Path,
|
||||
collection: &str,
|
||||
name: &str,
|
||||
suffix: &str,
|
||||
) -> std::sync::Arc<ValidatedProgramImage> {
|
||||
let path = root.join(format!("pbs-{collection}-{name}{suffix}.pbx"));
|
||||
let bytes =
|
||||
std::fs::read(&path).unwrap_or_else(|e| panic!("mandatory {}: {e}", path.display()));
|
||||
ValidatedProgramImage::load(
|
||||
&bytes,
|
||||
&mut LoadBudget::new(LoadLimits::default()),
|
||||
caps::NONE,
|
||||
)
|
||||
.unwrap_or_else(|e| panic!("{}: {e:?}", path.display()))
|
||||
}
|
||||
fn state(
|
||||
vm: &VirtualMachine,
|
||||
image: &ValidatedProgramImage,
|
||||
collection: &str,
|
||||
) -> Vec<StorageObject> {
|
||||
let objects = vm.heap().diagnostic_typed_storage();
|
||||
let name = format!("{collection}<int>");
|
||||
let owner = objects
|
||||
.iter()
|
||||
.find(|o| {
|
||||
image.registry().declarations().types[o.type_id.0 as usize]
|
||||
.name
|
||||
.as_deref()
|
||||
== Some(&name)
|
||||
})
|
||||
.expect("owner")
|
||||
.clone();
|
||||
let V::Reference(storage) = owner.groups[0][0] else {
|
||||
panic!("backing reference")
|
||||
};
|
||||
let backing = objects
|
||||
.iter()
|
||||
.find(|o| o.reference == storage)
|
||||
.expect("backing")
|
||||
.clone();
|
||||
vec![owner, backing]
|
||||
}
|
||||
fn integer(group: &[V]) -> i64 {
|
||||
let [V::Int64(value)] = group else {
|
||||
panic!("long field {group:?}")
|
||||
};
|
||||
*value
|
||||
}
|
||||
fn validate(
|
||||
vm: &VirtualMachine,
|
||||
image: &ValidatedProgramImage,
|
||||
collection: &str,
|
||||
expected: &[i32],
|
||||
capacity: usize,
|
||||
start: usize,
|
||||
) {
|
||||
let objects = state(vm, image, collection);
|
||||
let owner = &objects[0];
|
||||
let backing = &objects[1];
|
||||
assert_eq!(backing.groups.len(), capacity);
|
||||
assert_eq!(
|
||||
integer(&owner.groups[if collection == "stack" { 1 } else { 2 }]),
|
||||
expected.len() as i64
|
||||
);
|
||||
if collection == "queue" {
|
||||
assert_eq!(integer(&owner.groups[1]), start as i64);
|
||||
}
|
||||
let mut occupied = std::collections::BTreeSet::new();
|
||||
for (offset, expected) in expected.iter().enumerate() {
|
||||
let index = (start + offset) % capacity;
|
||||
occupied.insert(index);
|
||||
let [V::Int64(_), V::Int32(value)] = backing.groups[index].as_slice() else {
|
||||
panic!("present complete int group")
|
||||
};
|
||||
assert_eq!(value, expected);
|
||||
}
|
||||
for (index, group) in backing.groups.iter().enumerate() {
|
||||
if !occupied.contains(&index) {
|
||||
assert_eq!(*group, vec![V::Null, V::Null], "inactive slot {index}");
|
||||
}
|
||||
}
|
||||
}
|
||||
fn release(vm: VirtualMachine) {
|
||||
let observer = vm.resource_observer();
|
||||
drop(vm);
|
||||
for q in [
|
||||
Q::GuestBytes,
|
||||
Q::HandleSlots,
|
||||
Q::AuxiliaryBytes,
|
||||
Q::TemporaryBytes,
|
||||
Q::StringBytes,
|
||||
Q::StringAllocations,
|
||||
] {
|
||||
assert_eq!(observer.used(q), 0, "last owner release {q:?}");
|
||||
}
|
||||
}
|
||||
pub(super) fn verify(root: &std::path::Path) {
|
||||
let successes = [
|
||||
"basic",
|
||||
"capacity",
|
||||
"arithmetic",
|
||||
"cursor-empty",
|
||||
"cursor-single",
|
||||
"snapshot",
|
||||
"cursor-order",
|
||||
"groups",
|
||||
"references",
|
||||
"native",
|
||||
"evaluation",
|
||||
];
|
||||
let mut cases = 0;
|
||||
for collection in ["stack", "queue"] {
|
||||
for (name, fault) in successes
|
||||
.into_iter()
|
||||
.map(|n| (n, None))
|
||||
.chain(
|
||||
["fault-negative", "fault-too-large", "fault-required"]
|
||||
.into_iter()
|
||||
.map(|n| (n, Some(prometeu_bytecode::TRAP_EXPLICIT))),
|
||||
)
|
||||
.chain((collection == "queue").then_some(("wrap", None)))
|
||||
{
|
||||
for suffix in ["", "-optimized"] {
|
||||
let image = load(root, collection, name, suffix);
|
||||
let mut vm = VirtualMachine::from_image(image, Default::default());
|
||||
vm.prepare_boot_call().unwrap();
|
||||
let report = vm
|
||||
.run_budget(20_000_000, &mut NoNative, &mut HostContext::new(None))
|
||||
.unwrap();
|
||||
if let Some(expected) = fault {
|
||||
let End::Trap(info) = report.reason else {
|
||||
panic!("{collection}/{name}{suffix}: {report:?}")
|
||||
};
|
||||
assert_eq!(info.code, expected);
|
||||
} else {
|
||||
assert!(
|
||||
matches!(report.reason, End::Halted | End::EndOfRom),
|
||||
"{collection}/{name}{suffix}: {report:?}"
|
||||
);
|
||||
assert_eq!(
|
||||
vm.operand_stack_top(1),
|
||||
vec![Value::Int32(42)],
|
||||
"{collection}/{name}{suffix}"
|
||||
);
|
||||
}
|
||||
release(vm);
|
||||
cases += 1;
|
||||
println!("STACK QUEUE SOURCE PASS {collection}/{name}{suffix}");
|
||||
}
|
||||
}
|
||||
refusals(root, collection);
|
||||
postwrite_probe(root, collection);
|
||||
gc(root, collection);
|
||||
}
|
||||
distribution(root);
|
||||
println!("STACK QUEUE MANDATORY BEHAVIOR CASES {cases}");
|
||||
}
|
||||
fn marker(image: &ValidatedProgramImage, value: i32) -> usize {
|
||||
let mut pc = 0;
|
||||
let mut found = Vec::new();
|
||||
while pc < image.code().len() {
|
||||
let i = decode_next(pc, image.code()).unwrap();
|
||||
if i.opcode == Op::PushI32 && i.imm_i32().unwrap() == value {
|
||||
found.push(pc);
|
||||
}
|
||||
pc = i.next_pc;
|
||||
}
|
||||
assert_eq!(found.len(), 1);
|
||||
found[0]
|
||||
}
|
||||
fn refusals(root: &std::path::Path, collection: &str) {
|
||||
let mut total = 0;
|
||||
let mut after_writes = 0;
|
||||
let mut backing_refusal = false;
|
||||
let mut snapshot_refusal = false;
|
||||
for name in [
|
||||
"insert", "growth", "zero", "remove", "clear", "peek", "cursor", "empty",
|
||||
]
|
||||
.into_iter()
|
||||
.chain((collection == "queue").then_some("wrapped"))
|
||||
{
|
||||
for suffix in ["", "-optimized"] {
|
||||
let image = load(root, collection, &format!("refusal-{name}"), suffix);
|
||||
let before_pc = marker(&image, 314160);
|
||||
let after_pc = marker(&image, 314161);
|
||||
let prepare = |limits| {
|
||||
let mut vm = VirtualMachine::from_image(image.clone(), limits);
|
||||
vm.prepare_boot_call().unwrap();
|
||||
vm.insert_breakpoint(before_pc);
|
||||
vm.insert_breakpoint(after_pc);
|
||||
vm
|
||||
};
|
||||
let mut baseline = prepare(RuntimeLimits::default());
|
||||
assert!(matches!(
|
||||
baseline
|
||||
.run_budget(20_000_000, &mut NoNative, &mut HostContext::new(None))
|
||||
.unwrap()
|
||||
.reason,
|
||||
End::Breakpoint
|
||||
));
|
||||
let initial: Vec<i32> = if name == "zero" || name == "empty" {
|
||||
vec![]
|
||||
} else if name == "wrapped" {
|
||||
vec![2, 3, 4, 5]
|
||||
} else {
|
||||
vec![0, 1, 2, 3]
|
||||
};
|
||||
let old_capacity = if name == "zero" || name == "empty" {
|
||||
0
|
||||
} else if name == "growth" || name == "wrapped" {
|
||||
4
|
||||
} else {
|
||||
8
|
||||
};
|
||||
validate(
|
||||
&baseline,
|
||||
&image,
|
||||
collection,
|
||||
&initial,
|
||||
old_capacity,
|
||||
if name == "wrapped" { 2 } else { 0 },
|
||||
);
|
||||
let old = state(&baseline, &image, collection);
|
||||
let before = baseline.resource_snapshot();
|
||||
baseline.remove_breakpoint(before_pc);
|
||||
let mut successful = Vec::new();
|
||||
let mut max_arrays = 0;
|
||||
loop {
|
||||
max_arrays = max_arrays.max(
|
||||
baseline
|
||||
.heap()
|
||||
.diagnostic_typed_storage()
|
||||
.iter()
|
||||
.filter(|o| {
|
||||
matches!(
|
||||
image.registry().declarations().types[o.type_id.0 as usize].kind,
|
||||
prometeu_bytecode::registry::TypeKind::Array(_)
|
||||
)
|
||||
})
|
||||
.count(),
|
||||
);
|
||||
successful.push((baseline.pc(), observe_originals(&baseline, &old)));
|
||||
let report = baseline
|
||||
.run_budget(1, &mut NoNative, &mut HostContext::new(None))
|
||||
.unwrap();
|
||||
if baseline.pc() == after_pc {
|
||||
break;
|
||||
}
|
||||
assert!(
|
||||
matches!(report.reason, End::BudgetExhausted),
|
||||
"{collection}/{name}: {report:?}"
|
||||
);
|
||||
assert!(successful.len() < 200_000);
|
||||
}
|
||||
let after = baseline.resource_snapshot();
|
||||
let mut expected = initial.clone();
|
||||
match name {
|
||||
"insert" | "growth" | "zero" | "wrapped" => expected.push(42),
|
||||
"remove" => {
|
||||
if collection == "stack" {
|
||||
expected.pop();
|
||||
} else {
|
||||
expected.remove(0);
|
||||
}
|
||||
}
|
||||
"clear" => expected.clear(),
|
||||
_ => (),
|
||||
}
|
||||
let capacity = match name {
|
||||
"zero" => 1,
|
||||
"growth" | "wrapped" => 6,
|
||||
_ => old_capacity,
|
||||
};
|
||||
validate(
|
||||
&baseline,
|
||||
&image,
|
||||
collection,
|
||||
&expected,
|
||||
capacity,
|
||||
if collection == "queue" && name == "remove" {
|
||||
1
|
||||
} else {
|
||||
0
|
||||
},
|
||||
);
|
||||
if ["growth", "zero", "wrapped"].contains(&name) {
|
||||
assert!(max_arrays >= 2, "old/candidate coexistence");
|
||||
} else {
|
||||
assert_eq!(
|
||||
max_arrays, 1,
|
||||
"ordinary update/capture never reconstructs backing"
|
||||
);
|
||||
}
|
||||
if ["peek", "cursor", "empty"].contains(&name) {
|
||||
assert_eq!(state(&baseline, &image, collection), old);
|
||||
}
|
||||
println!(
|
||||
"STACK QUEUE PEAK {collection}/{name}{suffix} arrays={max_arrays} before={:?} after={:?}",
|
||||
before.budget.peaks, after.budget.peaks
|
||||
);
|
||||
let mut count = 0;
|
||||
let mut partial = 0;
|
||||
for q in [
|
||||
Q::GuestBytes,
|
||||
Q::HandleSlots,
|
||||
Q::AuxiliaryBytes,
|
||||
Q::TemporaryBytes,
|
||||
Q::CallDepth,
|
||||
] {
|
||||
let lower = before.budget.peaks[q as usize];
|
||||
let upper = after.budget.peaks[q as usize];
|
||||
if lower >= upper {
|
||||
continue;
|
||||
}
|
||||
let mut limits = vec![lower, lower + (upper - lower) / 2, upper - 1];
|
||||
if q == Q::HandleSlots {
|
||||
limits.extend(lower..upper.min(lower + 24));
|
||||
}
|
||||
limits.sort_unstable();
|
||||
limits.dedup();
|
||||
for limit in limits {
|
||||
let mut vm = prepare(RuntimeLimits::default().lowered(q, limit).unwrap());
|
||||
assert!(
|
||||
matches!(
|
||||
vm.run_budget(20_000_000, &mut NoNative, &mut HostContext::new(None))
|
||||
.unwrap()
|
||||
.reason,
|
||||
End::Breakpoint
|
||||
),
|
||||
"{collection}/{name}/{q:?}={limit} setup"
|
||||
);
|
||||
let original = state(&vm, &image, collection);
|
||||
vm.remove_breakpoint(before_pc);
|
||||
let (report, prefix, mutated) =
|
||||
trace_collection_attempt(&mut vm, &original, after_pc);
|
||||
assert_mutation_prefix(&prefix, &successful);
|
||||
if let End::Trap(info) = report.reason {
|
||||
assert_eq!(info.code, TRAP_RESOURCE_LIMIT);
|
||||
let current = observe_originals(&vm, &original);
|
||||
if !mutated {
|
||||
assert_eq!(
|
||||
current, original,
|
||||
"before first write preserves full original state"
|
||||
);
|
||||
}
|
||||
if ["peek", "cursor", "empty"].contains(&name) {
|
||||
assert_eq!(current, original);
|
||||
}
|
||||
let instruction = decode_next(info.pc as usize, image.code()).unwrap();
|
||||
backing_refusal |= instruction.opcode == Op::ArrayNew;
|
||||
if instruction.opcode == Op::StructNew {
|
||||
snapshot_refusal |= image.registry().declarations().types
|
||||
[instruction.imm_u32().unwrap() as usize]
|
||||
.name
|
||||
.as_deref()
|
||||
== Some("_SnapshotNode<int>");
|
||||
}
|
||||
count += 1;
|
||||
partial += usize::from(mutated);
|
||||
println!(
|
||||
"STACK QUEUE REFUSAL {collection}/{name}{suffix} mutated={mutated} resource={q:?} limit={limit} opcode={:?}",
|
||||
instruction.opcode
|
||||
);
|
||||
} else {
|
||||
assert!(
|
||||
matches!(report.reason, End::BudgetExhausted | End::Breakpoint)
|
||||
&& vm.pc() == after_pc
|
||||
);
|
||||
}
|
||||
release(vm);
|
||||
}
|
||||
}
|
||||
assert!(
|
||||
count > 0,
|
||||
"{collection}/{name}: operation-specific natural refusal required"
|
||||
);
|
||||
total += count;
|
||||
after_writes += partial;
|
||||
println!(
|
||||
"STACK QUEUE PHASE SUMMARY {collection}/{name}{suffix} refusals={count} after_write={partial}"
|
||||
);
|
||||
}
|
||||
}
|
||||
assert!(
|
||||
backing_refusal && snapshot_refusal,
|
||||
"backing and snapshot preparation refusals required"
|
||||
);
|
||||
println!("STACK QUEUE NATURAL REFUSALS {collection} total={total} after_write={after_writes}");
|
||||
}
|
||||
fn postwrite_probe(root: &std::path::Path, collection: &str) {
|
||||
// Separate test-only instrumentation: not natural failure frequency evidence.
|
||||
for suffix in ["", "-optimized"] {
|
||||
let image = load(root, collection, "injected-growth", suffix);
|
||||
let mut vm = VirtualMachine::from_image(
|
||||
image.clone(),
|
||||
RuntimeLimits::default()
|
||||
.lowered(Q::GuestBytes, 500_000)
|
||||
.unwrap(),
|
||||
);
|
||||
vm.prepare_boot_call().unwrap();
|
||||
let mut found = false;
|
||||
for _ in 0..100_000 {
|
||||
let instruction = decode_next(vm.pc(), image.code()).unwrap();
|
||||
if instruction.opcode == Op::ArrayNew
|
||||
&& vm.operand_stack_top(1) == vec![Value::Int64(1_000_000)]
|
||||
{
|
||||
let original = vm.heap().diagnostic_typed_storage();
|
||||
let objects = state(&vm, &image, collection);
|
||||
assert_eq!(
|
||||
integer(&objects[0].groups[if collection == "stack" { 1 } else { 2 }]),
|
||||
2
|
||||
);
|
||||
assert_eq!(objects[1].groups.len(), 3);
|
||||
assert!(matches!(
|
||||
objects[1].groups[2].as_slice(),
|
||||
[V::Int64(_), V::Int32(42)]
|
||||
));
|
||||
let operands = vm.operand_stack_top(1).to_vec();
|
||||
let report = vm
|
||||
.run_budget(1, &mut NoNative, &mut HostContext::new(None))
|
||||
.unwrap();
|
||||
let End::Trap(info) = report.reason else {
|
||||
panic!("post-write probe: {report:?}")
|
||||
};
|
||||
assert_eq!(info.code, TRAP_RESOURCE_LIMIT);
|
||||
assert_eq!(vm.heap().diagnostic_typed_storage(), original);
|
||||
assert_eq!(vm.operand_stack_top(1), operands);
|
||||
println!(
|
||||
"STACK QUEUE TEST-ONLY POST-WRITE PASS {collection}{suffix}: backing=3 old size=2 appended=42 retained"
|
||||
);
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
let report = vm
|
||||
.run_budget(1, &mut NoNative, &mut HostContext::new(None))
|
||||
.unwrap();
|
||||
assert!(matches!(report.reason, End::BudgetExhausted));
|
||||
}
|
||||
assert!(found);
|
||||
release(vm);
|
||||
}
|
||||
}
|
||||
fn gc(root: &std::path::Path, collection: &str) {
|
||||
for suffix in ["", "-optimized"] {
|
||||
for (name, counts) in [
|
||||
("gc-snapshot", vec![1200, 1, 1, 0]),
|
||||
("gc-collection", vec![64, 61, 0, 1, 0]),
|
||||
] {
|
||||
let image = load(root, collection, name, suffix);
|
||||
let mut vm = VirtualMachine::from_image(image.clone(), Default::default());
|
||||
vm.prepare_boot_call().unwrap();
|
||||
let mut previous = 0;
|
||||
for (round, count) in counts.into_iter().enumerate() {
|
||||
let report = vm
|
||||
.run_budget(100_000_000, &mut NoNative, &mut HostContext::new(None))
|
||||
.unwrap();
|
||||
assert!(
|
||||
matches!(report.reason, End::FrameSync),
|
||||
"{collection}/{name}/{round}: {report:?}"
|
||||
);
|
||||
let collections = vm.resource_snapshot().gc.collections;
|
||||
assert!(
|
||||
collections > previous,
|
||||
"actual collection, not only safepoint"
|
||||
);
|
||||
previous = collections;
|
||||
let objects = vm.heap().diagnostic_typed_storage();
|
||||
let named = |n: &str| {
|
||||
objects
|
||||
.iter()
|
||||
.filter(|o| {
|
||||
image.registry().declarations().types[o.type_id.0 as usize]
|
||||
.name
|
||||
.as_deref()
|
||||
== Some(n)
|
||||
})
|
||||
.count()
|
||||
};
|
||||
assert_eq!(
|
||||
named("Item"),
|
||||
count,
|
||||
"{collection}/{name}/{round}: payload roots"
|
||||
);
|
||||
let arrays = objects
|
||||
.iter()
|
||||
.filter(|o| {
|
||||
matches!(
|
||||
image.registry().declarations().types[o.type_id.0 as usize].kind,
|
||||
prometeu_bytecode::registry::TypeKind::Array(_)
|
||||
)
|
||||
})
|
||||
.count();
|
||||
if name == "gc-snapshot" {
|
||||
assert_eq!(named("_SnapshotNode<Item>"), count);
|
||||
assert_eq!(arrays, 0, "snapshot retains no source backing");
|
||||
} else {
|
||||
assert_eq!(
|
||||
arrays,
|
||||
usize::from(round < 4),
|
||||
"only retained backing, no replaced arrays"
|
||||
);
|
||||
assert_eq!(named("_SnapshotNode<Item>"), 0);
|
||||
}
|
||||
println!(
|
||||
"STACK QUEUE GC PASS {collection}/{name}{suffix} round={round} items={count} arrays={arrays}"
|
||||
);
|
||||
}
|
||||
let report = vm
|
||||
.run_budget(100_000, &mut NoNative, &mut HostContext::new(None))
|
||||
.unwrap();
|
||||
assert!(matches!(report.reason, End::Halted | End::EndOfRom));
|
||||
assert_eq!(vm.operand_stack_top(1), vec![Value::Int32(42)]);
|
||||
release(vm);
|
||||
}
|
||||
}
|
||||
}
|
||||
fn distribution(root: &std::path::Path) {
|
||||
for name in ["imports", "installed"] {
|
||||
let image = load(root, "stack-queue", name, "");
|
||||
let mut vm = VirtualMachine::from_image(image.clone(), Default::default());
|
||||
vm.prepare_boot_call().unwrap();
|
||||
let report = vm
|
||||
.run_budget(2_000_000, &mut NoNative, &mut HostContext::new(None))
|
||||
.unwrap();
|
||||
assert!(
|
||||
matches!(report.reason, End::FrameSync | End::Halted | End::EndOfRom),
|
||||
"{name}: {report:?}"
|
||||
);
|
||||
let objects = vm.heap().diagnostic_typed_storage();
|
||||
let get = |reference| objects.iter().find(|o| o.reference == reference).unwrap();
|
||||
let mut lasts = Vec::new();
|
||||
for cursor in objects.iter().filter(|o| {
|
||||
image.registry().declarations().types[o.type_id.0 as usize]
|
||||
.name
|
||||
.as_deref()
|
||||
== Some("_SnapshotCursor<int>")
|
||||
}) {
|
||||
let V::Reference(carrier) = cursor.groups[0][0] else {
|
||||
panic!("current carrier")
|
||||
};
|
||||
let V::Reference(node) = get(carrier).groups[0][0] else {
|
||||
panic!("node")
|
||||
};
|
||||
let node = get(node);
|
||||
assert_eq!(node.groups[1], vec![V::Null], "completed traversal");
|
||||
let V::Int32(value) = node.groups[0][0] else {
|
||||
panic!("value")
|
||||
};
|
||||
lasts.push(value);
|
||||
}
|
||||
lasts.sort_unstable();
|
||||
assert_eq!(
|
||||
lasts,
|
||||
vec![20, 22],
|
||||
"both order-sensitive snapshots traversed"
|
||||
);
|
||||
release(vm);
|
||||
println!("STACK QUEUE DISTRIBUTION PASS {name}");
|
||||
}
|
||||
}
|
||||
@@ -1,44 +0,0 @@
|
||||
"""Explicit provider check; ordinary Studio compilation does not invoke this tool."""
|
||||
import argparse
|
||||
import hashlib
|
||||
import pathlib
|
||||
import platform
|
||||
import subprocess
|
||||
import tempfile
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--runtime", type=pathlib.Path, required=True)
|
||||
args = parser.parse_args()
|
||||
studio = pathlib.Path(__file__).resolve().parents[2]
|
||||
mirror = studio / "docs/vm-arch"
|
||||
properties = dict(line.split("=", 1) for line in
|
||||
(mirror / "runtime-catalog.properties").read_text().splitlines() if line)
|
||||
runtime = args.runtime.resolve(strict=True)
|
||||
revision = subprocess.check_output(["git", "-C", str(runtime), "rev-parse", "HEAD"], text=True).strip()
|
||||
if revision != properties["runtime.revision"]:
|
||||
raise SystemExit(f"Expected selected provider {properties['runtime.revision']}, found {revision}; "
|
||||
"this is an evidence-target mismatch, not a runtime compatibility verdict")
|
||||
# Evidence must correspond to committed source, not just two matching local copies.
|
||||
dirty = subprocess.check_output(["git", "-C", str(runtime), "status", "--porcelain"], text=True)
|
||||
if dirty:
|
||||
raise SystemExit("Provider checkout is dirty; verify the selected revision in a clean checkout")
|
||||
for name in ("INTRINSICS.csv", "BUILTIN_CONSTANTS.csv"):
|
||||
committed = subprocess.check_output(["git", "-C", str(runtime), "show", f"{revision}:docs/vm-arch/{name}"])
|
||||
if committed != (runtime / "docs/vm-arch" / name).read_bytes() or committed != (mirror / name).read_bytes():
|
||||
raise SystemExit(f"Provider/mirror bytes differ: {name}")
|
||||
digest = hashlib.sha256(committed).hexdigest()
|
||||
if digest != properties[name + ".sha256"]:
|
||||
raise SystemExit(f"Provenance hash mismatch: {name}")
|
||||
print(f"MATCH {name} sha256={digest}", flush=True)
|
||||
print(f"Provider {revision}; {platform.platform()}; Cargo test profile, default features", flush=True)
|
||||
with tempfile.TemporaryDirectory(prefix="studio-catalog-provider-") as target:
|
||||
subprocess.run(["cargo", "test", "--locked", "--offline", "--target-dir", target,
|
||||
"-p", "prometeu-vm", "--test", "numeric_contract",
|
||||
"exported_artifacts_match_the_single_runtime_catalog", "--", "--exact"],
|
||||
cwd=runtime, check=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user