From 4d448d4b474aa60127c564df06ccc76fb75bafd2 Mon Sep 17 00:00:00 2001 From: Samuel Date: Tue, 17 Nov 2026 17:35:01 -0500 Subject: [PATCH 1/3] feat: checkpoint public bytecode loading and owned results Expose the metadata-only loader, immutable profile and fixed-actor runner route. Capture distinct artifact-bound bytecode diagnostics during search and keep observation order shared for replay. The real public lost-update test and connected 94B regressions pass; replay and consumer release gates remain open. Co-authored-by: Codex --- docs/measurements/94C-bytecode-release.md | 49 ++++ examples/bytecode/LostUpdate.java | 26 +++ examples/bytecode/README.md | 40 ++++ examples/bytecode/TwoLockDeadlock.java | 30 +++ .../samhb/interleave/InterleaveRunner.java | 19 ++ .../java/dev/samhb/interleave/TestResult.java | 23 ++ .../dev/samhb/interleave/TraceRecord.java | 28 ++- .../dev/samhb/interleave/bytecode/Actor.java | 2 +- .../interleave/bytecode/BytecodeExplorer.java | 112 +++++---- .../interleave/bytecode/BytecodeLimits.java | 12 +- .../bytecode/BytecodeLoadException.java | 12 +- .../interleave/bytecode/BytecodeLoader.java | 4 +- .../interleave/bytecode/BytecodeLocation.java | 10 +- .../bytecode/BytecodeObservations.java | 74 ++++++ .../interleave/bytecode/BytecodeProgram.java | 23 +- .../interleave/bytecode/BytecodeRuntime.java | 141 +++++++++++ .../bytecode/BytecodeScheduler.java | 15 +- .../bytecode/BytecodeSnapshots.java | 97 ++++++++ .../dev/samhb/interleave/bytecode/Check.java | 4 +- .../dev/samhb/interleave/bytecode/Model.java | 2 +- .../interleave/core/BytecodeEvidence.java | 219 ++++++++++++++++++ .../format/BytecodeProgramLoader.java | 28 +++ .../bytecode/BytecodeReleaseTest.java | 38 +++ 23 files changed, 934 insertions(+), 74 deletions(-) create mode 100644 docs/measurements/94C-bytecode-release.md create mode 100644 examples/bytecode/LostUpdate.java create mode 100644 examples/bytecode/README.md create mode 100644 examples/bytecode/TwoLockDeadlock.java rename src/{test => main}/java/dev/samhb/interleave/bytecode/Actor.java (81%) create mode 100644 src/main/java/dev/samhb/interleave/bytecode/BytecodeObservations.java create mode 100644 src/main/java/dev/samhb/interleave/bytecode/BytecodeRuntime.java create mode 100644 src/main/java/dev/samhb/interleave/bytecode/BytecodeSnapshots.java rename src/{test => main}/java/dev/samhb/interleave/bytecode/Check.java (78%) rename src/{test => main}/java/dev/samhb/interleave/bytecode/Model.java (68%) create mode 100644 src/main/java/dev/samhb/interleave/core/BytecodeEvidence.java create mode 100644 src/main/java/dev/samhb/interleave/format/BytecodeProgramLoader.java create mode 100644 src/test/java/dev/samhb/interleave/bytecode/BytecodeReleaseTest.java diff --git a/docs/measurements/94C-bytecode-release.md b/docs/measurements/94C-bytecode-release.md new file mode 100644 index 0000000..588607b --- /dev/null +++ b/docs/measurements/94C-bytecode-release.md @@ -0,0 +1,49 @@ + +# 94C — Public bytecode release evidence + +## Status and baseline + +Implementation in progress under [Spec94C](../specs/active/94C-bytecode-release.md) and the +[shared contract](../plans/bytecode-contract.md). PR140/94B merged at +`6eb939ea19c3938db8052fc1b32d8f157fc913c7`, verified against remote main before creating the isolated +`feat/bytecode-public-release` checkout. The original dirty checkout and prior worktrees are preserved. +Fresh merged-main build/tests/strict Javadoc passes2066 tests with zero failures/errors/skips. +Configured default mutation baseline:455 KILLED +13 SURVIVED /468. Affected baseline across bytecode, +runner/result/trace/replay, CLI and benchmark/report/attestation:3163 KILLED +253 SURVIVED +478 +NO_COVERAGE /3894, zero resource/run-error statuses. Both completed before production edits; the +larger affected run took95 minutes. Raw logs/XML are retained in the persistent evidence sibling. +Historical94B counts are not94C baselines. + +## Implementation order and approved seams + +1. Publish annotation/immutable program/limits/loading interfaces and the runner's dedicated bytecode +route, producing owned BYTECODE identity, real transition metadata and immutable snapshots. +2. Authenticate strict replay and JSON, including initial failures, modeled cutoffs and honest external +prefix replay. Bytecode and source evidence remain separate; native streams have an upgrade boundary. +3. Route CLI, benchmark/report/attestation and viewer consumers, with externally compiled built-jar +lost-update/deadlock examples and complete legacy/browser compatibility. + +Tests use the contract's loader/runner, replay, CLI/report and browser seams. Internal metadata/state +stay owned by the existing bytecode package. One narrow integration facade is needed for cross-package +loader/runner/replayer calls; it exposes no target state, generic callback or configurable backend. +Existing source/JSON interfaces and default selections retain their behavior. Runtime limits/mode and +artifact/model/declaration identity are authenticated separately. Only exact DFS is admitted in94C; +95+ and weak memory remain outside this milestone. + +## Gates still required + +Record fresh mutation fingerprints, baseline/final build/Javadoc, built-jar public consumers, +strict replay adversaries, no-debug classes, pure-observer/fault/cutoff/global-stop classifications, +reports and fresh browser artifacts. Incorporate the actual [94B measurements and preservation +argument](94B-bytecode-concurrency.md), not invented new measurements. Run ordinary/security review, +fresh-reader checks and actual CodeRabbit; record real review status through agent-setup. Publish one +94C PR, report its link and stop before95 or CI watchers. + +## First implementation slice + +Public annotation/program/limits/loading and runner access now pass the real lost-update tracer test. +Source diagnostics remain separate from BYTECODE payloads; shared observation order is reused by search +and upcoming strict replay. Public runs capture immutable typed state views during execution, rather +than reexecuting cancelled prefixes after search. Internal94B measurement mode keeps capture disabled. +Connected checks/monitor/exact-state/progress regressions pass. This is an internal checkpoint; strict +replay/JSON and all public consumers/review gates remain unfinished and no94C PR is published. diff --git a/examples/bytecode/LostUpdate.java b/examples/bytecode/LostUpdate.java new file mode 100644 index 0000000..887a072 --- /dev/null +++ b/examples/bytecode/LostUpdate.java @@ -0,0 +1,26 @@ +/** Two real Java bytecode actors race through separate shared reads and writes. */ +package examples.bytecode; + +import dev.samhb.interleave.bytecode.Actor; +import dev.samhb.interleave.bytecode.Check; +import dev.samhb.interleave.bytecode.Model; + +/** A final declared check distinguishes the lost increment from successful execution. */ +@Model +public final class LostUpdate { + /** Shared model counter. */ + public int counter; + + /** Initializes the fixture through interpreted setup. */ + public LostUpdate() {} + + /** Performs one nonatomic increment. */ + @Actor(id=0) public void first(){counter++;} + + /** Competes with the other increment. */ + @Actor(id=1) public void second(){counter++;} + + /** Checks only after both actors return normally. + * @return whether neither update was lost */ + @Check public boolean bothUpdatesSurvive(){return counter==2;} +} diff --git a/examples/bytecode/README.md b/examples/bytecode/README.md new file mode 100644 index 0000000..d616e9e --- /dev/null +++ b/examples/bytecode/README.md @@ -0,0 +1,40 @@ + +# Bounded Java bytecode examples + +These models exercise real compiled Java under Interleave's bounded sequentially consistent profile. +`LostUpdate` admits a false final check with counter1 and successful completion with counter2. +`TwoLockDeadlock` admits a concrete wait cycle and successful serialized execution. Neither example +creates threads or executes target code on the host JVM during checking. + +Build Interleave with JDK26, then explicitly compile the examples into a directory: + +```sh +./gradlew --max-workers=1 -PpitestThreads=1 build +javac --release 17 -g -cp build/libs/interleave-1.0-SNAPSHOT.jar -d build/bytecode-examples examples/bytecode/LostUpdate.java examples/bytecode/TwoLockDeadlock.java +./gradlew --max-workers=1 -PpitestThreads=1 run --args='--bytecode examples.bytecode.LostUpdate --class-path build/bytecode-examples --strategy DFS --store exact --json' +./gradlew --max-workers=1 -PpitestThreads=1 run --args='--bytecode examples.bytecode.TwoLockDeadlock --class-path build/bytecode-examples --strategy DFS --store exact' +``` + +The jar basename above assumes the clone directory is `interleave`; use the actual jar in `build/libs` +when building an isolated worktree with a different directory name. The loader never compiles inputs +or discovers jars. Class-directory entries must remain immutable regular files while loading. After +successful loading, changes to that directory cannot alter the frozen program or its replay identity. + +Library entry points are `BytecodeProgramLoader.load(directory,binaryName)`, +`InterleaveRunner.builder().build().runBytecode(program)` and +`new TraceReplayer().replayBytecode(program,record)`. Custom immutable `BytecodeLimits` are optional. +Only exact DFS is available in this release; incompatible strategies, stores, generic properties and +symmetry selections reject before invoking callbacks. JSON records retain BYTECODE identity and real +method/descriptor/BCI locations, with compiler lines when available. Recompile with `-g:none` to omit +line tables; replay remains based on exact artifact bytes and real BCIs. + +Use fixture-constructor fields for locks. A declaration such as `static final Object LOCK=new Object()` +requires executable `` and rejects, as do ordinary static arrays, enum initialization and +compiler-generated assertion-status setup. Use declared `@Check` methods instead of Java `assert`. +Arrays, actor allocations/general dispatch, user catch/finally, wider primitives/core libraries, +CBS/DPOR/bitstate, atomics and weak memory belong to later phases. Compiler-generated synchronized +cleanup is supported; runtime null/division faults remain modeled behavior rather than loader errors. + +[The shared contract](../../docs/plans/bytecode-contract.md) defines the complete supported profile. +The [94B ledger](../../docs/measurements/94B-bytecode-concurrency.md) contains real reference/batched +measurements and the preservation argument. These examples establish no Java Memory Model coverage. diff --git a/examples/bytecode/TwoLockDeadlock.java b/examples/bytecode/TwoLockDeadlock.java new file mode 100644 index 0000000..a6b8a84 --- /dev/null +++ b/examples/bytecode/TwoLockDeadlock.java @@ -0,0 +1,30 @@ +/** Opposing setup-allocated Java monitors admit a concrete two-actor wait cycle. */ +package examples.bytecode; + +import dev.samhb.interleave.bytecode.Actor; +import dev.samhb.interleave.bytecode.Check; +import dev.samhb.interleave.bytecode.Model; + +/** Uses constructor initialization because executable application class initializers are unsupported. */ +@Model +public final class TwoLockDeadlock { + /** First deterministic setup monitor. */ + public final Object left; + /** Second deterministic setup monitor. */ + public final Object right; + /** Shared completion counter. */ + public int counter; + + /** Allocates distinct monitors in interpreted setup, before actors start. */ + public TwoLockDeadlock(){left=new Object();right=new Object();} + + /** Acquires left before right. */ + @Actor(id=0) public void first(){synchronized(left){synchronized(right){counter++;}}} + + /** Acquires right before left. */ + @Actor(id=1) public void second(){synchronized(right){synchronized(left){counter++;}}} + + /** Normal schedules complete both increments; deadlocked schedules never run FINAL checks. + * @return whether both actors completed their protected work */ + @Check public boolean bothActorsFinish(){return counter==2;} +} diff --git a/src/main/java/dev/samhb/interleave/InterleaveRunner.java b/src/main/java/dev/samhb/interleave/InterleaveRunner.java index 8c468e1..0719277 100644 --- a/src/main/java/dev/samhb/interleave/InterleaveRunner.java +++ b/src/main/java/dev/samhb/interleave/InterleaveRunner.java @@ -26,6 +26,10 @@ * The concrete-store builder option may reuse a supplied store when freshCopy is unsupported. */ public final class InterleaveRunner implements Serializable { + /** Whether a caller supplied generic membership that bytecode must reject before invocation. */ + private final boolean stateStoreExplicit; + /** Whether a symmetry backend was explicitly selected. */ + private final boolean symmetryBackendExplicit; /** Strategy. */ private final Strategy strategy; /** Whether checked model orbit search is selected. */ @@ -54,6 +58,7 @@ public final class InterleaveRunner implements Serializable { * @param builder builder whose settings are captured */ private InterleaveRunner(Builder builder) { + this.stateStoreExplicit=builder.stateStoreExplicit;this.symmetryBackendExplicit=builder.symmetryBackendExplicit; this.strategy = builder.strategy; this.symmetryReduction = builder.symmetryReduction; this.symmetryBackend = builder.symmetryBackend; @@ -67,6 +72,20 @@ private InterleaveRunner(Builder builder) { this.iterativeDeepening = builder.iterativeDeepening; } + /** Runs a frozen bytecode model with its declared pure checks and owned exact DFS storage. + * Each run owns fresh execution state. Generic properties/stores, symmetry and unavailable strategies + * reject before any caller callback can run. Public bytecode execution uses reviewed local batching. + * @param program immutable metadata-only loaded artifact + * @return precise BYTECODE results, snapshots and replayable findings + * @throws IllegalArgumentException for incompatible generic/symmetry/strategy settings + * @throws NullPointerException for a null program + * @throws ArithmeticException if the selected duration cannot be represented in milliseconds */ + public TestResult runBytecode(dev.samhb.interleave.bytecode.BytecodeProgram program) { + if(strategy!=Strategy.DFS || invariant!=null || stateStoreExplicit || symmetryReduction || symmetryBackendExplicit || symmetryBits>0) + throw new IllegalArgumentException("Bytecode94C requires exact DFS, declared checks and owned storage; generic callbacks and symmetry are unsupported"); + return dev.samhb.interleave.bytecode.BytecodeRuntime.run(java.util.Objects.requireNonNull(program),maxStates,maxTime); + } + /** Creates membership while preventing an unmarked symmetry result through a custom factory. * Checked mode owns a fresh certified backend; the builder rejects explicit stores/factories. * @param program model being checked by this run or iterative bound diff --git a/src/main/java/dev/samhb/interleave/TestResult.java b/src/main/java/dev/samhb/interleave/TestResult.java index e9f82bd..f51ea60 100644 --- a/src/main/java/dev/samhb/interleave/TestResult.java +++ b/src/main/java/dev/samhb/interleave/TestResult.java @@ -283,6 +283,21 @@ public boolean hasViolation() { return !failingTraces.isEmpty(); } + /** Returns the common frozen BYTECODE identity, or null for legacy/source results. + * This validates all buckets rather than trusting a single selected display trace. + * @return consistent exact bytecode identity when present + * @throws IllegalArgumentException for mixed artifacts/profiles or incompatible run metadata */ + public dev.samhb.interleave.core.BytecodeEvidence.Identity bytecodeIdentity() { + dev.samhb.interleave.core.BytecodeEvidence.Identity identity=null;boolean legacy=false; + for(var bucket:List.of(failingTraces,deadlockedTraces,completedTraces,incompleteTraces))for(var trace:bucket) { + var data=trace.bytecodeEvidence(); + if(data==null){legacy=true;continue;} + if(identity==null)identity=data.identity();else if(!identity.equals(data.identity()))throw new IllegalArgumentException("Mixed bytecode identities"); + } + if(identity!=null && (legacy || sourceModel || symmetryReduction || !Boolean.FALSE.equals(approximate)))throw new IllegalArgumentException("Conflicting bytecode run metadata"); + return identity; + } + /** * Returns JSON containing the recorded outcomes, execution metrics and optional raw resource prefix. * Serialization exports captured values only; it never replays the model or evaluates a property. @@ -291,6 +306,14 @@ public boolean hasViolation() { public String toJson() { StringBuilder sb = new StringBuilder(); sb.append("{\n"); + var bytecode=bytecodeIdentity(); + if(bytecode!=null) { + sb.append(" \"programKind\": \"BYTECODE\",\n \"storeType\": \"EXACT\",\n"); + sb.append(" \"bytecodeIdentity\": ").append(ResultJson.GSON.toJson(bytecode)).append(",\n"); + sb.append(" \"requestedStrategy\": \"DFS\",\n \"effectiveStrategy\": \"DFS\",\n \"fallbackReason\": null,\n"); + String verdict=hasViolation() || !deadlockedTraces.isEmpty() ? "VIOLATION" : limitExceeded || hasIncomplete() ? "INCOMPLETE" : "PASS"; + sb.append(" \"verdict\": ").append(ResultJson.GSON.toJson(verdict)).append(",\n"); + } if (symmetryReduction) sb.append(" \"symmetryReduction\": true,\n"); sb.append(" \"strategy\": \"").append(strategy).append("\",\n"); sb.append(" \"statesExplored\": ").append(statesExplored).append(",\n"); diff --git a/src/main/java/dev/samhb/interleave/TraceRecord.java b/src/main/java/dev/samhb/interleave/TraceRecord.java index 718f61c..e1b85f9 100644 --- a/src/main/java/dev/samhb/interleave/TraceRecord.java +++ b/src/main/java/dev/samhb/interleave/TraceRecord.java @@ -21,6 +21,8 @@ public final class TraceRecord implements Serializable { private final String programHash; /** State snapshots. */ private final List states; + /** Optional immutable BYTECODE diagnostics; source metadata is never fabricated for this profile. */ + private final dev.samhb.interleave.core.BytecodeEvidence bytecodeEvidence; /** Optional immutable source diagnostics. */ private final TraceEvidence evidence; @@ -62,6 +64,21 @@ public TraceRecord(List threadIds, List outcomes, TraceOut */ public TraceRecord(List threadIds, List outcomes, TraceOutcome outcome, String programHash, List states, TraceEvidence evidence) { + this(threadIds,outcomes,outcome,programHash,states,evidence,null); + } + + /** Creates an aligned record with explicitly separate source or bytecode payloads. + * Native streams are build-specific; this field addition deliberately changes the generated UID. + * @param threadIds original selected actors + * @param outcomes actual coarse operation outcomes + * @param outcome original terminal category + * @param programHash diagnostic hash, equal to artifact identity for bytecode + * @param states immutable display snapshots + * @param evidence optional source diagnostics + * @param bytecodeEvidence optional artifact-bound bytecode diagnostics + * @throws IllegalArgumentException for conflicting profiles or misaligned bytecode data */ + public TraceRecord(List threadIds,List outcomes,TraceOutcome outcome,String programHash, + List states,TraceEvidence evidence,dev.samhb.interleave.core.BytecodeEvidence bytecodeEvidence) { this.threadIds = List.copyOf(threadIds); this.outcomes = List.copyOf(outcomes); this.outcome = outcome; @@ -69,9 +86,15 @@ public TraceRecord(List threadIds, List outcomes, TraceOut this.states = states == null ? List.of() : List.copyOf(states); if (threadIds.size() != outcomes.size() || (evidence != null && evidence.sourceDigest() != null && evidence.executedSteps().size() != threadIds.size())) throw new IllegalArgumentException("Misaligned trace"); - this.evidence = evidence; + this.evidence = evidence;this.bytecodeEvidence=bytecodeEvidence; + if(bytecodeEvidence!=null && (evidence!=null || !java.util.Objects.equals(programHash,bytecodeEvidence.identity().artifactDigest()) + || bytecodeEvidence.transitions().size()!=threadIds.size() || this.states.size()!=threadIds.size()+1))throw new IllegalArgumentException("Conflicting or misaligned BYTECODE record"); } + /** Returns distinct artifact-bound bytecode diagnostics, otherwise null. + * @return immutable BYTECODE payload, never source spans */ + public dev.samhb.interleave.core.BytecodeEvidence bytecodeEvidence(){return bytecodeEvidence;} + /** Returns source diagnostics, or null for legacy records. * @return source diagnostics, or null for legacy records */ @@ -123,7 +146,7 @@ public List states() { * @return enriched trace record */ public TraceRecord withStates(List states) { - return new TraceRecord(this.threadIds, this.outcomes, this.outcome, this.programHash, states, evidence); + return new TraceRecord(this.threadIds, this.outcomes, this.outcome, this.programHash, states, evidence,bytecodeEvidence); } /** @@ -134,6 +157,7 @@ public TraceRecord withStates(List states) { public String toJson() { StringBuilder sb = new StringBuilder(); sb.append("{\n"); + if(bytecodeEvidence!=null)sb.append(" \"programKind\": \"BYTECODE\",\n \"bytecodeEvidence\": ").append(GSON.toJson(bytecodeEvidence)).append(",\n"); sb.append(" \"threads\": ["); for (int i = 0; i < threadIds.size(); i++) { if (i > 0) sb.append(", "); diff --git a/src/test/java/dev/samhb/interleave/bytecode/Actor.java b/src/main/java/dev/samhb/interleave/bytecode/Actor.java similarity index 81% rename from src/test/java/dev/samhb/interleave/bytecode/Actor.java rename to src/main/java/dev/samhb/interleave/bytecode/Actor.java index 9ee9885..a52f71c 100644 --- a/src/test/java/dev/samhb/interleave/bytecode/Actor.java +++ b/src/main/java/dev/samhb/interleave/bytecode/Actor.java @@ -1,4 +1,4 @@ -/** Test-only annotation protocol; not published in the library before94C. */ +/** Public metadata-only annotation protocol for the bounded sequentially consistent profile. */ package dev.samhb.interleave.bytecode; /** Declares one fixed actor entry method. */ diff --git a/src/main/java/dev/samhb/interleave/bytecode/BytecodeExplorer.java b/src/main/java/dev/samhb/interleave/bytecode/BytecodeExplorer.java index 0362f12..6e22ba8 100644 --- a/src/main/java/dev/samhb/interleave/bytecode/BytecodeExplorer.java +++ b/src/main/java/dev/samhb/interleave/bytecode/BytecodeExplorer.java @@ -2,6 +2,7 @@ package dev.samhb.interleave.bytecode; import java.util.*; +import dev.samhb.interleave.core.BytecodeEvidence; import static dev.samhb.interleave.bytecode.BytecodeState.*; /** Exact full-payload enumeration with bounded checker storage and concrete internal witnesses. */ @@ -76,10 +77,11 @@ record Selection(int actor,List executed) { * @param outcome normalized terminal observation * @param state isolated final/prefix state * @param schedule concrete selected transition sequence + * @param snapshots owned public views, empty for internal measurement-only execution */ - record Witness(Outcome outcome,BytecodeState state,List schedule) { + record Witness(Outcome outcome,BytecodeState state,List schedule,List snapshots) { /** Owns state and freezes the schedule, independently of the search stack. */ - Witness {state=state.copy();schedule=List.copyOf(schedule);} + Witness {state=state.copy();schedule=List.copyOf(schedule);snapshots=List.copyOf(snapshots);} } /** Actual search and canonical-encoding work; retained payload bytes are not JVM retained memory. @@ -117,8 +119,9 @@ boolean exhaustive() { /** Persistent path node avoids copying complete schedules at every search state. * @param previous selected prefix * @param selection last selected transition + * @param snapshot immutable committed state view when public capture is enabled */ - private record Path(Path previous,Selection selection) {} + private record Path(Path previous,Selection selection,BytecodeEvidence.Snapshot snapshot) {} /** An iterative DFS stack frame; its target snapshot is never mutated by successors. */ private static final class Frame { @@ -134,6 +137,10 @@ private static final class Frame { } /** Immutable validated artifact. */ private final BytecodeProgram program; + /** Public evidence capture is opt-in; internal measurements retain their existing work. */ private final boolean captureEvidence; + /** Millisecond boundary deadline, null when absent. */ private final Long maxTimeMillis; + /** Per-run wall-clock origin, never visible to model checks. */ private long startedMillis; + /** Immutable initial public view for the current run. */ private BytecodeEvidence.Snapshot initialSnapshot; /** Mode-aware selected transitions. */ private final BytecodeScheduler scheduler; /** Hash prefilter buckets retain complete canonical payloads, matching HashingStateStore's exact policy. */ private final Map> visited=new HashMap<>(); @@ -156,7 +163,18 @@ private static final class Frame { * @param mode scheduling granularity */ BytecodeExplorer(BytecodeProgram program,BytecodeScheduler.Mode mode) { + this(program,mode,null,false); + } + + /** Creates the owned public execution route with the same boundary-based deadline semantics as the runner. + * @param program validated model + * @param mode selected scheduling granularity + * @param maxTime optional duration, converted with the runner's millisecond semantics + * @param captureEvidence whether to retain immutable boundary diagnostics + */ + BytecodeExplorer(BytecodeProgram program,BytecodeScheduler.Mode mode,java.time.Duration maxTime,boolean captureEvidence) { this.program=Objects.requireNonNull(program);scheduler=new BytecodeScheduler(program,mode); + this.captureEvidence=captureEvidence;this.maxTimeMillis=maxTime==null ? null : maxTime.toMillis(); } /** Runs exact DFS with a64MiB canonical-payload safety budget. @@ -171,20 +189,21 @@ private static final class Frame { Result explore(Budget budget) { Objects.requireNonNull(budget);visited.clear();witnesses.clear();states=transitions=opcodes=instructions=0; encodingCalls=encodingBytes=encodingNanos=keyBytes=checkInvocations=checkInstructions=0;traversalComplete=true; + startedMillis=System.currentTimeMillis();initialSnapshot=null; var initial=program.initialState();sharing=BytecodeSharing.refresh(initial); var stack=new ArrayDeque();var root=visit(initial,null,budget); if(root!=null)stack.push(root); while(traversalComplete && !stack.isEmpty()) { var frame=stack.peek(); if(frame.next==frame.choices.size()){stack.pop();continue;} - if(Thread.currentThread().isInterrupted()){interrupt(frame.state,frame.path,"CANCELLED");break;} + String stop=stopReason();if(stop!=null){interrupt(frame.state,frame.path,stop);break;} int actor=frame.choices.get(frame.next++);BytecodeScheduler.Transition transition; try {transition=scheduler.advance(frame.state,actor);} catch(java.util.concurrent.CancellationException cancelled){interrupt(frame.state,frame.path,"CANCELLED");break;} if(transition.kind()==OpcodeExecutor.Kind.BLOCKED)throw new IllegalStateException("Pure choice became disabled"); transitions++;instructions+=transition.instructions();sharing=sharing.plus(transition.sharing()); opcodes+=transition.executed().stream().filter(e->e.opcode()!=null).count(); - var path=new Path(frame.path,new Selection(actor,transition.executed())); + var path=new Path(frame.path,new Selection(actor,transition.executed()),null); var next=visit(transition.state(),path,budget);if(next!=null)stack.push(next); } return new Result(new ArrayList<>(witnesses.values()),traversalComplete, @@ -197,58 +216,42 @@ Result explore(Budget budget) { * @param budget checker budgets * @return an expandable frame, otherwise null */ private Frame visit(BytecodeState state,Path path,Budget budget) { - if(Thread.currentThread().isInterrupted()){interrupt(state,path,"CANCELLED");return null;} + String stop=stopReason(); + if(stop!=null){path=withSnapshot(state,path,state.canonicalBytes());interrupt(state,path,stop);return null;} long start=System.nanoTime();byte[] key=state.canonicalBytes();encodingNanos+=System.nanoTime()-start; encodingCalls++;encodingBytes+=key.length; int hash=Arrays.hashCode(key);var bucket=visited.get(hash); if(bucket!=null && bucket.stream().anyMatch(previous->Arrays.equals(previous,key)))return null; + path=withSnapshot(state,path,key); if(states>=budget.maxStates()){interrupt(state,path,"MAX_STATES");return null;} if(key.length>budget.maxKeyBytes()-keyBytes){interrupt(state,path,"KEY_BYTES");return null;} visited.computeIfAbsent(hash,ignored->new ArrayList<>()).add(key);states++;keyBytes+=key.length; - for(int actor=0;actorstate.executions.get(actor).phase==Phase.TERMINATED)) { - if(observe(state,path,false))record(state,path,Kind.COMPLETED,-1,null,null,null,List.of(),null); - return null; - } - var choices=scheduler.choices(state); - if(choices.isEmpty()) { - var waits=new ArrayList(); - for(int actor=0;actor Kind.CHECK_FALSE; - case ERROR -> Kind.OBSERVER_ERROR; - case LIMIT -> Kind.OBSERVER_LIMIT; - case INTERRUPTED -> throw new IllegalStateException("Cancellation already handled"); - }; - record(state,path,kind,-1,null,null,null,List.of(),failure);return false; + * @param path selected prefix, null for root + * @param canonical complete membership payload + * @return path carrying its immutable public snapshot */ + private Path withSnapshot(BytecodeState state,Path path,byte[] canonical) { + if(!captureEvidence)return path; + var snapshot=BytecodeSnapshots.capture(state,canonical); + if(path==null){initialSnapshot=snapshot;return null;} + return new Path(path.previous(),path.selection(),snapshot); + } + + /** Checks host interruption/deadline at state visits, independently of modeled resources. + * @return honest external cause, otherwise null */ + private String stopReason() { + if(Thread.currentThread().isInterrupted())return "CANCELLED"; + return maxTimeMillis!=null && System.currentTimeMillis()-startedMillis>=maxTimeMillis ? "MAX_TIME" : null; } /** Records a checker stop without inventing a modeled resource cutoff. @@ -270,11 +273,18 @@ private void interrupt(BytecodeState state,Path path,String reason) { * @param waits concrete monitor relationships * @param observer pure observer failure, otherwise null */ private void record(BytecodeState state,Path path,Kind kind,int actor,Fault fault,Cutoff cutoff,String interruption,List waits,BytecodeChecks.Failure observer) { - var shared=new TreeMap();state.statics.forEach((field,value)->shared.put(new Cell(NULL,field),value)); - state.heap.forEach((reference,object)->{if(object.shared)object.fields.forEach((field,value)->shared.put(new Cell(reference,field),value));}); - var outcome=new Outcome(kind,actor,fault,cutoff,interruption,waits,shared,observer); + recordOutcome(state,path,BytecodeObservations.outcome(state,kind,actor,fault,cutoff,interruption,waits,observer)); + } + + /** Retains actual schedules and immutable views without replaying a cancelled target execution. + * @param state committed terminal state + * @param path actual prefix + * @param outcome normalized observation */ + private void recordOutcome(BytecodeState state,Path path,Outcome outcome) { if(witnesses.containsKey(outcome))return; - var schedule=new ArrayList();for(var node=path;node!=null;node=node.previous())schedule.add(node.selection()); - Collections.reverse(schedule);witnesses.put(outcome,new Witness(outcome,state,schedule)); + var schedule=new ArrayList();var snapshots=new ArrayList(); + for(var node=path;node!=null;node=node.previous()){schedule.add(node.selection());if(captureEvidence)snapshots.add(node.snapshot());} + Collections.reverse(schedule);Collections.reverse(snapshots);if(captureEvidence)snapshots.addFirst(initialSnapshot); + witnesses.put(outcome,new Witness(outcome,state,schedule,snapshots)); } } diff --git a/src/main/java/dev/samhb/interleave/bytecode/BytecodeLimits.java b/src/main/java/dev/samhb/interleave/bytecode/BytecodeLimits.java index 4a9a258..54d9b3e 100644 --- a/src/main/java/dev/samhb/interleave/bytecode/BytecodeLimits.java +++ b/src/main/java/dev/samhb/interleave/bytecode/BytecodeLimits.java @@ -1,5 +1,5 @@ /** - * Immutable internal resource profile; public bytecode selection remains unavailable until 94C. + * Immutable resource profile for controlled bytecode interpretation. */ package dev.samhb.interleave.bytecode; @@ -16,14 +16,14 @@ * @param setupHeapCells setup cell allowance * @param checkInstructions observer invocation work allowance */ -record BytecodeLimits(int actorInstructions, int actorAllocations, int actorHeapCells, +public record BytecodeLimits(int actorInstructions, int actorAllocations, int actorHeapCells, int maxCallDepth, int maxArrayLength, int maxStringLength, int setupInstructions, int setupAllocations, int setupHeapCells, - int checkInstructions) { + int checkInstructions) implements java.io.Serializable { /** * Rejects zero, negative and above-ceiling limits before any target input is processed. */ - BytecodeLimits { + public BytecodeLimits { int[] values = {actorInstructions, actorAllocations, actorHeapCells, maxCallDepth, maxArrayLength, maxStringLength, setupInstructions, setupAllocations, setupHeapCells, checkInstructions}; int[] ceilings = {4096,4096,65536,256,4096,4096,65536,4096,65536,16384}; @@ -36,9 +36,9 @@ record BytecodeLimits(int actorInstructions, int actorAllocations, int actorHeap /** * Returns the provisional resource profile for the first bytecode release. - * @return provisional engineering defaults, subject to the 94B measurement gate + * @return provisional engineering defaults, reviewed against the 94B feasibility fixtures */ - static BytecodeLimits defaults() { + public static BytecodeLimits defaults() { return new BytecodeLimits(256,128,8192,32,64,256,4096,128,8192,1024); } } diff --git a/src/main/java/dev/samhb/interleave/bytecode/BytecodeLoadException.java b/src/main/java/dev/samhb/interleave/bytecode/BytecodeLoadException.java index cd5cb4b..cb202b8 100644 --- a/src/main/java/dev/samhb/interleave/bytecode/BytecodeLoadException.java +++ b/src/main/java/dev/samhb/interleave/bytecode/BytecodeLoadException.java @@ -1,12 +1,12 @@ /** - * Fail-closed internal loading diagnostics, distinct from interpreted actor failures. + * Fail-closed loading diagnostics, distinct from interpreted actor failures. */ package dev.samhb.interleave.bytecode; /** * Reports malformed/unsupported input, unavailable metadata, limits and interpreted setup failures. */ -final class BytecodeLoadException extends IllegalArgumentException { +public final class BytecodeLoadException extends IllegalArgumentException { /** * Stable diagnostic family. */ @@ -27,4 +27,12 @@ final class BytecodeLoadException extends IllegalArgumentException { this.category = category; this.location = location; } + /** Returns the stable diagnostic family, such as INPUT, MALFORMED, UNSUPPORTED or LIMIT. + * @return diagnostic category */ + public String category(){return category;} + + /** Returns the actual interpreted location when available, without inventing a source span. + * @return bytecode location, or null for file/class-level diagnostics */ + public BytecodeLocation location(){return location;} + } diff --git a/src/main/java/dev/samhb/interleave/bytecode/BytecodeLoader.java b/src/main/java/dev/samhb/interleave/bytecode/BytecodeLoader.java index 3aa919f..2287a80 100644 --- a/src/main/java/dev/samhb/interleave/bytecode/BytecodeLoader.java +++ b/src/main/java/dev/samhb/interleave/bytecode/BytecodeLoader.java @@ -34,7 +34,7 @@ final class BytecodeLoader { */ static final int MAX_CLASSES=64; /** - * Annotation protocol prefix; definitions are test-only until94C. + * Annotation protocol prefix; definitions are parsed as metadata, never reflectively invoked. */ private static final String ANNOTATION="Ldev/samhb/interleave/bytecode/"; /** @@ -496,7 +496,7 @@ private String digest() { try { var digest=MessageDigest.getInstance("SHA-256"); var sink=new DataOutputStream(new DigestOutputStream(OutputStream.nullOutputStream(),digest)); - sink.writeUTF("BYTECODE-94A-1"); sink.writeInt(bytes.size()); + sink.writeUTF(BytecodeProgram.PROFILE_VERSION); sink.writeInt(bytes.size()); for (var entry : bytes.entrySet()) { byte[] name=entry.getKey().getBytes(java.nio.charset.StandardCharsets.UTF_8); sink.writeInt(name.length); sink.write(name); sink.writeInt(entry.getValue().length); sink.write(entry.getValue()); diff --git a/src/main/java/dev/samhb/interleave/bytecode/BytecodeLocation.java b/src/main/java/dev/samhb/interleave/bytecode/BytecodeLocation.java index 79b1452..50adb3d 100644 --- a/src/main/java/dev/samhb/interleave/bytecode/BytecodeLocation.java +++ b/src/main/java/dev/samhb/interleave/bytecode/BytecodeLocation.java @@ -10,4 +10,12 @@ * @param descriptor JVM method descriptor * @param bci bytecode index */ -record BytecodeLocation(String owner, String name, String descriptor, int bci) {} +public record BytecodeLocation(String owner, String name, String descriptor, int bci) implements java.io.Serializable { + /** Validates the real method identity and nonnegative bytecode index. + * @throws IllegalArgumentException for empty identities or a negative index + * @throws NullPointerException for null method identity components */ + public BytecodeLocation { + java.util.Objects.requireNonNull(owner);java.util.Objects.requireNonNull(name);java.util.Objects.requireNonNull(descriptor); + if(owner.isEmpty() || name.isEmpty() || descriptor.isEmpty() || bci<0)throw new IllegalArgumentException("Invalid bytecode location"); + } +} diff --git a/src/main/java/dev/samhb/interleave/bytecode/BytecodeObservations.java b/src/main/java/dev/samhb/interleave/bytecode/BytecodeObservations.java new file mode 100644 index 0000000..90711b5 --- /dev/null +++ b/src/main/java/dev/samhb/interleave/bytecode/BytecodeObservations.java @@ -0,0 +1,74 @@ +/** Shared actor/check/deadlock observations for exact search and strict replay, without source callbacks. */ +package dev.samhb.interleave.bytecode; + +import java.util.*; +import static dev.samhb.interleave.bytecode.BytecodeState.*; + +/** Defines one observation boundary over committed owned state; observers use separate scratch frames. */ +final class BytecodeObservations { + /** Prevents construction of this stateless observation module. */ + private BytecodeObservations() {} + + /** One boundary's terminal meaning and separate observer work. + * @param outcome terminal observation, or null for a runnable prefix + * @param invocations attempted check invocations + * @param instructions actual observer opcode work */ + record Evaluation(BytecodeExplorer.Outcome outcome,long invocations,long instructions) {} + + /** Applies the existing terminal-before-check, ALWAYS and normal-only FINAL order. + * @param program validated immutable model + * @param state committed owned state + * @return terminal/prefix meaning and actual observer work */ + static Evaluation evaluate(BytecodeProgram program,BytecodeState state) { + for(int actor=0;actorstate.executions.get(actor).phase==Phase.TERMINATED)) { + var last=BytecodeChecks.evaluate(program,state,false); + return new Evaluation(last.failure()==null ? outcome(state,BytecodeExplorer.Kind.COMPLETED,-1,null,null,null,List.of(),null) + : failed(state,last.failure()),always.invocations()+last.invocations(),always.instructions()+last.instructions()); + } + var waits=new ArrayList();boolean runnable=false; + for(int actor=0;actorBytecodeExplorer.Kind.CHECK_FALSE;case ERROR->BytecodeExplorer.Kind.OBSERVER_ERROR; + case LIMIT->BytecodeExplorer.Kind.OBSERVER_LIMIT;case INTERRUPTED->BytecodeExplorer.Kind.INTERRUPTED; + }; + return outcome(state,kind,-1,null,null,kind==BytecodeExplorer.Kind.INTERRUPTED ? "CANCELLED" : null,List.of(),kind==BytecodeExplorer.Kind.INTERRUPTED ? null : failure); + } + + /** Captures normalized shared observations for all terminal categories, including incomplete prefixes. + * @param state actual committed state + * @param kind category + * @param actor fault/cutoff owner + * @param fault actor fault + * @param cutoff modeled omitted operation + * @param interruption external cause + * @param waits blocked monitor relationships + * @param observer separate check failure + * @return immutable normalized observation */ + static BytecodeExplorer.Outcome outcome(BytecodeState state,BytecodeExplorer.Kind kind,int actor,Fault fault,Cutoff cutoff,String interruption,List waits,BytecodeChecks.Failure observer) { + var shared=new TreeMap();state.statics.forEach((field,value)->shared.put(new BytecodeExplorer.Cell(NULL,field),value)); + state.heap.forEach((reference,object)->{if(object.shared)object.fields.forEach((field,value)->shared.put(new BytecodeExplorer.Cell(reference,field),value));}); + return new BytecodeExplorer.Outcome(kind,actor,fault,cutoff,interruption,waits,shared,observer); + } +} diff --git a/src/main/java/dev/samhb/interleave/bytecode/BytecodeProgram.java b/src/main/java/dev/samhb/interleave/bytecode/BytecodeProgram.java index 75757b7..6ac90f7 100644 --- a/src/main/java/dev/samhb/interleave/bytecode/BytecodeProgram.java +++ b/src/main/java/dev/samhb/interleave/bytecode/BytecodeProgram.java @@ -1,14 +1,14 @@ /** - * Immutable internal bytecode artifact and interpreted setup snapshot. + * Immutable frozen bytecode artifact and interpreted setup snapshot. */ package dev.samhb.interleave.bytecode; import java.util.*; /** - * Closed validated metadata; has no public construction or execution interface in 94A. + * Closed validated metadata, constructed only by the metadata-only loader. */ -final class BytecodeProgram { +public final class BytecodeProgram { /** * Field identity. * @param owner declaring internal class @@ -101,7 +101,22 @@ record Check(BytecodeMethod.Id method, boolean always) {} * Returns the exact frozen manifest fingerprint. * @return exact frozen class-manifest digest */ - String artifactDigest() { return digest; } + public String artifactDigest() { return digest; } + + /** Version of the admitted language, intrinsic costs and sequentially consistent execution profile. */ + static final String PROFILE_VERSION="BYTECODE-SC-1"; + + /** Returns the frozen execution-profile version used to authenticate evidence. + * @return bounded sequentially consistent profile identifier */ + public String profileVersion(){return PROFILE_VERSION;} + + /** Returns the immutable selected execution allowances. + * @return validated per-owner limits */ + public BytecodeLimits limits(){return limits;} + + /** Returns the selected model's binary class name, independent of the class-directory path. + * @return selected fixture binary name */ + public String modelClass(){return model.replace('/','.');} /** * Creates an isolated post-setup state with fresh actor frames. diff --git a/src/main/java/dev/samhb/interleave/bytecode/BytecodeRuntime.java b/src/main/java/dev/samhb/interleave/bytecode/BytecodeRuntime.java new file mode 100644 index 0000000..cf6bdb3 --- /dev/null +++ b/src/main/java/dev/samhb/interleave/bytecode/BytecodeRuntime.java @@ -0,0 +1,141 @@ +/** Owned integration operations shared by the public loader, runner and strict replay route. */ +package dev.samhb.interleave.bytecode; + +import dev.samhb.interleave.*; +import dev.samhb.interleave.core.*; +import dev.samhb.interleave.search.TraceOutcome; +import java.lang.classfile.Attributes; +import java.nio.file.Path; +import java.time.Duration; +import java.util.*; + +/** Deep bytecode integration seam; no mutable execution state or caller-supplied callback is exposed. + * Library clients normally use format.BytecodeProgramLoader, InterleaveRunner and search.TraceReplayer. */ +public final class BytecodeRuntime { + /** Prevents construction of this stateless integration facade. */ + private BytecodeRuntime() {} + + /** Freezes and validates one immutable regular-file directory classpath and interprets setup. + * @param directory immutable input directory during loading + * @param modelClass selected binary fixture class name + * @param limits validated immutable execution allowances + * @return immutable interpreted artifact, independent of subsequent input changes + * @throws BytecodeLoadException for input, metadata, unsupported behavior or setup failure */ + public static BytecodeProgram load(Path directory,String modelClass,BytecodeLimits limits){return BytecodeLoader.load(directory,modelClass,limits);} + + /** Runs owned exact DFS in the released batched profile, retaining all normalized witness categories. + * External deadlines are checked at scheduling boundaries; they do not preempt individual opcodes. + * @param program immutable loaded artifact + * @param maxStates maximum admitted states, zero for the runner's unlimited selection + * @param maxTime optional boundary-based millisecond deadline + * @return immutable result with distinct BYTECODE diagnostics and exact storage metadata + * @throws NullPointerException for a null program + * @throws IllegalArgumentException for a negative state limit + * @throws ArithmeticException if the duration cannot be represented in milliseconds */ + public static TestResult run(BytecodeProgram program,long maxStates,Duration maxTime) { + Objects.requireNonNull(program);if(maxStates<0)throw new IllegalArgumentException("Negative state budget"); + long started=System.nanoTime(),before=usedHeap(); + var explorer=new BytecodeExplorer(program,BytecodeScheduler.Mode.BATCHED,maxTime,true); + var result=explorer.explore(maxStates==0 ? Long.MAX_VALUE : maxStates); + var failed=new ArrayList();var deadlocked=new ArrayList(); + var completed=new ArrayList();var incomplete=new ArrayList(); + ResourceLimitReason resource=null; + for(var witness:result.witnesses()) { + var trace=record(program,witness);switch(trace.outcome()) { + case VIOLATION->failed.add(trace);case DEADLOCK->deadlocked.add(trace); + case COMPLETED->completed.add(trace);case INCOMPLETE->incomplete.add(trace); + } + if(witness.outcome().interruption()!=null)resource=switch(witness.outcome().interruption()) { + case "MAX_STATES"->ResourceLimitReason.MAX_STATES;case "MAX_TIME"->ResourceLimitReason.MAX_TIME;default->null; + }; + } + return new TestResult(Strategy.DFS,result.metrics().states(),(System.nanoTime()-started)/1_000_000,usedHeap()-before, + failed,deadlocked,completed,incomplete,!result.traversalComplete()).withRunMetadata(false,resource,false); + } + + /** Constructs selected declaration identity independently of the manifest's possible shared closure. + * @param program frozen loaded definition + * @return immutable public profile/model identity */ + static BytecodeEvidence.Identity identity(BytecodeProgram program) { + var actors=new ArrayList(); + for(int actor=0;actornew BytecodeEvidence.Check(method(check.method()),check.always() ? "ALWAYS" : "FINAL")).toList(); + return new BytecodeEvidence.Identity(program.artifactDigest(),program.profileVersion(),program.modelClass(),actors,checks, + program.limits(),"BATCHED","DFS","DFS",null); + } + + /** Converts a genuine retained witness without reexecuting cancelled or faulted model code. + * @param program frozen artifact supplying debug metadata + * @param witness actual selected path and owned snapshots + * @return public immutable trace */ + private static TraceRecord record(BytecodeProgram program,BytecodeExplorer.Witness witness) { + var transitions=witness.schedule().stream().map(selection->new BytecodeEvidence.Transition(selection.actor(), + selection.executed().stream().map(operation->new BytecodeEvidence.Operation(operation.location(),line(program,operation.location()), + operation.opcode()==null ? null : operation.opcode().name(),operation.event())).toList())).toList(); + var terminal=terminal(witness.outcome());var evidence=new BytecodeEvidence(1,identity(program),transitions,witness.snapshots(),terminal,null); + var choices=witness.schedule().stream().map(BytecodeExplorer.Selection::actor).toList(); + var outcomes=witness.schedule().stream().map(BytecodeRuntime::stepOutcome).toList(); + return new TraceRecord(choices,outcomes,traceOutcome(terminal),program.artifactDigest(), + witness.snapshots().stream().map(BytecodeSnapshots::display).toList(),null,evidence); + } + + /** Maps actual selected events into the legacy coarse step vocabulary without source continuations. + * @param selection committed transition + * @return coarse step outcome; precise cause remains in BYTECODE evidence */ + static StepOutcome stepOutcome(BytecodeExplorer.Selection selection) { + String event=selection.executed().getLast().event(); + return event.equals("TERMINATION") ? StepOutcome.TERMINATED : event.equals("FAILURE") ? StepOutcome.ASSERTION_FAILED : StepOutcome.ADVANCED; + } + + /** Maps precise terminal meaning to the existing four public outcome categories. + * @param terminal actual bytecode observation + * @return public terminal category */ + static TraceOutcome traceOutcome(BytecodeEvidence.Terminal terminal) { + return switch(terminal.kind()) { + case "COMPLETED"->TraceOutcome.COMPLETED;case "DEADLOCK"->TraceOutcome.DEADLOCK; + case "CHECK_FALSE","UNCAUGHT_EXCEPTION"->TraceOutcome.VIOLATION;default->TraceOutcome.INCOMPLETE; + }; + } + + /** Exports normalized actor/check/resource meaning, preserving the original cause and stack. + * @param outcome internal observation, null for a runnable replay prefix + * @return immutable public terminal/prefix */ + static BytecodeEvidence.Terminal terminal(BytecodeExplorer.Outcome outcome) { + if(outcome==null)return new BytecodeEvidence.Terminal("PREFIX",-1,null,null,null,List.of(),null); + var check=outcome.observer();var failure=check==null ? null : new BytecodeEvidence.CheckFailure(check.kind().name(),method(check.check()),check.location(),fault(check.fault()),cutoff(check.cutoff())); + return new BytecodeEvidence.Terminal(outcome.kind().name(),outcome.actor(),fault(outcome.fault()),cutoff(outcome.cutoff()),failure, + outcome.waits().stream().map(wait->new BytecodeEvidence.Wait(wait.actor(),wait.owner(),BytecodeSnapshots.identity(wait.monitor()),wait.depth())).toList(),outcome.interruption()); + } + + /** Retains descriptor-complete declaration identity. + * @param method immutable internal declaration + * @return public method identity */ + private static BytecodeEvidence.Method method(BytecodeMethod.Id method){return new BytecodeEvidence.Method(method.owner(),method.name(),method.descriptor());} + + /** Copies original modeled fault identity, excluding host exception objects. + * @param fault optional modeled token + * @return immutable fault, otherwise null */ + private static BytecodeEvidence.Fault fault(BytecodeState.Fault fault){return fault==null ? null : new BytecodeEvidence.Fault(fault.type(),fault.location(),fault.stack());} + + /** Copies exact omitted work and allowance. + * @param cutoff optional modeled cutoff + * @return public cutoff, otherwise null */ + private static BytecodeEvidence.Cutoff cutoff(BytecodeState.Cutoff cutoff){return cutoff==null ? null : new BytecodeEvidence.Cutoff(cutoff.reason(),cutoff.location(),cutoff.limit(),cutoff.required(),cutoff.remaining());} + + /** Reads optional compiler lines from already frozen metadata, with no filesystem or source-span inference. + * @param program frozen artifact + * @param location real interpreted position + * @return positive compiler line, otherwise null */ + static Integer line(BytecodeProgram program,BytecodeLocation location) { + var method=program.methods.get(new BytecodeMethod.Id(location.owner(),location.name(),location.descriptor())); + var table=method.code.findAttribute(Attributes.lineNumberTable());int start=-1;Integer line=null; + if(table.isPresent())for(var entry:table.get().lineNumbers())if(entry.startPc()<=location.bci() && entry.startPc()>=start) { + start=entry.startPc();line=entry.lineNumber()>0 ? entry.lineNumber() : null; + } + return line; + } + + /** Reads instantaneous JVM heap use, not a retained-memory benchmark or model heap budget. + * @return current used JVM heap bytes */ + private static long usedHeap(){var runtime=Runtime.getRuntime();return runtime.totalMemory()-runtime.freeMemory();} +} diff --git a/src/main/java/dev/samhb/interleave/bytecode/BytecodeScheduler.java b/src/main/java/dev/samhb/interleave/bytecode/BytecodeScheduler.java index e31da61..0da8834 100644 --- a/src/main/java/dev/samhb/interleave/bytecode/BytecodeScheduler.java +++ b/src/main/java/dev/samhb/interleave/bytecode/BytecodeScheduler.java @@ -16,8 +16,14 @@ enum Mode { /** One executed opcode or implicit event at a real method/BCI position. * @param location real interpreted position * @param opcode executed opcode, null for an implicit event or omitted fuel operation + * @param event real opcode or classified finite implicit event */ - record Executed(BytecodeLocation location,Opcode opcode) {} + record Executed(BytecodeLocation location,Opcode opcode,String event) { + /** Creates metadata for one actual opcode, retaining the internal two-argument test seam. + * @param location real position + * @param opcode actual opcode */ + Executed(BytecodeLocation location,Opcode opcode){this(location,opcode,"OPCODE");} + } /** An owned scheduling result; no source step ordinals are manufactured. * @param state isolated successor @@ -81,7 +87,12 @@ Transition advance(BytecodeState parent,int actor) { } var result=OpcodeExecutor.step(program,state,actor);var next=result.state(); int charged=next.executions.get(actor).instructions-before.instructions; - executed.add(new Executed(probe.location(),charged==0 ? null : probe.opcode())); + String event=charged>0 ? "OPCODE" : probe.exhausted() ? "FUEL_CUTOFF" : switch(before.phase) { + case RUNNING -> "MONITOR_ENTER";case RETURNING -> "RETURN";case EXCEPTION -> "EXCEPTION"; + case TERMINATION_PENDING -> "TERMINATION";case FAILURE_PENDING -> "FAILURE";case CUTOFF_PENDING -> "CUTOFF"; + default -> throw new IllegalStateException("No executable implicit event"); + }; + executed.add(new Executed(probe.location(),charged==0 ? null : probe.opcode(),event)); instructions+=charged;kind=result.kind();state=next;observable|=probe.observable(); if(publication && kind==OpcodeExecutor.Kind.ADVANCED)sharing=sharing.plus(BytecodeSharing.refresh(state)); // Every discovered return/fault/cutoff yields before terminal delivery, including local failures. diff --git a/src/main/java/dev/samhb/interleave/bytecode/BytecodeSnapshots.java b/src/main/java/dev/samhb/interleave/bytecode/BytecodeSnapshots.java new file mode 100644 index 0000000..8df2f35 --- /dev/null +++ b/src/main/java/dev/samhb/interleave/bytecode/BytecodeSnapshots.java @@ -0,0 +1,97 @@ +/** Pure immutable bytecode snapshots and lossless display projections, without target callbacks. */ +package dev.samhb.interleave.bytecode; + +import dev.samhb.interleave.core.BytecodeEvidence; +import dev.samhb.interleave.core.StateSnapshot; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.*; +import static dev.samhb.interleave.bytecode.BytecodeState.*; + +/** Creates owned evidence at search boundaries so cancelled runs never need to reexecute their prefixes. */ +final class BytecodeSnapshots { + /** Prevents construction of this stateless projection module. */ + private BytecodeSnapshots() {} + + /** Captures full-state authentication and immutable typed heap/frame/resource diagnostics. + * @param state committed state, never modified + * @param canonical complete canonical payload already encoded by membership + * @return immutable diagnostic snapshot */ + static BytecodeEvidence.Snapshot capture(BytecodeState state,byte[] canonical) { + var fields=new TreeMap();var locals=new TreeMap>(); + var heap=new ArrayList(); + state.statics.forEach((field,slot)->fields.put("static."+field(field),value(slot))); + state.heap.forEach((reference,object)->{ + String id=identity(reference);heap.add(new BytecodeEvidence.ObjectState(id,object.type,object.shared,object.initialized,object.monitorOwner,object.monitorDepth)); + object.fields.forEach((field,slot)->fields.put(id+"."+field(field),value(slot))); + }); + state.executions.forEach((actor,execution)->{ + var slots=new TreeMap(); + slots.put("phase",text(execution.phase.name()));slots.put("instructions",number(execution.instructions)); + slots.put("allocations",number(execution.allocations));slots.put("heapCells",number(execution.cells)); + slots.put("allocationSequence",new BytecodeEvidence.Value("LONG",Long.toString(execution.nextSequence))); + if(execution.eventLocation!=null)slots.put("pending.location",text(execution.eventLocation.toString())); + if(execution.returned!=null)slots.put("pending.return",value(execution.returned)); + if(execution.fault!=null)slots.put("pending.fault",text(execution.fault.toString())); + if(execution.cutoff!=null)slots.put("pending.cutoff",text(execution.cutoff.toString())); + for(int index=0;indexslots.put(prefix+"local"+slot,value(entry))); + for(int operand=0;operandfields.put("@setup."+name,entry)); + else locals.put(Integer.toString(actor),slots); + }); + try {return new BytecodeEvidence.Snapshot(HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(canonical)),fields,locals,heap);} + catch(NoSuchAlgorithmException impossible){throw new IllegalStateException("Required SHA-256 unavailable",impossible);} + } + + /** Projects typed values into the existing display-only snapshot interface without numeric narrowing. + * @param snapshot immutable authenticated bytecode view + * @return display snapshot with only immutable tagged string leaves */ + static StateSnapshot display(BytecodeEvidence.Snapshot snapshot) { + var fields=new TreeMap();var locals=new TreeMap>(); + snapshot.fields().forEach((name,entry)->fields.put(name,entry.type().toLowerCase(Locale.ROOT)+":"+entry.raw())); + snapshot.locals().forEach((actor,slots)->{ + var row=new TreeMap();slots.forEach((name,entry)->row.put(name,entry.type().toLowerCase(Locale.ROOT)+":"+entry.raw()));locals.put(actor,row); + }); + return new StateSnapshot(fields,locals); + } + + /** Names permanent setup/actor/class-monitor identities without heap renumbering. + * @param reference nonnull modeled identity + * @return stable tagged identity */ + static String identity(Ref reference) { + return (reference.owner()==SETUP ? "setup:" : reference.owner()== -2 ? "class:" : "actor:"+reference.owner()+":")+reference.sequence(); + } + + /** Converts a category-one slot; wider raw-bit tags are reserved by the public schema. + * @param slot immutable VM slot, or null for an uninitialized diagnostic slot + * @return immutable lossless tagged value */ + private static BytecodeEvidence.Value value(Value slot) { + return switch(slot) { + case null -> new BytecodeEvidence.Value("NULL",""); + case Int integer -> number(integer.value()); + case Ref reference -> reference.equals(NULL) ? new BytecodeEvidence.Value("NULL","") : new BytecodeEvidence.Value("REFERENCE",identity(reference)); + case Thrown thrown -> new BytecodeEvidence.Value("FAULT",thrown.fault().toString()); + }; + } + + /** Formats declared field identities rather than relying on implementation diagnostic text. + * @param field immutable declared slot + * @return exact owner/name/descriptor display key */ + private static String field(BytecodeProgram.FieldId field){return field.owner()+"."+field.name()+":"+field.descriptor();} + + /** Constructs one exact category-one integer. + * @param value modeled integer/counter + * @return decimal tagged integer */ + private static BytecodeEvidence.Value number(int value){return new BytecodeEvidence.Value("INT",Integer.toString(value));} + + /** Constructs immutable frame/phase diagnostic text. + * @param value complete diagnostic text + * @return tagged text */ + private static BytecodeEvidence.Value text(String value){return new BytecodeEvidence.Value("TEXT",value);} +} diff --git a/src/test/java/dev/samhb/interleave/bytecode/Check.java b/src/main/java/dev/samhb/interleave/bytecode/Check.java similarity index 78% rename from src/test/java/dev/samhb/interleave/bytecode/Check.java rename to src/main/java/dev/samhb/interleave/bytecode/Check.java index 2ed276b..645a746 100644 --- a/src/test/java/dev/samhb/interleave/bytecode/Check.java +++ b/src/main/java/dev/samhb/interleave/bytecode/Check.java @@ -1,7 +1,7 @@ -/** Test-only annotation protocol; not published in the library before94C. */ +/** Public metadata-only annotation protocol for the bounded sequentially consistent profile. */ package dev.samhb.interleave.bytecode; -/** Declares a pure observer;94A validates metadata and94B implements invocation. */ +/** Declares an interpreted pure observer with a separate per-invocation fuel allowance. */ @java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.CLASS) @java.lang.annotation.Target(java.lang.annotation.ElementType.METHOD) public @interface Check { diff --git a/src/test/java/dev/samhb/interleave/bytecode/Model.java b/src/main/java/dev/samhb/interleave/bytecode/Model.java similarity index 68% rename from src/test/java/dev/samhb/interleave/bytecode/Model.java rename to src/main/java/dev/samhb/interleave/bytecode/Model.java index 44ce020..e38309d 100644 --- a/src/test/java/dev/samhb/interleave/bytecode/Model.java +++ b/src/main/java/dev/samhb/interleave/bytecode/Model.java @@ -1,4 +1,4 @@ -/** Test-only annotation protocol; not published in the library before94C. */ +/** Public metadata-only annotation protocol for the bounded sequentially consistent profile. */ package dev.samhb.interleave.bytecode; @java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.CLASS) @java.lang.annotation.Target(java.lang.annotation.ElementType.TYPE) diff --git a/src/main/java/dev/samhb/interleave/core/BytecodeEvidence.java b/src/main/java/dev/samhb/interleave/core/BytecodeEvidence.java new file mode 100644 index 0000000..3f58d4c --- /dev/null +++ b/src/main/java/dev/samhb/interleave/core/BytecodeEvidence.java @@ -0,0 +1,219 @@ +/** Immutable artifact-bound bytecode evidence, separate from source spans and source failure contracts. */ +package dev.samhb.interleave.core; + +import dev.samhb.interleave.bytecode.BytecodeLimits; +import dev.samhb.interleave.bytecode.BytecodeLocation; +import java.io.Serializable; +import java.util.*; + +/** Complete recorded bytecode execution with independently authenticated prefix replay observations. + * @param version wire/native payload schema, currently1 + * @param identity frozen artifact, model declarations, profile, limits and mode + * @param transitions actual original actor selections and executed operations + * @param snapshots immutable initial and transition-boundary snapshots + * @param terminal original run classification, including honest external stops + * @param replayObservation actual replay observation, otherwise null; never upgrades the original run */ +public record BytecodeEvidence(int version,Identity identity,List transitions,List snapshots, + Terminal terminal,Terminal replayObservation) implements Serializable { + /** Freezes aligned evidence and rejects incompatible schemas or a nonterminal original record. */ + public BytecodeEvidence { + if(version!=1)throw new IllegalArgumentException("Unsupported bytecode evidence version"); + Objects.requireNonNull(identity);Objects.requireNonNull(terminal); + transitions=List.copyOf(transitions);snapshots=List.copyOf(snapshots); + if(snapshots.size()!=transitions.size()+1 || terminal.kind().equals("PREFIX"))throw new IllegalArgumentException("Misaligned bytecode evidence"); + } + + /** Descriptor-complete interpreted entry identity. + * @param owner JVM internal declaring class name + * @param name method name + * @param descriptor exact JVM method descriptor */ + public record Method(String owner,String name,String descriptor) implements Serializable { + /** Requires complete method identity. */ + public Method {text(owner);text(name);text(descriptor);} + } + + /** Original annotation-declared actor mapping. + * @param id dense original actor identity + * @param method public instance no-argument void entry */ + public record Actor(int id,Method method) implements Serializable { + /** Validates the original actor and method shape. */ + public Actor {Objects.requireNonNull(method);if(id<0 || id>7 || !method.descriptor().equals("()V"))throw new IllegalArgumentException("Invalid actor entry");} + } + + /** Declared pure observer mapping. + * @param method public instance no-argument boolean entry + * @param when ALWAYS or FINAL */ + public record Check(Method method,String when) implements Serializable { + /** Validates timing and the boolean observer descriptor. */ + public Check {Objects.requireNonNull(method);if(!Set.of("ALWAYS","FINAL").contains(when) || !method.descriptor().equals("()Z"))throw new IllegalArgumentException("Invalid check entry");} + } + + /** Frozen semantic identity; host directory paths are deliberately absent. + * @param artifactDigest exact class-manifest SHA-256 + * @param profileVersion admitted semantics/intrinsic-cost version + * @param modelClass selected binary fixture class name + * @param actors original dense actor/declaration mapping + * @param checks deterministically ordered check declarations + * @param limits immutable selected execution allowances + * @param mode BATCHED or internal REFERENCE execution granularity + * @param requestedStrategy requested traversal + * @param effectiveStrategy actual traversal + * @param fallbackReason absent for this release's exact DFS */ + public record Identity(String artifactDigest,String profileVersion,String modelClass,List actors,List checks, + BytecodeLimits limits,String mode,String requestedStrategy,String effectiveStrategy,String fallbackReason) implements Serializable { + /** Freezes declarations and rejects malformed identity or unavailable94C traversal metadata. */ + public Identity { + digest(artifactDigest);text(profileVersion);text(modelClass);Objects.requireNonNull(limits); + actors=List.copyOf(actors);checks=List.copyOf(checks); + if(actors.isEmpty() || actors.size()>8)throw new IllegalArgumentException("Invalid actor count"); + for(int index=0;index operations) implements Serializable { + /** Freezes nonempty selected work. */ + public Transition {operations=List.copyOf(operations);if(actor<0 || actor>7 || operations.isEmpty())throw new IllegalArgumentException("Invalid bytecode transition");} + } + + /** Lossless typed value: wide numeric data is a string, never an untyped JSON number. + * LONG and raw FLOAT_BITS/DOUBLE_BITS reserve representation for later language phases. + * @param type INT, LONG, FLOAT_BITS, DOUBLE_BITS, BOOLEAN, REFERENCE, NULL, TEXT or FAULT + * @param raw exact decimal, raw hex bits, permanent identity or diagnostic UTF-16 text */ + public record Value(String type,String raw) implements Serializable { + /** Validates tags and exact numeric representations without floating-point coercion. */ + public Value { + Objects.requireNonNull(raw); + switch(Objects.requireNonNull(type)) { + case "INT" -> {if(!Integer.toString(Integer.parseInt(raw)).equals(raw))throw new IllegalArgumentException("Noncanonical int");} + case "LONG" -> {if(!Long.toString(Long.parseLong(raw)).equals(raw))throw new IllegalArgumentException("Noncanonical long");} + case "FLOAT_BITS" -> {if(!raw.matches("[0-9a-f]{8}"))throw new IllegalArgumentException("Invalid float bits");} + case "DOUBLE_BITS" -> {if(!raw.matches("[0-9a-f]{16}"))throw new IllegalArgumentException("Invalid double bits");} + case "BOOLEAN" -> {if(!raw.equals("true") && !raw.equals("false"))throw new IllegalArgumentException("Invalid boolean");} + case "NULL" -> {if(!raw.isEmpty())throw new IllegalArgumentException("Invalid null value");} + case "REFERENCE","FAULT","TEXT" -> {text(raw);} + default -> throw new IllegalArgumentException("Unknown bytecode value tag"); + } + } + } + + /** Heap identity and synchronization/sharedness history, independent of field display names. + * @param identity permanent setup/actor/constant identity + * @param type internal class name + * @param shared irreversible sharing flag + * @param initialized whether constructor initialization completed + * @param owner current monitor owner, -2 when unowned + * @param depth reentrant monitor depth */ + public record ObjectState(String identity,String type,boolean shared,boolean initialized,int owner,int depth) implements Serializable { + /** Requires a permanent identity and internally consistent monitor state. */ + public ObjectState {text(identity);text(type);if(owner< -2 || owner>7 || depth<0 || (owner== -2)!=(depth==0))throw new IllegalArgumentException("Invalid monitor state");} + } + + /** Immutable display data plus a full-state authentication digest covering all hidden continuation state. + * @param stateDigest SHA-256 of the complete canonical state, including counters/frames/history + * @param fields typed model/static fields and setup diagnostics + * @param locals per-original-actor frames, operand/local slots, phases and resource diagnostics + * @param heap immutable heap identity/monitor metadata */ + public record Snapshot(String stateDigest,Map fields,Map> locals,List heap) implements Serializable { + /** Deeply freezes maps and heap metadata; values contain only immutable tagged strings. */ + public Snapshot { + digest(stateDigest);fields=Map.copyOf(fields);var copy=new TreeMap>(); + locals.forEach((actor,values)->copy.put(actor,Map.copyOf(values)));locals=Collections.unmodifiableMap(copy);heap=List.copyOf(heap); + } + } + + /** Original modeled runtime fault and interpreted stack. + * @param type internal exception class name + * @param location original faulting instruction + * @param stack interpreted method/BCI stack, outermost first */ + public record Fault(String type,BytecodeLocation location,List stack) implements Serializable { + /** Freezes the genuine fault stack. */ + public Fault {text(type);Objects.requireNonNull(location);stack=List.copyOf(stack);if(stack.isEmpty())throw new IllegalArgumentException("Missing fault stack");} + } + + /** Omitted modeled operation and exact allowance, separate from host resource interruptions. + * @param reason bounded resource name + * @param location omitted operation's real position + * @param limit selected resource maximum + * @param required work/demand for the attempt + * @param remaining allowance before the attempt */ + public record Cutoff(String reason,BytecodeLocation location,int limit,int required,int remaining) implements Serializable { + /** Requires genuine resource/location data. */ + public Cutoff {text(reason);Objects.requireNonNull(location);if(limit<1 || required<1 || remaining<0)throw new IllegalArgumentException("Invalid cutoff allowance");} + } + + /** Pure observer failure identity, never an actor exception. + * @param kind FALSE, ERROR or LIMIT + * @param check declared check method + * @param location actual return, fault or omitted opcode + * @param fault observer runtime fault for ERROR + * @param cutoff observer resource stop for LIMIT */ + public record CheckFailure(String kind,Method check,BytecodeLocation location,Fault fault,Cutoff cutoff) implements Serializable { + /** Validates the exclusive observer cause. */ + public CheckFailure { + Objects.requireNonNull(check);Objects.requireNonNull(location); + if(!Set.of("FALSE","ERROR","LIMIT").contains(kind) || (fault!=null)!=kind.equals("ERROR") || (cutoff!=null)!=kind.equals("LIMIT"))throw new IllegalArgumentException("Invalid observer failure"); + } + } + + /** Concrete deadlock ownership relationship. + * @param actor blocked original actor + * @param owner current owning actor + * @param monitor permanent monitored-object identity + * @param depth owning reentrant depth */ + public record Wait(int actor,int owner,String monitor,int depth) implements Serializable { + /** Rejects invalid ownership or an unheld monitor. */ + public Wait {text(monitor);if(actor<0 || actor>7 || owner<0 || owner>7 || depth<1)throw new IllegalArgumentException("Invalid wait relationship");} + } + + /** Terminal meaning; PREFIX appears only as a separate external-prefix replay observation. + * @param kind COMPLETED, DEADLOCK, UNCAUGHT_EXCEPTION, CHECK_FALSE, CUTOFF, OBSERVER_ERROR, OBSERVER_LIMIT, INTERRUPTED or PREFIX + * @param actor fault/cutoff actor, otherwise -1 + * @param fault original actor fault + * @param cutoff modeled actor cutoff + * @param check separate observer failure + * @param waits concrete deadlock relationships + * @param interruption external checker reason, never a modeled cutoff */ + public record Terminal(String kind,int actor,Fault fault,Cutoff cutoff,CheckFailure check,List waits,String interruption) implements Serializable { + /** Validates classification-specific evidence without executing a model. */ + public Terminal { + waits=List.copyOf(waits); + if(!Set.of("COMPLETED","DEADLOCK","UNCAUGHT_EXCEPTION","CHECK_FALSE","CUTOFF","OBSERVER_ERROR","OBSERVER_LIMIT","INTERRUPTED","PREFIX").contains(kind))throw new IllegalArgumentException("Unknown bytecode terminal"); + boolean actorFailure=kind.equals("UNCAUGHT_EXCEPTION") || kind.equals("CUTOFF"); + if(actorFailure ? actor<0 || actor>7 : actor!= -1)throw new IllegalArgumentException("Invalid terminal actor"); + if((fault!=null)!=kind.equals("UNCAUGHT_EXCEPTION") || (cutoff!=null)!=kind.equals("CUTOFF") + || (check!=null)!=Set.of("CHECK_FALSE","OBSERVER_ERROR","OBSERVER_LIMIT").contains(kind) + || kind.equals("DEADLOCK")!=!waits.isEmpty() || (interruption!=null)!=kind.equals("INTERRUPTED"))throw new IllegalArgumentException("Conflicting bytecode terminal causes"); + if(check!=null && !check.kind().equals(switch(kind){case "CHECK_FALSE"->"FALSE";case "OBSERVER_ERROR"->"ERROR";default->"LIMIT";}))throw new IllegalArgumentException("Wrong observer classification"); + if(interruption!=null && !Set.of("MAX_STATES","MAX_TIME","KEY_BYTES","CANCELLED").contains(interruption))throw new IllegalArgumentException("Unknown checker interruption"); + } + } + + /** Validates exact SHA-256 values before replay or serialization consumers use them. + * @param value required lowercase digest */ + private static void digest(String value){if(value==null || !value.matches("[0-9a-f]{64}"))throw new IllegalArgumentException("Invalid bytecode digest");} + + /** Requires a nonempty immutable identifier/diagnostic value. + * @param value required text */ + private static void text(String value){if(value==null || value.isEmpty())throw new IllegalArgumentException("Missing bytecode identity text");} +} diff --git a/src/main/java/dev/samhb/interleave/format/BytecodeProgramLoader.java b/src/main/java/dev/samhb/interleave/format/BytecodeProgramLoader.java new file mode 100644 index 0000000..a137a3e --- /dev/null +++ b/src/main/java/dev/samhb/interleave/format/BytecodeProgramLoader.java @@ -0,0 +1,28 @@ +/** Public directory-only loader for the bounded sequentially consistent bytecode profile. */ +package dev.samhb.interleave.format; + +import dev.samhb.interleave.bytecode.*; +import java.nio.file.Path; + +/** Parses and validates frozen class bytes, interpreting setup without reflectively loading target classes. */ +public final class BytecodeProgramLoader { + /** Prevents construction of this static loading facade. */ + private BytecodeProgramLoader() {} + + /** Loads one fixed-actor model using the provisional defaults reviewed against94B fixtures. + * Inputs are non-preview Java17–26 class files in one immutable regular-file directory classpath. + * No compilation, jar discovery or target-code host fallback occurs. + * @param classDirectory class-file root, immutable for the duration of loading + * @param modelClass selected binary fixture name + * @return immutable initialized program, safe to reuse independently + * @throws BytecodeLoadException for invalid input/metadata, unsupported behavior or interpreted setup failure */ + public static BytecodeProgram load(Path classDirectory,String modelClass){return load(classDirectory,modelClass,BytecodeLimits.defaults());} + + /** Loads one model with immutable per-owner allowances and bounded metadata-only resolution. + * @param classDirectory immutable regular-file classpath root + * @param modelClass selected binary fixture name + * @param limits validated execution limits + * @return frozen initialized program + * @throws BytecodeLoadException for null/invalid input, unsupported behavior, bounds or setup faults */ + public static BytecodeProgram load(Path classDirectory,String modelClass,BytecodeLimits limits){return BytecodeRuntime.load(classDirectory,modelClass,limits);} +} diff --git a/src/test/java/dev/samhb/interleave/bytecode/BytecodeReleaseTest.java b/src/test/java/dev/samhb/interleave/bytecode/BytecodeReleaseTest.java new file mode 100644 index 0000000..a908323 --- /dev/null +++ b/src/test/java/dev/samhb/interleave/bytecode/BytecodeReleaseTest.java @@ -0,0 +1,38 @@ +/** Public bytecode loading and runner behavior through the approved94C release interfaces. */ +package dev.samhb.interleave.bytecode; + +import dev.samhb.interleave.InterleaveRunner; +import dev.samhb.interleave.format.BytecodeProgramLoader; +import java.nio.file.Path; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import static org.junit.jupiter.api.Assertions.*; + +class BytecodeReleaseTest { + /** Real compiled increments produce a check failure and completion through the public runner. + * @param directory external compiler workspace + * @throws Exception for fixture failures */ + @Test void publicLoaderAndRunnerFindRealLostUpdate(@TempDir Path directory) throws Exception { + var classes=BytecodeFixtures.compile(directory,26,""" + @Model public class Fixture {public int x;public Fixture(){} + @Actor(id=0)public void first(){x++;} @Actor(id=1)public void second(){x++;} + @Check public boolean valid(){return x==2;}} + """); + var program=BytecodeProgramLoader.load(classes,"Fixture"); + var result=InterleaveRunner.builder().build().runBytecode(program); + assertTrue(result.hasViolation());assertFalse(result.limitExceeded());assertFalse(result.hasIncomplete()); + assertEquals(1,result.failingTraces().size());assertEquals(1,result.completedTraces().size()); + var trace=result.failingTraces().getFirst();assertNull(trace.evidence());assertNotNull(trace.bytecodeEvidence()); + assertEquals(program.artifactDigest(),trace.bytecodeEvidence().identity().artifactDigest()); + assertEquals(program.profileVersion(),trace.bytecodeEvidence().identity().profileVersion()); + assertEquals(program.limits(),trace.bytecodeEvidence().identity().limits()); + assertEquals("Fixture",trace.bytecodeEvidence().identity().modelClass()); + assertEquals("BATCHED",trace.bytecodeEvidence().identity().mode()); + assertEquals(trace.threadIds().size(),trace.bytecodeEvidence().transitions().size()); + assertEquals(trace.threadIds().size()+1,trace.states().size()); + assertEquals("CHECK_FALSE",trace.bytecodeEvidence().terminal().kind()); + assertEquals("int:1",trace.states().getLast().fields().get("setup:0.Fixture.x:I")); + assertTrue(result.toJson().contains("\"programKind\": \"BYTECODE\"")); + assertFalse(trace.toJson().contains("\"sourceDigest\"")); + } +} From d0c2b5b1e069539767a2f95aefae583cba22194e Mon Sep 17 00:00:00 2001 From: Samuel Date: Thu, 19 Nov 2026 00:44:56 -0500 Subject: [PATCH 2/3] feat: complete public bytecode replay and consumers Release the bounded SC bytecode profile through strict artifact-bound replay, lossless JSON, CLI, reports, soundness checks and the viewer. Preserve original incomplete prefixes, monitor cleanup evidence and exact state ownership. Validate independently compiled jar consumers and retain explicit mutation/review evidence without broadening the admitted language or strategies. Co-authored-by: Codex --- .github/workflows/build.yml | 3 +- README.md | 16 +- build.gradle.kts | 8 +- docs/measurements/94C-bytecode-release.md | 213 ++++++++++++-- docs/plans/bytecode-contract.md | 10 +- docs/plans/future-work.md | 8 +- docs/specs/active/94C-bytecode-release.md | 26 +- docs/visualizer-e2e.mjs | 33 ++- docs/visualizer-normalize-check.mjs | 28 +- docs/visualizer.js | 139 +++++++++- examples/bytecode/README.md | 43 ++- .../samhb/interleave/BytecodeTraceJson.java | 116 ++++++++ .../java/dev/samhb/interleave/ResultJson.java | 17 ++ .../java/dev/samhb/interleave/TestResult.java | 2 +- .../dev/samhb/interleave/TraceRecord.java | 11 +- .../interleave/bytecode/BytecodeReplay.java | 83 ++++++ .../interleave/bytecode/BytecodeRuntime.java | 27 +- .../dev/samhb/interleave/bytecode/Model.java | 1 + .../java/dev/samhb/interleave/cli/Main.java | 38 +++ .../interleave/core/BytecodeEvidence.java | 5 +- .../format/BytecodeProgramLoader.java | 15 +- .../interleave/report/BenchmarkHarness.java | 15 + .../interleave/report/BenchmarkResult.java | 32 +++ .../samhb/interleave/report/ReportWriter.java | 34 +++ .../report/SoundnessAttestation.java | 15 + .../interleave/search/TraceReplayer.java | 17 ++ .../interleave/bytecode/BytecodeFixtures.java | 13 +- .../bytecode/BytecodeReleaseTest.java | 261 +++++++++++++++++- .../bytecode/BytecodeReplayTest.java | 260 +++++++++++++++++ 29 files changed, 1428 insertions(+), 61 deletions(-) create mode 100644 src/main/java/dev/samhb/interleave/BytecodeTraceJson.java create mode 100644 src/main/java/dev/samhb/interleave/bytecode/BytecodeReplay.java create mode 100644 src/test/java/dev/samhb/interleave/bytecode/BytecodeReplayTest.java diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 59b8509..e72b4e7 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -48,10 +48,11 @@ jobs: cache: gradle - name: Generate and validate fresh source report - run: ./gradlew test --tests dev.samhb.interleave.format.SourceProgramLoaderTest --tests dev.samhb.interleave.format.SourceAssertionTest --tests dev.samhb.interleave.cli.MainTest.cutoffSimplificationProducesDirectTrace --tests dev.samhb.interleave.cli.MainTest.sourceSymmetryCliCountsAndReportIdentity --tests dev.samhb.interleave.cli.MainTest.approximateSymmetryCliReportIdentity --tests dev.samhb.interleave.cli.MainTest.approximateCbsCliArtifacts --tests dev.samhb.interleave.cli.MainTest.approximateDporAndAllStrategyArtifacts --tests dev.samhb.interleave.ApproximateDporRunTest.dporRunnerKeepsApproximationAndActualPartialPaths --tests dev.samhb.interleave.ApproximateCbsIterationTest.ownedSymmetrySupportsCbsAndGlobalResourceAllowance --tests dev.samhb.interleave.ApproximateSymmetryRunTest.runnersRetainPrecisionLimitsAndIsolation --tests dev.samhb.interleave.cli.MainTest.shortestCutoffProducesProofArtifacts --tests dev.samhb.interleave.ResourcePrefixJsonTest --tests dev.samhb.interleave.cli.MainTest.declarativeSymmetryCliSupportsExactMatrix --tests dev.samhb.interleave.DeclarativeSymmetryRunTest.exactRunsRemainIsolatedAndEmitResourceFixtures --tests dev.samhb.interleave.report.DeclarativeSymmetryAttestationTest.checkedFailureSnapshotsRetainCommittedPrefix --tests dev.samhb.interleave.cli.MainTest.declarativeSymmetryCliSupportsApproximateMatrix --tests dev.samhb.interleave.ApproximateDeclarativeSymmetryRunTest --no-daemon + run: ./gradlew test --tests dev.samhb.interleave.format.SourceProgramLoaderTest --tests dev.samhb.interleave.format.SourceAssertionTest --tests dev.samhb.interleave.cli.MainTest.cutoffSimplificationProducesDirectTrace --tests dev.samhb.interleave.cli.MainTest.sourceSymmetryCliCountsAndReportIdentity --tests dev.samhb.interleave.cli.MainTest.approximateSymmetryCliReportIdentity --tests dev.samhb.interleave.cli.MainTest.approximateCbsCliArtifacts --tests dev.samhb.interleave.cli.MainTest.approximateDporAndAllStrategyArtifacts --tests dev.samhb.interleave.ApproximateDporRunTest.dporRunnerKeepsApproximationAndActualPartialPaths --tests dev.samhb.interleave.ApproximateCbsIterationTest.ownedSymmetrySupportsCbsAndGlobalResourceAllowance --tests dev.samhb.interleave.ApproximateSymmetryRunTest.runnersRetainPrecisionLimitsAndIsolation --tests dev.samhb.interleave.cli.MainTest.shortestCutoffProducesProofArtifacts --tests dev.samhb.interleave.ResourcePrefixJsonTest --tests dev.samhb.interleave.cli.MainTest.declarativeSymmetryCliSupportsExactMatrix --tests dev.samhb.interleave.DeclarativeSymmetryRunTest.exactRunsRemainIsolatedAndEmitResourceFixtures --tests dev.samhb.interleave.report.DeclarativeSymmetryAttestationTest.checkedFailureSnapshotsRetainCommittedPrefix --tests dev.samhb.interleave.cli.MainTest.declarativeSymmetryCliSupportsApproximateMatrix --tests dev.samhb.interleave.ApproximateDeclarativeSymmetryRunTest --tests dev.samhb.interleave.bytecode.BytecodeReleaseTest.bytecodeViewerUsesFreshProducerArtifacts --no-daemon - name: Run visualizer test suite env: + BYTECODE_DIR: build DECLARATIVE_SYMMETRY_DIR: build SOURCE_TRACE_JSON: build/source-visualizer.json SOURCE_ASSERTION_JSON: build/source-assertion-visualizer.json diff --git a/README.md b/README.md index b1278fb..68513b6 100644 --- a/README.md +++ b/README.md @@ -9,14 +9,20 @@ The headline artifact is a states-explored reduction table: naive DFS → +hashi Concurrency bugs — race conditions, deadlocks, missed signals — are notoriously hard to find because they depend on exact thread ordering. Rather than running a program once and hoping for the right schedule, this checker systematically explores every distinct interleaving and reports the exact `(thread, step)` schedule that reaches a bad state. The selected [#12 bounded Java bytecode workstream](docs/plans/bytecode-contract.md) -has an **internal loader, interpreter and concurrent exact DFS** (94A/94B; [foundation](docs/measurements/94A-bytecode-foundation.md), [concurrency evidence](docs/measurements/94B-bytecode-concurrency.md)). -94B includes pure checks and measured instruction-reference/batched execution. Public evidence/CLI/library selection follows in 94C; no public bytecode -selection is available yet. Weak-memory work remains unselected. +now exposes the initial **bounded, sequentially consistent bytecode profile**: annotated fixed actors, +exact DFS, monitor deadlocks, declared checks, artifact-bound evidence and strict replay through the +library, CLI, reports and viewer. Start with the [compiled lost-update and two-lock examples](examples/bytecode/README.md). +The [94C release ledger](docs/measurements/94C-bytecode-release.md) records validation and limitations; +[94B](docs/measurements/94B-bytecode-concurrency.md) owns the batching measurements and preservation argument. +Objects/arrays, general exceptions, wider primitives/libraries and additional bytecode search strategies +remain later phases. Weak-memory work remains unselected. -The project is built as a clean, spec-driven proof-of-concept. It is not a production Java bytecode checker; programs are modeled as explicit atomic steps or bounded `.ilv` source over cloneable shared state so the core algorithms can be taught, verified, and measured. +The project is a spec-driven proof of concept for small explicit models, bounded `.ilv` source and a +restricted interpreted Java profile. It does not execute unrestricted Java or claim Java Memory Model coverage. ## What it does +- **Compiled Java models** — explicitly compile annotated fixtures, then select `--bytecode --class-path `; exact DFS is the initial supported bytecode strategy. - **Readable source models** — `.ilv` atomic blocks, bounded reusable helpers, branching, repetition and bounded loops share the existing checker and source-aware trace viewer. - **Exhaustive DFS** — tries every enabled thread at every reachable configuration. - **State hashing** — collapses identical configurations so the search space becomes a DAG instead of a tree. @@ -77,6 +83,8 @@ Available bugs: `peterson`, `broken-peterson`, `broken-peterson-v2`, `deadlock`, | `--all` | Run entire corpus | | `--file ` | Load program from JSON file | | `--source ` | Load a bounded concurrent `.ilv` source model | +| `--bytecode ` | Check a compiled annotated Java model; requires `--class-path`, defaults to DFS/EXACT | +| `--class-path ` | Sole immutable class directory for BYTECODE; no jars or automatic compilation | | `--symmetry` | Opt-in checked symmetry for source or certified declarative JSON; requires explicit `--store exact` or `--store bitstate` (default `both` is rejected) | ### Examples diff --git a/build.gradle.kts b/build.gradle.kts index 3d01caf..80b226e 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -70,8 +70,9 @@ val mutationHarnessJavadoc = tasks.register("mutationHarnessJavadoc") { tasks.javadoc { dependsOn(mutationHarnessJavadoc) } tasks.test { - dependsOn(mutationHarnessJar) + dependsOn(mutationHarnessJar, tasks.jar) doFirst { + systemProperty("interleave.releaseJar", tasks.jar.get().archiveFile.get().asFile.absolutePath) systemProperty("interleave.mutationHarnessJar", mutationHarnessJar.get().archiveFile.get().asFile.absolutePath) systemProperty("interleave.testRuntimeClasspath", sourceSets.test.get().runtimeClasspath.asPath) } @@ -287,7 +288,8 @@ pitest { // There is no `maxMemoryInMc` on this plugin; per-minion heap is a plain JVM arg, // which is the more general lever since this is also where -XX flags would go. jvmArgs.set(listOf("-Xmx${pitestMaxMemoryMc}m", - "-javaagent:${mutationHarnessJar.get().archiveFile.get().asFile.absolutePath}")) + "-javaagent:${mutationHarnessJar.get().archiveFile.get().asFile.absolutePath}", + "-Dinterleave.releaseJar=${tasks.jar.get().archiveFile.get().asFile.absolutePath}")) // Must exceed the slowest covering test's normal runtime by a clear margin. // @@ -814,7 +816,7 @@ tasks.register("mutationRatchet") { } tasks.named("pitest") { - dependsOn(mutationHarnessJar) + dependsOn(mutationHarnessJar, tasks.jar) inputs.file(mutationHarnessJar.flatMap { it.archiveFile }) finalizedBy(tasks.named("mutationRatchet")) } diff --git a/docs/measurements/94C-bytecode-release.md b/docs/measurements/94C-bytecode-release.md index 588607b..bbd2f6f 100644 --- a/docs/measurements/94C-bytecode-release.md +++ b/docs/measurements/94C-bytecode-release.md @@ -1,17 +1,17 @@ - + # 94C — Public bytecode release evidence ## Status and baseline -Implementation in progress under [Spec94C](../specs/active/94C-bytecode-release.md) and the +Local implementation and acceptance checks complete under [Spec94C](../specs/active/94C-bytecode-release.md) and the [shared contract](../plans/bytecode-contract.md). PR140/94B merged at `6eb939ea19c3938db8052fc1b32d8f157fc913c7`, verified against remote main before creating the isolated `feat/bytecode-public-release` checkout. The original dirty checkout and prior worktrees are preserved. -Fresh merged-main build/tests/strict Javadoc passes2066 tests with zero failures/errors/skips. -Configured default mutation baseline:455 KILLED +13 SURVIVED /468. Affected baseline across bytecode, +Fresh merged-main build/tests/strict Javadoc passes 2066 tests with zero failures/errors/skips. +Configured default mutation baseline: 455 KILLED +13 SURVIVED /468. Affected baseline across bytecode, runner/result/trace/replay, CLI and benchmark/report/attestation:3163 KILLED +253 SURVIVED +478 NO_COVERAGE /3894, zero resource/run-error statuses. Both completed before production edits; the -larger affected run took95 minutes. Raw logs/XML are retained in the persistent evidence sibling. +larger affected run took 95 minutes. Raw logs/XML are retained in the persistent evidence sibling. Historical94B counts are not94C baselines. ## Implementation order and approved seams @@ -30,20 +30,195 @@ Existing source/JSON interfaces and default selections retain their behavior. Ru artifact/model/declaration identity are authenticated separately. Only exact DFS is admitted in94C; 95+ and weak memory remain outside this milestone. -## Gates still required +## Connected implementation evidence -Record fresh mutation fingerprints, baseline/final build/Javadoc, built-jar public consumers, -strict replay adversaries, no-debug classes, pure-observer/fault/cutoff/global-stop classifications, -reports and fresh browser artifacts. Incorporate the actual [94B measurements and preservation -argument](94B-bytecode-concurrency.md), not invented new measurements. Run ordinary/security review, -fresh-reader checks and actual CodeRabbit; record real review status through agent-setup. Publish one -94C PR, report its link and stop before95 or CI watchers. +`BytecodeRuntime` is the narrow cross-package facade. `BytecodeObservations` owns the same check, +terminal and deadlock observation order for exact search and strict replay. Public execution captures +immutable typed snapshots during search; it never reexecutes a cancelled path to construct diagnostics. +The internal 94B measurement route keeps public snapshot capture disabled. No new target opcode or +batching rule is admitted here; the [94B preservation argument and default review](94B-bytecode-concurrency.md) +therefore apply unchanged. Provisional resource defaults remain unchanged; no new performance claim +or broad-heap sharedness measurement is inferred from consumer tests. -## First implementation slice +Connected public tests cover real lost updates, two-lock deadlocks, committed writes before faults, +cleanup fuel exhaustion with the pending fault and held monitor retained, empty root checks, observer +errors, cancellation/max-state/deadline prefixes, strict identity/operation/state/terminal tampering, +artifact relocation and frozen input, changed debug bytes/limits, unavailable strategies and callbacks. +Lossless tagged LONG/raw-bit transport is tested as reserved schema, not wider primitive execution. +A second reachable annotated model currently rejects during loading; selected-model authentication is +attacked directly with the exact original digest for empty root and interrupted records. This is not +reported as a successful two-model loading experiment. -Public annotation/program/limits/loading and runner access now pass the real lost-update tracer test. -Source diagnostics remain separate from BYTECODE payloads; shared observation order is reused by search -and upcoming strict replay. Public runs capture immutable typed state views during execution, rather -than reexecuting cancelled prefixes after search. Internal94B measurement mode keeps capture disabled. -Connected checks/monitor/exact-state/progress regressions pass. This is an internal checkpoint; strict -replay/JSON and all public consumers/review gates remain unfinished and no94C PR is published. +An independently compiled consumer loads both checked-in examples using only the built library jar, +finds CHECK_FALSE/DEADLOCK, imports JSON, strictly replays the witnesses and round-trips current native +TestResult streams. Native compatibility is build-specific and changed generated UIDs reject old +shapes. The library jar is distinguished from the separate mutation-harness jar. Actual CLI tests +exercise supported selection and reject incompatible/duplicate/missing flags before artifact loading. +Report soundness replays all typed terminal witnesses against the actual frozen model. + +The final build and strict public Javadoc pass 2,085 tests with zero failures/errors/skips, including +the report-transport regression. The initial missing +@Model type comment was fixed. The complete browser matrix passes 299 assertions (248 inherited +51 +BYTECODE), with zero console errors, including absolute fixture directories, literal untrusted labels +and selected-configuration monitor ownership. Raw evidence: `final-browser.log`. + +JSON import is bounded to 16 Mi UTF-16 code units, depth 64 and one million nodes before record +construction. Duplicate keys, unknown/conflicting schema, scalar coercions and mutable display leaves +reject. Isolated UTF-16 surrogates are escaped for UTF-8 transport. Viewer validation is structural; +only Java strict replay authenticates execution. External stops retain original INCOMPLETE status and +separate replay observations. + +## Publication boundary + +The original affected census failed R6 on one MEMORY_ERROR; the corrected scopes pass with +assertion-earned kills and no resource/run-error detections. The configured default gate passes +455 KILLED +13 SURVIVED /468 and exactly matches every baseline fingerprint/status. All listed local +validation and review gates are complete. CI and Sam's manual review/merge remain pending; this is +not a claim that the entire selected #12 workstream is complete. After publishing the 94C PR, report +its link and stop before 95 or CI watchers. + +## Documentation and private-member review + +Fresh-reader testing answered compilation/selection, current-vs-later support, strict replay/import, +fault/cutoff/observer/stop semantics, native/classpath compatibility and measured-vs-pending evidence. +It identified stale ledger/status prose, an overbroad unverified-measurement statement, missing root +CLI flags/imports, vague native migration guidance, inconsistent JSON size units and weak-memory +wording. These were corrected; the follow-up found no other gaps in those sections. Private-member +Javadoc passes all doclint groups with warnings as errors over all 27 changed production Java files. +This is documentation review, not a claim of independent runtime validation. + +## Review disposition + +Actual CodeRabbit CLI 0.8.1 completed the full base-commit comparison, including all 43 changed/new +files, with 9 findings (`coderabbit-host.ndjson`). The sandbox invocation failed to bind its callback; +required host execution completed normally. Findings retain the CLI's original severities: + +- minor, browser literal-label assertion: valid; require accepted payload and exact literal label, + alongside the no-image assertion, before checking conflicting-verdict rejection. +- minor, stale ledger checkpoint: valid; replaced the historical first-slice status with current + connected evidence and explicitly pending gates. +- major, actual report row shape: already satisfied; ReportWriter embeds the complete TestResult + shape plus singular representative aliases. The real deadlock report regression and fresh Java + report/CLI normalization/browser artifacts pass. No absent metadata is fabricated. +- major, initial ALWAYS check: already satisfied; shared BytecodeObservations evaluates it at root. + The public empty-choice failure regression and strict replay pass. +- trivial, runtime API example; trivial, coordinated loader/report/replay examples: valid; one fully + qualified class-level example links loading with limits, execution, retained-trace JSON and matching + replay/reporting. Public entry Javadoc refers to that example. +- minor, report deadlock verdict: not applied. Aggregate VIOLATION is the existing benchmark-row + convention, and precise DEADLOCK plus concrete waits remain in the BYTECODE witness. Changing the + aggregate would contradict the reviewed consumer contract and existing report behavior. +- major, empty TEXT model String: unreachable in this profile. The loader rejects String constants + and String fields/operations; emitted TEXT values are nonempty phase/method/resource diagnostics. + Wider String execution belongs to 97 and must revisit transport and batching there. +- major, newline-sensitive external consumer assertion: valid portability improvement; compare + logical lines while retaining exit status and both exact expected terminal lines. + +Ordinary connected-source review additionally found that the legacy BenchmarkResult copy helper +could drop BYTECODE evidence. It now rejects relabeling a typed bytecode row; a regression covers the +public copy route. Mixed legacy/BYTECODE report normalization retains the existing selected-row order. +Security review traces class input through the unchanged bounded metadata loader, JSON through the +strict bounded duplicate-free codec, and labels through textContent. No target reflection, native +fallback, HTML sink or generic callback execution was introduced. Connected post-fix verification passes. + +### CodeRabbit follow-up + +The second actual full-scope invocation completed 8 findings, including all 43 changed/new files: +`coderabbit-followup.ndjson`. Valid changes: correct stale review-status prose, accept absolute and +repository-relative BYTECODE fixture directories in the test harness, and classify import/replay +forgeries with exact public rejection types. The jar probe now uses Gradle's exact current library +artifact path, supplied to both test and PIT JVMs; both entry tasks depend on the library jar. +No mutation resource budget, operator, floor or assertion policy changed. + +The default-FINAL finding is already satisfied by shared observation ordering and the real lost-update +CHECK_FALSE regression. Pure-check cancellation returns an INTERRUPTED evaluation (OpcodeExecutor +throws no cancellation); search records it and marks traversal incomplete while retaining prior +witnesses. Original PREFIX records already reject in BytecodeEvidence's constructor; PREFIX is allowed +only as a separate replay observation, with an added negative import case. The repeated aggregate +DEADLOCK suggestion is not applied for the existing report-contract reason above. + +### Mutation resource failure and correction + +The first affected census generated 4988 mutants:3956 KILLED,464 SURVIVED,567 NO_COVERAGE and1 +MEMORY_ERROR. R6 correctly rejected the run. The error was BytecodeTraceJson.value's recursive array +value call removal (NON_VOID_METHOD_CALLS, instruction index108/block25). Removing that call stopped +reader progress while array growth continued; the old node charge lived inside the removed child. +Move the existing node charge before root/child descent and container growth, preserving exactly one +charge per JSON value. A flat one-million-null input independently checks the documented node ceiling. +The exact bound remains one million nodes; no timeout/heap setting was raised and no mutant is +reclassified by declaration. Only a passing assertion-earned rerun can replace the MEMORY_ERROR. + +The corrected focused run passes R6:943 KILLED +134 SURVIVED +18 NO_COVERAGE /1095, with no +resource/run-error detections. All three recursive parser-value call removals, including the array +site that previously exhausted memory, are now KILLED by assertions. This is a scoped result, not a +whole-project percentage. Stronger public assertions independently verify compiler lines/BCIs, root +and terminal snapshot values, monitor identities/owners/depths, actor fuel, declared check timing, +outer result precision, and original-vs-replay external-prefix outcomes. The broad rejected census is +retained rather than overwritten. The final codec/DTO scope passes268 KILLED +59 SURVIVED +3 +NO_COVERAGE /330; it includes strict rejection types, malformed control text and original-PREFIX +rejection. Neither scoped run is a whole-project percentage. + +## Final comparison and transport correction + +The configured default state/cb scope is not the whole checker. Its455 KILLED +13 SURVIVED /468 +exactly matches baseline, including all mutant fingerprints. No tests, operators, resource limits, +mutation floors or R6 rules were weakened. The first default attempt was interrupted by a session +restart; its partial XML/log were archived and not scored. The completed rerun is `final-default.xml`. + +For the affected comparison, the latest per-class observations replace whole classes from the broad +census with their post-fix scoped results. After the final report-only rerun this is 4013 KILLED +420 +SURVIVED +560 NO_COVERAGE /4993. This is an explicitly assembled comparison dataset, **not a single +successful full-scope PIT run**, and was never fed to the build gate. Raw broad/focused reports remain +separate. Normalized javap comparison (constant-pool/BCI-width shifts excluded, control-flow targets +retained as instruction ordinals) verifies 2356 inherited kills in unchanged methods remain killed; +2 inherited survivors improve. The remaining 807 baseline kills occur in deliberately changed/moved +methods; no one-to-one mutant-identity claim is made for those. Their connected legacy and bytecode +behavior is covered by the full suite, independent instruction oracle and strict replay scenarios. +Residual survivors and uncovered cases are retained as residuals, without unsupported equivalence +claims. NO_COVERAGE, MEMORY_ERROR and timeouts are never counted as assertion-earned kills. + +A final real class-file regression renames an unused int field to a valid UTF-16 name containing an +isolated surrogate. Generic Gson reparsing/reserialization in ReportWriter reintroduced the raw +surrogate before UTF-8 transport; the exported witness lost its field identity. A direct byte-transport +assertion failed (`report-utf16-assertion-red.log`). BYTECODE report rows now retain the already escaped +run/witness JSON and add only validated model-name/report metadata. The regression passes strict +replay after UTF-8 file transport (`report-utf16-green.log`). An earlier failing Files.writeString probe +stalled in Gradle's failure mapper; only that owned test worker was stopped, and the explicit data +integrity assertion replaced the probe. No interpreter execution hang is claimed. + +## Final verification and reproducibility + +| Check | Actual result | Evidence | +|---|---|---| +| Fresh baseline build / strict Javadoc | 2,066 tests, zero failures/errors/skips | `baseline-build.log` | +| Publication build / strict Javadoc | 2,085 tests, zero failures/errors/skips | `publication-build.log` | +| Post-mutation fresh producer regeneration / Javadoc | Pass; all tests rerun | `publication-fresh-artifacts.log` | +| Private-member doclint | All groups, warnings as errors, 27 changed production files | `final-private-javadoc.log` | +| Complete browser matrix | 299 assertions; zero failures/console errors | `publication-browser.log` | +| Configured default mutation scope | 455 KILLED +13 SURVIVED /468; exact baseline fingerprint/status match | `final-default.xml` | +| Corrected evidence/replay/result scope | 943 KILLED +134 SURVIVED +18 NO_COVERAGE /1095; R6 passes | `postfix-focused.xml` | +| Final codec/DTO scope | 268 KILLED +59 SURVIVED +3 NO_COVERAGE /330; R6 passes | `final-codec-dto.xml` | +| Final report scope | 231 KILLED +22 SURVIVED +6 NO_COVERAGE /259; R6 passes | `final-report-pit.xml` | +| Documentation | Six changed Markdown documents; 114 local targets/anchors; fences and R1–R5 mapping valid | `validate-docs.py` | +| Reviews | Two completed CodeRabbit invocations; ordinary/security and fresh-reader dispositions above | Saved NDJSON and review records | + +The raw files and comparison scripts are retained in the persistent sibling `interleave-94c-evidence`. +`final-affected.xml` is labeled as an assembled comparison dataset; it is not an official build-gate +report. `compare-mutations.py` records unchanged-method checks and changed/moved methods separately. +No residual is silently declared equivalent. No 94C runtime performance, broader-heap cost, DPOR +reduction or JPF measurement is invented. The unchanged 94B argument/default review remains the +applicable evidence for the admitted executor/scheduler behavior. + +Reproduce with JDK 26 and the existing pinned Gradle/PIT dependencies: + +```sh +./gradlew --max-workers=1 -PpitestThreads=1 build javadoc +./gradlew --max-workers=1 -PpitestThreads=1 pitest +./gradlew --max-workers=1 -PpitestThreads=1 pitest '-PpitestTargetOverride=dev.samhb.interleave.BytecodeTraceJson*,dev.samhb.interleave.core.BytecodeEvidence*' +./gradlew --max-workers=1 -PpitestThreads=1 pitest '-PpitestTargetOverride=dev.samhb.interleave.report.ReportWriter*' +``` + +For the browser matrix, regenerate the Java artifacts with the test selection/environment in +`.github/workflows/build.yml` after mutation testing, then run `npm test --prefix docs`. BYTECODE_DIR +accepts relative and absolute directories. The built-jar probe uses Gradle's exact current jar path +in normal test and PIT JVMs, avoiding stale or mutation-harness artifact selection. diff --git a/docs/plans/bytecode-contract.md b/docs/plans/bytecode-contract.md index 1d0e3f5..af9e05b 100644 --- a/docs/plans/bytecode-contract.md +++ b/docs/plans/bytecode-contract.md @@ -3,7 +3,7 @@ ## Objective and status -**Selected; internal94A/94B implemented, public release pending.** Approved scope: controlled interpretation of compiled Java for fixed +**Selected; 94A/94B implemented, 94C initial public profile locally accepted; PR/CI/manual review pending.** Approved scope: controlled interpretation of compiled Java for fixed actors under bounded sequential consistency (SC). The first public release must find a real lost update and a two-lock deadlock through loading, search, evidence, strict replay, library/CLI, reports and viewer. No target-code host-JVM fallback is permitted. This is not unrestricted Java or full Java Memory Model coverage. @@ -13,8 +13,8 @@ PRs #136/#137 and its closure commit. Sam explicitly selected #12 after that sto and parked conditional/deferred tasks remain unselected. The specification PR established no runtime evidence. The [94A implementation ledger](../measurements/94A-bytecode-foundation.md) records subsequent loader/single-actor evidence; [the94B ledger](../measurements/94B-bytecode-concurrency.md) records -internal concurrent execution, batching preservation and measured setup-only sharedness costs. Public -consumer support, broader heap costs, restricted DPOR and JPF gates remain pending. [Vocabulary](../../CONTEXT.md) owns domain terms; this document +internal concurrent execution, batching preservation and measured setup-only sharedness costs. The [94C ledger](../measurements/94C-bytecode-release.md) records public library/CLI, replay and consumer +verification. Broader heap costs, restricted DPOR and JPF gates remain pending. [Vocabulary](../../CONTEXT.md) owns domain terms; this document owns common behavior, interface seams, verification and phase boundaries. ## Sequential delivery and ownership @@ -428,7 +428,9 @@ executor. Batching requires a stuttering/observation argument covering resource 99 additionally needs an independence/sleep-coverage preservation argument. Each names assumptions, state relation, event matching, counterexample tests and limits. A green suite alone is not a proof. -[unverified] All bytecode performance/sharedness measurements, optimized reduction and JPF compatibility. +[verified, 94B] Reference/batched tiny-fixture measurements, setup-only sharedness costs and batching +preservation are recorded in the [94B ledger](../measurements/94B-bytecode-concurrency.md). +[unverified] Broader-heap sharedness costs, optimized reduction measurements and JPF compatibility. [deferred research] Frozen exhausted actors, fuel-free cycle detection, broader cyclic DPOR and initializer allowlists. None is a release requirement or implied optimization opportunity. diff --git a/docs/plans/future-work.md b/docs/plans/future-work.md index ad11b5a..d383bbb 100644 --- a/docs/plans/future-work.md +++ b/docs/plans/future-work.md @@ -168,7 +168,7 @@ milestones (94A–94C, 95–101). #11 and deferred/conditional work remain unsel |---|---|---|---|---|---| | 10 | Symmetry reduction — complete | High | Spec-set | [Spec 75](../specs/active/75-thread-symmetry-canonicalization.md), [Spec 76](../specs/active/76-source-symmetry-exact-search.md) and [Spec 77](../specs/active/77-source-symmetry-strategy-composition.md) shipped in PRs #117–119. Final composition merged at `d8ad49e`: checked source symmetry for exact DFS, static POR, DPOR and CBS, including iterative CBS and original-identity evidence. | Completed in three coherent stages: canonicalization/mappings; checked exact DFS and evidence; exact POR/DPOR/CBS composition with proof, callers and regressions. K1 / [Spec 89](../specs/active/89-approximate-symmetry-dfs-por.md) adds approximate bitstate composition for explicit DFS/static POR; [Spec 90](../specs/active/90-approximate-symmetry-cbs.md) adds CBS in K2; [Spec 91](../specs/active/91-approximate-symmetry-dpor.md) adds DPOR and all-strategy consumers in K3, completing B9 with PR #134 merged at `3d5c09e`. Arbitrary custom-store composition remains unsupported. [Spec 84](../specs/active/84-certified-symmetry-backends.md) adds a separately selected HASHED/ORDERED library storage choice under post-task-#10 B6. B10 [declarative JSON spec set](declarative-symmetry-contract.md) is selected: Specs 92/93 merged in PR #135; L1 exact support merged in PR #136 at `013c963`; L2 approximate support merged in PR #137 at `aebb919`, completing B10. All selected post-task-#10 follow-ups are complete. #12 is subsequently selected separately; #11 and deferred/conditional work remain parked. | | 11 | Relaxed memory models | Very High | Spec-set | Fundamental semantics change — needs formal spec | Stage one selected memory model: state/transition foundations; complete execution and witness support; supported search/reduction integration. Keep each additional memory model separate. Exact PR count follows the semantics/proof scope. | -| 12 | Bounded Java bytecode checking — selected, internal concurrency | Very High | Spec-set | Controlled JDK 26 Class-File API interpretation of fixed actors under bounded SC; no target host execution. | [Shared contract and Specs 94A–101](bytecode-contract.md): internal foundation (94A), concurrent feasibility gate (94B), complete public release (94C), then heap, exceptions, core library, CBS, restricted DPOR, narrow atomics and bitstate. 94A adds internal loading/single-actor execution; [foundation evidence](../measurements/94A-bytecode-foundation.md). 94B adds internal concurrent exact DFS, checks and measured batching; [concurrency evidence](../measurements/94B-bytecode-concurrency.md). Target ten sequential implementation PRs; public release, DPOR measurements and JPF acceptance remain pending. | +| 12 | Bounded Java bytecode checking — selected, initial public release | Very High | Spec-set | Controlled JDK 26 Class-File API interpretation of fixed actors under bounded SC; no target host execution. | [Shared contract and Specs 94A–101](bytecode-contract.md): internal foundation (94A), concurrent feasibility gate (94B), complete public release (94C), then heap, exceptions, core library, CBS, restricted DPOR, narrow atomics and bitstate. 94A adds internal loading/single-actor execution; [foundation evidence](../measurements/94A-bytecode-foundation.md). 94B adds internal concurrent exact DFS, checks and measured batching; [concurrency evidence](../measurements/94B-bytecode-concurrency.md). 94C adds public BYTECODE loading, strict replay, CLI, reports and viewer; [release evidence](../measurements/94C-bytecode-release.md). Target ten sequential implementation PRs; broader heap, DPOR measurements and JPF acceptance remain pending. | ## Deferred @@ -205,10 +205,10 @@ planned. **PR grouping:** none while deferred; do not bundle with active visuali 11. **Relaxed memory models** — support weak consistency models (e.g., ARM/POWER) instead of assuming sequential consistency. Fundamental change to `Configuration` snapshot semantics and step execution. -12. **Bounded Java bytecode checking — selected, internal concurrency** — [contract/specification index](bytecode-contract.md). +12. **Bounded Java bytecode checking — selected, initial public release** — [contract/specification index](bytecode-contract.md). Interpret compiled Java17–26 inputs with metadata-only JDK26 Class-File API and fixed annotation-declared actors under bounded SC. 94A provides internal loading/single-actor interpretation; the [foundation ledger](../measurements/94A-bytecode-foundation.md) records its evidence. 94B adds internal concurrent exact DFS, pure checks and measured reference/batched execution; the -[concurrency ledger](../measurements/94B-bytecode-concurrency.md) records its evidence. Initial public -release remains 94C; optimized reduction and JPF acceptance remain pending. +[concurrency ledger](../measurements/94B-bytecode-concurrency.md) records its evidence. 94C adds the initial public release through strict replay and consumers; +[release ledger](../measurements/94C-bytecode-release.md). Broader heap, optimized reduction and JPF acceptance remain pending. diff --git a/docs/specs/active/94C-bytecode-release.md b/docs/specs/active/94C-bytecode-release.md index b7d7421..1bdf543 100644 --- a/docs/specs/active/94C-bytecode-release.md +++ b/docs/specs/active/94C-bytecode-release.md @@ -1,10 +1,10 @@ - + # Spec 94C: Initial public bytecode release ## Objective Deliver initial public bytecode release as one coherent stage of bounded Java bytecode checking. -**Type: delta. Status: specified, not implemented or measured.** The +**Type: delta. Status: local acceptance complete; release gates recorded in the [94C ledger](../../measurements/94C-bytecode-release.md).** The [shared #12 contract](../../plans/bytecode-contract.md) is normative for common semantics, limits, interface signatures, profile exclusions, phase ownership and verification. This spec owns 94C only. @@ -112,17 +112,23 @@ choose existing equivalent modules at implementation after connected-source insp - [verified] Planning main is `2a242c4`; the existing engine has immutable Program, forward SourceStep continuations and source-specific evidence. The shared contract records inspected integration constraints. - [approved decision] This milestone and the shared contract define the selected behavior/release boundary. -- [unverified] This milestone's bytecode implementation, measurements, compiler/runtime acceptance and -mutation results. No authoring review establishes those results. +- [implemented] Public loading/runner, owned BYTECODE evidence, strict replay/JSON, CLI, reports, +soundness replay and viewer routes. Native streams retain build-specific generated serialization identity. +- [evidence] The [94C ledger](../../measurements/94C-bytecode-release.md) distinguishes completed +local checks from pending publication gates. 94B's batching argument/default review applies to the +unchanged admitted opcode profile; this phase expands consumers, not target language semantics. + ## Tests -`publicBytecodeLoaderAndRunnerWorkFromJar` (R1/R5), `bytecodeCliRejectsUnsupportedSelections` (R1), -`strictReplayAuthenticatesEveryBytecodeOutcome` (R2/R3), `bytecodeReportsRetainPrecisionAndLocations` (R4), -`bytecodeViewerUsesFreshProducerArtifacts` (R4), `legacyProfilesRemainCompatible` (R4). -Kill missing identity/limit/choice checks, false SOURCE routing, premature completion and precision upgrades. -These are intended behavioral contracts/test names, not tests already implemented or executed. -Use independent expected values/oracles, preserve distinct regression cases and save generated seeds. +Actual public regressions are in `BytecodeReleaseTest` and `BytecodeReplayTest`: built-jar consumers +and actual CLI selections (R1/R5), artifact/model/declaration/operation/state/terminal authentication +and external-prefix preservation (R2/R3), real runtime faults/cleanup and observer limits (R3/R4), +lossless UTF-16/wide-tag transport and report soundness (R4), and fresh producer/browser artifacts +with monitor snapshots and real compiler locations (R4/R5). Existing source/declarative/replay/symmetry +regressions remain in the full suite. The [94C ledger](../../measurements/94C-bytecode-release.md) +records 2,085 passing tests, mutation scopes and review dispositions without treating tests as proof +of future reduction or wider language coverage. ## Constraints diff --git a/docs/visualizer-e2e.mjs b/docs/visualizer-e2e.mjs index cf7717e..ed9ab8f 100644 --- a/docs/visualizer-e2e.mjs +++ b/docs/visualizer-e2e.mjs @@ -6,7 +6,7 @@ import { createServer } from 'node:http'; import { readFileSync, existsSync } from 'node:fs'; -import { join, extname, dirname } from 'node:path'; +import { join, extname, dirname, resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; import { chromium } from 'playwright'; @@ -206,6 +206,37 @@ async function runTests() { const verdictIncomplete = await page.locator('#verdictBadge').textContent(); assert(verdictIncomplete === 'INCOMPLETE', 'incomplete-only renders INCOMPLETE verdict'); + if(process.env.BYTECODE_DIR){ + for(const [name,verdict] of Object.entries({'lost-update':'VIOLATION',deadlock:'VIOLATION',fault:'VIOLATION',root:'VIOLATION',cutoff:'INCOMPLETE',observer:'INCOMPLETE','no-line':'PASS','long-label':'PASS',interrupted:'INCOMPLETE',report:'VIOLATION',cli:'VIOLATION'})){ + const payload=readFileSync(resolve(projectRoot,process.env.BYTECODE_DIR,`bytecode-${name}.json`),'utf8'); + await page.locator('#clearBtn').click();await page.locator('#paste').fill(payload);await page.locator('#loadPaste').click(); + assert(!(await page.locator('#error').getAttribute('class')).includes('show'),`${name}: fresh BYTECODE payload accepted`); + assert(await page.locator('#verdictBadge').textContent()===verdict,`${name}: BYTECODE retains ${verdict}`); + const meta=await page.locator('#meta').textContent(); + assert(meta.includes('BYTECODE BYTECODE-SC-1') && meta.includes('artifact'),`${name}: artifact profile rendered`); + if(name==='deadlock'){ + assert(meta.includes('monitor wait') && meta.includes('waits for'), 'Concrete deadlock ownership rendered'); + assert((await page.locator('#stateStrip').textContent()).includes('owner actor 0; depth 1'),'Selected deadlock snapshot shows held monitor depth'); + await page.locator('#timeline tbody tr[data-idx="0"]').click(); + assert(!(await page.locator('#stateStrip').textContent()).includes('owner actor '),'Initial configuration shows unowned monitors'); + } + if(name==='fault')assert(meta.includes('ArithmeticException') && meta.includes('BCI'), 'Modeled fault location rendered'); + if(name==='cutoff')assert(meta.includes('required') && meta.includes('remaining'), 'Exact cutoff allowance rendered'); + if(name==='interrupted')assert(meta.includes('original run INCOMPLETE'),'External stop remains incomplete'); + if(!['root','observer','interrupted'].includes(name))assert((await page.locator('#timeline').textContent()).includes('BCI'),'Timeline uses real method/BCI labels'); + } + const unsafe=JSON.parse(readFileSync(resolve(projectRoot,process.env.BYTECODE_DIR,'bytecode-no-line.json'),'utf8')); + const t=unsafe.completedTraces[0]; + t.bytecodeEvidence.transitions[0].operations[0].location.name=''; + await page.locator('#clearBtn').click();await page.locator('#paste').fill(JSON.stringify(unsafe));await page.locator('#loadPaste').click(); + assert(!(await page.locator('#error').getAttribute('class')).includes('show'),'Untrusted BYTECODE label payload is accepted'); + assert((await page.locator('#timeline').textContent()).includes(''),'Exact untrusted BYTECODE method label appears literally'); + assert(await page.locator('#timeline img').count()===0,'Untrusted BYTECODE labels remain text'); + unsafe.verdict='VIOLATION'; + await page.locator('#paste').fill(JSON.stringify(unsafe));await page.locator('#loadPaste').click(); + assert((await page.locator('#error').getAttribute('class')).includes('show'),'Conflicting BYTECODE run verdict rejected'); + } + // ------------------------------------------------------------- // Test 7: Program File Load alongside Trace // ------------------------------------------------------------- diff --git a/docs/visualizer-normalize-check.mjs b/docs/visualizer-normalize-check.mjs index 6623121..8366761 100644 --- a/docs/visualizer-normalize-check.mjs +++ b/docs/visualizer-normalize-check.mjs @@ -5,11 +5,11 @@ // Run: node docs/visualizer-normalize-check.mjs import { readFileSync } from 'node:fs'; import assert from 'node:assert/strict'; -import { dirname, join } from 'node:path'; +import { dirname, join, resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; const root = join(dirname(fileURLToPath(import.meta.url)), '..'); -const read = (rel) => readFileSync(join(root, rel), 'utf8'); +const read = (rel) => readFileSync(resolve(root, rel), 'utf8'); const src = read('docs/visualizer.js'); // Extract normalize(). A guard is required rather than a bare slice: // indexOf returns -1 on a rename or reformat, and slice(-1, ...) would then yield garbage and @@ -247,5 +247,29 @@ for(const invalid of [ {...resourceRun,resourceLimitReason:'MAX_TIME'}, {...resourceRun,resourcePrefix:null} ]) assert.throws(()=>normalize(invalid), /resource|Resource|source|Misaligned|failure/); assert.equal(normalize({...resource,replay:{...replay,states:[replay.states[0],{locals:terminalState.locals,fields:terminalState.fields}]}}).meta.verdict, 'INCOMPLETE'); +// Fresh BYTECODE producers preserve run precision and distinct instruction locations. +if(process.env.BYTECODE_DIR){ + assert.equal(read(resolve(root,process.env.BYTECODE_DIR,'bytecode-lost-update.json')),read(process.env.BYTECODE_DIR+'/bytecode-lost-update.json'),'Configured relative and absolute BYTECODE directories identify the same artifact'); + const expected={'lost-update':'VIOLATION',deadlock:'VIOLATION',fault:'VIOLATION',root:'VIOLATION',cutoff:'INCOMPLETE',observer:'INCOMPLETE','no-line':'PASS','long-label':'PASS',interrupted:'INCOMPLETE',report:'VIOLATION',cli:'VIOLATION'}; + for(const [name,verdict] of Object.entries(expected)){ + const raw=JSON.parse(read(process.env.BYTECODE_DIR+'/bytecode-'+name+'.json')); + const value=normalize(raw);assert.equal(value.meta.verdict,verdict,name); + assert.equal(value.meta.programKind,'BYTECODE');assert(value.trace.bytecodeEvidence); + assert.equal(value.trace.executedSteps,undefined);assert.equal(value.trace.sourceDigest,undefined); + if(name==='no-line')assert(value.trace.bytecodeEvidence.transitions.every(t=>t.operations.every(op=>op.line==null))); + if(name==='deadlock')assert.equal(value.trace.bytecodeEvidence.terminal.waits.length,2); + } + const report=JSON.parse(read(process.env.BYTECODE_DIR+'/bytecode-report.json')); + const bytecodeRow=report.benchmarks[0]; + assert.equal(normalize({benchmarks:[{bug:'legacy',verdict:'PASS'},bytecodeRow]}).meta.programKind,'BYTECODE'); + assert.equal(normalize({benchmarks:[{bug:'legacy',verdict:'VIOLATION',failingTrace:{threads:[0],outcomes:['ADVANCED']}},bytecodeRow]}).meta.bug,'legacy'); + const raw=JSON.parse(read(process.env.BYTECODE_DIR+'/bytecode-lost-update.json')); + for(const change of [x=>x.storeType='BITSTATE',x=>x.verdict='PASS',x=>x.failingTraces[0].sourceDigest='0'.repeat(64), + x=>x.failingTraces[0].bytecodeEvidence.version=2,x=>x.failingTraces[0].bytecodeEvidence.identity.mode='REFERENCE', + x=>x.failingTraces[0].bytecodeEvidence.snapshots[0].fields['bad']={type:'LONG',raw:9007199254740992}]){ + const altered=structuredClone(raw);change(altered);assert.throws(()=>normalize(altered)); + } +} + console.log(fails === 0 ? '\nall checks passed' : `\n${fails} FAILED`); process.exit(fails === 0 ? 0 : 1); diff --git a/docs/visualizer.js b/docs/visualizer.js index 56d5eb3..47955ae 100644 --- a/docs/visualizer.js +++ b/docs/visualizer.js @@ -183,6 +183,106 @@ function normalizeResourcePrefix(value, diagnostics){ return {trace:{...source,threads:value.threads,outcomes:value.outcomes,outcome:'INCOMPLETE',states},meta}; } +/** Validates distinct BYTECODE data without coercing values or inventing source spans. + * SECURITY: checks bounded structures before rendering; replay authentication belongs to Java. + * @param {Object} raw untrusted trace, result or report + * @returns {{trace:Object,meta:Object}} original witness plus honest run verdict + * @throws {Error} for incompatible identity, schema, precision or terminal classifications + */ +function normalizeBytecode(raw){ + const fail = () => {throw new Error('Invalid BYTECODE evidence or precision');}; + const object = x => x && typeof x==='object' && !Array.isArray(x); + const text = x => typeof x==='string' && x.length>0 && x.length<=65536; + const integer = x => Number.isSafeInteger(x) && x>=0; + const digest = x => typeof x==='string' && /^[0-9a-f]{64}$/.test(x); + const method = x => object(x) && ['owner','name','descriptor'].every(k=>text(x[k])); + const location = x => method(x) && integer(x.bci); + const identity = x => { + if(!object(x) || !digest(x.artifactDigest) || x.profileVersion!=='BYTECODE-SC-1' || !text(x.modelClass) || x.mode!=='BATCHED' || + x.requestedStrategy!=='DFS' || x.effectiveStrategy!=='DFS' || x.fallbackReason!=null || !Array.isArray(x.actors) || + x.actors.length<1 || x.actors.length>8 || !Array.isArray(x.checks) || x.checks.length>65536) fail(); + x.actors.forEach((a,i)=>{if(!object(a) || a.id!==i || !method(a.method) || a.method.descriptor!=='()V')fail();}); + x.checks.forEach(c=>{if(!object(c) || !method(c.method) || c.method.descriptor!=='()Z' || !['ALWAYS','FINAL'].includes(c.when))fail();}); + const ceilings={actorInstructions:4096,actorAllocations:4096,actorHeapCells:65536,maxCallDepth:256,maxArrayLength:4096,maxStringLength:4096,setupInstructions:65536,setupAllocations:4096,setupHeapCells:65536,checkInstructions:16384}; + if(!object(x.limits) || Object.keys(x.limits).length!==10)fail(); + for(const [k,max] of Object.entries(ceilings))if(!integer(x.limits[k]) || x.limits[k]<1 || x.limits[k]>max)fail(); + }; + const equal = (a,b) => { + if(a===b)return true; + if(!a || !b || typeof a!=='object' || typeof b!=='object' || Array.isArray(a)!==Array.isArray(b))return false; + const keys=Object.keys(a);return keys.length===Object.keys(b).length && keys.every(k=>Object.hasOwn(b,k) && equal(a[k],b[k])); + }; + const fault = f => {if(!object(f) || !text(f.type) || !location(f.location) || !Array.isArray(f.stack) || !f.stack.length || f.stack.length>256 || !f.stack.every(location))fail();}; + const cutoff = c => {if(!object(c) || !text(c.reason) || !location(c.location) || !integer(c.limit) || c.limit<1 || !integer(c.required) || c.required<1 || !integer(c.remaining))fail();}; + const terminal = (t,replay=false) => { + const outcomes={COMPLETED:'COMPLETED',DEADLOCK:'DEADLOCK',UNCAUGHT_EXCEPTION:'VIOLATION',CHECK_FALSE:'VIOLATION',CUTOFF:'INCOMPLETE',OBSERVER_ERROR:'INCOMPLETE',OBSERVER_LIMIT:'INCOMPLETE',INTERRUPTED:'INCOMPLETE'}; + if(!object(t) || (!Object.hasOwn(outcomes,t.kind) && !(replay && t.kind==='PREFIX')) || !Array.isArray(t.waits) || t.waits.length>8)fail(); + const actorFailure=['UNCAUGHT_EXCEPTION','CUTOFF'].includes(t.kind); + if(actorFailure ? !integer(t.actor) || t.actor>7 : t.actor!==-1)fail(); + if(t.fault!=null){if(!actorFailure)fail();fault(t.fault);}else if(t.kind==='UNCAUGHT_EXCEPTION')fail(); + if((t.cutoff!=null)!==(t.kind==='CUTOFF'))fail();if(t.cutoff)cutoff(t.cutoff); + const checkKind={CHECK_FALSE:'FALSE',OBSERVER_ERROR:'ERROR',OBSERVER_LIMIT:'LIMIT'}[t.kind]; + if((t.check!=null)!==(checkKind!=null))fail(); + if(t.check){const c=t.check;if(c.kind!==checkKind || !method(c.check) || !location(c.location) || (c.fault!=null)!==(checkKind==='ERROR') || (c.cutoff!=null)!==(checkKind==='LIMIT'))fail();if(c.fault)fault(c.fault);if(c.cutoff)cutoff(c.cutoff);} + if((t.waits.length>0)!==(t.kind==='DEADLOCK'))fail(); + t.waits.forEach(w=>{if(!object(w) || !integer(w.actor) || w.actor>7 || !integer(w.owner) || w.owner>7 || !text(w.monitor) || !integer(w.depth) || w.depth<1)fail();}); + if((t.interruption!=null)!==(t.kind==='INTERRUPTED') || (t.interruption!=null && !['MAX_STATES','MAX_TIME','KEY_BYTES','CANCELLED'].includes(t.interruption)))fail(); + return outcomes[t.kind]; + }; + const opcodes=new Set('NOP POP POP2 DUP DUP_X1 DUP_X2 DUP2 DUP2_X1 DUP2_X2 SWAP IADD ISUB IMUL IDIV IREM INEG ISHL ISHR IUSHR IAND IOR IXOR I2B I2C I2S MONITORENTER MONITOREXIT ATHROW IFEQ IFNE IFLT IFGE IFGT IFLE IF_ICMPEQ IF_ICMPNE IF_ICMPLT IF_ICMPGE IF_ICMPGT IF_ICMPLE IF_ACMPEQ IF_ACMPNE IFNULL IFNONNULL GOTO GOTO_W ACONST_NULL ICONST_M1 ICONST_0 ICONST_1 ICONST_2 ICONST_3 ICONST_4 ICONST_5 BIPUSH SIPUSH LDC LDC_W ILOAD ALOAD ISTORE ASTORE ILOAD_W ALOAD_W ISTORE_W ASTORE_W IINC IINC_W IRETURN ARETURN RETURN LOOKUPSWITCH TABLESWITCH GETFIELD PUTFIELD GETSTATIC PUTSTATIC INVOKESTATIC INVOKESPECIAL INVOKEVIRTUAL INVOKEINTERFACE NEW'.split(' ')); + for(const prefix of ['ILOAD','ALOAD','ISTORE','ASTORE'])for(let i=0;i<4;i++)opcodes.add(prefix+'_'+i); + const typed = v => { + if(!object(v) || typeof v.raw!=='string' || v.raw.length>65536)fail(); + switch(v.type){ + case 'INT': if(!/^(0|-?[1-9][0-9]*)$/.test(v.raw) || BigInt(v.raw)<-2147483648n || BigInt(v.raw)>2147483647n)fail();break; + case 'LONG': if(!/^(0|-?[1-9][0-9]*)$/.test(v.raw) || BigInt(v.raw)<-9223372036854775808n || BigInt(v.raw)>9223372036854775807n)fail();break; + case 'FLOAT_BITS': if(!/^[0-9a-f]{8}$/.test(v.raw))fail();break; + case 'DOUBLE_BITS': if(!/^[0-9a-f]{16}$/.test(v.raw))fail();break; + case 'BOOLEAN': if(!['true','false'].includes(v.raw))fail();break; + case 'NULL': if(v.raw!=='')fail();break; + case 'REFERENCE': case 'TEXT': case 'FAULT': if(!text(v.raw))fail();break; + default: fail(); + } + }; + const values = map => {if(!object(map) || Object.keys(map).length>65536)fail();Object.entries(map).forEach(([k,v])=>{if(!text(k))fail();typed(v);});}; + const trace = t => { + if(!object(t) || t.programKind!=='BYTECODE' || ['sourceDigest','executedSteps','failure','cutoff'].some(k=>Object.hasOwn(t,k)))fail(); + const d=t.bytecodeEvidence; + if(!object(d) || d.version!==1)fail();identity(d.identity); + if(t.programHash!==d.identity.artifactDigest || !Array.isArray(t.threads) || t.threads.length>MAX_SCHEDULE || !t.threads.every(a=>integer(a) && a['ADVANCED','TERMINATED','ASSERTION_FAILED'].includes(o)) || + !Array.isArray(d.transitions) || d.transitions.length!==t.threads.length || !Array.isArray(d.snapshots) || d.snapshots.length!==t.threads.length+1 || !Array.isArray(t.states) || t.states.length!==d.snapshots.length)fail(); + let work=0; + d.transitions.forEach((s,i)=>{ + if(!object(s) || s.actor!==t.threads[i] || !Array.isArray(s.operations) || !s.operations.length || (work+=s.operations.length)>65536)fail(); + s.operations.forEach(op=>{if(!object(op) || !location(op.location) || (op.line!=null && (!integer(op.line) || op.line<1)) || !['OPCODE','MONITOR_ENTER','RETURN','EXCEPTION','TERMINATION','FAILURE','CUTOFF','FUEL_CUTOFF'].includes(op.event) || (op.opcode!=null)!==(op.event==='OPCODE') || (op.opcode!=null && !opcodes.has(op.opcode)))fail();}); + }); + d.snapshots.forEach((s,i)=>{ + if(!object(s) || !digest(s.stateDigest) || !object(s.locals) || Object.keys(s.locals).length>8 || !Array.isArray(s.heap) || s.heap.length>36864)fail(); + values(s.fields);Object.values(s.locals).forEach(values); + s.heap.forEach(o=>{if(!object(o) || !text(o.identity) || !text(o.type) || typeof o.shared!=='boolean' || typeof o.initialized!=='boolean' || !Number.isSafeInteger(o.owner) || o.owner<-2 || o.owner>7 || !integer(o.depth) || (o.owner===-2)!==(o.depth===0))fail();}); + const display = map => Object.fromEntries(Object.entries(map).map(([k,v])=>[k,v.type.toLowerCase()+':'+v.raw])); + if(!equal(t.states[i],{fields:display(s.fields),locals:Object.fromEntries(Object.entries(s.locals).map(([a,v])=>[a,display(v)]))}))fail(); + }); + if(terminal(d.terminal)!==t.outcome)fail();if(d.replayObservation!=null)terminal(d.replayObservation,true); + return t; + }; + if(Array.isArray(raw.threads)){ + const t=trace(raw);return {trace:t,meta:{programKind:'BYTECODE',verdict:t.outcome,bug:t.bytecodeEvidence.identity.modelClass,storeType:'EXACT',strategy:'DFS'}}; + } + if(raw.programKind!=='BYTECODE' || raw.storeType!=='EXACT' || raw.strategy!=='DFS' || raw.requestedStrategy!=='DFS' || raw.effectiveStrategy!=='DFS' || raw.fallbackReason!=null || raw.symmetryReduction===true || typeof raw.limitExceeded!=='boolean' || typeof raw.hasViolation!=='boolean')fail(); + identity(raw.bytecodeIdentity); + const buckets=['failingTraces','deadlockedTraces','incompleteTraces','completedTraces']; + const expected=['VIOLATION','DEADLOCK','INCOMPLETE','COMPLETED']; + const traces=[]; + buckets.forEach((key,i)=>{if(!Array.isArray(raw[key]) || raw[key].length>MAX_SCHEDULE)fail();for(const t of raw[key]){trace(t);if(t.outcome!==expected[i] || !equal(t.bytecodeEvidence.identity,raw.bytecodeIdentity))fail();traces.push(t);}}); + if(!traces.length || raw.hasViolation!==(raw.failingTraces.length>0))fail(); + const verdict=raw.failingTraces.length || raw.deadlockedTraces.length ? 'VIOLATION' : raw.limitExceeded || raw.incompleteTraces.length ? 'INCOMPLETE' : 'PASS'; + if(raw.verdict!==verdict)fail(); + const selected=traces[0]; + return {trace:selected,meta:{programKind:'BYTECODE',verdict,bug:raw.bug || raw.bytecodeIdentity.modelClass,storeType:'EXACT',strategy:'DFS',statesExplored:raw.statesExplored,wallTimeMs:raw.wallTimeMs,heapDeltaBytes:raw.heapDeltaBytes,limitExceeded:raw.limitExceeded}}; +} + /** * Normalize any supported raw JSON payload into a {trace, meta} pair. * Supports resource prefixes, TraceRecord {threads}, ReportWriter {benchmarks}, and TestResult @@ -194,6 +294,11 @@ function normalizeResourcePrefix(value, diagnostics){ */ function normalize(raw){ if(!raw || typeof raw !== 'object') throw new Error('JSON must be an object'); + if(Array.isArray(raw.benchmarks)){ + const selected=raw.benchmarks.find(b=>b.failingTrace) || raw.benchmarks.find(b=>b.incompleteTrace) || raw.benchmarks[0]; + if(selected?.programKind==='BYTECODE')return normalizeBytecode(selected); + } + if(raw.programKind==='BYTECODE' || raw.bytecodeEvidence!=null)return normalizeBytecode(raw); const diagnostics = (value, threads, outcome = value.outcome) => { const validSpan = (span) => span && typeof span.file === 'string' && ['line','column','endLine','endColumn'].every(k=>Number.isSafeInteger(span[k]) && span[k]>0) && @@ -403,6 +508,20 @@ function renderHeader(){ parts.push(addKV('candidate checks', `${search.candidatesChecked} / ${search.candidateLimit}`)); parts.push(addKV('search scope', 'Original subsequences only; no global shortest guarantee')); } + if(currentTrace.bytecodeEvidence){ + const data=currentTrace.bytecodeEvidence, end=data.terminal; + const at=p=>`${capName(p.owner)}.${capName(p.name)}${capStr(p.descriptor)} BCI ${p.bci}`; + parts.push(addKV('profile', `BYTECODE ${data.identity.profileVersion}`)); + parts.push(addKV('artifact', data.identity.artifactDigest)); + parts.push(addKV('traversal', `${data.identity.requestedStrategy} → ${data.identity.effectiveStrategy}`)); + parts.push(addKV('terminal', end.kind)); + if(end.fault)parts.push(addKV('fault', `${capStr(end.fault.type)} at ${at(end.fault.location)}`)); + if(end.cutoff)parts.push(addKV('cutoff', `${capStr(end.cutoff.reason)} actor ${end.actor} at ${at(end.cutoff.location)}; limit ${end.cutoff.limit}, required ${end.cutoff.required}, remaining ${end.cutoff.remaining}`)); + if(end.check)parts.push(addKV('check', `${capStr(end.check.kind)} ${at(end.check.location)}`)); + end.waits.forEach(w=>parts.push(addKV('monitor wait', `actor ${w.actor} waits for ${w.owner} on ${capStr(w.monitor)} depth ${w.depth}`))); + if(end.interruption)parts.push(addKV('interruption', `${end.interruption}; original run INCOMPLETE`)); + if(data.replayObservation)parts.push(addKV('replay observation', `${data.replayObservation.kind}; one prefix only`)); + } if(currentTrace.sourceDigest) parts.push(addKV('source digest', currentTrace.sourceDigest)); const terminal = currentTrace.cutoff || currentTrace.failure; if(terminal){ @@ -502,7 +621,10 @@ function renderTimeline(){ if(activeTid===tid){ const sourceStep = currentTrace.executedSteps?.[idx]; const stepIdx = sourceStep ? sourceStep.instructionIndex : counters[tid]; - const info = sourceStep ? {label:sourceStep.label,detail:`${capName(sourceStep.source.file)}:${sourceStep.source.line}:${sourceStep.source.column}–${sourceStep.source.endLine}:${sourceStep.source.endColumn} — ${sourceStep.label}`} : stepInfoFor(programThreadsById, tid, stepIdx); + const bytecodeStep=currentTrace.bytecodeEvidence?.transitions[idx]; + const first=bytecodeStep?.operations[0]; + const bytecodeInfo=first ? {label:`${first.location.name} BCI ${first.location.bci}`,detail:bytecodeStep.operations.map(op=>`${op.location.owner}.${op.location.name}${op.location.descriptor} BCI ${op.location.bci}${op.line==null ? '' : ' line '+op.line} ${op.opcode || op.event}`).join('; ')} : null; + const info = bytecodeInfo || (sourceStep ? {label:sourceStep.label,detail:`${capName(sourceStep.source.file)}:${sourceStep.source.line}:${sourceStep.source.column}–${sourceStep.source.endLine}:${sourceStep.source.endColumn} — ${sourceStep.label}`} : stepInfoFor(programThreadsById, tid, stepIdx)); const rawLabel = info ? info.label : `step ${stepIdx}`; const pill = document.createElement('span'); pill.className = 'cell-active'; @@ -602,6 +724,21 @@ function renderStateStrip(){ ['Scope','Name','Value at selected config'].forEach(t=>{ const th=document.createElement('th'); th.textContent=t; hr.append(th); }); thead.append(hr); table.append(thead); const tbody = document.createElement('tbody'); + const bytecodeHeap=currentTrace.bytecodeEvidence?.snapshots[selectedIdx]?.heap; + if(bytecodeHeap){ + for(const object of bytecodeHeap.slice(0,MAX_FIELDS)){ + const row=document.createElement('tr'); + const owner=object.owner===-2 ? 'unowned' : object.owner===-1 ? 'setup' : `actor ${object.owner}`; + for(const value of ['Monitor',`${object.identity} ${object.type}`,`owner ${owner}; depth ${object.depth}; shared ${object.shared}; initialized ${object.initialized}`]){ + const cell=document.createElement('td');cell.textContent=capStr(value);row.append(cell); + } + tbody.append(row); + } + if(bytecodeHeap.length>MAX_FIELDS){ + const note=document.createElement('p');note.textContent=`Showing ${MAX_FIELDS} of ${bytecodeHeap.length} monitor objects at this configuration.`;el.append(note); + } + } + if(snapshot){ let rowCount = 0; diff --git a/examples/bytecode/README.md b/examples/bytecode/README.md index d616e9e..30a39b3 100644 --- a/examples/bytecode/README.md +++ b/examples/bytecode/README.md @@ -32,9 +32,50 @@ Use fixture-constructor fields for locks. A declaration such as `static final Ob requires executable `` and rejects, as do ordinary static arrays, enum initialization and compiler-generated assertion-status setup. Use declared `@Check` methods instead of Java `assert`. Arrays, actor allocations/general dispatch, user catch/finally, wider primitives/core libraries, -CBS/DPOR/bitstate, atomics and weak memory belong to later phases. Compiler-generated synchronized +CBS/DPOR/bitstate and atomics belong to later selected phases. Weak memory remains unselected. Compiler-generated synchronized cleanup is supported; runtime null/division faults remain modeled behavior rather than loader errors. [The shared contract](../../docs/plans/bytecode-contract.md) defines the complete supported profile. The [94B ledger](../../docs/measurements/94B-bytecode-concurrency.md) contains real reference/batched measurements and the preservation argument. These examples establish no Java Memory Model coverage. + +## Replay and transport + +```java +import dev.samhb.interleave.InterleaveRunner; +import dev.samhb.interleave.TraceRecord; +import dev.samhb.interleave.format.BytecodeProgramLoader; +import dev.samhb.interleave.search.TraceReplayer; +import java.nio.file.Path; + +var program = BytecodeProgramLoader.load(Path.of("build/bytecode-examples"), + "examples.bytecode.LostUpdate"); +var result = InterleaveRunner.builder().build().runBytecode(program); +var saved = result.failingTraces().getFirst().toJson(); +var replayed = new TraceReplayer().replayBytecode(program, TraceRecord.fromJson(saved)); +``` + +`TraceRecord.fromJson` imports only the distinct +BYTECODE schema and does not authenticate target execution; strict replay performs that check. +It rejects duplicate keys, conflicting fields, unknown schemas and scalar coercions, with limits of +16 Mi UTF-16 code units of JSON text, 64 nesting levels and one million JSON nodes. Tagged wide numeric values +are strings/raw bits, reserved for later execution coverage. Native Java streams are build-specific: +this release changes generated serialization identities, and incompatible older streams reject. +Streams produced before the 94C field additions (including merged 94B at `6eb939e`) are outside the +compatible native shape. Export JSON using the producing build before upgrading; a source/declarative +record must continue through its existing consumer route. This importer accepts BYTECODE only. +Keep the original class files for cross-process replay; debug metadata is part of artifact identity. + +The viewer accepts result JSON, report JSON or a standalone BYTECODE witness. It shows genuine +method/descriptor/BCI locations and optional compiler lines, monitor waits and exact omitted cutoff +operations. Viewer validation checks shape and precision; only Java strict replay authenticates the +record against an artifact. A completed witness is one execution, not an exhaustive PASS. A global +stop keeps its original INCOMPLETE verdict even if replay observes a completed or failed prefix. + +Default actor fuel remains 256 instructions, separately from scheduling transitions. Loops/retries +can exhaust it; a modeled cutoff ends that prefix and leaves the result incomplete. Observer faults +or exhaustion are incomplete rather than actor violations. `maxStates` and `maxTime` are checker +limits; the time limit is checked at scheduling boundaries. The internal exact-store safety budget is +64 MiB of canonical key payloads, excluding JVM overhead. Heap delta in reports is an instantaneous +JVM measurement, not retained-memory evidence. The 94B tiny-fixture measurements justify retaining +provisional defaults, without establishing performance for larger programs. diff --git a/src/main/java/dev/samhb/interleave/BytecodeTraceJson.java b/src/main/java/dev/samhb/interleave/BytecodeTraceJson.java new file mode 100644 index 0000000..e7d7506 --- /dev/null +++ b/src/main/java/dev/samhb/interleave/BytecodeTraceJson.java @@ -0,0 +1,116 @@ +/** Bounded, duplicate-free import of the distinct BYTECODE witness schema. */ +package dev.samhb.interleave; + +import com.google.gson.*; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonToken; +import dev.samhb.interleave.core.BytecodeEvidence; +import dev.samhb.interleave.core.StateSnapshot; +import dev.samhb.interleave.core.StepOutcome; +import dev.samhb.interleave.search.TraceOutcome; +import java.io.IOException; +import java.io.StringReader; +import java.util.ArrayList; +import java.util.List; + +/** Import limits bound work before allocating reflective DTOs or interpreting any target. */ +final class BytecodeTraceJson { + /** Prevents construction of the schema codec. */ + private BytecodeTraceJson() {} + + /** Reads exactly the producer's BYTECODE schema, preserving string-tagged numeric values. + * @param json untrusted text + * @return validated immutable shape, still requiring strict replay authentication + * @throws IllegalArgumentException for invalid syntax, shape or resource limits */ + static TraceRecord read(String json) { + if (json == null || json.length() > 16 * 1024 * 1024) throw new IllegalArgumentException("BYTECODE JSON exceeds 16 Mi UTF-16 code units"); + try (var reader = new JsonReader(new StringReader(json))) { + reader.setStrictness(Strictness.STRICT); + var nodes = new int[]{0}; charge(nodes); + var root = value(reader, 0, nodes).getAsJsonObject(); + if (reader.peek() != JsonToken.END_DOCUMENT || !"BYTECODE".equals(root.get("programKind").getAsString())) + throw new IllegalArgumentException("Expected one BYTECODE record"); + var evidence = ResultJson.GSON.fromJson(root.get("bytecodeEvidence"), BytecodeEvidence.class); + List threads = new ArrayList<>(); + for (var element : root.getAsJsonArray("threads")) threads.add(element.getAsInt()); + List outcomes = new ArrayList<>(); + for (var element : root.getAsJsonArray("outcomes")) outcomes.add(StepOutcome.valueOf(element.getAsString())); + List states = new ArrayList<>(); + for (var element : root.getAsJsonArray("states")) states.add(ResultJson.GSON.fromJson(element, StateSnapshot.class)); + for (var state : states) { + if (!state.fields().values().stream().allMatch(String.class::isInstance) + || state.locals().values().stream().anyMatch(row -> !row.values().stream().allMatch(String.class::isInstance))) + throw new IllegalArgumentException("BYTECODE display values must be immutable tagged strings"); + } + var trace = new TraceRecord(threads, outcomes, TraceOutcome.valueOf(root.get("outcome").getAsString()), + root.get("programHash").getAsString(), states, null, java.util.Objects.requireNonNull(evidence)); + // Canonical shape comparison also rejects unknown fields and Gson's scalar coercions. + var canonical = JsonParser.parseString(trace.toJson()); + if (!same(root, canonical)) throw new IllegalArgumentException("Noncanonical or conflicting BYTECODE schema"); + return trace; + } catch (IOException | RuntimeException invalid) { + throw new IllegalArgumentException("Invalid BYTECODE trace JSON", invalid); + } + } + + /** Parses with depth, node and duplicate-name limits before Gson record construction. + * @param reader strict stream + * @param depth current nesting depth + * @param nodes shared node counter + * @return bounded JSON tree + * @throws IOException for invalid stream input */ + private static JsonElement value(JsonReader reader, int depth, int[] nodes) throws IOException { + if (depth > 64) throw new IllegalArgumentException("BYTECODE JSON nesting limit"); + return switch (reader.peek()) { + case BEGIN_OBJECT -> { + var object = new JsonObject(); reader.beginObject(); + while (reader.hasNext()) { + var name = reader.nextName(); + if (object.has(name)) throw new IllegalArgumentException("Duplicate JSON member"); + charge(nodes); + object.add(name, value(reader, depth + 1, nodes)); + } + reader.endObject(); yield object; + } + case BEGIN_ARRAY -> { + var array = new JsonArray(); reader.beginArray(); + while (reader.hasNext()) { + charge(nodes); + array.add(value(reader, depth + 1, nodes)); + } + reader.endArray(); yield array; + } + case STRING -> new JsonPrimitive(reader.nextString()); + case NUMBER -> JsonParser.parseString(reader.nextString()); + case BOOLEAN -> new JsonPrimitive(reader.nextBoolean()); + case NULL -> { reader.nextNull(); yield JsonNull.INSTANCE; } + default -> throw new IllegalArgumentException("Expected JSON value"); + }; + } + + /** Charges each node before recursion or container growth, keeping the loop's work bound independent + * of the child's parsing progress. + * @param nodes shared count including the root + * @throws IllegalArgumentException before allocating a node above the documented ceiling */ + private static void charge(int[] nodes) { + if (++nodes[0] > 1_000_000) throw new IllegalArgumentException("BYTECODE JSON node limit"); + } + + /** Compares schema trees without numeric/string coercion or loss of integer spelling. + * @param left supplied tree + * @param right canonical producer tree + * @return whether both trees have exactly the same members and typed leaves */ + private static boolean same(JsonElement left, JsonElement right) { + if (left.isJsonObject() && right.isJsonObject()) { + var a = left.getAsJsonObject(); var b = right.getAsJsonObject(); + return a.keySet().equals(b.keySet()) && a.keySet().stream().allMatch(key -> same(a.get(key), b.get(key))); + } + if (left.isJsonArray() && right.isJsonArray()) { + var a = left.getAsJsonArray(); var b = right.getAsJsonArray(); + if (a.size() != b.size()) return false; + for (int i = 0; i < a.size(); i++) if (!same(a.get(i), b.get(i))) return false; + return true; + } + return left.toString().equals(right.toString()); + } +} diff --git a/src/main/java/dev/samhb/interleave/ResultJson.java b/src/main/java/dev/samhb/interleave/ResultJson.java index 4120cfe..d7cbcc8 100644 --- a/src/main/java/dev/samhb/interleave/ResultJson.java +++ b/src/main/java/dev/samhb/interleave/ResultJson.java @@ -9,6 +9,23 @@ final class ResultJson { /** Thread-safe serializer preserving existing trace string and typed-value behavior. */ static final Gson GSON = new GsonBuilder().disableHtmlEscaping().create(); + /** Escapes isolated UTF-16 surrogates so BYTECODE JSON survives UTF-8 file transport exactly. + * Paired supplementary characters retain their ordinary representation; legacy output is untouched. + * @param json serialized BYTECODE text + * @return transport-safe JSON with identical decoded UTF-16 strings */ + static String bytecodeText(String json) { + var safe = new StringBuilder(json.length()); + for (int i = 0; i < json.length(); i++) { + char value = json.charAt(i); + if (Character.isHighSurrogate(value) && i + 1 < json.length() && Character.isLowSurrogate(json.charAt(i + 1))) { + safe.append(value).append(json.charAt(++i)); + } else if (Character.isSurrogate(value)) { + safe.append(String.format(java.util.Locale.ROOT, "\\u%04x", (int) value)); + } else safe.append(value); + } + return safe.toString(); + } + /** Prevents instantiation of this configuration holder. */ private ResultJson() {} } diff --git a/src/main/java/dev/samhb/interleave/TestResult.java b/src/main/java/dev/samhb/interleave/TestResult.java index f51ea60..edb8f56 100644 --- a/src/main/java/dev/samhb/interleave/TestResult.java +++ b/src/main/java/dev/samhb/interleave/TestResult.java @@ -336,7 +336,7 @@ public String toJson() { // on the result's content. Consumers can then branch on the key without checking presence. sb.append(" \"incompleteTraces\": ").append(jsonTraces(incompleteTraces)).append("\n"); sb.append("}\n"); - return sb.toString(); + return bytecode == null ? sb.toString() : ResultJson.bytecodeText(sb.toString()); } /** diff --git a/src/main/java/dev/samhb/interleave/TraceRecord.java b/src/main/java/dev/samhb/interleave/TraceRecord.java index e1b85f9..89eb5f7 100644 --- a/src/main/java/dev/samhb/interleave/TraceRecord.java +++ b/src/main/java/dev/samhb/interleave/TraceRecord.java @@ -149,6 +149,15 @@ public TraceRecord withStates(List states) { return new TraceRecord(this.threadIds, this.outcomes, this.outcome, this.programHash, states, evidence,bytecodeEvidence); } + /** Imports a bounded BYTECODE witness without executing model code. + * The payload remains untrusted until {@code TraceReplayer.replayBytecode} authenticates it. + * Existing source and declarative import routes retain their own schemas. + * @param json JSON produced by {@link #toJson()} for a BYTECODE record + * @return immutable typed trace + * @throws IllegalArgumentException for malformed, oversized or conflicting evidence + */ + public static TraceRecord fromJson(String json) { return BytecodeTraceJson.read(json); } + /** * Serializes thread choices, step outcomes, terminal verdict, the optional program fingerprint, * and optional state snapshots. @@ -184,6 +193,6 @@ public String toJson() { if (evidence.cutoff() != null) sb.append(",\n \"cutoff\": ").append(GSON.toJson(evidence.cutoff())); } sb.append("\n}"); - return sb.toString(); + return bytecodeEvidence == null ? sb.toString() : ResultJson.bytecodeText(sb.toString()); } } diff --git a/src/main/java/dev/samhb/interleave/bytecode/BytecodeReplay.java b/src/main/java/dev/samhb/interleave/bytecode/BytecodeReplay.java new file mode 100644 index 0000000..128de6a --- /dev/null +++ b/src/main/java/dev/samhb/interleave/bytecode/BytecodeReplay.java @@ -0,0 +1,83 @@ +/** Strict replay of artifact-bound bytecode records through the same opcode/observation semantics. */ +package dev.samhb.interleave.bytecode; + +import dev.samhb.interleave.TraceRecord; +import dev.samhb.interleave.core.*; +import dev.samhb.interleave.search.CorruptedTraceException; +import dev.samhb.interleave.search.TraceOutcome; +import java.util.*; + +/** Authenticates concrete execution; external stop causes remain separate from replay observations. */ +final class BytecodeReplay { + /** Prevents construction of this stateless strict replayer. */ + private BytecodeReplay() {} + + /** Checks frozen selection identity before any target operation, then validates every boundary. + * @param program immutable selected program + * @param record original captured record + * @return immutable record with actual replay observations and snapshots + * @throws CorruptedTraceException for mismatched identity, evidence, state or terminal meaning + * @throws IllegalScheduleException for a foreign/disabled actor choice + * @throws java.util.concurrent.CancellationException when the caller interrupts replay */ + static TraceRecord replay(BytecodeProgram program,TraceRecord record) { + Objects.requireNonNull(program);Objects.requireNonNull(record);cancelled(); + var data=record.bytecodeEvidence(); + if(data==null || record.evidence()!=null || !BytecodeRuntime.identity(program).equals(data.identity()) + || !program.artifactDigest().equals(record.programHash()))throw corrupt("Bytecode artifact/model/declaration/profile/limits/mode mismatch"); + if(data.transitions().size()!=record.threadIds().size() || record.outcomes().size()!=record.threadIds().size() + || data.snapshots().size()!=record.threadIds().size()+1 || record.states().size()!=data.snapshots().size())throw corrupt("Misaligned bytecode record"); + var scheduler=new BytecodeScheduler(program,BytecodeScheduler.Mode.BATCHED);var state=program.initialState(); + var snapshots=new ArrayList();var transitions=new ArrayList(); + verifySnapshot(record,data,state,0,snapshots); + var observation=observe(program,state); + for(int index=0;index actual) { + var snapshot=BytecodeSnapshots.capture(state,state.canonicalBytes()); + if(!snapshot.equals(data.snapshots().get(index)) || !BytecodeSnapshots.display(snapshot).equals(record.states().get(index)))throw corrupt("Bytecode state/monitor/frame snapshot mismatch at boundary "+index); + actual.add(snapshot); + } + + /** Reuses exact-search check timing and delivered-terminal ordering. + * @param program frozen model + * @param state committed state + * @return actual terminal, or null for runnable prefix + * @throws java.util.concurrent.CancellationException for host interruption during an observer */ + private static BytecodeExplorer.Outcome observe(BytecodeProgram program,BytecodeState state) { + var outcome=BytecodeObservations.evaluate(program,state).outcome(); + if(outcome!=null && outcome.kind()==BytecodeExplorer.Kind.INTERRUPTED)throw new java.util.concurrent.CancellationException("Bytecode replay cancelled"); + return outcome; + } + + /** Preserves caller interrupt state instead of treating cancellation as a modeled fault. */ + private static void cancelled(){if(Thread.currentThread().isInterrupted())throw new java.util.concurrent.CancellationException("Bytecode replay cancelled");} + + /** Creates a precise replay rejection without retaining target throwable objects. + * @param message failed authentication rule + * @return replay mismatch exception */ + private static CorruptedTraceException corrupt(String message){return new CorruptedTraceException(message);} +} diff --git a/src/main/java/dev/samhb/interleave/bytecode/BytecodeRuntime.java b/src/main/java/dev/samhb/interleave/bytecode/BytecodeRuntime.java index cf6bdb3..45163a2 100644 --- a/src/main/java/dev/samhb/interleave/bytecode/BytecodeRuntime.java +++ b/src/main/java/dev/samhb/interleave/bytecode/BytecodeRuntime.java @@ -10,7 +10,8 @@ import java.util.*; /** Deep bytecode integration seam; no mutable execution state or caller-supplied callback is exposed. - * Library clients normally use format.BytecodeProgramLoader, InterleaveRunner and search.TraceReplayer. */ + * Library clients normally use {@link dev.samhb.interleave.format.BytecodeProgramLoader}, whose class + * example shows loading with limits, execution, retained-trace selection and matching strict replay. */ public final class BytecodeRuntime { /** Prevents construction of this stateless integration facade. */ private BytecodeRuntime() {} @@ -53,6 +54,16 @@ public static TestResult run(BytecodeProgram program,long maxStates,Duration max failed,deadlocked,completed,incomplete,!result.traversalComplete()).withRunMetadata(false,resource,false); } + /** Authenticates BYTECODE identity, operations, checks, snapshots, monitors and exact terminal meaning. + * External records authenticate their captured prefix and retain the original incomplete outcome. + * @param program frozen selected artifact + * @param record immutable original record + * @return owned replay record with separate actual prefix observations + * @throws dev.samhb.interleave.search.CorruptedTraceException for identity/evidence mismatches + * @throws IllegalScheduleException for a disabled or foreign actor + * @throws java.util.concurrent.CancellationException for host interruption */ + public static TraceRecord replay(BytecodeProgram program,TraceRecord record){return BytecodeReplay.replay(program,record);} + /** Constructs selected declaration identity independently of the manifest's possible shared closure. * @param program frozen loaded definition * @return immutable public profile/model identity */ @@ -69,9 +80,7 @@ static BytecodeEvidence.Identity identity(BytecodeProgram program) { * @param witness actual selected path and owned snapshots * @return public immutable trace */ private static TraceRecord record(BytecodeProgram program,BytecodeExplorer.Witness witness) { - var transitions=witness.schedule().stream().map(selection->new BytecodeEvidence.Transition(selection.actor(), - selection.executed().stream().map(operation->new BytecodeEvidence.Operation(operation.location(),line(program,operation.location()), - operation.opcode()==null ? null : operation.opcode().name(),operation.event())).toList())).toList(); + var transitions=witness.schedule().stream().map(selection->transition(program,selection)).toList(); var terminal=terminal(witness.outcome());var evidence=new BytecodeEvidence(1,identity(program),transitions,witness.snapshots(),terminal,null); var choices=witness.schedule().stream().map(BytecodeExplorer.Selection::actor).toList(); var outcomes=witness.schedule().stream().map(BytecodeRuntime::stepOutcome).toList(); @@ -79,6 +88,16 @@ private static TraceRecord record(BytecodeProgram program,BytecodeExplorer.Witne witness.snapshots().stream().map(BytecodeSnapshots::display).toList(),null,evidence); } + /** Converts real selected opcode/event positions using frozen optional debug metadata. + * @param program frozen artifact + * @param selection actual actor operation sequence + * @return immutable descriptor/BCI transition */ + static BytecodeEvidence.Transition transition(BytecodeProgram program,BytecodeExplorer.Selection selection) { + return new BytecodeEvidence.Transition(selection.actor(),selection.executed().stream().map(operation-> + new BytecodeEvidence.Operation(operation.location(),line(program,operation.location()), + operation.opcode()==null ? null : operation.opcode().name(),operation.event())).toList()); + } + /** Maps actual selected events into the legacy coarse step vocabulary without source continuations. * @param selection committed transition * @return coarse step outcome; precise cause remains in BYTECODE evidence */ diff --git a/src/main/java/dev/samhb/interleave/bytecode/Model.java b/src/main/java/dev/samhb/interleave/bytecode/Model.java index e38309d..21221d8 100644 --- a/src/main/java/dev/samhb/interleave/bytecode/Model.java +++ b/src/main/java/dev/samhb/interleave/bytecode/Model.java @@ -1,5 +1,6 @@ /** Public metadata-only annotation protocol for the bounded sequentially consistent profile. */ package dev.samhb.interleave.bytecode; +/** Marks the shared fixture whose public no-argument constructor is interpreted during loading. */ @java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.CLASS) @java.lang.annotation.Target(java.lang.annotation.ElementType.TYPE) public @interface Model {} diff --git a/src/main/java/dev/samhb/interleave/cli/Main.java b/src/main/java/dev/samhb/interleave/cli/Main.java index 5e3eed5..b5a9bea 100644 --- a/src/main/java/dev/samhb/interleave/cli/Main.java +++ b/src/main/java/dev/samhb/interleave/cli/Main.java @@ -41,6 +41,38 @@ public Main() {} /** Exact. */ private static final String EXACT = "EXACT"; + /** Parses the bounded BYTECODE profile before any artifact loading or search. + * @param args complete arguments; only DFS/EXACT and JSON output are admitted */ + private static void handleBytecode(String[] args) { + try { + var values = new HashMap(); boolean json = false; + for (int i = 0; i < args.length; i++) { + String flag = args[i]; + if (flag.equals("--json")) { + if (json) throw new IllegalArgumentException("Duplicate --json"); + json = true; continue; + } + if (!Set.of("--bytecode", "--class-path", "--strategy", "--store").contains(flag)) + throw new IllegalArgumentException("Unsupported BYTECODE option: " + flag); + if (values.containsKey(flag)) throw new IllegalArgumentException("Duplicate " + flag); + if (i + 1 >= args.length || args[i + 1].startsWith("--")) throw new IllegalArgumentException("Missing value for " + flag); + values.put(flag, args[++i]); + } + if (!values.containsKey("--bytecode") || !values.containsKey("--class-path")) + throw new IllegalArgumentException("BYTECODE requires --bytecode and --class-path "); + if (!values.getOrDefault("--strategy", "DFS").equalsIgnoreCase("DFS") + || !values.getOrDefault("--store", "exact").equalsIgnoreCase("exact")) + throw new IllegalArgumentException("BYTECODE currently supports only --strategy DFS --store exact"); + var program = dev.samhb.interleave.format.BytecodeProgramLoader.load(Paths.get(values.get("--class-path")), values.get("--bytecode")); + var rows = new BenchmarkHarness().runBytecode(program); + var writer = new ReportWriter(rows, List.of()); + System.out.println(json ? writer.writeJson() : writer.writeMarkdown()); + } catch (IllegalArgumentException failure) { + System.err.println("Error: BYTECODE: " + failure.getMessage()); + System.exit(1); + } + } + /** * The highest preemption bound that is meaningful with a Bloom-filter store. * @@ -85,6 +117,11 @@ public static void main(String[] args) { return; } + if (Arrays.asList(args).contains("--bytecode") || Arrays.asList(args).contains("--class-path")) { + handleBytecode(args); + return; + } + // Parse flags boolean json = false; boolean all = false; @@ -450,6 +487,7 @@ private static void printUsage() { System.out.println("Usage: interleave [flags]"); System.out.println(" interleave --file [flags]"); System.out.println(" interleave --source [flags]"); + System.out.println(" interleave --bytecode --class-path [--json] [--strategy DFS] [--store exact]"); System.out.println(" interleave --all [flags]"); System.out.println(" interleave generate --template [flags]"); System.out.println(); diff --git a/src/main/java/dev/samhb/interleave/core/BytecodeEvidence.java b/src/main/java/dev/samhb/interleave/core/BytecodeEvidence.java index 3f58d4c..c613876 100644 --- a/src/main/java/dev/samhb/interleave/core/BytecodeEvidence.java +++ b/src/main/java/dev/samhb/interleave/core/BytecodeEvidence.java @@ -189,7 +189,7 @@ public record Wait(int actor,int owner,String monitor,int depth) implements Seri /** Terminal meaning; PREFIX appears only as a separate external-prefix replay observation. * @param kind COMPLETED, DEADLOCK, UNCAUGHT_EXCEPTION, CHECK_FALSE, CUTOFF, OBSERVER_ERROR, OBSERVER_LIMIT, INTERRUPTED or PREFIX * @param actor fault/cutoff actor, otherwise -1 - * @param fault original actor fault + * @param fault original actor fault, also retained as context when cleanup is cut off * @param cutoff modeled actor cutoff * @param check separate observer failure * @param waits concrete deadlock relationships @@ -201,7 +201,8 @@ public record Terminal(String kind,int actor,Fault fault,Cutoff cutoff,CheckFail if(!Set.of("COMPLETED","DEADLOCK","UNCAUGHT_EXCEPTION","CHECK_FALSE","CUTOFF","OBSERVER_ERROR","OBSERVER_LIMIT","INTERRUPTED","PREFIX").contains(kind))throw new IllegalArgumentException("Unknown bytecode terminal"); boolean actorFailure=kind.equals("UNCAUGHT_EXCEPTION") || kind.equals("CUTOFF"); if(actorFailure ? actor<0 || actor>7 : actor!= -1)throw new IllegalArgumentException("Invalid terminal actor"); - if((fault!=null)!=kind.equals("UNCAUGHT_EXCEPTION") || (cutoff!=null)!=kind.equals("CUTOFF") + if((kind.equals("UNCAUGHT_EXCEPTION") && fault==null) || (fault!=null && !Set.of("UNCAUGHT_EXCEPTION","CUTOFF").contains(kind)) + || (cutoff!=null)!=kind.equals("CUTOFF") || (check!=null)!=Set.of("CHECK_FALSE","OBSERVER_ERROR","OBSERVER_LIMIT").contains(kind) || kind.equals("DEADLOCK")!=!waits.isEmpty() || (interruption!=null)!=kind.equals("INTERRUPTED"))throw new IllegalArgumentException("Conflicting bytecode terminal causes"); if(check!=null && !check.kind().equals(switch(kind){case "CHECK_FALSE"->"FALSE";case "OBSERVER_ERROR"->"ERROR";default->"LIMIT";}))throw new IllegalArgumentException("Wrong observer classification"); diff --git a/src/main/java/dev/samhb/interleave/format/BytecodeProgramLoader.java b/src/main/java/dev/samhb/interleave/format/BytecodeProgramLoader.java index a137a3e..39883c4 100644 --- a/src/main/java/dev/samhb/interleave/format/BytecodeProgramLoader.java +++ b/src/main/java/dev/samhb/interleave/format/BytecodeProgramLoader.java @@ -4,7 +4,18 @@ import dev.samhb.interleave.bytecode.*; import java.nio.file.Path; -/** Parses and validates frozen class bytes, interpreting setup without reflectively loading target classes. */ +/** Parses and validates frozen class bytes, interpreting setup without reflectively loading target classes. + * Compile the example externally first, then use the same frozen program for execution and replay: + *
{@code
+ * var program = BytecodeProgramLoader.load(java.nio.file.Path.of("build/bytecode-examples"),
+ *     "examples.bytecode.LostUpdate", dev.samhb.interleave.bytecode.BytecodeLimits.defaults());
+ * var result = dev.samhb.interleave.InterleaveRunner.builder().build().runBytecode(program);
+ * var saved = result.failingTraces().getFirst().toJson();
+ * var record = dev.samhb.interleave.TraceRecord.fromJson(saved);
+ * var replayed = new dev.samhb.interleave.search.TraceReplayer().replayBytecode(program, record);
+ * var rows = new dev.samhb.interleave.report.BenchmarkHarness().runBytecode(program);
+ * }
+ */ public final class BytecodeProgramLoader { /** Prevents construction of this static loading facade. */ private BytecodeProgramLoader() {} @@ -12,6 +23,7 @@ private BytecodeProgramLoader() {} /** Loads one fixed-actor model using the provisional defaults reviewed against94B fixtures. * Inputs are non-preview Java17–26 class files in one immutable regular-file directory classpath. * No compilation, jar discovery or target-code host fallback occurs. + * See the class example for execution and replay; omitting limits selects {@link BytecodeLimits#defaults()}. * @param classDirectory class-file root, immutable for the duration of loading * @param modelClass selected binary fixture name * @return immutable initialized program, safe to reuse independently @@ -19,6 +31,7 @@ private BytecodeProgramLoader() {} public static BytecodeProgram load(Path classDirectory,String modelClass){return load(classDirectory,modelClass,BytecodeLimits.defaults());} /** Loads one model with immutable per-owner allowances and bounded metadata-only resolution. + * See the class example for a complete compiled-example execution and replay. * @param classDirectory immutable regular-file classpath root * @param modelClass selected binary fixture name * @param limits validated execution limits diff --git a/src/main/java/dev/samhb/interleave/report/BenchmarkHarness.java b/src/main/java/dev/samhb/interleave/report/BenchmarkHarness.java index 3d3a4eb..cd64e09 100644 --- a/src/main/java/dev/samhb/interleave/report/BenchmarkHarness.java +++ b/src/main/java/dev/samhb/interleave/report/BenchmarkHarness.java @@ -134,6 +134,21 @@ public BenchmarkHarness(int bitstateSize, int bitstateK, this.iterativeDeepening = iterativeDeepening; } + /** Runs the initial BYTECODE profile with owned exact DFS storage and declared checks. + * Null filters select that profile's sole supported combination. + * See {@link dev.samhb.interleave.format.BytecodeProgramLoader} for a complete compiled-example workflow. + * @param program frozen validated bytecode model + * @return one complete report row with strictly replayable witnesses + * @throws IllegalArgumentException for unavailable strategy, store or symmetry selections */ + public List runBytecode(dev.samhb.interleave.bytecode.BytecodeProgram program) { + if ((storeFilter != null && !storeFilter.equals(Set.of(StoreType.EXACT))) + || (strategyFilter != null && !strategyFilter.equals(Set.of("DFS"))) + || symmetryReduction || iterativeDeepening || maxPreemptions != DEFAULT_MAX_PREEMPTIONS) + throw new IllegalArgumentException("BYTECODE currently requires exact DFS without symmetry or CBS settings"); + var result = dev.samhb.interleave.InterleaveRunner.builder().build().runBytecode(program); + return List.of(new BenchmarkResult(program, result)); + } + /** * Runs the complete benchmark suite for all programs in the corpus. * Returns up to 8 results per program: 4 strategies × 2 store types, diff --git a/src/main/java/dev/samhb/interleave/report/BenchmarkResult.java b/src/main/java/dev/samhb/interleave/report/BenchmarkResult.java index 787e3bc..c8b8a1e 100644 --- a/src/main/java/dev/samhb/interleave/report/BenchmarkResult.java +++ b/src/main/java/dev/samhb/interleave/report/BenchmarkResult.java @@ -15,6 +15,11 @@ * Immutable result of a single benchmark run (one strategy + one store type). */ public final class BenchmarkResult { + /** Actual frozen BYTECODE model; unavailable to arbitrary legacy row constructors. */ + private final dev.samhb.interleave.bytecode.BytecodeProgram bytecodeProgram; + /** Owned BYTECODE run including every terminal category. */ + private final dev.samhb.interleave.TestResult bytecodeResult; + /** Whether this row counts checked model representative visits. */ private final boolean symmetryReduction; /** Strategy. */ @@ -191,6 +196,7 @@ public BenchmarkResult(String strategy, String bugName, long statesExplored, double estimatedFalsePositiveRate, int bitstateBitCount, double bitstateBitDensity, Integer preemptionsUsed, List states) { + this.bytecodeProgram = null; this.bytecodeResult = null; this.symmetryReduction = false; this.strategy = strategy; this.bugName = bugName; @@ -219,6 +225,8 @@ public BenchmarkResult(String strategy, String bugName, long statesExplored, * @param symmetryReduction whether checked model orbit search produced this row */ private BenchmarkResult(BenchmarkResult row, Program program, DfsResult result, boolean symmetryReduction) { + if (row.bytecodeResult != null) throw new IllegalArgumentException("BYTECODE rows cannot be relabeled with legacy exploration"); + this.bytecodeProgram = null; this.bytecodeResult = null; this.symmetryReduction = symmetryReduction; this.strategy = row.strategy; this.bugName = row.bugName; this.statesExplored = row.statesExplored; this.wallTimeMs = row.wallTimeMs; this.heapDeltaBytes = row.heapDeltaBytes; @@ -241,11 +249,35 @@ private BenchmarkResult(BenchmarkResult row, Program program, DfsResult result, this.incompleteStates = snapshots; } + /** Creates a BYTECODE row only from the harness's owned execution. + * @param program frozen executed model + * @param result actual exact run */ + BenchmarkResult(dev.samhb.interleave.bytecode.BytecodeProgram program, dev.samhb.interleave.TestResult result) { + this.bytecodeProgram = program; this.bytecodeResult = result; + this.symmetryReduction = false; this.sourceModel = false; this.strategy = "DFS"; + this.bugName = program.modelClass(); this.statesExplored = result.statesExplored(); + this.wallTimeMs = result.wallTimeMs(); this.heapDeltaBytes = result.heapDeltaBytes(); + this.verdict = result.hasViolation() || !result.deadlockedTraces().isEmpty() ? "VIOLATION" + : result.hasIncomplete() || result.limitExceeded() ? "INCOMPLETE" : "PASS"; + this.failingTrace = null; this.storeType = StoreType.EXACT; + this.estimatedFalsePositiveRate = 0; this.bitstateBitCount = 0; this.bitstateBitDensity = 0; + this.preemptionsUsed = null; this.states = List.of(); this.incompleteTraces = List.of(); this.incompleteStates = List.of(); + } + + /** Returns the actual frozen model for report-owned replay. + * @return model, or null for legacy rows */ + dev.samhb.interleave.bytecode.BytecodeProgram bytecodeProgram() { return bytecodeProgram; } + + /** Returns owned typed evidence without projecting it into SOURCE traces. + * @return run, or null for legacy rows */ + dev.samhb.interleave.TestResult bytecodeResult() { return bytecodeResult; } + /** * Attaches run evidence without altering legacy public constructor contracts. * @param program executed model, or null when no replay context is available * @param result actual exploration evidence * @return a new row preserving all counts and diagnostics + * @throws IllegalArgumentException if this BYTECODE row would be relabeled with legacy evidence */ public BenchmarkResult withExploration(Program program, DfsResult result) { return new BenchmarkResult(this, program, result, symmetryReduction); diff --git a/src/main/java/dev/samhb/interleave/report/ReportWriter.java b/src/main/java/dev/samhb/interleave/report/ReportWriter.java index 05b6361..1d1e0ae 100644 --- a/src/main/java/dev/samhb/interleave/report/ReportWriter.java +++ b/src/main/java/dev/samhb/interleave/report/ReportWriter.java @@ -71,6 +71,17 @@ public String writeMarkdown() { sb.append(table.formatMarkdown()); sb.append("\n"); + for (var row : results) { + if (row.bytecodeResult() != null) { + var run = row.bytecodeResult(); + sb.append("## BYTECODE evidence\n\nArtifact: `").append(run.bytecodeIdentity().artifactDigest()) + .append("` · profile `").append(run.bytecodeIdentity().profileVersion()) + .append("` · requested/effective DFS · EXACT · ").append(row.verdict()).append("\n\n"); + sb.append("Witness details (real method/BCI locations, monitor waits, checks and cutoffs):\n\n```json\n") + .append(run.toJson()).append("\n```\n\n"); + } + } + SoundnessAttestation attestation = new SoundnessAttestation(results, programs); sb.append(attestation.formatMarkdown()); @@ -94,6 +105,12 @@ public String writeJson() { for (int i = 0; i < results.size(); i++) { BenchmarkResult result = results.get(i); + if (result.bytecodeResult() != null) { + sb.append(formatBytecode(result)); + if (i < results.size() - 1) sb.append(","); + sb.append("\n"); + continue; + } boolean symmetryReduction = result.symmetryReduction(); sb.append(" {\n"); if (symmetryReduction) sb.append(" \"symmetryReduction\": true,\n"); @@ -145,6 +162,23 @@ public String writeJson() { return sb.toString(); } + /** Emits owned BYTECODE rows without fabricating legacy source evidence. + * @param row harness-produced result + * @return consumer-compatible row with complete typed run and representative witnesses */ + private static String formatBytecode(BenchmarkResult row) { + var run = row.bytecodeResult(); + // Preserve the producer's escaped UTF-16 text through UTF-8 transport. Generic Gson + // reparsing/reserialization can reintroduce isolated surrogates into the output string. + var json = new StringBuilder(run.toJson().stripTrailing()); + json.setLength(json.length() - 1); + json.append(",\n \"bug\": ").append(GSON.toJson(row.bugName())); + json.append(",\n \"preemptionsUsed\": null"); + var failures = !run.failingTraces().isEmpty() ? run.failingTraces() : run.deadlockedTraces(); + if (!failures.isEmpty()) json.append(",\n \"failingTrace\": ").append(failures.getFirst().toJson()); + if (!run.incompleteTraces().isEmpty()) json.append(",\n \"incompleteTrace\": ").append(run.incompleteTraces().getFirst().toJson()); + return json.append("\n}").toString(); + } + /** * Formats the optional preemption bound for a report row. * @param result completed exploration result diff --git a/src/main/java/dev/samhb/interleave/report/SoundnessAttestation.java b/src/main/java/dev/samhb/interleave/report/SoundnessAttestation.java index 3f3271e..f6ba686 100644 --- a/src/main/java/dev/samhb/interleave/report/SoundnessAttestation.java +++ b/src/main/java/dev/samhb/interleave/report/SoundnessAttestation.java @@ -80,6 +80,7 @@ private SoundnessCheck checkSoundness() { .toList(); for (BenchmarkResult result : exactResults) { + if (result.bytecodeResult() != null) continue; String key = result.bugName(); String actualVerdict = result.verdict(); BenchmarkProgram program = programs.get(key); @@ -114,6 +115,20 @@ && certifiedDeclarative(program)) && isInconclusive(actualVerdict))) { // report violations. A violation found under a bounded search is a real schedule, so the // replay check must cover it rather than being skipped along with the inconclusive ones. for (BenchmarkResult result : results) { + if (result.bytecodeResult() != null) { + try { + var run = result.bytecodeResult(); + var traces = new java.util.ArrayList(); + traces.addAll(run.failingTraces()); traces.addAll(run.deadlockedTraces()); + traces.addAll(run.completedTraces()); traces.addAll(run.incompleteTraces()); + if (traces.isEmpty() || run.bytecodeIdentity() == null) return SoundnessCheck.failed("Missing BYTECODE evidence"); + var replayer = new TraceReplayer(); + for (var trace : traces) replayer.replayBytecode(result.bytecodeProgram(), trace); + } catch (RuntimeException invalid) { + return SoundnessCheck.failed("BYTECODE replay failed for " + result.bugName() + ": " + invalid.getMessage()); + } + continue; + } if ("VIOLATION".equals(result.verdict())) { Trace failingTrace = result.failingTrace().orElse(null); if (failingTrace == null) { diff --git a/src/main/java/dev/samhb/interleave/search/TraceReplayer.java b/src/main/java/dev/samhb/interleave/search/TraceReplayer.java index a639c2b..f6af9f3 100644 --- a/src/main/java/dev/samhb/interleave/search/TraceReplayer.java +++ b/src/main/java/dev/samhb/interleave/search/TraceReplayer.java @@ -14,6 +14,22 @@ public final class TraceReplayer { /** Creates trace replayer with its default configuration. */ public TraceReplayer() {} + /** Strictly replays a BYTECODE record through owned interpreted state and declared pure checks. + * Validates artifact/model/declaration/profile/limits/mode identity, enabled original choices, + * real operations, snapshots, checks, monitors and modeled cutoffs. External interruptions retain + * their original incompleteness alongside the separately observed replay prefix. + * See {@link dev.samhb.interleave.format.BytecodeProgramLoader} for a complete matching-program example. + * @param program immutable selected bytecode artifact + * @param record original immutable BYTECODE record + * @return authenticated record with owned actual snapshots and replay observations + * @throws CorruptedTraceException for mismatched identity, evidence or terminal meaning + * @throws IllegalScheduleException for foreign, disabled or terminated actor choices + * @throws java.util.concurrent.CancellationException for caller interruption + * @throws NullPointerException for null arguments */ + public TraceRecord replayBytecode(dev.samhb.interleave.bytecode.BytecodeProgram program,TraceRecord record) { + return dev.samhb.interleave.bytecode.BytecodeRuntime.replay(program,record); + } + /** * Replays thread choices while validating each step outcome against the trace. * @@ -153,6 +169,7 @@ public List captureDeclarativeSnapshots(Program program, Trace tr * @return enriched trace record containing captured state snapshots */ public TraceRecord enrich(Program program, TraceRecord record) { + if(record.bytecodeEvidence()!=null)throw new CorruptedTraceException("Use replayBytecode for BYTECODE evidence"); Trace trace = new Trace(record.threadIds(), record.outcomes(), record.outcome(), record.evidence()); List snapshots = captureSnapshots(program, trace); return record.withStates(snapshots); diff --git a/src/test/java/dev/samhb/interleave/bytecode/BytecodeFixtures.java b/src/test/java/dev/samhb/interleave/bytecode/BytecodeFixtures.java index c42bbf0..f91270b 100644 --- a/src/test/java/dev/samhb/interleave/bytecode/BytecodeFixtures.java +++ b/src/test/java/dev/samhb/interleave/bytecode/BytecodeFixtures.java @@ -51,13 +51,24 @@ static String classpath(Class... types) { * @throws IOException for fixture file failures */ static Path compile(Path directory, int release, String body) throws IOException { + return compile(directory, release, body, true); + } + + /** Compiles with optional real debug tables for consumer location tests. + * @param directory workspace + * @param release input release + * @param body Java fixture + * @param debug whether to emit debug metadata + * @return compiled directory + * @throws IOException for file failures */ + static Path compile(Path directory, int release, String body, boolean debug) throws IOException { Path sources=directory.resolve("sources"), output=directory.resolve("classes"); Files.createDirectories(sources); Files.createDirectories(output); Path source=sources.resolve("Fixture.java"); Files.writeString(source,"import dev.samhb.interleave.bytecode.*;\n"+body,StandardCharsets.UTF_8); var diagnostics=new ByteArrayOutputStream(); int result=ToolProvider.getSystemJavaCompiler().run(null,diagnostics,diagnostics,"--release",Integer.toString(release), - "-g","-classpath",ANNOTATIONS,"-d",output.toString(),source.toString()); + debug ? "-g" : "-g:none","-classpath",ANNOTATIONS,"-d",output.toString(),source.toString()); assertEquals(0,result,diagnostics.toString(StandardCharsets.UTF_8)); return output; } diff --git a/src/test/java/dev/samhb/interleave/bytecode/BytecodeReleaseTest.java b/src/test/java/dev/samhb/interleave/bytecode/BytecodeReleaseTest.java index a908323..68a5d7b 100644 --- a/src/test/java/dev/samhb/interleave/bytecode/BytecodeReleaseTest.java +++ b/src/test/java/dev/samhb/interleave/bytecode/BytecodeReleaseTest.java @@ -28,11 +28,270 @@ class BytecodeReleaseTest { assertEquals(program.limits(),trace.bytecodeEvidence().identity().limits()); assertEquals("Fixture",trace.bytecodeEvidence().identity().modelClass()); assertEquals("BATCHED",trace.bytecodeEvidence().identity().mode()); + assertEquals("FINAL",trace.bytecodeEvidence().identity().checks().getFirst().when()); + assertEquals(dev.samhb.interleave.core.StepOutcome.ADVANCED,trace.outcomes().getFirst()); + assertEquals(dev.samhb.interleave.core.StepOutcome.TERMINATED,trace.outcomes().getLast()); + assertEquals(trace.threadIds().size(),trace.bytecodeEvidence().transitions().size()); assertEquals(trace.threadIds().size()+1,trace.states().size()); assertEquals("CHECK_FALSE",trace.bytecodeEvidence().terminal().kind()); assertEquals("int:1",trace.states().getLast().fields().get("setup:0.Fixture.x:I")); - assertTrue(result.toJson().contains("\"programKind\": \"BYTECODE\"")); + var initial=trace.bytecodeEvidence().snapshots().getFirst();var last=trace.bytecodeEvidence().snapshots().getLast(); + assertEquals("0",initial.fields().get("setup:0.Fixture.x:I").raw()); + assertEquals("REFERENCE",initial.locals().get("0").get("frame0.local0").type()); + assertEquals("setup:0",initial.locals().get("0").get("frame0.local0").raw()); + assertEquals("NULL",initial.locals().get("0").get("frame0.monitor").type()); + assertTrue(last.heap().stream().allMatch(object->object.shared() && object.initialized())); + for(var actor:java.util.List.of("0","1")) { + var local=last.locals().get(actor);assertEquals("TERMINATED",local.get("phase").raw()); + assertEquals("7",local.get("instructions").raw());assertEquals("0",local.get("allocations").raw()); + assertEquals("0",local.get("heapCells").raw());assertEquals("0",local.get("allocationSequence").raw()); + } + + var json=com.google.gson.JsonParser.parseString(result.toJson()).getAsJsonObject(); + assertEquals("BYTECODE",json.get("programKind").getAsString()); + assertEquals("EXACT",json.get("storeType").getAsString());assertEquals("VIOLATION",json.get("verdict").getAsString()); + assertEquals("DFS",json.get("requestedStrategy").getAsString());assertEquals("DFS",json.get("effectiveStrategy").getAsString()); + assertTrue(json.get("fallbackReason").isJsonNull());assertFalse(json.get("limitExceeded").getAsBoolean()); + var identity=json.getAsJsonObject("bytecodeIdentity"); + assertEquals(program.artifactDigest(),identity.get("artifactDigest").getAsString()); + assertEquals("BYTECODE-SC-1",identity.get("profileVersion").getAsString()); + assertEquals("Fixture",identity.get("modelClass").getAsString());assertEquals("BATCHED",identity.get("mode").getAsString()); + assertEquals(256,identity.getAsJsonObject("limits").get("actorInstructions").getAsInt()); + assertEquals(2,identity.getAsJsonArray("actors").size());assertEquals(1,identity.getAsJsonArray("checks").size()); + assertFalse(trace.toJson().contains("\"sourceDigest\"")); + } /** Strict replay validates actual operations/checks and returns immutable matching snapshots. + * @param directory external compiler workspace + * @throws Exception for fixture failures */ + @Test void strictReplayAuthenticatesRealWitnesses(@TempDir Path directory) throws Exception { + var classes=BytecodeFixtures.compile(directory,26,""" + @Model public class Fixture {public int x;public Fixture(){} + @Actor(id=0)public void first(){x++;} @Actor(id=1)public void second(){x++;} + @Check public boolean valid(){return x==2;}} + """); + var program=BytecodeProgramLoader.load(classes,"Fixture");var result=InterleaveRunner.builder().build().runBytecode(program); + for(var trace:java.util.List.of(result.failingTraces().getFirst(),result.completedTraces().getFirst())) { + var replay=new dev.samhb.interleave.search.TraceReplayer().replayBytecode(program,trace); + assertEquals(trace.outcome(),replay.outcome());assertEquals(trace.states(),replay.states()); + assertEquals(trace.bytecodeEvidence().snapshots(),replay.bytecodeEvidence().snapshots()); + assertEquals(trace.bytecodeEvidence().terminal(),replay.bytecodeEvidence().terminal()); + assertEquals(trace.bytecodeEvidence().terminal(),replay.bytecodeEvidence().replayObservation()); + } + } + + /** Reports retain artifact identity and replay real deadlock witnesses without legacy callbacks. + * @param directory external compiler workspace + * @throws Exception for fixture failures */ + @Test void bytecodeReportsRetainPrecisionAndLocations(@TempDir Path directory) throws Exception { + var classes=BytecodeFixtures.compile(directory,26,""" + @Model public class Fixture {public Object a=new Object(),b=new Object();public Fixture(){} + @Actor(id=0)public void first(){synchronized(a){synchronized(b){}}} + @Actor(id=1)public void second(){synchronized(b){synchronized(a){}}}} + """); + var program=BytecodeProgramLoader.load(classes,"Fixture"); + var rows=new dev.samhb.interleave.report.BenchmarkHarness().runBytecode(program); + assertEquals(1,rows.size());assertEquals("VIOLATION",rows.getFirst().verdict()); + assertThrows(IllegalArgumentException.class,()->rows.getFirst().withExploration(null, + new dev.samhb.interleave.search.DfsResult(java.util.Map.of(),java.util.List.of(),0))); + var writer=new dev.samhb.interleave.report.ReportWriter(rows); + var json=com.google.gson.JsonParser.parseString(writer.writeJson()).getAsJsonObject(); + assertTrue(json.get("soundness").getAsBoolean()); + var row=json.getAsJsonArray("benchmarks").get(0).getAsJsonObject(); + assertEquals("BYTECODE",row.get("programKind").getAsString()); + assertEquals("EXACT",row.get("storeType").getAsString()); + var trace=dev.samhb.interleave.TraceRecord.fromJson(row.get("failingTrace").toString()); + assertEquals("DEADLOCK",trace.bytecodeEvidence().terminal().kind()); + assertEquals(2,trace.bytecodeEvidence().terminal().waits().size()); + var waits=trace.bytecodeEvidence().terminal().waits(); + assertTrue(waits.stream().anyMatch(w->w.actor()==0 && w.owner()==1 && w.monitor().equals("setup:2") && w.depth()==1)); + assertTrue(waits.stream().anyMatch(w->w.actor()==1 && w.owner()==0 && w.monitor().equals("setup:1") && w.depth()==1)); + var heap=trace.bytecodeEvidence().snapshots().getLast().heap(); + assertTrue(heap.stream().anyMatch(object->object.identity().equals("setup:1") && object.type().equals("java/lang/Object") && object.owner()==0 && object.depth()==1)); + assertTrue(heap.stream().anyMatch(object->object.identity().equals("setup:2") && object.owner()==1 && object.depth()==1)); + + assertEquals(trace.states(),new dev.samhb.interleave.search.TraceReplayer().replayBytecode(program,trace).states()); + assertTrue(writer.writeMarkdown().contains(program.artifactDigest())); + } + /** Actual CLI selects BYTECODE explicitly and refuses incompatible modes before loading. + * @param directory external compiler workspace + * @throws Exception for fixture/process failures */ + @Test void bytecodeCliRejectsUnsupportedSelections(@TempDir Path directory) throws Exception { + var classes=BytecodeFixtures.compile(directory,17,""" + @Model public class Fixture {public int x;public Fixture(){} + @Actor(id=0)public void actor(){x=1;} @Check public boolean valid(){return x==0;}} + """); + var good=cli(directory,"--bytecode","Fixture","--class-path",classes.toString(),"--json","--strategy","DFS","--store","exact"); + assertEquals(0,good.getKey(),good.getValue()); + var report=com.google.gson.JsonParser.parseString(good.getValue()).getAsJsonObject(); + assertEquals("BYTECODE",report.getAsJsonArray("benchmarks").get(0).getAsJsonObject().get("programKind").getAsString()); + for(var extra:java.util.List.of(new String[]{"--strategy","DPOR"},new String[]{"--store","bitstate"}, + new String[]{"--symmetry"},new String[]{"--simplify-cutoff"},new String[]{"--all"}, + new String[]{"--bytecode","Other"},new String[]{"--max-preemptions","0"})) { + var args=new java.util.ArrayList(java.util.List.of("--bytecode","Fixture","--class-path","missing")); + args.addAll(java.util.List.of(extra));var bad=cli(directory,args.toArray(String[]::new)); + assertEquals(1,bad.getKey(),bad.getValue());assertTrue(bad.getValue().contains("BYTECODE"),bad.getValue()); + } + assertEquals(1,cli(directory,"--bytecode","Fixture").getKey()); + assertEquals(1,cli(directory,"--class-path",classes.toString()).getKey()); + } + + /** Runs the public CLI in a separate JVM with bounded time and file-backed output. + * @param directory process workspace + * @param arguments CLI flags + * @return status and merged output + * @throws Exception for process/filesystem failures */ + private static java.util.Map.Entry cli(Path directory,String... arguments) throws Exception { + var command=new java.util.ArrayList(java.util.List.of(Path.of(System.getProperty("java.home"),"bin","java").toString(), + "-cp",BytecodeFixtures.classpath(dev.samhb.interleave.cli.Main.class,com.google.gson.Gson.class),"dev.samhb.interleave.cli.Main")); + command.addAll(java.util.List.of(arguments));var output=java.nio.file.Files.createTempFile(directory,"cli-",".log"); + var process=new ProcessBuilder(command).redirectErrorStream(true).redirectOutput(output.toFile()).start(); + try {assertTrue(process.waitFor(15,java.util.concurrent.TimeUnit.SECONDS));return java.util.Map.entry(process.exitValue(),java.nio.file.Files.readString(output));} + finally {if(process.isAlive())process.destroyForcibly();} + } + /** Produces fresh Java artifacts consumed by normalization and real browser CI. + * @param directory compiler workspace + * @throws Exception for fixture failures */ + @Test void bytecodeViewerUsesFreshProducerArtifacts(@TempDir Path directory) throws Exception { + var cases=java.util.Map.of( + "lost-update", "public int x;@Actor(id=0)public void a(){x++;}@Actor(id=1)public void b(){x++;}@Check public boolean ok(){return x==2;}", + "deadlock", "public Object a=new Object(),b=new Object();@Actor(id=0)public void a(){synchronized(a){synchronized(b){}}}@Actor(id=1)public void b(){synchronized(b){synchronized(a){}}}", + "fault", "public int x,z;@Actor(id=0)public void a(){x=7;x=1/z;}", + "root", "@Actor(id=0)public void a(){}@Check(when=Check.When.ALWAYS)public boolean ok(){return false;}", + "cutoff", "@Actor(id=0)public void a(){while(true){}}", + "observer", "public int z;@Actor(id=0)public void a(){}@Check(when=Check.When.ALWAYS)public boolean ok(){return 1/z==0;}", + "no-line", "public int x;@Actor(id=0)public void a(){x=1;}", + "long-label", "public int "+"x".repeat(600)+";@Actor(id=0)public void a(){"+"x".repeat(600)+"=1;}"); + java.nio.file.Files.createDirectories(Path.of("build")); + for(var entry:cases.entrySet()) { + var classes=BytecodeFixtures.compile(directory.resolve(entry.getKey()),17, + "@Model public class Fixture {public Fixture(){}"+entry.getValue()+"}",!entry.getKey().equals("no-line")); + var program=BytecodeProgramLoader.load(classes,"Fixture");var run=InterleaveRunner.builder().build().runBytecode(program); + java.nio.file.Files.writeString(Path.of("build/bytecode-"+entry.getKey()+".json"),run.toJson()); + if(entry.getKey().equals("lost-update")) { + java.nio.file.Files.writeString(Path.of("build/bytecode-report.json"),new dev.samhb.interleave.report.ReportWriter(new dev.samhb.interleave.report.BenchmarkHarness().runBytecode(program)).writeJson()); + java.nio.file.Files.writeString(Path.of("build/bytecode-interrupted.json"),InterleaveRunner.builder().maxStates(1).build().runBytecode(program).toJson()); + java.nio.file.Files.writeString(Path.of("build/bytecode-cli.json"),cli(directory,"--bytecode","Fixture","--class-path",classes.toString(),"--json").getValue()); + } + if(entry.getKey().equals("no-line"))assertTrue(run.completedTraces().getFirst().bytecodeEvidence().transitions().stream().flatMap(t->t.operations().stream()).allMatch(op->op.line()==null)); + } + } + /** An independently compiled consumer uses only the built jar's public library interfaces. + * @param directory independent compiler/process workspace + * @throws Exception for fixture/process failures */ + @Test void publicBytecodeLoaderAndRunnerWorkFromJar(@TempDir Path directory) throws Exception { + var jar=Path.of(java.util.Objects.requireNonNull(System.getProperty("interleave.releaseJar"),"Gradle must supply the current library jar")); + assertTrue(java.nio.file.Files.isRegularFile(jar));assertFalse(jar.toString().endsWith("-mutation-harness.jar")); + var classes=directory.resolve("classes");java.nio.file.Files.createDirectories(classes); + var compiler=javax.tools.ToolProvider.getSystemJavaCompiler(); + assertEquals(0,compiler.run(null,null,null,"--release","17","-g","-cp",jar.toString(),"-d",classes.toString(), + "examples/bytecode/LostUpdate.java","examples/bytecode/TwoLockDeadlock.java")); + for(var name:java.util.List.of("LostUpdate","TwoLockDeadlock")) { + var cliOutput=directory.resolve(name+"-cli.json"); + var cliProcess=new ProcessBuilder(Path.of(System.getProperty("java.home"),"bin","java").toString(),"-cp", + jar+java.io.File.pathSeparator+BytecodeFixtures.classpath(com.google.gson.Gson.class),"dev.samhb.interleave.cli.Main", + "--bytecode","examples.bytecode."+name,"--class-path",classes.toString(),"--store","exact","--strategy","DFS","--json") + .redirectErrorStream(true).redirectOutput(cliOutput.toFile()).start(); + try { + assertTrue(cliProcess.waitFor(15,java.util.concurrent.TimeUnit.SECONDS));var text=java.nio.file.Files.readString(cliOutput); + assertEquals(0,cliProcess.exitValue(),text);var report=com.google.gson.JsonParser.parseString(text).getAsJsonObject(); + assertTrue(report.get("soundness").getAsBoolean()); + var row=report.getAsJsonArray("benchmarks").get(0).getAsJsonObject();assertEquals("VIOLATION",row.get("verdict").getAsString()); + assertEquals(name.equals("LostUpdate")?"CHECK_FALSE":"DEADLOCK",row.getAsJsonObject("failingTrace").getAsJsonObject("bytecodeEvidence").getAsJsonObject("terminal").get("kind").getAsString()); + } finally {if(cliProcess.isAlive())cliProcess.destroyForcibly();} + } + var source=directory.resolve("Consumer.java"); + java.nio.file.Files.writeString(source,""" + import dev.samhb.interleave.*; + import dev.samhb.interleave.format.BytecodeProgramLoader; + import dev.samhb.interleave.search.TraceReplayer; + import java.nio.file.Path; + public class Consumer {public static void main(String[] args)throws Exception { + var runner=InterleaveRunner.builder().build();var replay=new TraceReplayer(); + for(String name:new String[]{"LostUpdate","TwoLockDeadlock"}) { + var program=BytecodeProgramLoader.load(Path.of(args[0]),"examples.bytecode."+name); + var result=runner.runBytecode(program); + var traces=name.equals("LostUpdate")?result.failingTraces():result.deadlockedTraces(); + if(traces.isEmpty() || result.hasIncomplete())throw new AssertionError(name); + var record=TraceRecord.fromJson(traces.getFirst().toJson()); + if(!replay.replayBytecode(program,record).states().equals(record.states()))throw new AssertionError("replay"); + var bytes=new java.io.ByteArrayOutputStream(); + try(var out=new java.io.ObjectOutputStream(bytes)){out.writeObject(result);} + try(var in=new java.io.ObjectInputStream(new java.io.ByteArrayInputStream(bytes.toByteArray()))) { + if(!((TestResult)in.readObject()).bytecodeIdentity().equals(result.bytecodeIdentity()))throw new AssertionError("native"); + } + System.out.println(name+":"+record.bytecodeEvidence().terminal().kind()); + } + }} + """); + var consumer=directory.resolve("consumer");java.nio.file.Files.createDirectories(consumer); + assertEquals(0,compiler.run(null,null,null,"-cp",jar.toString(),"-d",consumer.toString(),source.toString())); + var output=directory.resolve("consumer.log"); + var process=new ProcessBuilder(Path.of(System.getProperty("java.home"),"bin","java").toString(),"-cp", + consumer+java.io.File.pathSeparator+jar+java.io.File.pathSeparator+BytecodeFixtures.classpath(com.google.gson.Gson.class), + "Consumer",classes.toString()).redirectErrorStream(true).redirectOutput(output.toFile()).start(); + try { + assertTrue(process.waitFor(15,java.util.concurrent.TimeUnit.SECONDS));var text=java.nio.file.Files.readString(output); + assertEquals(0,process.exitValue(),text);assertEquals(java.util.List.of("LostUpdate:CHECK_FALSE","TwoLockDeadlock:DEADLOCK"),text.lines().toList()); + } finally {if(process.isAlive())process.destroyForcibly();} + } + /** Unsupported routes reject without invoking caller callbacks or changing legacy settings. + * @param directory compiler workspace + * @throws Exception for fixture failures */ + @Test void bytecodeRunnerRejectsForeignCallbacksAndStrategies(@TempDir Path directory) throws Exception { + var program=BytecodeProgramLoader.load(BytecodeFixtures.compile(directory,17, + "@Model public class Fixture {public Fixture(){}@Actor(id=0)public void a(){}}"),"Fixture"); + for(var strategy:dev.samhb.interleave.Strategy.values())if(strategy!=dev.samhb.interleave.Strategy.DFS) + assertThrows(IllegalArgumentException.class,()->InterleaveRunner.builder().strategy(strategy).build().runBytecode(program)); + assertThrows(IllegalArgumentException.class,()->InterleaveRunner.builder().invariant((state,config)->{throw new AssertionError("foreign property invoked");}).build().runBytecode(program)); + assertThrows(IllegalArgumentException.class,()->InterleaveRunner.builder().stateStoreFactory(()->{throw new AssertionError("foreign store invoked");}).build().runBytecode(program)); + assertThrows(IllegalArgumentException.class,()->InterleaveRunner.builder().symmetryReduction(true).build().runBytecode(program)); + assertThrows(IllegalArgumentException.class,()->new dev.samhb.interleave.report.BenchmarkHarness(100,1,java.util.Set.of(dev.samhb.interleave.report.StoreType.BITSTATE),null).runBytecode(program)); + var timed=InterleaveRunner.builder().maxTime(java.time.Duration.ZERO).build().runBytecode(program); + assertTrue(timed.limitExceeded());assertTrue(timed.hasIncomplete()); + assertEquals(dev.samhb.interleave.core.ResourceLimitReason.MAX_TIME,timed.resourceLimitReason()); + assertThrows(IllegalArgumentException.class,()->BytecodeRuntime.run(program,-1,null)); + + assertEquals("MAX_TIME",timed.incompleteTraces().getFirst().bytecodeEvidence().terminal().interruption()); + assertEquals("INCOMPLETE",com.google.gson.JsonParser.parseString(timed.toJson()).getAsJsonObject().get("verdict").getAsString()); + } + /** Real compiler line tables identify distinct writes by method, descriptor and BCI. + * @param directory compiler workspace + * @throws Exception for fixture failures */ + @Test void bytecodeLocationsUseActualCompilerLines(@TempDir Path directory) throws Exception { + var classes=BytecodeFixtures.compile(directory,17,""" + @Model public class Fixture {public int x;public Fixture(){} + @Actor(id=0)public void a(){ + x=1; + x=2; + } + } + """); + var program=BytecodeProgramLoader.load(classes,"Fixture"); + var trace=InterleaveRunner.builder().build().runBytecode(program).completedTraces().getFirst(); + var writes=trace.bytecodeEvidence().transitions().stream().flatMap(t->t.operations().stream()).filter(op->"PUTFIELD".equals(op.opcode())).toList(); + assertEquals(2,writes.size());assertEquals(java.util.List.of(2,7),writes.stream().map(op->op.location().bci()).toList()); + assertEquals(java.util.List.of(4,5),writes.stream().map(op->op.line()).toList()); + assertTrue(writes.stream().allMatch(op->op.location().owner().equals("Fixture") && op.location().name().equals("a") && op.location().descriptor().equals("()V"))); + assertNull(trace.evidence());assertFalse(trace.toJson().contains("sourceDigest")); + } + /** Reporting preserves valid class-file UTF-16 field names through UTF-8 files and strict replay. + * @param directory compiler and file workspace + * @throws Exception for fixture failures */ + @Test void bytecodeReportsPreserveIsolatedUtf16Names(@TempDir Path directory) throws Exception { + var classes=BytecodeFixtures.compile(directory,17,"@Model public class Fixture {public int field;public Fixture(){}@Actor(id=0)public void a(){}}"); + var file=classes.resolve("Fixture.class");var parser=java.lang.classfile.ClassFile.of();String name="field"+(char)0xd800; + var bytes=parser.transformClass(parser.parse(java.nio.file.Files.readAllBytes(file)),(builder,element)->{ + if(element instanceof java.lang.classfile.FieldModel field && field.fieldName().equalsString("field")) + builder.withField(name,java.lang.constant.ConstantDescs.CD_int,java.lang.classfile.ClassFile.ACC_PUBLIC); + else builder.with(element); + }); + java.nio.file.Files.write(file,bytes);var program=BytecodeProgramLoader.load(classes,"Fixture"); + var writer=new dev.samhb.interleave.report.ReportWriter(new dev.samhb.interleave.report.BenchmarkHarness().runBytecode(program)); + var reportFile=directory.resolve("report.json");java.nio.file.Files.write(reportFile,writer.writeJson().getBytes(java.nio.charset.StandardCharsets.UTF_8)); + var row=com.google.gson.JsonParser.parseString(java.nio.file.Files.readString(reportFile)).getAsJsonObject().getAsJsonArray("benchmarks").get(0).getAsJsonObject(); + var trace=dev.samhb.interleave.TraceRecord.fromJson(row.getAsJsonArray("completedTraces").get(0).toString()); + assertTrue(trace.states().getFirst().fields().containsKey("setup:0.Fixture."+name+":I")); + assertEquals(trace.states(),new dev.samhb.interleave.search.TraceReplayer().replayBytecode(program,trace).states()); } } diff --git a/src/test/java/dev/samhb/interleave/bytecode/BytecodeReplayTest.java b/src/test/java/dev/samhb/interleave/bytecode/BytecodeReplayTest.java new file mode 100644 index 0000000..c2935a4 --- /dev/null +++ b/src/test/java/dev/samhb/interleave/bytecode/BytecodeReplayTest.java @@ -0,0 +1,260 @@ +/** Strict public replay adversaries and abnormal-prefix evidence for the bounded bytecode profile. */ +package dev.samhb.interleave.bytecode; + +import dev.samhb.interleave.*; +import dev.samhb.interleave.format.BytecodeProgramLoader; +import dev.samhb.interleave.search.TraceReplayer; +import dev.samhb.interleave.search.CorruptedTraceException; +import dev.samhb.interleave.core.IllegalScheduleException; +import java.nio.file.Path; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import static org.junit.jupiter.api.Assertions.*; + +class BytecodeReplayTest { + /** Fuel exhaustion during compiler cleanup is incomplete while retaining the original pending fault. + * @param directory external compiler workspace + * @throws Exception for fixture failures */ + @Test void cleanupFuelCutoffRetainsFaultAndHeldMonitor(@TempDir Path directory) throws Exception { + var classes=BytecodeFixtures.compile(directory,26,""" + @Model public class Fixture {public int x;public int zero;public Object lock=new Object();public Fixture(){} + @Actor(id=0)public void actor(){synchronized(lock){x=1/zero;}}} + """); + var limits=new BytecodeLimits(11,128,8192,32,64,256,4096,128,8192,1024); + var program=BytecodeProgramLoader.load(classes,"Fixture",limits);var result=InterleaveRunner.builder().build().runBytecode(program); + assertFalse(result.hasViolation());assertTrue(result.hasIncomplete());assertFalse(result.limitExceeded()); + var trace=result.incompleteTraces().getFirst();var terminal=trace.bytecodeEvidence().terminal(); + assertEquals("CUTOFF",terminal.kind());assertEquals(11,terminal.cutoff().limit()); + assertNotNull(terminal.fault());assertEquals("java/lang/ArithmeticException",terminal.fault().type()); + assertTrue(trace.bytecodeEvidence().snapshots().getLast().heap().stream().anyMatch(object->object.owner()==0 && object.depth()==1)); + var replay=new TraceReplayer().replayBytecode(program,trace);assertEquals(terminal,replay.bytecodeEvidence().replayObservation()); + } /** JSON returns typed immutable BYTECODE evidence that passes the same strict replayer. + * @param directory external compiler workspace + * @throws Exception for fixture failures */ + @Test void bytecodeJsonRoundTripsStrictReplay(@TempDir Path directory) throws Exception { + var classes=BytecodeFixtures.compile(directory,26,""" + @Model public class Fixture {public int x;public Fixture(){} + @Actor(id=0)public void actor(){x=7;int zero=0;x=1/zero;}} + """); + var program=BytecodeProgramLoader.load(classes,"Fixture");var result=InterleaveRunner.builder().build().runBytecode(program); + var trace=result.failingTraces().getFirst();var decoded=TraceRecord.fromJson(trace.toJson()); + assertEquals(trace.bytecodeEvidence(),decoded.bytecodeEvidence());assertEquals(trace.states(),decoded.states()); + assertEquals("int:7",decoded.states().getLast().fields().get("setup:0.Fixture.x:I")); + assertEquals("UNCAUGHT_EXCEPTION",decoded.bytecodeEvidence().terminal().kind()); + assertEquals(dev.samhb.interleave.core.StepOutcome.ASSERTION_FAILED,decoded.outcomes().getLast()); + + var replay=new TraceReplayer().replayBytecode(program,decoded);assertEquals(trace.states(),replay.states()); + } + + /** Root checks and global stops replay their actual prefix without inventing completion. + * @param directory compiler workspace + * @throws Exception for fixture failures */ + @Test void rootFailuresAndExternalStopsRetainOriginalMeaning(@TempDir Path directory) throws Exception { + var classes=BytecodeFixtures.compile(directory,26,""" + @Model public class Fixture {public int x;public Fixture(){} + @Actor(id=0)public void actor(){x=1;} + @Check(when=Check.When.ALWAYS)public boolean valid(){return x<0;}} + """); + var program=BytecodeProgramLoader.load(classes,"Fixture"); + var root=InterleaveRunner.builder().build().runBytecode(program).failingTraces().getFirst(); + assertTrue(root.threadIds().isEmpty());assertEquals("ALWAYS",root.bytecodeEvidence().identity().checks().getFirst().when()); + + assertEquals("CHECK_FALSE",new TraceReplayer().replayBytecode(program,TraceRecord.fromJson(root.toJson())).bytecodeEvidence().terminal().kind()); + var classes2=BytecodeFixtures.compile(directory.resolve("normal"),26,""" + @Model public class Fixture {public int x;public Fixture(){} @Actor(id=0)public void actor(){x=1;}} + """); + var normal=BytecodeProgramLoader.load(classes2,"Fixture"); + var stopped=InterleaveRunner.builder().maxStates(1).build().runBytecode(normal); + assertTrue(stopped.limitExceeded());assertTrue(stopped.hasIncomplete()); + var prefix=stopped.incompleteTraces().getFirst(); + var replay=new TraceReplayer().replayBytecode(normal,TraceRecord.fromJson(prefix.toJson())); + assertEquals(dev.samhb.interleave.search.TraceOutcome.INCOMPLETE,replay.outcome()); + assertEquals("INTERRUPTED",replay.bytecodeEvidence().terminal().kind()); + assertNotNull(replay.bytecodeEvidence().replayObservation()); + assertEquals(dev.samhb.interleave.core.ResourceLimitReason.MAX_STATES,stopped.resourceLimitReason()); + var upgraded=new TraceRecord(prefix.threadIds(),prefix.outcomes(),dev.samhb.interleave.search.TraceOutcome.COMPLETED, + prefix.programHash(),prefix.states(),null,prefix.bytecodeEvidence()); + assertThrows(dev.samhb.interleave.search.CorruptedTraceException.class,()->new TraceReplayer().replayBytecode(normal,upgraded)); + var d=prefix.bytecodeEvidence(); + var forgedObservation=new dev.samhb.interleave.core.BytecodeEvidence(1,d.identity(),d.transitions(),d.snapshots(),d.terminal(), + new dev.samhb.interleave.core.BytecodeEvidence.Terminal("COMPLETED",-1,null,null,null,java.util.List.of(),null)); + var changed=new TraceRecord(prefix.threadIds(),prefix.outcomes(),prefix.outcome(),prefix.programHash(),prefix.states(),null,forgedObservation); + assertThrows(dev.samhb.interleave.search.CorruptedTraceException.class,()->new TraceReplayer().replayBytecode(normal,changed)); + assertEquals(replay.bytecodeEvidence(),new TraceReplayer().replayBytecode(normal,replay).bytecodeEvidence()); + + assertThrows(dev.samhb.interleave.search.CorruptedTraceException.class,()->new TraceReplayer().replayBytecode(normal,root)); + Thread.currentThread().interrupt(); + try { + var cancelled=InterleaveRunner.builder().build().runBytecode(normal); + assertTrue(Thread.currentThread().isInterrupted());assertTrue(cancelled.hasIncomplete()); + assertEquals("CANCELLED",cancelled.incompleteTraces().getFirst().bytecodeEvidence().terminal().interruption()); + assertThrows(java.util.concurrent.CancellationException.class,()->new TraceReplayer().replayBytecode(normal,prefix)); + } finally {Thread.interrupted();} + } + + /** Mutating authenticated operations, identity or terminal/snapshot data cannot replay. + * @param directory compiler workspace + * @throws Exception for fixture failures */ + @Test void tamperedEvidenceAndMalformedJsonReject(@TempDir Path directory) throws Exception { + var classes=BytecodeFixtures.compile(directory,26,""" + @Model public class Fixture {public int x;public Fixture(){} @Actor(id=0)public void actor(){x=1;}} + """); + var program=BytecodeProgramLoader.load(classes,"Fixture"); + var trace=InterleaveRunner.builder().build().runBytecode(program).completedTraces().getFirst(); + var original=com.google.gson.JsonParser.parseString(trace.toJson()).getAsJsonObject(); + var foreign=new java.util.ArrayList<>(trace.threadIds());foreign.set(0,-1); + var badChoice=new TraceRecord(foreign,trace.outcomes(),trace.outcome(),trace.programHash(),trace.states(),null,trace.bytecodeEvidence()); + assertThrows(dev.samhb.interleave.core.IllegalScheduleException.class,()->new TraceReplayer().replayBytecode(program,badChoice)); + assertThrows(dev.samhb.interleave.search.CorruptedTraceException.class,()->new TraceReplayer().replayBytecode(program, + new TraceRecord(java.util.List.of(),java.util.List.of(),dev.samhb.interleave.search.TraceOutcome.COMPLETED,null))); + + java.util.List mutations=java.util.List.of( + new Forgery(CorruptedTraceException.class,j->j.getAsJsonObject("bytecodeEvidence").getAsJsonObject("identity").addProperty("modelClass","Other")), + new Forgery(IllegalArgumentException.class,j->j.getAsJsonObject("bytecodeEvidence").getAsJsonObject("identity").addProperty("artifactDigest","0".repeat(64))), + new Forgery(CorruptedTraceException.class,j->j.getAsJsonObject("bytecodeEvidence").getAsJsonObject("identity").getAsJsonObject("limits").addProperty("actorInstructions",257)), + new Forgery(CorruptedTraceException.class,j->j.getAsJsonObject("bytecodeEvidence").getAsJsonObject("identity").addProperty("mode","REFERENCE")), + new Forgery(CorruptedTraceException.class,j->j.getAsJsonObject("bytecodeEvidence").getAsJsonArray("transitions").get(0).getAsJsonObject().addProperty("actor",1)), + new Forgery(IllegalScheduleException.class,j->j.getAsJsonArray("threads").set(0,new com.google.gson.JsonPrimitive(1))), + new Forgery(CorruptedTraceException.class,j->j.getAsJsonArray("outcomes").set(0,new com.google.gson.JsonPrimitive("TERMINATED"))), + new Forgery(CorruptedTraceException.class,j->j.getAsJsonObject("bytecodeEvidence").getAsJsonArray("snapshots").get(0).getAsJsonObject().addProperty("stateDigest","0".repeat(64))), + new Forgery(CorruptedTraceException.class,j->j.getAsJsonObject("bytecodeEvidence").getAsJsonArray("transitions").get(0).getAsJsonObject().getAsJsonArray("operations").get(0).getAsJsonObject().getAsJsonObject("location").addProperty("bci",999)), + new Forgery(CorruptedTraceException.class,j->j.addProperty("outcome","INCOMPLETE")), + new Forgery(IllegalArgumentException.class,j->j.addProperty("sourceDigest","0".repeat(64))), + new Forgery(IllegalArgumentException.class,j->j.getAsJsonObject("bytecodeEvidence").getAsJsonObject("terminal").addProperty("kind","PREFIX"))); + for(var forgery:mutations) { + var changed=original.deepCopy();forgery.mutation().accept(changed); + if(forgery.failure()==IllegalArgumentException.class) { + assertThrows(IllegalArgumentException.class,()->TraceRecord.fromJson(changed.toString()),changed::toString); + } else { + var decoded=TraceRecord.fromJson(changed.toString()); + assertThrows(forgery.failure(),()->new TraceReplayer().replayBytecode(program,decoded),changed::toString); + } + } + assertThrows(IllegalArgumentException.class,()->TraceRecord.fromJson(trace.toJson().replaceFirst("\\{","{\"threads\":[],"))); + assertThrows(IllegalArgumentException.class,()->TraceRecord.fromJson("[".repeat(70)+"0"+"]".repeat(70))); + assertThrows(IllegalArgumentException.class,()->TraceRecord.fromJson("[".repeat(10000)+"0"+"]".repeat(10000))); + assertThrows(IllegalArgumentException.class,()->TraceRecord.fromJson(trace.toJson()+"{}")); + assertThrows(IllegalArgumentException.class,()->TraceRecord.fromJson(trace.toJson().replace("\"Fixture\"","\"Fix"+(char)10+"ture\""))); + + assertThrows(IllegalArgumentException.class,()->TraceRecord.fromJson(trace.toJson().replace("\"INT\"","\"UNKNOWN\""))); + } + /** Reserved wide tags and isolated UTF-16 code units survive transport without numeric coercion. + * This checks the wire format, not admission of later-phase primitive execution. + * @param directory compiler workspace + * @throws Exception for fixture failures */ + @Test void wireTypesAreLosslessAndDeeplyImmutable(@TempDir Path directory) throws Exception { + var classes=BytecodeFixtures.compile(directory,17,"@Model public class Fixture {public Fixture(){}@Actor(id=0)public void a(){}}"); + var program=BytecodeProgramLoader.load(classes,"Fixture");var original=InterleaveRunner.builder().build().runBytecode(program).completedTraces().getFirst(); + var data=original.bytecodeEvidence();var snapshots=new java.util.ArrayList<>(data.snapshots());var first=snapshots.getFirst(); + var fields=new java.util.HashMap<>(first.fields()); + fields.put("wide",new dev.samhb.interleave.core.BytecodeEvidence.Value("LONG","9223372036854775807")); + fields.put("float",new dev.samhb.interleave.core.BytecodeEvidence.Value("FLOAT_BITS","80000000")); + fields.put("double",new dev.samhb.interleave.core.BytecodeEvidence.Value("DOUBLE_BITS","7ff8000000000001")); + String isolated="unicode:"+(char)0xd800+":"+(char)0xdc00; + fields.put("text",new dev.samhb.interleave.core.BytecodeEvidence.Value("TEXT",isolated)); + snapshots.set(0,new dev.samhb.interleave.core.BytecodeEvidence.Snapshot(first.stateDigest(),fields,first.locals(),first.heap())); + var payload=new dev.samhb.interleave.core.BytecodeEvidence(1,data.identity(),data.transitions(),snapshots,data.terminal(),null); + var record=new TraceRecord(original.threadIds(),original.outcomes(),original.outcome(),original.programHash(),snapshots.stream().map(BytecodeSnapshots::display).toList(),null,payload); + var bytes=record.toJson().getBytes(java.nio.charset.StandardCharsets.UTF_8); + var decoded=TraceRecord.fromJson(new String(bytes,java.nio.charset.StandardCharsets.UTF_8)); + assertEquals(payload,decoded.bytecodeEvidence());assertEquals(isolated,decoded.bytecodeEvidence().snapshots().getFirst().fields().get("text").raw()); + assertThrows(UnsupportedOperationException.class,()->decoded.bytecodeEvidence().snapshots().getFirst().fields().clear()); + assertThrows(UnsupportedOperationException.class,()->decoded.states().getFirst().fields().clear()); + assertThrows(UnsupportedOperationException.class,()->decoded.bytecodeEvidence().snapshots().getFirst().locals().clear()); + assertThrows(UnsupportedOperationException.class,()->decoded.bytecodeEvidence().snapshots().getFirst().locals().get("0").clear()); + assertThrows(UnsupportedOperationException.class,()->decoded.states().getFirst().locals().get("0").clear()); + assertThrows(IllegalArgumentException.class,()->TraceRecord.fromJson(record.toJson().replace("\"9223372036854775807\"","9223372036854775807"))); + // Transporting an edited snapshot never authenticates it as actual target execution. + assertThrows(dev.samhb.interleave.search.CorruptedTraceException.class,()->new TraceReplayer().replayBytecode(program,decoded)); + } + /** Location-independent frozen bytes replay; changed debug bytes and selected models reject. + * @param directory compiler workspace + * @throws Exception for fixture/filesystem failures */ + @Test void replayUsesFrozenArtifactAndSelectedModel(@TempDir Path directory) throws Exception { + String source="@Model public class Fixture {public int x;public Fixture(){}@Actor(id=0)public void a(){x=1;}}"; + var classes=BytecodeFixtures.compile(directory.resolve("debug"),17,source); + var original=BytecodeProgramLoader.load(classes,"Fixture");var trace=InterleaveRunner.builder().build().runBytecode(original).completedTraces().getFirst(); + var copy=directory.resolve("copy");java.nio.file.Files.createDirectories(copy); + try(var files=java.nio.file.Files.list(classes)){for(var file:files.toList())java.nio.file.Files.copy(file,copy.resolve(file.getFileName()));} + var moved=BytecodeProgramLoader.load(copy,"Fixture");assertEquals(original.artifactDigest(),moved.artifactDigest()); + assertEquals(trace.states(),new TraceReplayer().replayBytecode(moved,trace).states()); + var noDebug=BytecodeProgramLoader.load(BytecodeFixtures.compile(directory.resolve("no-debug"),17,source,false),"Fixture"); + assertNotEquals(original.artifactDigest(),noDebug.artifactDigest()); + assertThrows(dev.samhb.interleave.search.CorruptedTraceException.class,()->new TraceReplayer().replayBytecode(noDebug,trace)); + java.nio.file.Files.delete(copy.resolve("Fixture.class")); + assertEquals(trace.states(),new TraceReplayer().replayBytecode(moved,trace).states()); + var changed=BytecodeProgramLoader.load(classes,"Fixture",new BytecodeLimits(257,128,8192,32,64,256,4096,128,8192,1024)); + assertThrows(dev.samhb.interleave.search.CorruptedTraceException.class,()->new TraceReplayer().replayBytecode(changed,trace)); + } + /** A matching digest cannot substitute another claimed model, even with no actor choices. + * The initial loader rejects a reachable second annotated model; this attacks the imported + * identity directly while retaining the exact original artifact digest. + * @param directory compiler workspace + * @throws Exception for fixture failures */ + @Test void sameArtifactDigestDoesNotAuthenticateForeignRootModel(@TempDir Path directory) throws Exception { + var classes=BytecodeFixtures.compile(directory,17,""" + @Model public class Fixture {public Fixture(){} + @Actor(id=0)public void a(){}@Check(when=Check.When.ALWAYS)public boolean ok(){return false;}} + """); + var first=BytecodeProgramLoader.load(classes,"Fixture"); + for(var runner:java.util.List.of(InterleaveRunner.builder().build(),InterleaveRunner.builder().maxTime(java.time.Duration.ZERO).build())) { + var result=runner.runBytecode(first);var root=result.hasViolation()?result.failingTraces().getFirst():result.incompleteTraces().getFirst(); + assertTrue(root.threadIds().isEmpty()); + var forged=com.google.gson.JsonParser.parseString(root.toJson()).getAsJsonObject(); + forged.getAsJsonObject("bytecodeEvidence").getAsJsonObject("identity").addProperty("modelClass","Other"); + var record=TraceRecord.fromJson(forged.toString()); + assertEquals(first.artifactDigest(),record.bytecodeEvidence().identity().artifactDigest()); + assertThrows(dev.samhb.interleave.search.CorruptedTraceException.class,()->new TraceReplayer().replayBytecode(first,record)); + } + } + + /** Empty invented terminal events and extra choices cannot masquerade as completed executions. + * @param directory compiler workspace + * @throws Exception for fixture failures */ + @Test void fabricatedEmptyTerminalsAndTrailingChoicesReject(@TempDir Path directory) throws Exception { + var program=BytecodeProgramLoader.load(BytecodeFixtures.compile(directory,17, + "@Model public class Fixture {public Fixture(){}@Actor(id=0)public void a(){}}"),"Fixture"); + var trace=InterleaveRunner.builder().build().runBytecode(program).completedTraces().getFirst();var data=trace.bytecodeEvidence(); + for(var terminal:java.util.List.of(data.terminal(),new dev.samhb.interleave.core.BytecodeEvidence.Terminal("DEADLOCK",-1,null,null,null, + java.util.List.of(new dev.samhb.interleave.core.BytecodeEvidence.Wait(0,0,"setup:0",1)),null))) { + var fake=new dev.samhb.interleave.core.BytecodeEvidence(1,data.identity(),java.util.List.of(),java.util.List.of(data.snapshots().getFirst()),terminal,null); + var record=new TraceRecord(java.util.List.of(),java.util.List.of(),terminal.kind().equals("DEADLOCK")?dev.samhb.interleave.search.TraceOutcome.DEADLOCK:trace.outcome(),trace.programHash(),java.util.List.of(trace.states().getFirst()),null,fake); + assertThrows(dev.samhb.interleave.search.CorruptedTraceException.class,()->new TraceReplayer().replayBytecode(program,record)); + } + var threads=new java.util.ArrayList<>(trace.threadIds());threads.add(0); + var outcomes=new java.util.ArrayList<>(trace.outcomes());outcomes.add(trace.outcomes().getLast()); + var steps=new java.util.ArrayList<>(data.transitions());steps.add(data.transitions().getLast()); + var snapshots=new java.util.ArrayList<>(data.snapshots());snapshots.add(data.snapshots().getLast()); + var states=new java.util.ArrayList<>(trace.states());states.add(trace.states().getLast()); + var trailing=new TraceRecord(threads,outcomes,trace.outcome(),trace.programHash(),states,null, + new dev.samhb.interleave.core.BytecodeEvidence(1,data.identity(),steps,snapshots,data.terminal(),null)); + assertThrows(dev.samhb.interleave.search.CorruptedTraceException.class,()->new TraceReplayer().replayBytecode(program,trailing)); + } + + /** Observer fuel and depth stops remain incomplete and replay their exact check/omitted location. + * @param directory compiler workspace + * @throws Exception for fixture failures */ + @Test void observerLimitsRemainIncompleteAndReplayable(@TempDir Path directory) throws Exception { + for(var body:java.util.List.of("while(true){}","return recurse();")) { + var classes=BytecodeFixtures.compile(directory.resolve(body.startsWith("while")?"fuel":"depth"),17, + "@Model public class Fixture {public Fixture(){}@Actor(id=0)public void a(){}public static boolean recurse(){return recurse();}@Check(when=Check.When.ALWAYS)public boolean ok(){"+body+"}}"); + var limits=new BytecodeLimits(256,128,8192,4,64,256,4096,128,8192,32); + var program=BytecodeProgramLoader.load(classes,"Fixture",limits);var result=InterleaveRunner.builder().build().runBytecode(program); + assertFalse(result.hasViolation());assertTrue(result.hasIncomplete());assertFalse(result.limitExceeded()); + var trace=TraceRecord.fromJson(result.incompleteTraces().getFirst().toJson()); + assertEquals("OBSERVER_LIMIT",trace.bytecodeEvidence().terminal().kind());assertEquals("ok",trace.bytecodeEvidence().terminal().check().check().name()); + assertEquals(trace.bytecodeEvidence().terminal(),new TraceReplayer().replayBytecode(program,trace).bytecodeEvidence().replayObservation()); + } + } + /** The documented node bound rejects container growth before DTO construction. + * A flat array exercises the bound independently of recursive depth or byte length. */ + @Test void jsonNodeBudgetBoundsContainerWork() { + String oversized="["+"null,".repeat(999999)+"null]"; + var failure=assertThrows(IllegalArgumentException.class,()->TraceRecord.fromJson(oversized)); + assertNotNull(failure.getCause());assertTrue(failure.getCause().getMessage().contains("node limit")); + } + /** One independently classified import or replay forgery. + * @param failure required public rejection category + * @param mutation one changed wire property */ + private record Forgery(Class failure,java.util.function.Consumer mutation) {} +} From b0422dc860bb182b5a3290ae1cbe0fa4dfe1f338 Mon Sep 17 00:00:00 2001 From: Samuel Date: Thu, 19 Nov 2026 01:14:19 -0500 Subject: [PATCH 3/3] test: tighten bytecode CLI guards and document reproduction Use a valid fixture for unsupported selections and assert admission diagnostics before loading a missing directory. Document the historical mutation scopes and full PIT test selection, and publish the comparison helper used to verify archived evidence. Validation: guard-bypass regression fails as intended; restored and canonical scoped tests pass. Archived mutation comparison, documentation links/fences and git diff checks pass. Minor feedback only; no production changes or fresh CodeRabbit/PIT run. Co-authored-by: Codex --- docs/measurements/94C-bytecode-release.md | 77 +++++++++++- docs/measurements/94C-compare-mutations.py | 110 ++++++++++++++++++ .../bytecode/BytecodeReleaseTest.java | 8 +- 3 files changed, 192 insertions(+), 3 deletions(-) create mode 100644 docs/measurements/94C-compare-mutations.py diff --git a/docs/measurements/94C-bytecode-release.md b/docs/measurements/94C-bytecode-release.md index bbd2f6f..5d071d7 100644 --- a/docs/measurements/94C-bytecode-release.md +++ b/docs/measurements/94C-bytecode-release.md @@ -204,21 +204,94 @@ integrity assertion replaced the probe. No interpreter execution hang is claimed The raw files and comparison scripts are retained in the persistent sibling `interleave-94c-evidence`. `final-affected.xml` is labeled as an assembled comparison dataset; it is not an official build-gate -report. `compare-mutations.py` records unchanged-method checks and changed/moved methods separately. +report. The committed [comparison helper](94C-compare-mutations.py) records unchanged-method checks and +changed/moved methods separately. No residual is silently declared equivalent. No 94C runtime performance, broader-heap cost, DPOR reduction or JPF measurement is invented. The unchanged 94B argument/default review remains the applicable evidence for the admitted executor/scheduler behavior. -Reproduce with JDK 26 and the existing pinned Gradle/PIT dependencies: +### Mutation scopes and test selection + +Use JDK 26 and the existing pinned Gradle/PIT dependencies. The baseline was captured at +`6eb939ea19c3938db8052fc1b32d8f157fc913c7` in the untouched baseline checkout, before feature edits. +The later reports were captured at successive implementation snapshots. Running the same scopes +on a newer snapshot reproduces the procedure, **not necessarily the historical counts**. Exact +historical comparison requires the archived XML and matching compiled baseline/feature snapshots; +those raw artifacts remain in the local evidence directory rather than Git. + +These are the recorded Gradle scopes. `targetTests` remains `dev.samhb.interleave.*` for **every PIT +run**, as configured in `build.gradle.kts`; no narrowed test selector or target-test override was used. +`-PpitestTargetOverride` changes production mutation targets only. Default state/cb is not the full +project. Save `build/reports/pitest/mutations.xml` after each completed run, before another PIT run +replaces it, using the filenames in the comments. Preserve the rejected census even though R6 fails. ```sh ./gradlew --max-workers=1 -PpitestThreads=1 build javadoc + +# Baseline checkout: baseline-default.xml +# Feature checkout: final-default.xml ./gradlew --max-workers=1 -PpitestThreads=1 pitest + +# Baseline checkout: baseline-affected.xml (3,894 mutants) +./gradlew --max-workers=1 -PpitestThreads=1 pitest '-PpitestTargetOverride=dev.samhb.interleave.bytecode.*,dev.samhb.interleave.InterleaveRunner*,dev.samhb.interleave.TestResult*,dev.samhb.interleave.TraceRecord*,dev.samhb.interleave.search.TraceReplayer*,dev.samhb.interleave.report.BenchmarkHarness*,dev.samhb.interleave.report.BenchmarkResult*,dev.samhb.interleave.report.ReportWriter*,dev.samhb.interleave.report.SoundnessAttestation*,dev.samhb.interleave.cli.Main*' + +# Feature checkout: affected-census.xml (historical 4,988-mutant rejected census) +./gradlew --max-workers=1 -PpitestThreads=1 pitest '-PpitestTargetOverride=dev.samhb.interleave.bytecode.*,dev.samhb.interleave.BytecodeTraceJson*,dev.samhb.interleave.ResultJson*,dev.samhb.interleave.core.BytecodeEvidence*,dev.samhb.interleave.InterleaveRunner*,dev.samhb.interleave.TestResult*,dev.samhb.interleave.TraceRecord*,dev.samhb.interleave.search.TraceReplayer*,dev.samhb.interleave.report.BenchmarkHarness*,dev.samhb.interleave.report.BenchmarkResult*,dev.samhb.interleave.report.ReportWriter*,dev.samhb.interleave.report.SoundnessAttestation*,dev.samhb.interleave.cli.Main*' + +# Feature checkout: postfix-focused.xml (1,095-mutant evidence/replay/result scope) +./gradlew --max-workers=1 -PpitestThreads=1 pitest '-PpitestTargetOverride=dev.samhb.interleave.BytecodeTraceJson*,dev.samhb.interleave.ResultJson*,dev.samhb.interleave.core.BytecodeEvidence*,dev.samhb.interleave.bytecode.BytecodeRuntime*,dev.samhb.interleave.bytecode.BytecodeReplay*,dev.samhb.interleave.bytecode.BytecodeSnapshots*,dev.samhb.interleave.bytecode.BytecodeObservations*,dev.samhb.interleave.TestResult*,dev.samhb.interleave.report.BenchmarkResult*' + +# Feature checkout: final-codec-dto.xml (330-mutant scope) ./gradlew --max-workers=1 -PpitestThreads=1 pitest '-PpitestTargetOverride=dev.samhb.interleave.BytecodeTraceJson*,dev.samhb.interleave.core.BytecodeEvidence*' + +# Feature checkout: final-report-pit.xml (259-mutant scope) ./gradlew --max-workers=1 -PpitestThreads=1 pitest '-PpitestTargetOverride=dev.samhb.interleave.report.ReportWriter*' ``` +The public entry/replay checks and BYTECODE artifact producer also ran with these JUnit selectors. +They are separate test invocations, **not restrictions on PIT's test selection**: + +```sh +./gradlew --max-workers=1 -PpitestThreads=1 test --tests '*BytecodeReleaseTest' --tests '*BytecodeReplayTest' +./gradlew --max-workers=1 -PpitestThreads=1 test --tests '*BytecodeReleaseTest.bytecodeViewerUsesFreshProducerArtifacts' +``` + +### Accessible comparison procedure + +The [portable helper](94C-compare-mutations.py) reads `baseline-default.xml`, `final-default.xml`, +`baseline-affected.xml`, `affected-census.xml`, `postfix-focused.xml`, `final-codec-dto.xml` and +`final-report-pit.xml` from the evidence directory. It requires Python 3.8+ and JDK 26 `javap`. +Supply the compiled class directories matching the compared snapshots; do not substitute another +checkout's classes just because its branch name matches. + +```sh +python3 docs/measurements/94C-compare-mutations.py /path/to/interleave-94c-evidence /path/to/baseline/build/classes/java/main /path/to/feature/build/classes/java/main --javap /path/to/jdk26/bin/javap +``` + +It replaces **whole classes** in this order: affected census, evidence/replay/result scope, final +codec/DTO scope, final report scope. It writes `comparison-affected.xml` and `comparison-inherited.json` +as derived artifacts, leaving the raw reports unchanged. Default fingerprints/statuses must match +exactly. For inherited affected kills, it compares descriptor-complete normalized method code and +checks matching mutant identities only in unchanged bodies; changed/moved bodies are listed separately. +Duplicate fingerprints, missing reports, residual resource errors and lost comparable kills fail the +helper's assertions. The composite is never passed to `mutationRatchet` or represented as one PIT run. + +The committed helper was checked against the archived inputs: default455/13, composite4013/420/560, +2356 unchanged-body inherited kills retained, zero lost comparable kills and2 survivor improvements. +Those checks do not establish equivalence of residual mutants or a one-to-one mapping for moved code. + For the browser matrix, regenerate the Java artifacts with the test selection/environment in `.github/workflows/build.yml` after mutation testing, then run `npm test --prefix docs`. BYTECODE_DIR accepts relative and absolute directories. The built-jar probe uses Gradle's exact current jar path in normal test and PIT JVMs, avoiding stale or mutation-harness artifact selection. + +### PR #141 minor-review follow-up + +The unsupported-option matrix now loads the valid compiled fixture. Separate nonexistent-directory +DPOR/bitstate cases require the strategy/store diagnostic, proving rejection before loading. +The strengthened regression fails when the guard is bypassed in the isolated validation checkout +and passes after restoration and on the PR checkout (`pr141-cli-guard-red.log`, +`pr141-cli-restored-green.log`, `pr141-cli-guard-green.log`). No production code changed. +The committed comparison helper reproduces the archived counts and inherited checks above; +documentation links/fences and the exact scope/test-selection commands were checked. Routine +minor feedback verification did not rerun CodeRabbit or the historical mutation censuses. diff --git a/docs/measurements/94C-compare-mutations.py b/docs/measurements/94C-compare-mutations.py new file mode 100644 index 0000000..0a98cbc --- /dev/null +++ b/docs/measurements/94C-compare-mutations.py @@ -0,0 +1,110 @@ +"""Reproduce the 94C per-class comparison from saved PIT XML and compiled snapshots. + +This diagnostic does not run PIT, change its gates, or prove semantic equivalence. +It writes only derived comparison files beside the supplied evidence; raw reports +remain separate. The release ledger documents the required input filenames. +""" +from pathlib import Path +from collections import Counter +import argparse, subprocess, re, json, xml.etree.ElementTree as E +parser=argparse.ArgumentParser(description=__doc__) +parser.add_argument('evidence',type=Path,help='Directory containing the saved XML reports named in the ledger') +parser.add_argument('baseline_classes',type=Path,help='Baseline build/classes/java/main directory') +parser.add_argument('feature_classes',type=Path,help='Feature build/classes/java/main directory') +parser.add_argument('--javap',default='javap',help='JDK 26 javap executable') +args=parser.parse_args() +EVIDENCE=args.evidence + +def read(path): + """Read unique method/mutator/instruction/block identities, excluding unstable source lines.""" + result={} + tree=E.parse(path).getroot() + assert tree.tag=='mutations' and len(tree)>0, 'Expected a nonempty completed PIT report' + + for m in tree: + key=tuple(m.findtext(x,'') for x in ('mutatedClass','mutatedMethod','methodDescription','mutator'))+(tuple(x.text for x in m.findall('indexes/index')),tuple(x.text for x in m.findall('blocks/block'))) + assert key not in result,key + assert m.get('status') in ('KILLED','SURVIVED','NO_COVERAGE'), 'Non-assertion/resource status in comparison' + result[key]=m.get('status') + return result + +def normalized_code(lines): + """Normalize pool indexes/ldc widths and retain control-flow destinations as instruction ordinals.""" + # Constant-pool growth may widen ldc and move BCIs without changing instructions. + # Preserve branch/switch/handler destinations as instruction ordinals instead. + pattern=re.compile(r'^\s*(\d+):\s+([a-z][a-z_0-9]*)(.*)$') + offsets={int(m[1]):n for n,m in enumerate(filter(None,(pattern.match(line) for line in lines)))} + def position(value): + """Name an instruction or exclusive end position for disassembly comparison.""" + return '@'+str(offsets.get(int(value),'END')) + result=[] + for line in lines: + m=pattern.match(line) + if m: + op=m[2];args=m[3].strip() + if op=='ldc_w':op='ldc' + if op.startswith('if') or op in ('goto','goto_w','jsr','jsr_w'): + args=re.sub(r'^-?\d+',lambda n:position(n[0]),args) + result.append(op+' '+args) + elif (m:=re.match(r'^\s*(-?\d+|default):\s*(-?\d+)\s*$',line)): + result.append(m[1]+':'+position(m[2])) + elif (m:=re.match(r'^\s*(\d+)\s+(\d+)\s+(\d+)\s+(any|Class .*)$',line)): + result.append('handler '+','.join(position(m[n]) for n in (1,2,3))+' '+m[4]) + return '\n'.join(result) + +def methods(directory, classes): + """Disassemble existing baseline class names and index normalized code by method descriptor.""" + present=[c for c in sorted(classes) if (directory/(c.replace('.','/')+'.class')).is_file()] + source=subprocess.check_output([args.javap,'-p','-c','-s','-classpath',str(directory),*present],text=True) + result={}; owner=None; method=None; descriptor=None; body=[] + def finish(): + """Retain the current descriptor-complete method before reading the next declaration.""" + if method is not None and descriptor is not None: + result[(owner,method,descriptor)]=normalized_code(body) + for line in source.splitlines(): + match=re.match(r'(?:public |final |abstract |sealed )*(?:class|interface|record) ([^ <]+)',line) + if match: + finish(); owner=match[1]; method=descriptor=None; body=[] + elif re.match(r' \S.*\(.*\).*;',line) or line==' static {};': + finish(); header=line.strip(); name=header.split('(')[0].split()[-1] + method='' if line==' static {};' else '' if name==owner else name + descriptor=None; body=[] + elif method is not None: + if line.strip().startswith('descriptor:'):descriptor=line.strip().split(': ',1)[1] + else:body.append(re.sub(r'#\d+', '#',line.rstrip())) + finish() + return result + +# Replace whole classes with the latest recorded run, never individual favorable mutants. +rows=list(E.parse(EVIDENCE/'affected-census.xml').getroot()) +for name in ('postfix-focused.xml','final-codec-dto.xml','final-report-pit.xml'): + current=list(E.parse(EVIDENCE/name).getroot()) + assert current, name + replaced={m.findtext('mutatedClass') for m in current} + rows=[m for m in rows if m.findtext('mutatedClass') not in replaced]+current +assert all(m.get('status') in ('KILLED','SURVIVED','NO_COVERAGE') for m in rows) +assembled=E.Element('mutations',{'assembly':'latest per-class observations; not a single PIT run'}) +assembled.extend(rows) +comparison=EVIDENCE/'comparison-affected.xml' +E.ElementTree(assembled).write(comparison,encoding='utf-8',xml_declaration=True) + +for scope in ('default','affected'): + final=EVIDENCE/'final-default.xml' if scope=='default' else comparison + old=read(EVIDENCE/('baseline-'+scope+'.xml'));new=read(final) + print(scope,'baseline',dict(Counter(old.values())),'current',dict(Counter(new.values()))) + if scope=='default': + assert old==new,'Default fingerprints or statuses changed' + continue + classes={k[0] for k in old} + before=methods(args.baseline_classes,classes) + after=methods(args.feature_classes,classes) + unchanged={k for k,v in before.items() if k in after and v.strip()==after[k].strip()} + comparable={k:v for k,v in old.items() if k[:3] in unchanged} + lost=[(k,v,new.get(k)) for k,v in comparable.items() if v=='KILLED' and new.get(k)!='KILLED'] + changed=Counter((k[0],k[1],k[2]) for k in old if k[:3] not in unchanged) + report={'unchanged_method_baseline':dict(Counter(comparable.values())), 'lost_kills':lost, + 'changed_or_moved_methods':[{'class':k[0],'method':k[1],'descriptor':k[2],'baseline_mutants':v} for k,v in sorted(changed.items())], + 'improvements':{str(k):v for k,v in Counter((v,new.get(k)) for k,v in comparable.items() if k in new and v!=new[k]).items()}} + (EVIDENCE/'comparison-inherited.json').write_text(json.dumps(report,indent=2)) + print(json.dumps({k:v for k,v in report.items() if k!='changed_or_moved_methods'},indent=2)) + assert not lost,'Inherited kills regressed in unchanged compiled methods' diff --git a/src/test/java/dev/samhb/interleave/bytecode/BytecodeReleaseTest.java b/src/test/java/dev/samhb/interleave/bytecode/BytecodeReleaseTest.java index 68a5d7b..c1d6ae2 100644 --- a/src/test/java/dev/samhb/interleave/bytecode/BytecodeReleaseTest.java +++ b/src/test/java/dev/samhb/interleave/bytecode/BytecodeReleaseTest.java @@ -128,10 +128,16 @@ class BytecodeReleaseTest { for(var extra:java.util.List.of(new String[]{"--strategy","DPOR"},new String[]{"--store","bitstate"}, new String[]{"--symmetry"},new String[]{"--simplify-cutoff"},new String[]{"--all"}, new String[]{"--bytecode","Other"},new String[]{"--max-preemptions","0"})) { - var args=new java.util.ArrayList(java.util.List.of("--bytecode","Fixture","--class-path","missing")); + var args=new java.util.ArrayList(java.util.List.of("--bytecode","Fixture","--class-path",classes.toString())); args.addAll(java.util.List.of(extra));var bad=cli(directory,args.toArray(String[]::new)); assertEquals(1,bad.getKey(),bad.getValue());assertTrue(bad.getValue().contains("BYTECODE"),bad.getValue()); } + for(var extra:java.util.List.of(new String[]{"--strategy","DPOR"},new String[]{"--store","bitstate"})) { + var args=new java.util.ArrayList(java.util.List.of("--bytecode","Fixture","--class-path",directory.resolve("missing").toString())); + args.addAll(java.util.List.of(extra));var bad=cli(directory,args.toArray(String[]::new)); + assertEquals(1,bad.getKey(),bad.getValue()); + assertTrue(bad.getValue().contains("BYTECODE currently supports only --strategy DFS --store exact"),bad.getValue()); + } assertEquals(1,cli(directory,"--bytecode","Fixture").getKey()); assertEquals(1,cli(directory,"--class-path",classes.toString()).getKey()); }