diff --git a/README.md b/README.md index 5c1474d..b1278fb 100644 --- a/README.md +++ b/README.md @@ -9,8 +9,8 @@ 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 94A loader and single-actor interpreter** ([evidence](docs/measurements/94A-bytecode-foundation.md)). -Concurrent search and public evidence/CLI/library selection follow in 94B/94C; no public bytecode +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. 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. diff --git a/build.gradle.kts b/build.gradle.kts index da43bc4..3d01caf 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -96,6 +96,24 @@ tasks.register("profileSearch") { args(layout.buildDirectory.dir("reports/search-profile/fork-${fork.get()}").get().asFile.absolutePath, fork.get()) } +// Internal 94B measurement runner; target programs remain interpreted, with no production selector. +tasks.register("profileBytecode") { + group = "verification" + description = "Measure instruction/reference bytecode execution (Spec 94B)" + dependsOn(tasks.testClasses) + classpath = sourceSets.test.get().runtimeClasspath + mainClass.set("dev.samhb.interleave.bytecode.BytecodeMeasurementTest") + javaLauncher.set(javaToolchains.launcherFor { languageVersion.set(JavaLanguageVersion.of(26)) }) + minHeapSize = "512m" + maxHeapSize = "512m" + // Eliminate SerialGC dead-space retention, which otherwise contaminates live-heap deltas. + jvmArgs("-XX:+UseSerialGC", "-XX:MarkSweepDeadRatio=0") + val fork = providers.gradleProperty("profileFork").orElse("1") + val output = providers.gradleProperty("bytecodeProfileOutput") + .orElse(layout.buildDirectory.dir("reports/bytecode-profile/fork-${fork.get()}").get().asFile.absolutePath) + args(output.get(), fork.get()) +} + tasks.withType { options.encoding = Charsets.UTF_8.name() options.release.set(26) diff --git a/docs/measurements/94B-bytecode-concurrency.md b/docs/measurements/94B-bytecode-concurrency.md new file mode 100644 index 0000000..dff8007 --- /dev/null +++ b/docs/measurements/94B-bytecode-concurrency.md @@ -0,0 +1,355 @@ + +# 94B — Concurrent bytecode execution evidence + +## Status and boundaries + +Internal implementation under [Spec94B](../specs/active/94B-bytecode-concurrency.md) and the +[shared contract](../plans/bytecode-contract.md). Exact DFS, pure checks, instruction-reference and +conservatively batched execution are implemented. Both modes find genuine lost updates and monitor +wait cycles. Local acceptance, measurement and review gates are complete; PR/CI/manual review remains +the publication boundary. Verification and remaining scope limits are recorded below. +Public library/CLI selection, serialized BYTECODE evidence, strict public replay, reports and viewer +remain **94C**. CBS, DPOR, atomics, bitstate and JPF comparison remain later milestones; no measurement +here establishes their correctness or performance. + +Starting merged main: `3c2c799d5d01054706e85bd8cdf89ab2ec2addba` (94A/PR139). +The original dirty checkout was preserved. An earlier temporary worktree/log directory disappeared; +authored source edits were recovered from the session's exact tool history into a persistent worktree, +and the baseline was regenerated. Lost temporary logs are not claimed as present evidence. + +## Implementation and independent evidence + +`OpcodeExecutor.probe` classifies enabled, blocked and pending choices without state/fuel effects. +`BytecodeScheduler` uses that same primitive executor in both modes, preserving real method/BCI +positions rather than source forward PCs. `BytecodeExplorer` uses iterative exact DFS and full canonical +payload equality after hash filtering, following `HashingStateStore`'s membership policy without +weakening `Configuration` or introducing a public backend. One deliberately colliding terminal-payload +fixture retains both outcomes (65 states,108 edges,109 encoding calls), independently derived by a +seven-stage-per-actor model and Python enumeration. Checker state/key limits and cancellation produce +external incomplete results; the internal default key-payload budget is64MiB, excluding JVM overhead. + +`BytecodeChecks` uses separate private frames/fuel and copied read-only model state. ALWAYS checks run +initially and after every reference opcode/event; batched omissions are justified below. FINAL runs +only after all actors terminate normally. False, observer error/limit, actor exception, modeled cutoff, +deadlock and external interruption retain separate internal identities. Check frames never enter model +keys, actor fuel or scheduling choices. Existing loader purity/unknown-metadata rejection remains active. + +`BytecodeInstructionOracle` independently enumerates each actor's primitive `step`, uses a sorted set +of its own full structural keys, runs its own private observers and builds its own observations. +It does not use production probes, scheduler, canonical encoder or outcome builder. It intentionally +shares the primitive opcode executor; separate JVM differential cases continue to check that layer. +The oracle's record-text tokens are restricted to these controlled ASCII-named fixtures, not an +alternative encoding for arbitrary application inputs. + +Both production modes agree with this oracle on the lost-update/two-lock fixtures, targeted terminal +competition, pure local infinite computation, fuel-sensitive shared branches, exact-limit return, +observer arithmetic failure, nested/reentrant cleanup and eight generated programs from seed94002. +Generated failures undergo statement-deletion shrinking and print the minimized fixture. No generated +failure was found; no fictitious saved counterexample is claimed. Targeted regression sources remain +in the tests and checked-in resource fixtures. Internal witness schedules replay through enabled actual +choices and reproduce owned states; that is not the public strict replay format promised by94C. +Independent concurrent runs share only immutable program metadata. + +## Batching preservation argument + +This argument is restricted to the loader-admitted94B profile. It does not justify future opcodes, +actor allocations, dispatch, general handlers, intrinsics or DPOR. Tests corroborate it; they are not +its proof. + +**State relation.** At a scheduling boundary, relate a batched state to the reference state obtained by +expanding its selected transition into the exact same primitive steps. Heap identities/aliases, fields, +statics, monitor owners/depths, every actor's frames/operand/local slots and BCIs, resource counters, +allocation sequences, sharing history and pending events are identical. Transition ordinals, host +measurement counters and number of selected transitions are excluded. At intermediate local points, +only the selected actor's local continuation, operand/local slots and fuel can differ. No observer may +inspect them. The complete encoder retains those differences rather than merging states across fuel. + +**Allowed local steps.** The current scheduler treats every field/static access, every explicit monitor +operation, every return/throw, implicit synchronized entry/exit, exception/unwind event, pending terminal +and actual exhaustion as observable. No heap access is classified actor-local. The remaining admitted +steps are operand/local arithmetic, branches and helper call setup. They neither read nor write shared +model cells nor acquire/release monitors. They change only the selected actor's private continuation +and charged fuel. Another actor's operation therefore preserves their enabledness, value computation +and charged cost, and those local steps preserve that actor's operation and observations. Helper calls +remain interpreted: synchronized entry is a distinct boundary; helper returns, depth stops and faults +use the same event protocol. There is no actor allocation or unbounded host callback in this profile. + +**Reordering.** A batch contains at most one observable step, with local prefix/suffix work. Moving other +actors' steps out of those local segments to the preceding/following preserved boundaries commutes by +the prior argument. Heap reads and writes cannot pass each other; in particular increment read/write +opportunities remain distinct. Pending monitor acquisition remains disabled with sufficient fuel and +consumes nothing. Fuel exhaustion takes priority over a blocked acquisition, so it cannot be mislabeled +a deadlock. Calls, cleanup and reentrant monitor depth follow the primitive semantics; implicit release +and explicit cleanup releases cannot be coalesced past another observable operation. + +**Errors and bounds.** Every executed opcode charges its actual work, including faulting instructions; +omitted work is uncharged. Normal return on instructionN succeeds. Probing never executes/charges a +candidate. Discovery of a fault, depth stop, return or fuel cutoff ends the current batch in its pending +phase, before terminal delivery. Another actor can therefore run before the prefix ends. Even a batch +containing only local infinite-loop steps terminates at its finite fuel allowance and yields before +cutoff delivery. Moving the other actor to that boundary preserves its competing false check/fault or +shared effect. A cutoff ends the entire selected prefix; no exhausted actor is frozen and no sentinel +is appended. This argument concerns exhaustive bounded runs; external checker interruptions may leave +different partial graphs at the two granularities and never establish absence. + +**Observers.** Loader-certified transitive purity excludes writes, allocation, synchronization and +resource/history/actor-stack inspection. Each invocation starts with the same independent allowance, +root call depth and model heap/statics. Omitted local intermediates leave all its possible reads, +branch results and errors unchanged, so both its value and failure identity are invariant. After the +batch's single observable step the resulting shared state is checked before any delivered actor +failure/cutoff. A pending local fault in its suffix cannot suppress that check. Ordered observers and +FINAL timing agree; FINAL requires all actors' normal terminal delivery in either mode. Observer errors +and exhausted observer fuel/depth remain incomplete, distinct from actor violations. + +**Sharedness.** Every object in94B is setup-allocated and conservative shared from initialization. +Reference writes refresh transitive fixture/static/frame roots before exposing their successor; +failed writes do not count as publication. Unknown reachability remains shared and promotion never +reverts. All history bits remain in keys. Because actor allocation/exclusive ownership is absent, +reachable runs cannot differ only in historical sharing flags: the measured history-only count is +zero by invariant, not an unperformed state-pair benchmark. Tests mutate the internal seam to confirm +encoding, frame roots and irreversible promotion; they do not claim95's nontrivial heap profile. + +**Conclusion and extension obligation.** Expanding batches gives reference executions with the same +normalized terminal observations, and commuting reference local interleavings to retained boundaries +gives matching batched outcomes. Compare violation/fault/check identities, final shared fields, deadlock +relationships and cutoff actor/reason/omitted location/limit; equal traces/local snapshots/counts are +not required. Every terminal category carries the last committed shared observations, including +false checks, actor faults, modeled cutoffs, observer failures, deadlocks and external interruptions; +these are not restricted to normally completed executions. Every newly admitted behavior must re-establish these commutation, observation, resource +and terminal-event premises before batching it. This argument makes no independence claim for DPOR. + +## Reproducible measurement conditions + +Measured on Apple M4 /16GiB RAM, macOS/aarch64, installed Homebrew OpenJDK26.0.2.1. +Java SHA-256: `38025293a292f9d2161c9c2683191555eabefeb8b987cde9d8c88cafb843d333`; +javac: `a587e4bfa51de17788dfc9de7b22960174f11cb5fed8f21bf2867151eb2524fa`. +Compiler target is `--release26`; existing17/21/26 fixtures use this same installed compiler, not +three independent compiler installations. Run each command separately for fork1 and fork2: + +```sh +./gradlew --max-workers=1 -PpitestThreads=1 profileBytecode -PprofileFork=1 +./gradlew --max-workers=1 -PpitestThreads=1 profileBytecode -PprofileFork=2 +``` + +Default output: `build/reports/bytecode-profile/fork-N/`; use `-PbytecodeProfileOutput=` +to retain results outside disposable builds. Each task launches a fresh JVM with512MiB fixed heap, +Serial GC and `-XX:MarkSweepDeadRatio=0`. It compiles each checked-in fixture once, loads it once, checks +outcome equality independently, warms each mode twice and measures three repetitions per fixture/mode. +Mode order alternates each repetition. Both modes use the identical artifact and provisional limits. +Elapsed time surrounds search only; GC, compilation, loading and outcome comparison are outside it. +Encoding nanoseconds are instrumented inside search and included in elapsed time. These short runs are +feasibility measurements, not a broad throughput benchmark; OS/JIT noise is visible in the ranges. + +Retained heap is actual used JVM heap after two verified explicit full collections while an explicit +root holds the explorer's full key store and result/witnesses. Delta subtracts the pre-search collected +baseline after releasing the preceding store. It includes live Java collection/array/witness overhead, +not merely encoded payload bytes; it excludes native memory and peak/transient allocation. Earlier +experimental runs without full compaction produced misleading/negative deltas because Serial GC may +retain dead space. A standalone10MB weak-reference probe reproduced this even after its referent was +cleared; setting `MarkSweepDeadRatio=0` reclaimed that space. Those preliminary runs are invalid memory +evidence and are excluded. They motivated the explicit compaction precondition in the runner. + +The measurements show stable states/transitions/encoding volume across all six samples per group. +No fixed percentage target was imposed. Both fixtures complete within actor fuel256 (no cutoffs), and +batching reduces encoding/storage work. Time ranges overlap for the tiny lost-update fixture, so do +not infer a universal speedup. Default model limits remain provisional and unchanged; these two tiny +fixtures alone cannot calibrate all admitted programs. Conservative all-shared setup traversal occurs +once per run here, visiting2 objects/0 edges (lost update) or4 objects/2 edges (two locks). Promotions +and history-only states are0. These fixtures perform no actor reference writes; the separate rewiring +test exercises actual publication traversals.95 must remeasure nontrivial sharedness cost. + +### Measured results + +Six samples per cell: two fresh forks × three repetitions. Time and retained-heap delta use median +[min,max]. State/transition/encoding/payload counts are identical across repetitions. + +|Fixture/mode|States|Transitions|Encoding calls/bytes|Key payload bytes|Elapsed ms median [min,max]|Encoding ms median [min,max]|Retained heap delta bytes median [min,max]| +|---|---:|---:|---:|---:|---:|---:|---:| +|lost-update/REFERENCE|140|246|247/118191|66946|2.943 [1.472,4.237]|1.084 [0.442,1.691]|95300 [95080,95648]| +|lost-update/BATCHED|60|98|99/45981|27942|1.964 [0.838,3.194]|0.611 [0.226,1.580]|43096 [43096,43376]| +|two-lock/REFERENCE|475|866|867/704665|385797|3.601 [2.734,4.407]|1.696 [1.386,2.223]|471020 [470984,471944]| +|two-lock/BATCHED|116|196|197/159723|93994|1.174 [0.968,1.484]|0.406 [0.335,0.625]|121664 [121664,121664]| + +The lost-update fixture declares FINAL `x==2`: the two outcomes are CHECK_FALSE/x=1 and COMPLETED/x=2. +The two-lock fixture has DEADLOCK/x=0 with both concrete waits, and COMPLETED/x=2. Its FINAL check is +absent on the deadlock prefix. The measurement gate asserts these known outcomes as well as equivalence, +so losing the same outcome in both implementations cannot pass. Observer invocation/work totals are +2/13 for lost update and1/7 for two locks in each mode/run; see raw rows below. + +### Artifact identities and raw repetitions + +Fork1: + +- Java: `26.0.2.1` +- VM: `OpenJDK 64-Bit Server VM` +- OS/architecture: `Mac OS X/aarch64` +- JVM arguments: `[-XX:+UseSerialGC, -XX:MarkSweepDeadRatio=0, -Xms512m, -Xmx512m, -Dfile.encoding=UTF-8, -Duser.country=US, -Duser.language=en, -Duser.variant]` +- Warmups: 2 per fixture/mode; repetitions: 3; modes alternate order per repetition. +- Retained heap: used heap after verified explicit GC and full compaction (MarkSweepDeadRatio=0), with explorer and result reachable; delta against pre-run used heap. +- Key bytes are only canonical payload, reported separately. History-only states are zero in the setup-only all-shared profile. +- lost-update source SHA-256: `1721b4fa9ec2937ac9087fdca03b392d6359f99aced3424f02591522344a2ab2`; artifact manifest: `8c00e19be1d23ccd6ab66d697c827a8c4083737439361768b58b9ac4a0f5745c`; limits: `BytecodeLimits[actorInstructions=256, actorAllocations=128, actorHeapCells=8192, maxCallDepth=32, maxArrayLength=64, maxStringLength=256, setupInstructions=4096, setupAllocations=128, setupHeapCells=8192, checkInstructions=1024]` +- two-lock source SHA-256: `2aa8585b0a91866e84d423e719b3bfe59b3625463d9e0943b3cf6c6a3a12b634`; artifact manifest: `b19cb7d7687fcd44aa045d05177c153032e8673d76fa02653cbe39d17fd052fc`; limits: `BytecodeLimits[actorInstructions=256, actorAllocations=128, actorHeapCells=8192, maxCallDepth=32, maxArrayLength=64, maxStringLength=256, setupInstructions=4096, setupAllocations=128, setupHeapCells=8192, checkInstructions=1024]` + +```csv +fixture,fork,repetition,mode,states,transitions,opcodes,instructions,encodingCalls,encodingBytes,encodingNanos,retainedKeyBytes,elapsedNanos,heapBefore,heapAfter,heapDelta,gcCollections,checkInvocations,checkInstructions,sharingTraversals,sharingObjects,sharingEdges,sharingPromotions,historyOnlyStates,outcomes +lost-update,1,0,REFERENCE,140,246,178,178,247,118191,1160295,66946,3527500,7044064,7139464,95400,2,2,13,1,2,0,0,0,2 +lost-update,1,0,BATCHED,60,98,102,102,99,45981,1580211,27942,3194125,7044672,7087768,43096,2,2,13,1,2,0,0,0,2 +lost-update,1,1,BATCHED,60,98,102,102,99,45981,642377,27942,2069625,7044824,7087920,43096,2,2,13,1,2,0,0,0,2 +lost-update,1,1,REFERENCE,140,246,178,178,247,118191,908213,66946,2843959,7044976,7140624,95648,2,2,13,1,2,0,0,0,2 +lost-update,1,2,REFERENCE,140,246,178,178,247,118191,1008201,66946,2213625,7045832,7140912,95080,2,2,13,1,2,0,0,0,2 +lost-update,1,2,BATCHED,60,98,102,102,99,45981,1157254,27942,2023250,7046120,7089216,43096,2,2,13,1,2,0,0,0,2 +two-lock,1,0,REFERENCE,475,866,762,762,867,704665,1712127,385797,3597959,7050128,7521112,470984,2,1,7,1,4,2,0,0,2 +two-lock,1,0,BATCHED,116,196,374,374,197,159723,533286,93994,1294416,7050288,7171952,121664,2,1,7,1,4,2,0,0,2 +two-lock,1,1,BATCHED,116,196,374,374,197,159723,340495,93994,969041,7050440,7172104,121664,2,1,7,1,4,2,0,0,2 +two-lock,1,1,REFERENCE,475,866,762,762,867,704665,1645235,385797,3604792,7050592,7521648,471056,2,1,7,1,4,2,0,0,2 +two-lock,1,2,REFERENCE,475,866,762,762,867,704665,1385878,385797,2733916,7050848,7522792,471944,2,1,7,1,4,2,0,0,2 +two-lock,1,2,BATCHED,116,196,374,374,197,159723,335462,93994,968375,7051968,7173632,121664,2,1,7,1,4,2,0,0,2 +``` + +Fork2: + +- Java: `26.0.2.1` +- VM: `OpenJDK 64-Bit Server VM` +- OS/architecture: `Mac OS X/aarch64` +- JVM arguments: `[-XX:+UseSerialGC, -XX:MarkSweepDeadRatio=0, -Xms512m, -Xmx512m, -Dfile.encoding=UTF-8, -Duser.country=US, -Duser.language=en, -Duser.variant]` +- Warmups: 2 per fixture/mode; repetitions: 3; modes alternate order per repetition. +- Retained heap: used heap after verified explicit GC and full compaction (MarkSweepDeadRatio=0), with explorer and result reachable; delta against pre-run used heap. +- Key bytes are only canonical payload, reported separately. History-only states are zero in the setup-only all-shared profile. +- lost-update source SHA-256: `1721b4fa9ec2937ac9087fdca03b392d6359f99aced3424f02591522344a2ab2`; artifact manifest: `8c00e19be1d23ccd6ab66d697c827a8c4083737439361768b58b9ac4a0f5745c`; limits: `BytecodeLimits[actorInstructions=256, actorAllocations=128, actorHeapCells=8192, maxCallDepth=32, maxArrayLength=64, maxStringLength=256, setupInstructions=4096, setupAllocations=128, setupHeapCells=8192, checkInstructions=1024]` +- two-lock source SHA-256: `2aa8585b0a91866e84d423e719b3bfe59b3625463d9e0943b3cf6c6a3a12b634`; artifact manifest: `b19cb7d7687fcd44aa045d05177c153032e8673d76fa02653cbe39d17fd052fc`; limits: `BytecodeLimits[actorInstructions=256, actorAllocations=128, actorHeapCells=8192, maxCallDepth=32, maxArrayLength=64, maxStringLength=256, setupInstructions=4096, setupAllocations=128, setupHeapCells=8192, checkInstructions=1024]` + +```csv +fixture,fork,repetition,mode,states,transitions,opcodes,instructions,encodingCalls,encodingBytes,encodingNanos,retainedKeyBytes,elapsedNanos,heapBefore,heapAfter,heapDelta,gcCollections,checkInvocations,checkInstructions,sharingTraversals,sharingObjects,sharingEdges,sharingPromotions,historyOnlyStates,outcomes +lost-update,2,0,REFERENCE,140,246,178,178,247,118191,1691248,66946,4236875,7044048,7139488,95440,2,2,13,1,2,0,0,0,2 +lost-update,2,0,BATCHED,60,98,102,102,99,45981,397912,27942,1749583,7044696,7087976,43280,2,2,13,1,2,0,0,0,2 +lost-update,2,1,BATCHED,60,98,102,102,99,45981,579540,27942,1904708,7045032,7088408,43376,2,2,13,1,2,0,0,0,2 +lost-update,2,1,REFERENCE,140,246,178,178,247,118191,1543113,66946,3041958,7045464,7140664,95200,2,2,13,1,2,0,0,0,2 +lost-update,2,2,REFERENCE,140,246,178,178,247,118191,442467,66946,1471500,7045872,7140952,95080,2,2,13,1,2,0,0,0,2 +lost-update,2,2,BATCHED,60,98,102,102,99,45981,225998,27942,837916,7046160,7089256,43096,2,2,13,1,2,0,0,0,2 +two-lock,2,0,REFERENCE,475,866,762,762,867,704665,1679261,385797,3597625,7050200,7521184,470984,2,1,7,1,4,2,0,0,2 +two-lock,2,0,BATCHED,116,196,374,374,197,159723,624669,93994,1484208,7050360,7172024,121664,2,1,7,1,4,2,0,0,2 +two-lock,2,1,BATCHED,116,196,374,374,197,159723,345708,93994,1054500,7050512,7172176,121664,2,1,7,1,4,2,0,0,2 +two-lock,2,1,REFERENCE,475,866,762,762,867,704665,1774319,385797,3805709,7050664,7521648,470984,2,1,7,1,4,2,0,0,2 +two-lock,2,2,REFERENCE,475,866,762,762,867,704665,2222790,385797,4406875,7050848,7522784,471936,2,1,7,1,4,2,0,0,2 +two-lock,2,2,BATCHED,116,196,374,374,197,159723,466198,93994,1312125,7051960,7173624,121664,2,1,7,1,4,2,0,0,2 +``` + +## Validation and review ledger + +Fresh untouched-main baseline:2020 tests, zero failures/errors/skips; full build/strict Javadoc passes. +Configured default state/cb PIT:455 KILLED +13 SURVIVED /468. Affected bytecode package baseline: +1344 KILLED +171 SURVIVED +105 NO_COVERAGE /1620. These are regenerated reports on the actual merged +starting SHA, not carried-forward94A authoring counts. The default scope is not the whole checker. + +Integrated final build/strict Javadoc:2066 tests, zero failures/errors/skips. Private bytecode and mutation-harness +member doclint passes with all groups and warnings as errors. The legacy browser suite passes the +normalization assertions plus248 browser checks against all freshly generated CI fixture families, with zero console errors; no new bytecode viewer path +is claimed. The actual library jar excludes test annotations, profiler/probe classes, the mutation +agent and the public bytecode facade. Legacy public/source/declarative consumers remain unchanged. + +The first affected run reported1677 KILLED +223 SURVIVED +111 NO_COVERAGE +3 TIMED_OUT /2014 and +**failed** the R6 mutation gate. The timeouts were DFS `ArrayDeque.pop` removal and observer root-return +condition/size removal. They are not kills. The existing test-only instrumentation agent now installs +`BytecodeWorkBudget`, which derives9S maximum DFS loop visits for at mostS admitted frames (8 actor +selections +1 pop per frame), saturating at Long.MAX_VALUE. Each pure observer gets at most2N+2 loop +visits for N opcode work, helper-return events and final/cutoff views; the allowance resets per check. +These counters do not change production code, target fuel or flags and never ship in the library. +Real-definition child-JVM tests preserve original outcomes, reject binding/checkpoint drift and turn +actual stalled mutations into AssertionErrors. The refreshed whole-bytecode-package census passed with1718 KILLED +194 SURVIVED +102 NO_COVERAGE +/2014, zero timeouts/run errors. Later focused assertions cover static publication/promotion and an +actually unreachable setup object (both local and operand roots removed). Their final focused census +is107 KILLED +13 SURVIVED /120, zero uncovered/resource/run-error statuses. Scheduler including its +transition record is71/71; sharing including Work is36/49, with13 survivors. No production bytecode +changed after the whole-package census; focused test patches were followed by integrated verification. +These are scoped bytecode results, not a whole-checker mutation score. +No timeout thresholds, operators, floors, mutation target tests or CI parallelism were weakened. + +Actual CodeRabbit0.8.1 reviewed all21 then-changed files and completed with6 findings (2 major, +2 minor,2 trivial). Dispositions: batch cancellation now checks each opcode boundary and Explorer +records external CANCELLED with no scratch commit; exact-state budget enforcement follows duplicate +membership (regression140 states/246 edges); observer fuel resets have repeated successful ALWAYS +coverage; the independent oracle derives fuel/monitor enabledness without probe and verifies `step`; +concurrent test futures are cancelled in finally; known completion/deadlock/lost-update observations +are asserted before measurement equality. The return-cleanup test correctly requires the faulting +actor's depths to be released; a competing actor may acquire before failure delivery. Follow-up +CodeRabbit reviewed all24 files, including the added PIT-only progress harness, and completed with +3 findings (2 major,1 minor). The major findings requested verification, rather than demonstrating +counterexamples: `step` already copies the complete owned state, and `probe` already treats GETSTATIC/ +PUTSTATIC as FieldInstructions. Added checks preserve static x=1/x=2 outcomes and both modes agree with +independent instruction enumeration. Deterministic test-only class-file injection interrupts immediately +after a real local opcode, shared write or implicit synchronized entry, proving the parent unchanged; +it also verifies Explorer's external CANCELLED prefix. This replaces a timing-dependent stack-sampling +worker test. No callback/pause hook was added to production. Those focused test patches were reviewed +locally; no third CLI loop was run after the two completed substantive reviews. + +A context-free doc-coauthoring reader answered all five scope/preservation/oracle/measurement/history +questions and found no blocking premise gap in the restricted argument. Its one ambiguity—whether +abnormal terminals carry shared observations—was clarified above. This was a document review, not a +source or runtime certification. Connected-source ordinary/ponytail and OWASP review checked owned +state, exact membership, modeled/external terminal distinctions, transitive check purity, metadata-only +target boundaries and host test instrumentation. No unresolved correctness/security finding remains +within94B. Actual ordinary and CodeRabbit evidence is recorded through agent-setup for this session; +focused review-test/status patches used local verification rather than an unbounded third CLI loop. +NO_COVERAGE, timeout and run errors are never counted as kills. No JPF experiment was performed here. + +### Mutation reconciliation and residuals + +Configured default state/cb:455 KILLED +13 SURVIVED /468; **all468 baseline fingerprints and statuses +match**, including every455 inherited kill. Fingerprints use class/method/descriptor/operator plus +instruction indexes/blocks; line-number shifts are not identities. This default is not the whole checker. +For affected bytecode, all1274 baseline kills in unchanged methods remain killed. The changed primitive +`step` is not compared by coincidentally overlapping instruction indexes; its semantics are covered by +JVM differential, exact-limit/fault/monitor and independent scheduling cases. Among unchanged methods, +9 formerly uncovered and4 formerly surviving mutants are now killed. + +The table below composes the whole-package report with the later Scheduler/Sharing report **by class**. +Its1724 KILLED +190 SURVIVED +100 NO_COVERAGE /2014 is a latest-per-class sum, not a single full-scope +PIT invocation. The separate actual invocation totals are stated above. Nested types are included. + +|Affected class/group|KILLED|SURVIVED|NO_COVERAGE| +|---|---:|---:|---:| +|BytecodeChecks|41|1|0| +|BytecodeExplorer|170|7|4| +|BytecodeFrame|15|0|0| +|BytecodeInput|108|10|16| +|BytecodeLimits|7|0|0| +|BytecodeLoadException|0|2|0| +|BytecodeLoader|484|72|57| +|BytecodeMethod|34|3|0| +|BytecodeProgram|23|2|0| +|BytecodeScheduler|71|0|0| +|BytecodeSharing|36|13|0| +|BytecodeState|185|13|0| +|BytecodeVerifier|239|59|21| +|OpcodeExecutor|311|8|2| + +All residuals remain in raw XML; none are excluded or declared generally equivalent. Most inherited +residuals concern overlapping input/JDK validation, diagnostics and defensive checks. New residuals +include redundant exact-hash/terminal guards, timing-sensitive cancellation paths and the observer's +partial-cancellation accounting. The13 sharing survivors affect redundant/empty/null roots or traversal +in the conservative setup-only heap;95 must revisit them when actual object graphs/local ownership +arrive. Zero history-only metrics do not prove these mutations equivalent for that wider profile. +The mutation ratchet/operators/floors and target-test policy remain unchanged. + +### Reproduction and retained evidence + +```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.bytecode.*' +./gradlew --max-workers=1 -PpitestThreads=1 pitest '-PpitestTargetOverride=dev.samhb.interleave.bytecode.BytecodeScheduler*,dev.samhb.interleave.bytecode.BytecodeSharing*' +``` + +Independent private doclint runs use `javadoc -private -Xdoclint:all -Werror` over bytecode and the +separate mutation-harness source tree. Browser verification uses all environment paths listed in the +existing Visualizer compatibility CI job after normal tests generate fresh artifacts, before PIT can +replace them. Context-store structural validation has0 errors and1 inherited machine-local link warning. +Documentation validation passes5 changed Markdown documents and all local targets/anchors; R1–R6 +mappings, code fences and whitespace checks pass. + +Local raw evidence lives in `Documents/repos/worktrees/interleave-94b-evidence` under Sam's home: +`baseline-{build,default,affected}` logs/XML; `publication-build.log`; `verified-{build-and-fork1,fork2}` +logs/directories; `complete-browser.log`; `final-default.log/.xml`; `verified-affected.log/.xml`; +`final-focused.log/.xml`; `compare-mutations.py`; strict/private doclint logs; +`coderabbit.ndjson` and `coderabbit-followup.ndjson`; failing/passing targeted regression logs. +Committed raw interpreter repetitions above make the measurement result independent of that local path. diff --git a/docs/plans/bytecode-contract.md b/docs/plans/bytecode-contract.md index b711cda..1d0e3f5 100644 --- a/docs/plans/bytecode-contract.md +++ b/docs/plans/bytecode-contract.md @@ -3,7 +3,7 @@ ## Objective and status -**Selected; 94A internal foundation implemented, public release pending.** Approved scope: controlled interpretation of compiled Java for fixed +**Selected; internal94A/94B implemented, public release 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. @@ -12,7 +12,9 @@ Planning baseline: remote main `2a242c4`, freshly fetched during authoring. B10 PRs #136/#137 and its closure commit. Sam explicitly selected #12 after that stopping point; #11 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; concurrency, batching, sharedness-cost, DPOR and JPF gates remain pending. [Vocabulary](../../CONTEXT.md) owns domain terms; this document +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 owns common behavior, interface seams, verification and phase boundaries. ## Sequential delivery and ownership diff --git a/docs/plans/future-work.md b/docs/plans/future-work.md index 8e1d4a2..ad11b5a 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 foundation | 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). Target ten sequential implementation PRs; concurrency/batching, DPOR and JPF measurements remain pending. | +| 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. | ## Deferred @@ -205,9 +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 foundation** — [contract/specification index](bytecode-contract.md). +12. **Bounded Java bytecode checking — selected, internal concurrency** — [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. Initial public -release follows 94B/94C; batching/sharedness measurements, optimized reduction and JPF acceptance -remain pending. +[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. diff --git a/docs/specs/active/94B-bytecode-concurrency.md b/docs/specs/active/94B-bytecode-concurrency.md index fceb33e..9e79b5e 100644 --- a/docs/specs/active/94B-bytecode-concurrency.md +++ b/docs/specs/active/94B-bytecode-concurrency.md @@ -1,10 +1,10 @@ - + # Spec 94B: Concurrent execution and feasibility ## Objective Deliver concurrent execution and feasibility as one coherent stage of bounded Java bytecode checking. -**Type: delta. Status: specified, not implemented or measured.** The +**Type: delta. Status: implemented; local acceptance complete, PR review pending.** 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 94B only. @@ -117,18 +117,28 @@ 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. +- [implementation] Internal `BytecodeScheduler`, `BytecodeExplorer`, `BytecodeChecks` and +`BytecodeSharing` now implement this milestone. REFERENCE and BATCHED share `OpcodeExecutor`. +No public bytecode selection/serialization is introduced. Current implementation baseline is merged +main `3c2c799`, distinct from the historical planning revision above. +- [measured] Independent instruction enumeration and real two-fork interpreter measurements are in +[the94B ledger](../../measurements/94B-bytecode-concurrency.md), including the restricted preservation +argument and raw repetitions. Final validation/review disposition is recorded there; authoring review +alone does not establish implementation evidence. JPF remains later-phase acceptance. ## Tests -`lostUpdateAndDeadlockMatchInstructionEnumeration` (R1/R2/R4), -`reentrantCleanupAndBlockedAttemptsKeepExactAccounting` (R2), `checksUseSeparatePureObservers` (R3), -`batchYieldsBeforeCompetingTerminalEvents` (R4/R5), `historyAndBudgetsAffectKeys` (R1/R4), -`referenceBatchOutcomeGate` (R5/R6). Kill read/write merging, missing shared-history bits, -premature terminal delivery, cleanup depth errors and cutoff-as-deadlock mutations. -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. +`BytecodeConcurrencyTest` covers split read/write choices, concrete deadlock relationships, +synchronized methods, frame roots, rewiring/publication and pending fault competition. +`BytecodeEventTest` / `BytecodeResourceTest` cover disabled/exhausted monitor attempts, exact limits, +null/nonowner releases and cleanup. `BytecodeCheckTest` covers both modes' observer timing, false, +fault/fuel/depth classifications and abnormal-prefix FINAL exclusions. +`BytecodeBatchingOracleTest` / `BytecodeInstructionOracle` independently enumerate targeted and +fixed-seed/shrunk tiny-program outcomes. `BytecodeSearchContractTest` covers complete payload hash +collisions, external stops, internal schedules and isolated concurrent/repeated runs. +`BytecodeMeasurementTest.referenceBatchOutcomeGate` verifies both real fixtures before the opt-in +`profileBytecode` runner measures them. [The ledger](../../measurements/94B-bytecode-concurrency.md) +records actual results and any remaining gate, without equating tests to a preservation proof. ## Constraints diff --git a/src/main/java/dev/samhb/interleave/bytecode/BytecodeChecks.java b/src/main/java/dev/samhb/interleave/bytecode/BytecodeChecks.java new file mode 100644 index 0000000..ec52b98 --- /dev/null +++ b/src/main/java/dev/samhb/interleave/bytecode/BytecodeChecks.java @@ -0,0 +1,70 @@ +/** Pure interpreted observers with private frames and per-invocation fuel, never scheduler actors. */ +package dev.samhb.interleave.bytecode; + +import java.util.List; +import static dev.samhb.interleave.bytecode.BytecodeState.*; + +/** Runs only loader-certified checks, returning diagnostics without modifying committed target state. */ +final class BytecodeChecks { + /** Prevents construction of the stateless observer runner. */ + private BytecodeChecks() {} + + /** Observer-specific failure reasons, separate from actor violations. */ + enum Kind { + /** A pure check returned false. */ FALSE, + /** A pure operation raised a modeled fault. */ ERROR, + /** Observer instruction or call-depth allowance was exhausted. */ LIMIT, + /** Host cancellation interrupted the checker, not the modeled program. */ INTERRUPTED + } + + /** One failed check with genuine method/BCI identity. + * @param kind observer disposition + * @param check declared check identity + * @param location actual return, fault or omitted instruction; null for host cancellation + * @param fault interpreted observer fault, if any + * @param cutoff observer resource diagnostic, if any + */ + record Failure(Kind kind,BytecodeMethod.Id check,BytecodeLocation location,Fault fault,Cutoff cutoff) {} + + /** Actual observer work for one ordered timing group. + * @param failure first failing check, otherwise null + * @param invocations attempted check invocations + * @param instructions executed observer instruction/intrinsic work + */ + record Evaluation(Failure failure,long invocations,long instructions) {} + + /** Executes ordered ALWAYS or FINAL declarations synchronously on private scratch state. + * @param program immutable validated artifact + * @param parent committed model state, never modified + * @param always true for ALWAYS, false for FINAL + * @return first failure and actual separate observer work + */ + static Evaluation evaluate(BytecodeProgram program,BytecodeState parent,boolean always) { + long invocations=0,instructions=0; + for(var check:program.checks) { + if(check.always()!=always)continue; + invocations++; + var scratch=new BytecodeState(); + for(var entry:parent.heap.entrySet())scratch.heap.put(entry.getKey(),entry.getValue().copy()); + scratch.statics.putAll(parent.statics); + scratch.start(OBSERVER,program.methods.get(check.method()),List.of(FIXTURE)); + while(true) { + var execution=scratch.executions.get(OBSERVER); + if(Thread.currentThread().isInterrupted()) + return new Evaluation(new Failure(Kind.INTERRUPTED,check.method(),null,null,null),invocations,instructions+execution.instructions); + if(execution.phase==Phase.EXCEPTION) + return new Evaluation(new Failure(Kind.ERROR,check.method(),execution.fault.location(),execution.fault,null),invocations,instructions+execution.instructions); + if(execution.phase==Phase.CUTOFF_PENDING) + return new Evaluation(new Failure(Kind.LIMIT,check.method(),execution.cutoff.location(),null,execution.cutoff),invocations,instructions+execution.instructions); + if(execution.phase==Phase.RETURNING && execution.frames.size()==1) { + instructions+=execution.instructions; + if(((Int)execution.returned).value()==0) + return new Evaluation(new Failure(Kind.FALSE,check.method(),execution.eventLocation,null,null),invocations,instructions); + break; + } + scratch=OpcodeExecutor.step(program,scratch,OBSERVER).state(); + } + } + return new Evaluation(null,invocations,instructions); + } +} diff --git a/src/main/java/dev/samhb/interleave/bytecode/BytecodeExplorer.java b/src/main/java/dev/samhb/interleave/bytecode/BytecodeExplorer.java new file mode 100644 index 0000000..0362f12 --- /dev/null +++ b/src/main/java/dev/samhb/interleave/bytecode/BytecodeExplorer.java @@ -0,0 +1,280 @@ +/** Internal exact DFS over complete bytecode states; source Configuration and its forward PCs stay unchanged. */ +package dev.samhb.interleave.bytecode; + +import java.util.*; +import static dev.samhb.interleave.bytecode.BytecodeState.*; + +/** Exact full-payload enumeration with bounded checker storage and concrete internal witnesses. */ +final class BytecodeExplorer { + /** Internal terminal classifications; public verdict/evidence adapters belong to94C. */ + enum Kind { + /** Every actor returned normally. */ COMPLETED, + /** All remaining actors wait on owned monitors, with no pending event. */ DEADLOCK, + /** A selected uncaught actor fault ended the prefix. */ UNCAUGHT_EXCEPTION, + /** A modeled resource cutoff ended the prefix. */ CUTOFF, + /** A declared pure check returned false. */ CHECK_FALSE, + /** A pure observer fault prevents an absence claim. */ OBSERVER_ERROR, + /** A pure observer exhausted its independent allowance. */ OBSERVER_LIMIT, + /** An external checker budget or cancellation stopped traversal. */ INTERRUPTED + } + + /** Explicit checker budgets, separate from modeled instruction/allocation limits. + * @param maxStates maximum admitted exact states + * @param maxKeyBytes maximum retained canonical payload bytes, excluding JVM overhead + */ + record Budget(long maxStates,long maxKeyBytes) { + /** Rejects negative budgets; zero requests an immediate honest interruption. */ + Budget {if(maxStates<0 || maxKeyBytes<0)throw new IllegalArgumentException("Negative search budget");} + } + + /** A typed model field cell; NULL as container identifies a static slot. + * @param object owning object or static-table sentinel + * @param field declared field identity + */ + record Cell(Ref object,BytecodeProgram.FieldId field) implements Comparable { + /** Orders field identities without relying on diagnostic text. + * @param other another shared cell + * @return deterministic order */ + @Override public int compareTo(Cell other) { + int order=object.compareTo(other.object);return order==0 ? field.compareTo(other.field) : order; + } + } + + /** Concrete monitor wait relationship at a deadlock. + * @param actor waiting actor + * @param owner current owning actor + * @param monitor permanent monitor identity + * @param depth owning reentrant depth + */ + record Wait(int actor,int owner,Ref monitor,int depth) {} + + /** Normalized relevant outcome, excluding schedules and intermediate local snapshots. + * @param kind terminal classification + * @param actor failing/cutoff actor, or -1 + * @param fault original interpreted failure, if present + * @param cutoff omitted modeled operation, if present + * @param interruption external checker reason, otherwise null + * @param waits concrete deadlock relationships + * @param shared relevant shared field observations + * @param observer failed pure check, otherwise null + */ + record Outcome(Kind kind,int actor,Fault fault,Cutoff cutoff,String interruption,List waits,Map shared,BytecodeChecks.Failure observer) { + /** Freezes observable payload containers. */ + Outcome {waits=List.copyOf(waits);shared=Collections.unmodifiableMap(new TreeMap<>(shared));} + } + + /** A selected scheduling transition with actual opcode/event positions. + * @param actor original actor identity + * @param executed committed opcode/event locations + */ + record Selection(int actor,List executed) { + /** Freezes transition metadata. */ + Selection {executed=List.copyOf(executed);} + } + + /** A concrete internal witness retained once per normalized outcome. + * @param outcome normalized terminal observation + * @param state isolated final/prefix state + * @param schedule concrete selected transition sequence + */ + record Witness(Outcome outcome,BytecodeState state,List schedule) { + /** Owns state and freezes the schedule, independently of the search stack. */ + Witness {state=state.copy();schedule=List.copyOf(schedule);} + } + + /** Actual search and canonical-encoding work; retained payload bytes are not JVM retained memory. + * @param states admitted unique states + * @param transitions selected scheduling transitions + * @param opcodes executed opcodes + * @param instructions charged instruction/intrinsic work + * @param encodingCalls canonical encoding invocations + * @param encodingBytes generated canonical bytes, including duplicates + * @param encodingNanos measured time in canonical encoding + * @param retainedKeyBytes live stored canonical payload bytes + * @param checkInvocations attempted pure checks + * @param checkInstructions separate observer instruction work + * @param sharing actual root/publication traversal work + */ + record Metrics(long states,long transitions,long opcodes,long instructions,long encodingCalls, + long encodingBytes,long encodingNanos,long retainedKeyBytes,long checkInvocations,long checkInstructions,BytecodeSharing.Work sharing) {} + + /** Run result with original incompleteness preserved alongside positive witnesses. + * @param witnesses one concrete schedule per normalized outcome + * @param traversalComplete whether all bounded scheduling alternatives were enumerated + * @param metrics actual run counters + */ + record Result(List witnesses,boolean traversalComplete,Metrics metrics) { + /** Freezes the result list. */ + Result {witnesses=List.copyOf(witnesses);} + /** Distinguishes bounded model/observer limits from exhaustive absence within the profile. + * @return whether traversal finished without any incomplete prefix */ + boolean exhaustive() { + return traversalComplete && witnesses.stream().noneMatch(w->w.outcome.kind==Kind.CUTOFF || w.outcome.kind==Kind.INTERRUPTED + || w.outcome.kind==Kind.OBSERVER_ERROR || w.outcome.kind==Kind.OBSERVER_LIMIT); + } + } + + /** Persistent path node avoids copying complete schedules at every search state. + * @param previous selected prefix + * @param selection last selected transition + */ + private record Path(Path previous,Selection selection) {} + + /** An iterative DFS stack frame; its target snapshot is never mutated by successors. */ + private static final class Frame { + /** Owned committed state. */ final BytecodeState state; + /** Concrete path to this state. */ final Path path; + /** Pure enabled original actor identities. */ final List choices; + /** Next untried actor choice. */ int next; + /** Creates one stack frame. + * @param state committed state + * @param path concrete prefix + * @param choices enabled choices */ + Frame(BytecodeState state,Path path,List choices){this.state=state;this.path=path;this.choices=choices;} + } + + /** Immutable validated artifact. */ private final BytecodeProgram program; + /** 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<>(); + /** Concrete outcomes found by this run. */ private final Map witnesses=new LinkedHashMap<>(); + /** Current admitted state count. */ private long states; + /** Selected transitions. */ private long transitions; + /** Executed opcodes. */ private long opcodes; + /** Executed instruction/intrinsic work. */ private long instructions; + /** Encoding calls. */ private long encodingCalls; + /** Encoded bytes. */ private long encodingBytes; + /** Time spent in encoding. */ private long encodingNanos; + /** Retained canonical payload bytes. */ private long keyBytes; + /** False only for an external checker stop. */ private boolean traversalComplete; + /** Pure observer invocations. */ private long checkInvocations; + /** Separate observer work. */ private long checkInstructions; + /** Actual sharing traversals, never part of modeled fuel. */ private BytecodeSharing.Work sharing; + + /** Creates an internal search owner; independent instances may share the immutable program. + * @param program validated model + * @param mode scheduling granularity + */ + BytecodeExplorer(BytecodeProgram program,BytecodeScheduler.Mode mode) { + this.program=Objects.requireNonNull(program);scheduler=new BytecodeScheduler(program,mode); + } + + /** Runs exact DFS with a64MiB canonical-payload safety budget. + * @param maxStates admitted state budget + * @return complete or honestly interrupted run */ + Result explore(long maxStates){return explore(new Budget(maxStates,64L*1024*1024));} + + /** Enumerates bounded executions without using the host call stack for DFS. + * Sequential reuse resets search storage; concurrent runs use independent explorer instances. + * @param budget checker budgets, distinct from modeled limits + * @return normalized outcomes and real witnesses */ + 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; + 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;} + 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 next=visit(transition.state(),path,budget);if(next!=null)stack.push(next); + } + return new Result(new ArrayList<>(witnesses.values()),traversalComplete, + new Metrics(states,transitions,opcodes,instructions,encodingCalls,encodingBytes,encodingNanos,keyBytes,checkInvocations,checkInstructions,sharing)); + } + + /** Admits one exact state, then classifies its terminal result or enabled choices. + * @param state owned successor + * @param path selected prefix + * @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;} + 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; + 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; + } + + /** Records a checker stop without inventing a modeled resource cutoff. + * @param state last committed state + * @param path real prefix + * @param reason external checker cause */ + private void interrupt(BytecodeState state,Path path,String reason) { + traversalComplete=false;record(state,path,Kind.INTERRUPTED,-1,null,null,reason,List.of(),null); + } + + /** Retains one concrete witness per normalized observable outcome. + * @param state committed terminal state + * @param path selected prefix + * @param kind terminal classification + * @param actor terminal actor or -1 + * @param fault original interpreted fault + * @param cutoff omitted modeled operation + * @param interruption external 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); + 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)); + } +} diff --git a/src/main/java/dev/samhb/interleave/bytecode/BytecodeScheduler.java b/src/main/java/dev/samhb/interleave/bytecode/BytecodeScheduler.java new file mode 100644 index 0000000..e31da61 --- /dev/null +++ b/src/main/java/dev/samhb/interleave/bytecode/BytecodeScheduler.java @@ -0,0 +1,93 @@ +/** Internal actor selection over real bytecode continuations, independent of source forward PCs. */ +package dev.samhb.interleave.bytecode; + +import java.lang.classfile.Opcode; +import java.lang.classfile.instruction.FieldInstruction; +import java.util.*; + +/** Pure choices and isolated selected transitions using the single opcode executor. */ +final class BytecodeScheduler { + /** Supported internal scheduling granularities. */ + enum Mode { + /** One opcode or explicit zero-work event per selection. */ REFERENCE, + /** At most one observable operation plus justified local work. */ BATCHED + } + + /** 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 + */ + record Executed(BytecodeLocation location,Opcode opcode) {} + + /** An owned scheduling result; no source step ordinals are manufactured. + * @param state isolated successor + * @param kind executed/pending/blocked/terminal result + * @param executed committed opcode/event locations + * @param instructions charged actor work, distinct from scheduling selections + * @param sharing actual reference-publication traversal work + */ + record Transition(BytecodeState state,OpcodeExecutor.Kind kind,List executed,int instructions,BytecodeSharing.Work sharing) { + /** Freezes the transition's location list. */ + Transition {executed=List.copyOf(executed);} + } + + /** Immutable validated model. */ + private final BytecodeProgram program; + /** Selected production granularity. */ + private final Mode mode; + + /** Creates an internal scheduler with no mutable target state. + * @param program validated model + * @param mode scheduling granularity + */ + BytecodeScheduler(BytecodeProgram program,Mode mode) { + this.program=Objects.requireNonNull(program);this.mode=Objects.requireNonNull(mode); + } + + /** Enumerates enabled original actor identities without committing probes. + * @param state committed state + * @return deterministic enabled choices, including selectable pending terminal events + */ + List choices(BytecodeState state) { + var choices=new ArrayList(); + for(int actor=0;actor=program.actors.size())throw new IllegalArgumentException("Unknown actor"); + var initial=OpcodeExecutor.probe(program,parent,actor); + if(initial.availability()!=OpcodeExecutor.Availability.READY) { + var result=OpcodeExecutor.step(program,parent,actor); + return new Transition(result.state(),result.kind(),List.of(),0,BytecodeSharing.Work.NONE); + } + var state=parent;var executed=new ArrayList();boolean observable=false; + int instructions=0;var sharing=BytecodeSharing.Work.NONE;var kind=OpcodeExecutor.Kind.ADVANCED; + while(true) { + if(Thread.currentThread().isInterrupted())throw new java.util.concurrent.CancellationException("Bytecode batch cancelled"); + var probe=OpcodeExecutor.probe(program,state,actor); + if(probe.availability()!=OpcodeExecutor.Availability.READY || (observable && probe.observable()))break; + var before=state.executions.get(actor);boolean publication=false; + if(probe.opcode()==Opcode.PUTFIELD || probe.opcode()==Opcode.PUTSTATIC) { + var frame=before.frames.getLast();var field=(FieldInstruction)frame.method.ops.get(frame.bci).instruction(); + publication=field.type().stringValue().startsWith("L"); + } + 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())); + 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. + if(mode==Mode.REFERENCE || kind!=OpcodeExecutor.Kind.ADVANCED + || state.executions.get(actor).phase!=BytecodeState.Phase.RUNNING)break; + } + return new Transition(state,kind,executed,instructions,sharing); + } +} diff --git a/src/main/java/dev/samhb/interleave/bytecode/BytecodeSharing.java b/src/main/java/dev/samhb/interleave/bytecode/BytecodeSharing.java new file mode 100644 index 0000000..38e9162 --- /dev/null +++ b/src/main/java/dev/samhb/interleave/bytecode/BytecodeSharing.java @@ -0,0 +1,68 @@ +/** Conservative transitive sharing for the setup-only heap, with actual traversal instrumentation. */ +package dev.samhb.interleave.bytecode; + +import java.util.*; +import static dev.samhb.interleave.bytecode.BytecodeState.*; + +/** Never establishes actor-exclusive heap ownership in94B; unknown and historical sharing stay shared. */ +final class BytecodeSharing { + /** Prevents construction of the stateless sharing traversal. */ + private BytecodeSharing() {} + + /** Actual sharedness work, outside the model's canonical state and resource counters. + * @param traversals refresh operations + * @param objects distinct heap objects processed across refreshes + * @param edges nonnull reference-field edges visited from roots + * @param promotions false-to-true historical sharing changes + */ + record Work(long traversals,long objects,long edges,long promotions) { + /** Empty work for transitions which do not change reference reachability. */ + static final Work NONE=new Work(0,0,0,0); + /** Combines actual work without changing target state. + * @param other additional traversal work + * @return summed counters */ + Work plus(Work other){return new Work(traversals+other.traversals,objects+other.objects,edges+other.edges,promotions+other.promotions);} + } + + /** Traverses fixture/static/actor roots and conservatively promotes unresolved ownership. + * The initial profile has setup-only objects; no heap access is batched as actor-local. + * @param state owned scratch, never an unselected committed parent + * @return actual object/edge work and irreversible promotions + */ + static Work refresh(BytecodeState state) { + var queue=new ArrayDeque();queue.add(FIXTURE); + for(var value:state.statics.values())enqueue(queue,value); + for(var entry:state.executions.entrySet()) { + if(entry.getKey()<0)continue; + var execution=entry.getValue();enqueue(queue,execution.returned); + for(var frame:execution.frames) { + for(var value:frame.locals.values())enqueue(queue,value); + for(var value:frame.stack)enqueue(queue,value); + enqueue(queue,frame.methodMonitor); + } + } + var seen=new HashSet();long objects=0,edges=0,promotions=0; + while(!queue.isEmpty()) { + var reference=queue.removeFirst();if(!seen.add(reference))continue; + var object=state.heap.get(reference);if(object==null)continue; + objects++;if(!object.shared){object.shared=true;promotions++;} + for(var value:object.fields.values()) { + if(value instanceof Ref target && !target.equals(NULL)){edges++;queue.addLast(target);} + } + } + // shortcut:94B cannot allocate actor-local objects; unresolved setup ownership remains shared until95 analysis. + for(var entry:state.heap.entrySet()) { + if(seen.add(entry.getKey())) { + objects++;if(!entry.getValue().shared){entry.getValue().shared=true;promotions++;} + } + } + return new Work(1,objects,edges,promotions); + } + + /** Adds actual reference roots, excluding null and non-reference VM metadata. + * @param queue pending roots + * @param value target slot or pending value */ + private static void enqueue(ArrayDeque queue,Value value) { + if(value instanceof Ref reference && !reference.equals(NULL))queue.addLast(reference); + } +} diff --git a/src/main/java/dev/samhb/interleave/bytecode/BytecodeState.java b/src/main/java/dev/samhb/interleave/bytecode/BytecodeState.java index 5016539..f8d17dc 100644 --- a/src/main/java/dev/samhb/interleave/bytecode/BytecodeState.java +++ b/src/main/java/dev/samhb/interleave/bytecode/BytecodeState.java @@ -19,6 +19,8 @@ final class BytecodeState { * Setup namespace also identifies its resource owner. */ static final int SETUP = -1; + /** Private observer execution owner; it never appears in committed actor state. */ + static final int OBSERVER = -4; /** * Null is a distinct tagged reference, never an integer zero. */ diff --git a/src/main/java/dev/samhb/interleave/bytecode/OpcodeExecutor.java b/src/main/java/dev/samhb/interleave/bytecode/OpcodeExecutor.java index 6195a6f..eb37d8b 100644 --- a/src/main/java/dev/samhb/interleave/bytecode/OpcodeExecutor.java +++ b/src/main/java/dev/samhb/interleave/bytecode/OpcodeExecutor.java @@ -40,6 +40,76 @@ enum Kind { * @param kind transition/event classification */ record Result(BytecodeState state,Kind kind) {} + /** Pure availability classification for one actor's next opcode or implicit event. */ + enum Availability { + /** A scheduler selection can commit an opcode or pending event. */ READY, + /** A sufficiently fueled monitor acquisition is disabled. */ BLOCKED, + /** The actor or its entire prefix has ended. */ DONE + } + + /** Describes a choice without consuming fuel or modifying target state. + * @param availability enabled, disabled or ended + * @param location actual next opcode or causing event position + * @param opcode next executed opcode, null for an implicit event or fuel cutoff + * @param monitor acquisition identity, otherwise null + * @param observable whether batching must preserve this scheduling point + * @param exhausted whether selection will omit the next opcode for insufficient fuel + */ + record Probe(Availability availability,BytecodeLocation location,Opcode opcode,Ref monitor, + boolean observable,boolean exhausted) {} + + /** Classifies the next operation, preserving fuel-before-blocking priority. + * @param program validated artifact + * @param state committed state, never modified + * @param owner selected execution owner + * @return pure next-operation classification + */ + static Probe probe(BytecodeProgram program,BytecodeState state,int owner) { + var execution=state.executions.get(owner); + if(state.executions.values().stream().anyMatch(e->e.phase==Phase.FAILED || e.phase==Phase.CUTOFF) + || execution.phase==Phase.TERMINATED) + return new Probe(Availability.DONE,execution.eventLocation,null,null,true,false); + if(execution.phase!=Phase.RUNNING) { + var location=execution.frames.isEmpty() ? execution.eventLocation + : execution.frames.getLast().method.location(execution.frames.getLast().bci); + return new Probe(Availability.READY,location,null,null,true,false); + } + var frame=execution.frames.getLast();var op=frame.method.ops.get(frame.bci);var location=frame.method.location(frame.bci); + if(work(op)>limit(program,owner)-execution.instructions) + return new Probe(Availability.READY,location,null,null,true,true); + if(!frame.entered) { + Ref monitor=(frame.method.flags & ACC_STATIC)!=0 ? classMonitor(frame.method.id.owner(),program) : (Ref)frame.locals.get(0); + return new Probe(busy(state,monitor,owner) ? Availability.BLOCKED : Availability.READY,location,null,monitor,true,false); + } + var code=op.instruction().opcode();Ref monitor=null; + if(code==Opcode.MONITORENTER) { + monitor=(Ref)frame.stack.getLast(); + if(!monitor.equals(NULL) && busy(state,monitor,owner)) + return new Probe(Availability.BLOCKED,location,code,monitor,true,false); + } + boolean observable=op.instruction() instanceof FieldInstruction || op.instruction() instanceof ReturnInstruction + || code==Opcode.MONITORENTER || code==Opcode.MONITOREXIT || code==Opcode.ATHROW; + return new Probe(Availability.READY,location,code,monitor,observable,false); + } + + /** Computes one admitted opcode's complete intrinsic work before execution. + * @param op decoded instruction + * @return opcode plus fixed intrinsic fuel + */ + private static int work(BytecodeMethod.Op op) { + return op.instruction() instanceof InvokeInstruction call && call.owner().asInternalName().equals("java/lang/Object") ? 2 : 1; + } + + /** Selects the independent setup, observer or actor fuel allowance. + * @param program immutable limits + * @param owner execution namespace + * @return maximum instruction/intrinsic work + */ + private static int limit(BytecodeProgram program,int owner) { + return owner==SETUP ? program.limits.setupInstructions() + : owner==OBSERVER ? program.limits.checkInstructions() : program.limits.actorInstructions(); + } + /** * Internal control transfer for a modeled VM fault, not a host throwable from target execution. */ @@ -68,7 +138,9 @@ static Result step(BytecodeProgram program,BytecodeState parent,int owner) { if (selected!=Phase.FAILED && selected!=Phase.CUTOFF && parent.executions.values().stream() .anyMatch(e->e.phase==Phase.FAILED || e.phase==Phase.CUTOFF)) throw new IllegalStateException("Execution prefix already ended"); + var choice=probe(program,parent,owner); BytecodeState state=parent.copy(); Execution execution=state.executions.get(owner); + if(choice.availability()==Availability.BLOCKED)return new Result(state,Kind.BLOCKED); switch(execution.phase) { case TERMINATED, FAILED, CUTOFF -> { return new Result(state,Kind.TERMINAL); } case TERMINATION_PENDING -> { execution.phase=Phase.TERMINATED; return new Result(state,Kind.TERMINAL); } @@ -79,20 +151,14 @@ static Result step(BytecodeProgram program,BytecodeState parent,int owner) { case RUNNING -> { /* Execute only after pure budget/enabledness decisions below. */ } } BytecodeFrame frame=execution.frames.getLast(); BytecodeMethod.Op op=frame.method.ops.get(frame.bci); - int required=op.instruction() instanceof InvokeInstruction call && call.owner().asInternalName().equals("java/lang/Object") ? 2 : 1; - int limit=owner==SETUP ? program.limits.setupInstructions() : program.limits.actorInstructions(); - if(required>limit-execution.instructions) { + int required=work(op), limit=limit(program,owner); + if(choice.exhausted()) { cutoff(execution,frame,"INSTRUCTION_FUEL",limit,required,limit-execution.instructions); return new Result(state,Kind.PENDING); } if(!frame.entered) { - Ref monitor=(frame.method.flags & ACC_STATIC)!=0 ? classMonitor(frame.method.id.owner(),program) : (Ref)frame.locals.get(0); - if(!acquire(state,monitor,owner)) return new Result(state,Kind.BLOCKED); - frame.methodMonitor=monitor; frame.entered=true; return new Result(state,Kind.ADVANCED); - } - if(op.instruction().opcode()==Opcode.MONITORENTER) { - var monitor=(Ref)frame.stack.getLast(); - if(!monitor.equals(NULL) && busy(state,monitor,owner)) return new Result(state,Kind.BLOCKED); + if(!acquire(state,choice.monitor(),owner))return new Result(state,Kind.BLOCKED); + frame.methodMonitor=choice.monitor();frame.entered=true;return new Result(state,Kind.ADVANCED); } execution.instructions+=required; try { diff --git a/src/mutationHarness/java/dev/samhb/mutationharness/BytecodeWorkBudget.java b/src/mutationHarness/java/dev/samhb/mutationharness/BytecodeWorkBudget.java new file mode 100644 index 0000000..bd83b84 --- /dev/null +++ b/src/mutationHarness/java/dev/samhb/mutationharness/BytecodeWorkBudget.java @@ -0,0 +1,120 @@ +/** PIT-only finite-graph and observer-event assertions, derived from model bounds rather than elapsed time. */ +package dev.samhb.mutationharness; + +import java.lang.classfile.*; +import java.lang.classfile.instruction.InvokeInstruction; +import java.lang.constant.*; +import java.lang.instrument.*; +import java.security.ProtectionDomain; +import static java.lang.constant.ConstantDescs.*; + +/** Instruments host checker loops only; target model bytecode is never loaded or executed on the host. */ +final class BytecodeWorkBudget { + /** Package containing the two owned checker loops. */ + private static final String PACKAGE="dev/samhb/interleave/bytecode/"; + /** Exact iterative search entry. */ + private static final String SEARCH="(L"+PACKAGE+"BytecodeExplorer$Budget;)L"+PACKAGE+"BytecodeExplorer$Result;"; + /** Exact pure observer entry. */ + private static final String CHECK="(L"+PACKAGE+"BytecodeProgram;L"+PACKAGE+"BytecodeState;Z)L"+PACKAGE+"BytecodeChecks$Evaluation;"; + /** Assertion has no runtime dependency on this agent. */ + private static final ClassDesc ASSERTION=ClassDesc.of("java.lang.AssertionError"); + + /** Prevents construction of this test-only transformer utility. */ + private BytecodeWorkBudget() {} + + /** Adds the two narrow transformers to the established PIT agent. + * @param instrumentation host instrumentation service */ + static void install(Instrumentation instrumentation){instrumentation.addTransformer(new Transformer(),true);} + + /** Adds invocation-local work bounds, rejecting initial binding or checkpoint drift. + * Search expands at mostS frames, with at most8 selections and1 pop per frame:9S loop visits. + * A pure observer has at mostN opcodes, N helper returns and2 final/cutoff views:2N+2 visits. + * @param bytes real original or singly mutated checker definition + * @param redefinition whether PIT replaces a previously validated definition + * @param loader host checker loader for stack-map resolution, never the model classpath + * @return verified-shape instrumented definition + * @throws IllegalArgumentException for binding drift */ + static byte[] instrument(byte[] bytes,boolean redefinition,ClassLoader loader) { + var file=ClassFile.of(ClassFile.ClassHierarchyResolverOption.of(ClassHierarchyResolver.ofClassLoading(loader))); + var model=file.parse(bytes);String name=model.thisClass().asInternalName();boolean search=name.equals(PACKAGE+"BytecodeExplorer"); + if(!search && !name.equals(PACKAGE+"BytecodeChecks"))throw new IllegalArgumentException("Unexpected bytecode checker class"); + if(model.methods().stream().filter(method->matches(method,search)).count()!=1)throw new IllegalArgumentException("Unexpected bytecode checker method"); + int[] checkpoints={0},resets={0}; + byte[] result=file.transformClass(model,ClassTransform.transformingMethodBodies(method->matches(method,search),CodeTransform.ofStateful(()->new CodeTransform(){ + /** Invocation-local counter; observer initialization resets it for each declaration. */ + private int remaining; + /** Initializes a saturated graph bound or an empty observer allowance pending root start. + * @param code destination body */ + @Override public void atStart(CodeBuilder code) { + remaining=code.allocateLocal(search ? TypeKind.LONG : TypeKind.INT); + if(search) { + var budget=ClassDesc.of((PACKAGE+"BytecodeExplorer$Budget").replace('/','.')); + code.aload(1).invokevirtual(budget,"maxStates",MethodTypeDesc.of(CD_long)).lstore(remaining); + code.lload(remaining).ldc(Long.MAX_VALUE/9).lcmp().ifThenElse(Opcode.IFGT, + high->high.ldc(Long.MAX_VALUE).lstore(remaining), + bounded->bounded.lload(remaining).ldc(9L).lmul().lstore(remaining)); + } else code.iconst_0().istore(remaining); + } + /** Charges independently derived loop work and resets each fresh observer invocation. + * @param code destination body + * @param element original or PIT-mutated instruction */ + @Override public void accept(CodeBuilder code,CodeElement element) { + boolean reset=false; + if(element instanceof InvokeInstruction call) { + boolean checkpoint=search ? call.owner().asInternalName().equals("java/util/ArrayDeque") + && call.name().equalsString("peek") && call.type().equalsString("()Ljava/lang/Object;") + : call.owner().asInternalName().equals("java/lang/Thread") && call.name().equalsString("currentThread") + && call.type().equalsString("()Ljava/lang/Thread;"); + if(checkpoint) { + checkpoints[0]++; + if(search)code.lload(remaining).lconst_1().lsub().lstore(remaining).lload(remaining).lconst_0().lcmp(); + else code.iinc(remaining,-1).iload(remaining); + code.ifThen(Opcode.IFLT,bad->bad.new_(ASSERTION).dup().ldc("Bytecode logical progress bound exceeded") + .invokespecial(ASSERTION,INIT_NAME,MethodTypeDesc.of(CD_void,CD_Object)).athrow()); + } + reset=!search && call.owner().asInternalName().equals(PACKAGE+"BytecodeState") && call.name().equalsString("start") + && call.type().equalsString("(IL"+PACKAGE+"BytecodeMethod;Ljava/util/List;)V"); + } + code.with(element); + if(reset) { + resets[0]++;var program=ClassDesc.of((PACKAGE+"BytecodeProgram").replace('/','.')); + var limits=ClassDesc.of((PACKAGE+"BytecodeLimits").replace('/','.')); + code.aload(0).getfield(program,"limits",limits).invokevirtual(limits,"checkInstructions",MethodTypeDesc.of(CD_int)) + .iconst_2().imul().iconst_2().iadd().istore(remaining); + } + } + }))); + // One call-removal mutation can omit a checkpoint/reset; its remaining original guards still run. + if((checkpoints[0]!=1 && !(redefinition && checkpoints[0]==0)) + || (!search && resets[0]!=1 && !(redefinition && resets[0]==0)))throw new IllegalArgumentException("Unexpected bytecode progress checkpoint shape"); + return result; + } + + /** Matches the exact static/instance method and local-slot layout used by the assertions. + * @param method candidate method + * @param search search or observer definition + * @return whether the method owns the expected loop */ + private static boolean matches(MethodModel method,boolean search) { + return method.methodName().equalsString(search ? "explore" : "evaluate") && method.methodType().equalsString(search ? SEARCH : CHECK) + && method.flags().has(java.lang.reflect.AccessFlag.STATIC)!=search; + } + + /** Filters unrelated classes and fails visibly if the owned host-checker shape drifts. */ + private static final class Transformer implements ClassFileTransformer { + /** Restricts construction to this utility. */ + private Transformer() {} + /** Handles original definitions and PIT redefinitions without touching model application classes. + * @param module host module + * @param loader checker loader + * @param name checker internal name + * @param redefining existing definition, otherwise null + * @param domain protection domain + * @param bytes incoming definition + * @return transformed bytes, null for unrelated classes, invalid bytes on binding failure */ + @Override public byte[] transform(Module module,ClassLoader loader,String name,Class redefining,ProtectionDomain domain,byte[] bytes) { + if(!(PACKAGE+"BytecodeExplorer").equals(name) && !(PACKAGE+"BytecodeChecks").equals(name))return null; + try {return instrument(bytes,redefining!=null,loader);} + catch(RuntimeException failure){System.err.println("Bytecode mutation harness rejected unexpected shape");return new byte[]{0};} + } + } +} diff --git a/src/mutationHarness/java/dev/samhb/mutationharness/SelectorBudgetAgent.java b/src/mutationHarness/java/dev/samhb/mutationharness/SelectorBudgetAgent.java index 724e0f4..cb844cb 100644 --- a/src/mutationHarness/java/dev/samhb/mutationharness/SelectorBudgetAgent.java +++ b/src/mutationHarness/java/dev/samhb/mutationharness/SelectorBudgetAgent.java @@ -30,6 +30,7 @@ public static void premain(String arguments, Instrumentation instrumentation) { instrumentation.addTransformer(new Transformer(), true); CompilerWorkBudget.install(instrumentation); ParserWorkBudget.install(instrumentation); + BytecodeWorkBudget.install(instrumentation); } /** Instruments one expected selector definition with an invocation-local expansion counter. @@ -96,6 +97,8 @@ private static boolean component(MethodModel method) { /** Keeps unrelated classes untouched and rejects selector shape drift instead of omitting the check. */ private static final class Transformer implements ClassFileTransformer { + /** Restricts construction to the owning agent. */ + private Transformer() {} /** Rewrites the selector on initial definition and PIT redefinition. * @param module defining module * @param loader defining class loader diff --git a/src/test/java/dev/samhb/interleave/bytecode/BytecodeBatchingOracleTest.java b/src/test/java/dev/samhb/interleave/bytecode/BytecodeBatchingOracleTest.java new file mode 100644 index 0000000..00dd3eb --- /dev/null +++ b/src/test/java/dev/samhb/interleave/bytecode/BytecodeBatchingOracleTest.java @@ -0,0 +1,158 @@ +/** Instruction-reference/batched outcomes; an independent opcode enumerator supplements these targeted cases. */ +package dev.samhb.interleave.bytecode; + +import java.nio.file.Path; +import java.util.*; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import static org.junit.jupiter.api.Assertions.*; + +class BytecodeBatchingOracleTest { + /** Real interpreter batching preserves lost-update detection while reducing selected transitions. + * @param directory compiler workspace + * @throws Exception for fixture failures */ + @Test void batchedLostUpdateMatchesReference(@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=BytecodeLoader.load(classes,"Fixture",BytecodeLimits.defaults()); + var reference=new BytecodeExplorer(program,BytecodeScheduler.Mode.REFERENCE).explore(100000); + var batched=new BytecodeExplorer(program,BytecodeScheduler.Mode.BATCHED).explore(100000); + assertTrue(reference.traversalComplete());assertTrue(batched.traversalComplete()); + assertEquals(outcomes(reference),outcomes(batched)); + assertEquals(Set.of(BytecodeExplorer.Kind.COMPLETED,BytecodeExplorer.Kind.CHECK_FALSE), + batched.witnesses().stream().map(w->w.outcome().kind()).collect(java.util.stream.Collectors.toSet())); + assertTrue(batched.metrics().transitions()(); + for(var witness:result.witnesses())observations.put(((BytecodeState.Int)witness.outcome().shared().get(cell)).value(),witness.outcome().kind()); + assertEquals(Map.of(1,BytecodeExplorer.Kind.CHECK_FALSE,2,BytecodeExplorer.Kind.COMPLETED),observations); + } + } + + /** Independent opcode enumeration covers terminal competition and bounded loops in both modes. + * @param directory compiler workspace + * @throws Exception for fixture failures */ + @Test void adversarialOutcomesMatchIndependentInstructions(@TempDir Path directory) throws Exception { + var cases=List.of( + "@Actor(id=0)public void first(){while(true){}} @Actor(id=1)public void second(){x=1;} @Check(when=Check.When.ALWAYS)public boolean valid(){return x==0;}", + "@Actor(id=0)public void first(){int a=1;int b=a+1;int c=1/(b-2);} @Actor(id=1)public void second(){x=1;}", + "@Actor(id=0)public void first(){int a=1;int b=a+1;int c=b+1;} @Actor(id=1)public void second(){x=1;} @Check(when=Check.When.ALWAYS)public boolean valid(){return x==0;}", + "@Actor(id=0)public void first(){if(x==0){int a=1;int b=a+1;x=b;}else{x=3;}} @Actor(id=1)public void second(){x=1;}", + "@Actor(id=0)public void first(){x++;} @Actor(id=1)public void second(){x++;} @Check public boolean valid(){return x==2;}", + "@Actor(id=0)public void first(){x=1;} @Actor(id=1)public void second(){x=2;} @Check(when=Check.When.ALWAYS)public boolean valid(){return 1/(x-1)>0;}", + "@Actor(id=0)public void first(){synchronized(this){synchronized(this){x=1/zero;}}} @Actor(id=1)public synchronized void second(){x=1;}", + "@Actor(id=0)public void first(){} @Actor(id=1)public void second(){}" + ); + for(int i=0;iw.outcome().kind()).collect(java.util.stream.Collectors.toSet()); + if(i==0 || i==2)assertEquals(Set.of(BytecodeExplorer.Kind.CUTOFF,BytecodeExplorer.Kind.CHECK_FALSE),kinds); + if(i==1 || i==6)assertEquals(Set.of(BytecodeExplorer.Kind.UNCAUGHT_EXCEPTION),kinds); + // The faulting actor releases its depths; a competitor may acquire before failure delivery. + if(i==6)for(var witness:result.witnesses())assertTrue(witness.state().heap.values().stream().noneMatch(object->object.monitorOwner==0)); + if(i==7)assertEquals(Set.of(BytecodeExplorer.Kind.COMPLETED),kinds); + } + } + + /** Saved deterministic seed generates tiny programs; failures shrink by deleting actor statements. + * @param directory compiler workspace + * @throws Exception for fixture failures */ + @Test void generatedProgramsMatchIndependentInstructions(@TempDir Path directory) throws Exception { + var random=new Random(94002L);var choices=List.of("x++;","x=1;","x=2;","if(x==0)x=3;","int local=1;local++;"); + for(int sample=0;sample<8;sample++) { + var actors=new ArrayList>(); + for(int actor=0;actor<2;actor++) { + var statements=new ArrayList();for(int operation=0;operation<2;operation++)statements.add(choices.get(random.nextInt(choices.size()))); + actors.add(statements); + } + // Each statement has its own lexical block, so generated local declarations never collide. + if(!matchesGenerated(directory.resolve("seed94002-case"+sample),actors)) { + int attempt=0; + for(int actor=0;actor<2;actor++)for(int index=actors.get(actor).size()-1;index>=0;index--) { + String removed=actors.get(actor).remove(index); + if(matchesGenerated(directory.resolve("shrink"+sample+"-"+attempt++),actors))actors.get(actor).add(index,removed); + } + fail("Independent outcome mismatch; seed94002 case"+sample+" minimized actors="+actors); + } + } + } + + /** Builds a generated fixture and compares outcomes, allowing deletion-based failure shrinking. + * @param directory isolated compiler workspace + * @param actors two ordered statement lists + * @return whether independent/reference/batched observations agree + * @throws Exception for fixture failures */ + private static boolean matchesGenerated(Path directory,List> actors) throws Exception { + var source=new StringBuilder("@Model public class Fixture {public int x;public Fixture(){}"); + for(int actor=0;actor<2;actor++) { + source.append("@Actor(id=").append(actor).append(")public void actor").append(actor).append("(){"); + for(String statement:actors.get(actor))source.append('{').append(statement).append('}');source.append('}'); + } + source.append('}');var classes=BytecodeFixtures.compile(directory,26,source.toString()); + var program=BytecodeLoader.load(classes,"Fixture",new BytecodeLimits(16,128,8192,32,64,256,4096,128,8192,1024)); + var expected=BytecodeInstructionOracle.enumerate(program); + for(var mode:BytecodeScheduler.Mode.values()) { + var result=new BytecodeExplorer(program,mode).explore(100000); + if(!result.traversalComplete() || !expected.equals(independentProjection(result)))return false; + } + return true; + } + + /** Compares both production granularities with the independently scheduled/encoded reference. + * @param program actual interpreter fixture */ + private static void compare(BytecodeProgram program) { + var expected=BytecodeInstructionOracle.enumerate(program); + for(var mode:BytecodeScheduler.Mode.values()) { + var result=new BytecodeExplorer(program,mode).explore(100000);assertTrue(result.traversalComplete()); + assertEquals(expected,independentProjection(result),mode.toString()); + } + } + + /** Projects public-to-this-package results into the oracle's observation vocabulary. + * This reads existing evidence and does not build the reference's outcomes or state keys. + * @param result actual search + * @return independently comparable observations */ + static Set independentProjection(BytecodeExplorer.Result result) { + var observations=new HashSet(); + for(var witness:result.witnesses()) { + var outcome=witness.outcome();var fields=new TreeMap(); + outcome.shared().forEach((cell,value)->fields.put(BytecodeInstructionOracle.cellKey(cell.object(),cell.field()),value)); + var waits=outcome.waits().stream().map(wait->BytecodeInstructionOracle.waitKey(wait.actor(),wait.owner(),wait.monitor(),wait.depth())).toList(); + var check=outcome.observer();String observer=check==null ? null : BytecodeInstructionOracle.checkKey(check.kind().toString(),check.check(),check.location(),check.fault(),check.cutoff()); + observations.add(new BytecodeInstructionOracle.Observation(outcome.kind().toString(),outcome.actor(),outcome.fault(),outcome.cutoff(),observer,waits,Map.copyOf(fields))); + } + return Set.copyOf(observations); + } + + /** Normalizes through the search result's explicit observable outcome contract. + * Independent enumeration below uses its own state keys and observation logic. + * @param result actual run + * @return normalized outcome set */ + private static Set outcomes(BytecodeExplorer.Result result) { + return result.witnesses().stream().map(BytecodeExplorer.Witness::outcome).collect(java.util.stream.Collectors.toSet()); + } +} diff --git a/src/test/java/dev/samhb/interleave/bytecode/BytecodeCheckTest.java b/src/test/java/dev/samhb/interleave/bytecode/BytecodeCheckTest.java new file mode 100644 index 0000000..a2132e7 --- /dev/null +++ b/src/test/java/dev/samhb/interleave/bytecode/BytecodeCheckTest.java @@ -0,0 +1,218 @@ +/** Pure observer timing, faults and budgets through the internal exact-search seam. */ +package dev.samhb.interleave.bytecode; + +import java.nio.file.Path; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.EnumSource; +import org.junit.jupiter.api.io.TempDir; +import static org.junit.jupiter.api.Assertions.*; + +class BytecodeCheckTest { + /** An initially false ALWAYS check ends the root prefix without selecting an actor. + * @param mode scheduling granularity + * @param directory compiler workspace + * @throws Exception for fixture failures */ + @ParameterizedTest @EnumSource(BytecodeScheduler.Mode.class) void initialAlwaysFailurePrecedesActorChoices(BytecodeScheduler.Mode mode,@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=BytecodeLoader.load(classes,"Fixture",BytecodeLimits.defaults()); + var result=new BytecodeExplorer(program,mode).explore(10000); + assertTrue(result.traversalComplete());assertEquals(1,result.witnesses().size()); + var witness=result.witnesses().getFirst(); + assertEquals(BytecodeExplorer.Kind.CHECK_FALSE,witness.outcome().kind()); + assertEquals("valid",witness.outcome().observer().check().name()); + assertEquals(new BytecodeState.Int(0),witness.state().fixtureField("x")); + assertEquals(0,witness.state().executions.get(0).instructions);assertTrue(witness.schedule().isEmpty()); + } + /** ALWAYS observes transient shared writes even when a later write would restore the property. + * @param mode scheduling granularity + * @param directory compiler workspace + * @throws Exception for fixture failures */ + @ParameterizedTest @EnumSource(BytecodeScheduler.Mode.class) void transientFailureCannotBeHiddenByALaterWrite(BytecodeScheduler.Mode mode,@TempDir Path directory) throws Exception { + var program=load(directory,""" + @Actor(id=0)public void actor(){x=1;x=0;} + @Check(when=Check.When.ALWAYS)public boolean valid(){return x!=1;} + """,BytecodeLimits.defaults()); + var result=new BytecodeExplorer(program,mode).explore(10000); + assertTrue(result.exhaustive());assertEquals(1,result.witnesses().size()); + assertEquals(BytecodeExplorer.Kind.CHECK_FALSE,result.witnesses().getFirst().outcome().kind()); + assertEquals(new BytecodeState.Int(1),result.witnesses().getFirst().state().fixtureField("x")); + } + + /** FINAL checks distinguish the lost update from normal x=2 completion. + * @param mode scheduling granularity + * @param directory compiler workspace + * @throws Exception for fixture failures */ + @ParameterizedTest @EnumSource(BytecodeScheduler.Mode.class) void finalCheckDetectsTheRealLostUpdate(BytecodeScheduler.Mode mode,@TempDir Path directory) throws Exception { + var program=load(directory,""" + @Actor(id=0)public void first(){x++;} @Actor(id=1)public void second(){x++;} + @Check public boolean valid(){return x==2;} + """,BytecodeLimits.defaults()); + var result=new BytecodeExplorer(program,mode).explore(100000); + assertTrue(result.exhaustive());assertEquals(2,result.witnesses().size()); + for(var witness:result.witnesses()) { + int x=((BytecodeState.Int)witness.state().fixtureField("x")).value(); + assertTrue(x==1 || x==2);assertEquals(x==1 ? BytecodeExplorer.Kind.CHECK_FALSE : BytecodeExplorer.Kind.COMPLETED,witness.outcome().kind()); + assertEquals(BytecodeState.Phase.TERMINATED,witness.state().executions.get(0).phase); + assertEquals(BytecodeState.Phase.TERMINATED,witness.state().executions.get(1).phase); + } + } + + /** An observer exception aborts only its private invocation and is honestly incomplete. + * @param mode scheduling granularity + * @param directory compiler workspace + * @throws Exception for fixture failures */ + @ParameterizedTest @EnumSource(BytecodeScheduler.Mode.class) void observerArithmeticFaultIsNotAnActorViolation(BytecodeScheduler.Mode mode,@TempDir Path directory) throws Exception { + var program=load(directory,""" + @Actor(id=0)public void actor(){x=1;} + @Check(when=Check.When.ALWAYS)public boolean valid(){return 1/x>0;} + """,BytecodeLimits.defaults()); + var result=new BytecodeExplorer(program,mode).explore(10000); + assertTrue(result.traversalComplete());assertFalse(result.exhaustive()); + var witness=result.witnesses().getFirst();assertEquals(BytecodeExplorer.Kind.OBSERVER_ERROR,witness.outcome().kind()); + assertEquals("java/lang/ArithmeticException",witness.outcome().observer().fault().type()); + assertEquals(new BytecodeMethod.Id("Fixture","valid","()Z"),witness.outcome().observer().check()); + assertEquals(new BytecodeLocation("Fixture","valid","()Z",5),witness.outcome().observer().location()); + assertEquals(4,result.metrics().checkInstructions());assertEquals(1,result.metrics().checkInvocations()); + assertEquals(0,witness.state().executions.get(0).instructions); + assertEquals(java.util.Set.of(-1,0),witness.state().executions.keySet()); + } + + /** Actor and observer instruction allowances are independent and observer fuel resets per invocation. + * @param mode scheduling granularity + * @param directory compiler workspace + * @throws Exception for fixture failures */ + @ParameterizedTest @EnumSource(BytecodeScheduler.Mode.class) void observersHaveTheirOwnFuel(BytecodeScheduler.Mode mode,@TempDir Path directory) throws Exception { + var program=load(directory,""" + @Actor(id=0)public void actor(){} + @Check public boolean valid(){return x==0;} + """,limits(1,16,32)); + var result=new BytecodeExplorer(program,mode).explore(10000); + assertTrue(result.exhaustive());assertEquals(BytecodeExplorer.Kind.COMPLETED,result.witnesses().getFirst().outcome().kind()); + assertEquals(1,result.metrics().checkInvocations());assertTrue(result.metrics().checkInstructions()>1); + assertEquals(1,result.witnesses().getFirst().state().executions.get(0).instructions); + program=load(directory.resolve("repeated"),""" + @Actor(id=0)public void actor(){x++;} + @Check(when=Check.When.ALWAYS)public boolean valid(){return x>=0;} + """,limits(16,16,32)); + result=new BytecodeExplorer(program,mode).explore(10000); + assertTrue(result.exhaustive());assertEquals(BytecodeExplorer.Kind.COMPLETED,result.witnesses().getFirst().outcome().kind()); + assertTrue(result.metrics().checkInstructions()>16);assertTrue(result.metrics().checkInvocations()>1); + program=load(directory.resolve("loop"),""" + @Actor(id=0)public void actor(){} + @Check(when=Check.When.ALWAYS)public boolean valid(){while(true){}} + """,limits(1,5,32)); + result=new BytecodeExplorer(program,mode).explore(10000); + var witness=result.witnesses().getFirst();assertEquals(BytecodeExplorer.Kind.OBSERVER_LIMIT,witness.outcome().kind()); + assertEquals(new BytecodeMethod.Id("Fixture","valid","()Z"),witness.outcome().observer().check()); + assertEquals(5,witness.outcome().observer().cutoff().limit());assertEquals(5,result.metrics().checkInstructions()); + assertEquals(0,witness.state().executions.get(0).instructions);assertEquals(4,witness.state().executions.get(-1).instructions); + assertFalse(result.exhaustive()); + } + + /** Observer recursion stops at the selected frame allowance, separately from actor completion. + * @param mode scheduling granularity + * @param directory compiler workspace + * @throws Exception for fixture failures */ + @ParameterizedTest @EnumSource(BytecodeScheduler.Mode.class) void observerDepthExhaustionIsIncomplete(BytecodeScheduler.Mode mode,@TempDir Path directory) throws Exception { + var program=load(directory,""" + @Actor(id=0)public void actor(){} + @Check public boolean valid(){return recurse();} static boolean recurse(){return recurse();} + """,limits(1,100,2)); + var result=new BytecodeExplorer(program,mode).explore(10000); + var witness=result.witnesses().getFirst();assertEquals(BytecodeExplorer.Kind.OBSERVER_LIMIT,witness.outcome().kind()); + assertEquals("CALL_DEPTH",witness.outcome().observer().cutoff().reason()); + assertEquals(2,witness.outcome().observer().cutoff().limit());assertEquals("recurse",witness.outcome().observer().location().name()); + assertEquals(BytecodeState.Phase.TERMINATED,witness.state().executions.get(0).phase);assertFalse(result.exhaustive()); + } + + /** FINAL cannot replace actor failure or cutoff with a false-check result. + * @param mode scheduling granularity + * @param directory compiler workspace + * @throws Exception for fixture failures */ + @ParameterizedTest @EnumSource(BytecodeScheduler.Mode.class) void finalNeverRunsOnAnAbnormalPrefix(BytecodeScheduler.Mode mode,@TempDir Path directory) throws Exception { + var bodies=java.util.List.of("x=1/zero();","while(true){}"); + var expected=java.util.List.of(BytecodeExplorer.Kind.UNCAUGHT_EXCEPTION,BytecodeExplorer.Kind.CUTOFF); + for(int index=0;index0;} + @Check(when=Check.When.ALWAYS)public boolean aFalse(){return false;} + """,BytecodeLimits.defaults()); + var result=new BytecodeExplorer(program,mode).explore(10000); + assertEquals(BytecodeExplorer.Kind.CHECK_FALSE,result.witnesses().getFirst().outcome().kind()); + assertEquals("aFalse",result.witnesses().getFirst().outcome().observer().check().name());assertEquals(1,result.metrics().checkInvocations()); + } + + /** Read-only observers receive actual static state, which also reaches normalized terminal evidence. + * @param directory compiler workspace + * @throws Exception for fixture failures */ + @Test void observersReadAndReportCommittedStatics(@TempDir Path directory) throws Exception { + var classes=BytecodeFixtures.compile(directory,26,""" + @Model public class Fixture {public static int shared;public int x;public Fixture(){shared=2;} + @Actor(id=0)public void actor(){x++;} + @Check(when=Check.When.ALWAYS)public boolean valid(){return shared==2 && x>=0;}} + """); + var program=BytecodeLoader.load(classes,"Fixture",BytecodeLimits.defaults()); + for(var mode:BytecodeScheduler.Mode.values()) { + var result=new BytecodeExplorer(program,mode).explore(100000);assertTrue(result.exhaustive()); + assertEquals(BytecodeExplorer.Kind.COMPLETED,result.witnesses().getFirst().outcome().kind()); + var cell=new BytecodeExplorer.Cell(BytecodeState.NULL,new BytecodeProgram.FieldId("Fixture","shared","I")); + assertEquals(new BytecodeState.Int(2),result.witnesses().getFirst().outcome().shared().get(cell)); + } + } + + /** Cancellation of the private observer leaves committed state and the interrupt flag intact. + * @param directory compiler workspace + * @throws Exception for fixture failures */ + @Test void observerCancellationLeavesCommittedStateUntouched(@TempDir Path directory) throws Exception { + var program=load(directory,"@Actor(id=0)public void actor(){} @Check(when=Check.When.ALWAYS)public boolean valid(){return true;}",BytecodeLimits.defaults()); + var state=program.initialState();var before=state.canonicalBytes(); + try { + Thread.currentThread().interrupt();var result=BytecodeChecks.evaluate(program,state,true); + assertEquals(BytecodeChecks.Kind.INTERRUPTED,result.failure().kind());assertEquals(1,result.invocations());assertEquals(0,result.instructions()); + assertEquals(new BytecodeMethod.Id("Fixture","valid","()Z"),result.failure().check()); + assertNull(result.failure().location());assertNull(result.failure().fault());assertNull(result.failure().cutoff()); + assertTrue(Thread.currentThread().isInterrupted());assertArrayEquals(before,state.canonicalBytes()); + } finally {Thread.interrupted();} + } + + /** Compiles a first-profile fixture with caller-selected actor/check declarations. + * @param directory compiler workspace + * @param members actor/check/helper declarations + * @param limits immutable execution profile + * @return loaded immutable artifact + * @throws Exception for fixture failures */ + private static BytecodeProgram load(Path directory,String members,BytecodeLimits limits) throws Exception { + var classes=BytecodeFixtures.compile(directory,26,"@Model public class Fixture {public int x;public Fixture(){} "+members+"}"); + return BytecodeLoader.load(classes,"Fixture",limits); + } + + /** Chooses independent actor/observer fuel and common frame depth for boundary cases. + * @param actor actor fuel + * @param check per-check fuel + * @param depth frame allowance + * @return immutable limits */ + private static BytecodeLimits limits(int actor,int check,int depth) { + return new BytecodeLimits(actor,128,8192,depth,64,256,4096,128,8192,check); + } + +} diff --git a/src/test/java/dev/samhb/interleave/bytecode/BytecodeConcurrencyTest.java b/src/test/java/dev/samhb/interleave/bytecode/BytecodeConcurrencyTest.java new file mode 100644 index 0000000..54586e8 --- /dev/null +++ b/src/test/java/dev/samhb/interleave/bytecode/BytecodeConcurrencyTest.java @@ -0,0 +1,219 @@ +/** Concurrent choices and exact outcomes through the internal94B scheduling/search seams. */ +package dev.samhb.interleave.bytecode; + +import java.nio.file.*; +import java.util.*; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import static dev.samhb.interleave.bytecode.BytecodeState.*; +import static org.junit.jupiter.api.Assertions.*; + +class BytecodeConcurrencyTest { + /** Shared x++ keeps a scheduling choice between its read and write. + * @param directory compiler workspace + * @throws Exception for compiler/resource failures */ + @Test void sharedReadAndWriteRemainSeparateChoices(@TempDir Path directory) throws Exception { + String source; + try(var resource=getClass().getResourceAsStream("/bytecode/concurrency/lost-update/Fixture.java")) { + assertNotNull(resource);source=new String(resource.readAllBytes(),java.nio.charset.StandardCharsets.UTF_8); + } + var program=BytecodeLoader.load(BytecodeFixtures.compile(directory,26,source),"Fixture",BytecodeLimits.defaults()); + var scheduler=new BytecodeScheduler(program,BytecodeScheduler.Mode.REFERENCE); + var initial=program.initialState();byte[] before=initial.canonicalBytes(); + assertEquals(List.of(0,1),scheduler.choices(initial));assertArrayEquals(before,initial.canonicalBytes()); + var state=initial; + for(int actor:new int[]{0,1})for(int instruction=0;instruction<3;instruction++)state=scheduler.advance(state,actor).state(); + assertEquals(new Int(0),state.fixtureField("x")); + assertEquals(3,state.executions.get(0).instructions);assertEquals(3,state.executions.get(1).instructions); + for(int actor:new int[]{0,1})for(int instruction=0;instruction<3;instruction++)state=scheduler.advance(state,actor).state(); + assertEquals(new Int(1),state.fixtureField("x")); + assertArrayEquals(before,initial.canonicalBytes()); + } + /** Exact search retains both lost and nonlost final observations. + * @param directory compiler workspace + * @throws Exception for fixture failures */ + @Test void exactDfsFindsBothIncrementOutcomes(@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++;} + } + """); + var program=BytecodeLoader.load(classes,"Fixture",BytecodeLimits.defaults()); + var result=new BytecodeExplorer(program,BytecodeScheduler.Mode.REFERENCE).explore(100000); + assertTrue(result.traversalComplete());assertTrue(result.exhaustive()); + var values=new TreeSet(); + for(var witness:result.witnesses()) { + assertEquals(BytecodeExplorer.Kind.COMPLETED,witness.outcome().kind()); + values.add(((Int)witness.state().fixtureField("x")).value()); + assertFalse(witness.schedule().isEmpty()); + } + assertEquals(Set.of(1,2),values); + } + + /** A real two-lock cycle is distinguished from schedules which release both monitors normally. + * @param directory compiler workspace + * @throws Exception for fixture failures */ + @Test void opposingLocksProduceDeadlockAndCompletion(@TempDir Path directory) throws Exception { + String source;try(var resource=getClass().getResourceAsStream("/bytecode/concurrency/two-lock/Fixture.java")) { + assertNotNull(resource);source=new String(resource.readAllBytes(),java.nio.charset.StandardCharsets.UTF_8); + } + var program=BytecodeLoader.load(BytecodeFixtures.compile(directory,26,source),"Fixture",BytecodeLimits.defaults()); + var result=new BytecodeExplorer(program,BytecodeScheduler.Mode.REFERENCE).explore(100000); + assertTrue(result.traversalComplete());assertTrue(result.exhaustive()); + assertEquals(Set.of(BytecodeExplorer.Kind.DEADLOCK,BytecodeExplorer.Kind.COMPLETED), + result.witnesses().stream().map(w->w.outcome().kind()).collect(java.util.stream.Collectors.toSet())); + for(var witness:result.witnesses()) { + if(witness.outcome().kind()==BytecodeExplorer.Kind.DEADLOCK) { + assertEquals(List.of(new BytecodeExplorer.Wait(0,1,new Ref(SETUP,2),1), + new BytecodeExplorer.Wait(1,0,new Ref(SETUP,1),1)),witness.outcome().waits()); + assertEquals(new Int(0),witness.state().fixtureField("x")); + } else { + assertEquals(new Int(2),witness.state().fixtureField("x")); + assertTrue(witness.state().heap.values().stream().allMatch(object->object.monitorDepth==0)); + } + } + } + + /** Class monitors on static synchronized helpers prevent lost updates. + * @param directory compiler workspace + * @throws Exception for fixture failures */ + @Test void staticSynchronizedHelpersProtectTheCounter(@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(){increment(this);} @Actor(id=1)public void second(){increment(this);} + private static synchronized void increment(Fixture fixture){fixture.x++;} + } + """); + var program=BytecodeLoader.load(classes,"Fixture",BytecodeLimits.defaults()); + var result=new BytecodeExplorer(program,BytecodeScheduler.Mode.REFERENCE).explore(100000); + assertTrue(result.exhaustive());assertEquals(1,result.witnesses().size()); + assertEquals(BytecodeExplorer.Kind.COMPLETED,result.witnesses().getFirst().outcome().kind()); + assertEquals(new Int(2),result.witnesses().getFirst().state().fixtureField("x")); + } + /** A local-prefix arithmetic fault yields while a competing actor is still enabled. + * @param directory compiler workspace + * @throws Exception for fixture failures */ + @Test void batchYieldsBeforeDeliveringLocalFailure(@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(){int a=1;int b=a-1;int c=1/b;} + @Actor(id=1)public void second(){x=1;} + } + """); + var program=BytecodeLoader.load(classes,"Fixture",BytecodeLimits.defaults()); + var scheduler=new BytecodeScheduler(program,BytecodeScheduler.Mode.BATCHED);var parent=program.initialState();var before=parent.canonicalBytes(); + var fault=scheduler.advance(parent,0);assertEquals(Phase.EXCEPTION,fault.state().executions.get(0).phase); + assertEquals(OpcodeExecutor.Kind.PENDING,fault.kind());assertTrue(fault.executed().size()>1); + assertEquals(List.of(0,1),scheduler.choices(fault.state())); + var other=scheduler.advance(fault.state(),1);assertEquals(new Int(1),other.state().fixtureField("x")); + assertEquals(Phase.EXCEPTION,other.state().executions.get(0).phase);assertArrayEquals(before,parent.canonicalBytes()); + } + + /** Publication/rewiring refreshes actual frame roots and never erases historical sharing. + * @param directory compiler workspace + * @throws Exception for fixture failures */ + @Test void frameRootsAndRewiringKeepSharingHistory(@TempDir Path directory) throws Exception { + var classes=BytecodeFixtures.compile(directory,26,""" + @Model public class Fixture {public Object lock=new Object();public Fixture(){} + @Actor(id=0)public void first(){Object remembered=lock;lock=null;synchronized(remembered){}} + } + """); + var program=BytecodeLoader.load(classes,"Fixture",BytecodeLimits.defaults());var state=program.initialState();var lock=(Ref)state.fixtureField("lock"); + var initial=BytecodeSharing.refresh(state);assertEquals(new BytecodeSharing.Work(1,3,1,0),initial); + var scheduler=new BytecodeScheduler(program,BytecodeScheduler.Mode.BATCHED); + state=scheduler.advance(state,0).state();var publication=scheduler.advance(state,0);state=publication.state(); + assertEquals(NULL,state.fixtureField("lock"));assertEquals(new BytecodeSharing.Work(1,3,0,0),publication.sharing()); + assertTrue(state.frame(0).locals.containsValue(lock));assertTrue(state.heap.get(lock).shared); + var historic=state.canonicalBytes();state.heap.get(lock).shared=false;assertFalse(Arrays.equals(historic,state.canonicalBytes())); + assertEquals(new BytecodeSharing.Work(1,3,0,1),BytecodeSharing.refresh(state));assertArrayEquals(historic,state.canonicalBytes()); + // Unknown/unreachable setup objects are also shared; the profile never infers exclusivity. + state.frame(0).locals.values().removeIf(lock::equals);state.frame(0).stack.clear();state.heap.get(lock).shared=false; + assertEquals(1,BytecodeSharing.refresh(state).promotions());assertTrue(state.heap.get(lock).shared); + assertEquals(0,BytecodeSharing.refresh(state).promotions()); + } + /** A failed reference write is a fault, not a committed publication traversal. + * @param directory compiler workspace + * @throws Exception for fixture failures */ + @Test void failedReferenceWriteDoesNotRefreshPublication(@TempDir Path directory) throws Exception { + var classes=BytecodeFixtures.compile(directory,26,""" + @Model public class Fixture {public Object lock=new Object();public Fixture(){} + @Actor(id=0)public void first(){Fixture absent=null;absent.lock=lock;} + } + """); + var program=BytecodeLoader.load(classes,"Fixture",BytecodeLimits.defaults()); + var scheduler=new BytecodeScheduler(program,BytecodeScheduler.Mode.BATCHED);var read=scheduler.advance(program.initialState(),0); + var write=scheduler.advance(read.state(),0);assertEquals(Phase.EXCEPTION,write.state().executions.get(0).phase); + assertEquals("java/lang/NullPointerException",write.state().executions.get(0).fault.type());assertEquals(BytecodeSharing.Work.NONE,write.sharing()); + } + /** A cancelled selection aborts externally without committing any target state or clearing the flag. + * Controlled child instrumentation separately tests cancellation after a primitive commit. + * @param directory compiler workspace + * @throws Exception for fixture failures */ + @Test void cancelledSelectionHonorsHostFlag(@TempDir Path directory) throws Exception { + var classes=BytecodeFixtures.compile(directory,26,""" + @Model public class Fixture {public Fixture(){} @Actor(id=0)public void actor(){while(true){}}} + """); + var program=BytecodeLoader.load(classes,"Fixture",BytecodeLimits.defaults());var initial=program.initialState();var before=initial.canonicalBytes(); + for(var mode:BytecodeScheduler.Mode.values()) { + try { + Thread.currentThread().interrupt();var scheduler=new BytecodeScheduler(program,mode); + assertThrows(java.util.concurrent.CancellationException.class,()->scheduler.advance(initial,0)); + assertTrue(Thread.currentThread().isInterrupted());assertArrayEquals(before,initial.canonicalBytes()); + } finally {Thread.interrupted();} + } + } + /** A disabled selected monitor returns an owned unchanged result and no charged or recorded work. + * @param directory compiler workspace + * @throws Exception for fixture failures */ + @Test void disabledSelectionAndInvalidActorsHaveExplicitContracts(@TempDir Path directory) throws Exception { + var classes=BytecodeFixtures.compile(directory,26,""" + @Model public class Fixture {public Fixture(){} + @Actor(id=0)public synchronized void first(){} @Actor(id=1)public synchronized void second(){}} + """); + var program=BytecodeLoader.load(classes,"Fixture",BytecodeLimits.defaults()); + for(var mode:BytecodeScheduler.Mode.values()) { + var scheduler=new BytecodeScheduler(program,mode);var held=scheduler.advance(program.initialState(),0).state(); + var before=held.canonicalBytes();assertEquals(List.of(0),scheduler.choices(held));var blocked=scheduler.advance(held,1); + assertEquals(OpcodeExecutor.Kind.BLOCKED,blocked.kind());assertArrayEquals(before,blocked.state().canonicalBytes()); + assertNotSame(held,blocked.state());assertTrue(blocked.executed().isEmpty());assertEquals(0,blocked.instructions());assertEquals(BytecodeSharing.Work.NONE,blocked.sharing()); + assertThrows(IllegalArgumentException.class,()->scheduler.advance(held,-1));assertThrows(IllegalArgumentException.class,()->scheduler.advance(held,2)); + } + } + + /** Actual javac increment BCIs/opcodes survive batching and keep the write in a later transition. + * @param directory compiler workspace + * @throws Exception for fixture failures */ + @Test void batchedTraceRetainsRealReadWritePositions(@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++;}} + """); + var program=BytecodeLoader.load(classes,"Fixture",BytecodeLimits.defaults());var scheduler=new BytecodeScheduler(program,BytecodeScheduler.Mode.BATCHED); + var read=scheduler.advance(program.initialState(),0); + assertEquals(List.of(0,1,2,5,6),read.executed().stream().map(step->step.location().bci()).toList()); + assertEquals(List.of(java.lang.classfile.Opcode.ALOAD_0,java.lang.classfile.Opcode.DUP,java.lang.classfile.Opcode.GETFIELD, + java.lang.classfile.Opcode.ICONST_1,java.lang.classfile.Opcode.IADD),read.executed().stream().map(BytecodeScheduler.Executed::opcode).toList()); + assertEquals(5,read.instructions());assertEquals(new Int(0),read.state().fixtureField("x")); + var write=scheduler.advance(read.state(),0);assertEquals(1,write.instructions());assertEquals(new Int(1),write.state().fixtureField("x")); + assertEquals(List.of(new BytecodeScheduler.Executed(new BytecodeLocation("Fixture","actor","()V",7),java.lang.classfile.Opcode.PUTFIELD)),write.executed()); + var returned=scheduler.advance(write.state(),0);assertEquals(1,returned.instructions());assertEquals(Phase.RETURNING,returned.state().executions.get(0).phase); + assertEquals(List.of(new BytecodeScheduler.Executed(new BytecodeLocation("Fixture","actor","()V",10),java.lang.classfile.Opcode.RETURN)),returned.executed()); + } + /** Reference static publication refreshes roots and charges historical promotion on the owned successor. + * @param directory compiler workspace + * @throws Exception for fixture failures */ + @Test void staticReferencePublicationRefreshesSharedness(@TempDir Path directory) throws Exception { + var classes=BytecodeFixtures.compile(directory,26,""" + @Model public class Fixture {public static Object published;public Object lock=new Object();public Fixture(){} + @Actor(id=0)public void actor(){published=lock;}} + """); + var program=BytecodeLoader.load(classes,"Fixture",BytecodeLimits.defaults());var scheduler=new BytecodeScheduler(program,BytecodeScheduler.Mode.BATCHED); + var read=scheduler.advance(program.initialState(),0).state();var field=new BytecodeProgram.FieldId("Fixture","published","Ljava/lang/Object;"); + assertEquals(NULL,read.statics.get(field));var published=scheduler.advance(read,0); + assertEquals(new Ref(SETUP,1),published.state().statics.get(field));assertEquals(new BytecodeSharing.Work(1,3,1,0),published.sharing()); + // A trusted history mutation checks promotion accounting without claiming95's reachable local heap. + var history=read.copy();history.heap.get(new Ref(SETUP,1)).shared=false;var before=history.canonicalBytes(); + var promoted=scheduler.advance(history,0);assertEquals(new BytecodeSharing.Work(1,3,1,1),promoted.sharing()); + assertTrue(promoted.state().heap.get(new Ref(SETUP,1)).shared);assertFalse(history.heap.get(new Ref(SETUP,1)).shared);assertArrayEquals(before,history.canonicalBytes()); + } + +} diff --git a/src/test/java/dev/samhb/interleave/bytecode/BytecodeEventTest.java b/src/test/java/dev/samhb/interleave/bytecode/BytecodeEventTest.java index ce6457b..53611bb 100644 --- a/src/test/java/dev/samhb/interleave/bytecode/BytecodeEventTest.java +++ b/src/test/java/dev/samhb/interleave/bytecode/BytecodeEventTest.java @@ -87,6 +87,34 @@ class BytecodeEventTest { assertEquals("java/lang/NullPointerException",result.state().executions.get(0).fault.type()); } + /** Release validates null/ownership, charges the faulting opcode and retains the other owner's depth. */ + @Test void invalidMonitorReleaseIsAModeledFault() { + var program=program(0,8,code->code.aload(0).monitorexit().return_()); + var ready=OpcodeExecutor.step(program,start(program),0).state(); + for(boolean absent:List.of(false,true)) { + var state=ready.copy();state.heap.get(FIXTURE).monitorOwner=1;state.heap.get(FIXTURE).monitorDepth=2; + if(absent){state.frame(0).stack.clear();state.frame(0).stack.add(NULL);} + var before=state.canonicalBytes();var next=OpcodeExecutor.step(program,state,0); + assertEquals(OpcodeExecutor.Kind.PENDING,next.kind());assertEquals(2,next.state().executions.get(0).instructions); + assertEquals(absent ? "java/lang/NullPointerException" : "java/lang/IllegalMonitorStateException",next.state().executions.get(0).fault.type()); + assertEquals(1,next.state().heap.get(FIXTURE).monitorOwner);assertEquals(2,next.state().heap.get(FIXTURE).monitorDepth); + assertArrayEquals(before,state.canonicalBytes()); + } + } + + /** Implicit synchronized probes are pure; exhausted work precedes a competing monitor owner. */ + @Test void implicitProbePreservesFuelBeforeBlocking() { + var program=program(ACC_SYNCHRONIZED,1,CodeBuilder::return_);var state=start(program); + state.heap.get(FIXTURE).monitorOwner=1;state.heap.get(FIXTURE).monitorDepth=1;var before=state.canonicalBytes(); + var blocked=OpcodeExecutor.probe(program,state,0);assertEquals(OpcodeExecutor.Availability.BLOCKED,blocked.availability()); + assertEquals(FIXTURE,blocked.monitor());assertTrue(blocked.observable());assertFalse(blocked.exhausted());assertArrayEquals(before,state.canonicalBytes()); + state.executions.get(0).instructions=1;before=state.canonicalBytes(); + var exhausted=OpcodeExecutor.probe(program,state,0);assertEquals(OpcodeExecutor.Availability.READY,exhausted.availability()); + assertTrue(exhausted.exhausted());assertNull(exhausted.opcode());assertArrayEquals(before,state.canonicalBytes()); + var next=OpcodeExecutor.step(program,state,0);assertEquals(Phase.CUTOFF_PENDING,next.state().executions.get(0).phase); + assertEquals(1,next.state().heap.get(FIXTURE).monitorOwner);assertEquals(1,next.state().executions.get(0).instructions); + } + /** Builds trusted test metadata directly so a broken setup event cannot stall a regression before its assertion. * * @param flags extra actor flags diff --git a/src/test/java/dev/samhb/interleave/bytecode/BytecodeInstructionOracle.java b/src/test/java/dev/samhb/interleave/bytecode/BytecodeInstructionOracle.java new file mode 100644 index 0000000..a4d1f31 --- /dev/null +++ b/src/test/java/dev/samhb/interleave/bytecode/BytecodeInstructionOracle.java @@ -0,0 +1,186 @@ +/** Test-only opcode-choice enumeration, independent of production scheduling, encoding and observers. */ +package dev.samhb.interleave.bytecode; + +import java.util.*; +import static dev.samhb.interleave.bytecode.BytecodeState.*; + +/** A small bounded reference for ASCII-named compiler fixtures, using sorted full structural text keys. */ +final class BytecodeInstructionOracle { + /** Prevents construction of this stateless test reference. */ + private BytecodeInstructionOracle() {} + + /** Normalized terminal observations without local snapshots or scheduling statistics. + * @param kind terminal category + * @param actor terminal actor, otherwise -1 + * @param fault original fault + * @param cutoff original omitted operation + * @param observer independently evaluated check identity/failure + * @param waits sorted monitor relationships + * @param fields sorted shared observations */ + record Observation(String kind,int actor,Fault fault,Cutoff cutoff,String observer,List waits,Map fields) {} + + /** Enumerates primitive steps without consulting probe, scheduler, explorer or canonicalBytes. + * @param program validated bounded fixture + * @return independent observable outcomes */ + static Set enumerate(BytecodeProgram program) { + var pending=new ArrayDeque();pending.push(program.initialState()); + var seen=new TreeSet();var outcomes=new HashSet(); + while(!pending.isEmpty()) { + var state=pending.pop();if(!seen.add(key(state)))continue; + if(seen.size()>200000)throw new AssertionError("Independent fixture exceeded its test ceiling"); + boolean terminal=false; + for(int actor=0;actore.getKey()>=0).allMatch(e->e.getValue().phase==Phase.TERMINATED)) { + failure=checks(program,state,false); + outcomes.add(failure==null ? observation(state,"COMPLETED",-1,null,null,null,List.of()) : failure);continue; + } + var waits=new ArrayList();int choices=0; + for(int actor=0;actorprogram.limits.actorInstructions())return false; + Ref monitor; + if(!frame.entered)monitor=(frame.method.flags & java.lang.classfile.ClassFile.ACC_STATIC)!=0 + ? BytecodeState.classMonitor(frame.method.id.owner(),program) : (Ref)frame.locals.get(0); + else if(instruction.opcode()==java.lang.classfile.Opcode.MONITORENTER)monitor=(Ref)frame.stack.getLast(); + else return false; + if(monitor.equals(NULL))return false; + var object=state.heap.get(monitor);return object.monitorOwner!=-2 && object.monitorOwner!=actor; + } + + /** Evaluates checks through private primitive execution, with no production observer adapter. + * @param program fixture + * @param parent committed actor state + * @param always selected timing + * @return first failed observation, otherwise null */ + private static Observation checks(BytecodeProgram program,BytecodeState parent,boolean always) { + for(var check:program.checks) { + if(check.always()!=always)continue; + var state=new BytecodeState();parent.heap.forEach((id,object)->state.heap.put(id,object.copy()));state.statics.putAll(parent.statics); + state.start(OBSERVER,program.methods.get(check.method()),List.of(FIXTURE)); + // Keep the mutable holder out of lambdas; successors are distinct owned values. + var scratch=state; + for(int event=0;;event++) { + if(event>100000)throw new AssertionError("Observer event protocol stalled"); + var execution=scratch.executions.get(OBSERVER); + if(execution.fault!=null)return observation(parent,"OBSERVER_ERROR",-1,null,null, + checkKey("ERROR",check.method(),execution.fault.location(),execution.fault,null),List.of()); + if(execution.cutoff!=null)return observation(parent,"OBSERVER_LIMIT",-1,null,null, + checkKey("LIMIT",check.method(),execution.cutoff.location(),null,execution.cutoff),List.of()); + if(execution.phase==Phase.RETURNING && execution.frames.size()==1) { + if(((Int)execution.returned).value()==0)return observation(parent,"CHECK_FALSE",-1,null,null, + checkKey("FALSE",check.method(),execution.eventLocation,null,null),List.of()); + break; + } + scratch=OpcodeExecutor.step(program,scratch,OBSERVER).state(); + } + } + return null; + } + + /** Projects terminal shared state independently of the production outcome builder. + * @param state terminal state + * @param kind category + * @param actor failing actor + * @param fault fault + * @param cutoff cutoff + * @param observer failed observer + * @param waits deadlock relationships + * @return normalized independent observation */ + private static Observation observation(BytecodeState state,String kind,int actor,Fault fault,Cutoff cutoff,String observer,List waits) { + var fields=new TreeMap(); + for(var entry:state.statics.entrySet())fields.put(cellKey(NULL,entry.getKey()),entry.getValue()); + for(var entry:state.heap.entrySet())if(entry.getValue().shared) + for(var field:entry.getValue().fields.entrySet())fields.put(cellKey(entry.getKey(),field.getKey()),field.getValue()); + return new Observation(kind,actor,fault,cutoff,observer,List.copyOf(waits),Map.copyOf(fields)); + } + + /** Independently writes every mutable state component with length-delimited fixture tokens. + * Metadata/value records contain only bounded ASCII fixture identifiers and numeric values here. + * @param state owned snapshot + * @return full key for the independent sorted set */ + private static String key(BytecodeState state) { + var key=new StringBuilder();tokens(key,"heap",state.heap.size()); + for(var entry:state.heap.entrySet()) { + var object=entry.getValue();tokens(key,entry.getKey(),object.type,object.shared,object.initialized,object.monitorOwner,object.monitorDepth,object.fields.size()); + object.fields.forEach((field,value)->tokens(key,field,value)); + } + tokens(key,"statics",state.statics.size());state.statics.forEach((field,value)->tokens(key,field,value)); + tokens(key,"executions",state.executions.size()); + for(var entry:state.executions.entrySet()) { + var execution=entry.getValue();tokens(key,entry.getKey(),execution.phase,execution.instructions,execution.allocations,execution.cells, + execution.nextSequence,execution.fault,execution.cutoff,execution.returned,execution.eventLocation,execution.frames.size()); + for(var frame:execution.frames) { + tokens(key,frame.method.id,frame.bci,frame.entered,frame.methodMonitor,frame.locals.size()); + frame.locals.forEach((slot,value)->tokens(key,slot,value));tokens(key,frame.stack.size());frame.stack.forEach(value->tokens(key,value)); + } + } + return key.toString(); + } + + /** Appends unambiguous null/scalar/immutable-record tokens for controlled compiler fixtures. + * @param sink key sink + * @param values complete tokens */ + private static void tokens(StringBuilder sink,Object... values) { + for(var value:values) {if(value==null)sink.append("N;");else {String text=value.toString();sink.append(text.length()).append(':').append(text);}} + } + + /** Names a shared cell without using the production Cell record. + * @param reference owning object or static sentinel + * @param field declared slot + * @return stable fixture cell token */ + static String cellKey(Ref reference,BytecodeProgram.FieldId field) {return reference+"/"+field;} + + /** Names a concrete wait without using production Wait. + * @param actor waiter + * @param owner owner + * @param monitor identity + * @param depth held depth + * @return concrete relationship */ + static String waitKey(int actor,int owner,Ref monitor,int depth) {return actor+"/"+owner+"/"+monitor+"/"+depth;} + + /** Names a check's real failure identity. + * @param kind observer reason + * @param method declared check + * @param location real position + * @param fault original fault + * @param cutoff omitted operation + * @return bounded diagnostic token */ + static String checkKey(String kind,BytecodeMethod.Id method,BytecodeLocation location,Fault fault,Cutoff cutoff) { + return kind+"/"+method+"/"+location+"/"+fault+"/"+cutoff; + } +} diff --git a/src/test/java/dev/samhb/interleave/bytecode/BytecodeMeasurementTest.java b/src/test/java/dev/samhb/interleave/bytecode/BytecodeMeasurementTest.java new file mode 100644 index 0000000..cda3e8a --- /dev/null +++ b/src/test/java/dev/samhb/interleave/bytecode/BytecodeMeasurementTest.java @@ -0,0 +1,152 @@ +/** Reproducible opt-in interpreter measurements with real post-GC retained heap, separate from key bytes. */ +package dev.samhb.interleave.bytecode; + +import java.lang.management.ManagementFactory; +import java.nio.charset.StandardCharsets; +import java.nio.file.*; +import java.security.MessageDigest; +import java.util.*; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import static org.junit.jupiter.api.Assertions.*; + +class BytecodeMeasurementTest { + /** Explicit sole measurement root; cleared before each baseline collection. */ + private static volatile Held retained; + /** Keeps the search store and witnesses live after the worker method has returned. + * @param explorer exact key store owner + * @param result concrete findings */ + private record Held(BytecodeExplorer explorer,BytecodeExplorer.Result result) {} + + /** Both measurement fixtures must agree with independent instruction enumeration before timing. + * @param directory compiler workspace + * @throws Exception for fixture failures */ + @Test void referenceBatchOutcomeGate(@TempDir Path directory) throws Exception { + for(String fixture:List.of("lost-update","two-lock")) { + var program=fixture(directory,fixture);var expected=BytecodeInstructionOracle.enumerate(program);requireOutcomes(fixture,expected); + for(var mode:BytecodeScheduler.Mode.values()) { + var result=new BytecodeExplorer(program,mode).explore(100000); + assertTrue(result.exhaustive());assertEquals(expected,BytecodeBatchingOracleTest.independentProjection(result)); + assertTrue(result.metrics().encodingBytes()>=result.metrics().retainedKeyBytes()); + assertEquals(1,result.metrics().sharing().traversals());assertEquals(0,result.metrics().sharing().promotions()); + assertEquals(fixture.equals("two-lock") ? 4 : 2,result.metrics().sharing().objects()); + assertEquals(fixture.equals("two-lock") ? 2 : 0,result.metrics().sharing().edges()); + } + } + } + + /** Runs one fresh measurement JVM; use the profileBytecode Gradle task for fixed heap/GC flags. + * Two warmups per fixture/mode precede three measured repetitions with alternating mode order. + * @param arguments output directory and fork identifier + * @throws Exception for compiler, output or correctness-gate failures */ + public static void main(String[] arguments) throws Exception { + if(arguments.length!=2)throw new IllegalArgumentException("Expected output directory and fork id"); + var flags=ManagementFactory.getRuntimeMXBean().getInputArguments(); + if(!flags.contains("-XX:+UseSerialGC") || !flags.contains("-XX:MarkSweepDeadRatio=0")) + throw new IllegalArgumentException("Retained-memory measurement requires SerialGC and MarkSweepDeadRatio=0"); + Path output=Path.of(arguments[0]);Files.createDirectories(output);String fork=arguments[1]; + var metadata=new StringBuilder("# 94B raw measurement fork ").append(fork).append("\n\n"); + metadata.append("- Java: `").append(System.getProperty("java.runtime.version")).append("`\n") + .append("- VM: `").append(System.getProperty("java.vm.name")).append("`\n") + .append("- OS/architecture: `").append(System.getProperty("os.name")).append('/').append(System.getProperty("os.arch")).append("`\n") + .append("- JVM arguments: `").append(ManagementFactory.getRuntimeMXBean().getInputArguments()).append("`\n") + .append("- Warmups: 2 per fixture/mode; repetitions: 3; modes alternate order per repetition.\n") + .append("- Retained heap: used heap after verified explicit GC and full compaction (MarkSweepDeadRatio=0), with explorer and result reachable; delta against pre-run used heap.\n") + .append("- Key bytes are only canonical payload, reported separately. History-only states are zero in the setup-only all-shared profile.\n"); + var rows=new ArrayList(); + rows.add("fixture,fork,repetition,mode,states,transitions,opcodes,instructions,encodingCalls,encodingBytes,encodingNanos,retainedKeyBytes,elapsedNanos,heapBefore,heapAfter,heapDelta,gcCollections,checkInvocations,checkInstructions,sharingTraversals,sharingObjects,sharingEdges,sharingPromotions,historyOnlyStates,outcomes"); + for(String fixture:List.of("lost-update","two-lock")) { + var program=fixture(output,fixture); + Path source=output.resolve(fixture).resolve("sources/Fixture.java"); + metadata.append("- ").append(fixture).append(" source SHA-256: `").append(hex(Files.readAllBytes(source))).append("`; artifact manifest: `").append(program.artifactDigest()).append("`; limits: `").append(program.limits).append("`\n"); + var expected=BytecodeInstructionOracle.enumerate(program);requireOutcomes(fixture,expected); + for(int warmup=0;warmup<2;warmup++)for(var mode:BytecodeScheduler.Mode.values())runRetained(program,expected,mode); + for(int repetition=0;repetition<3;repetition++) { + var order=repetition%2==0 ? List.of(BytecodeScheduler.Mode.REFERENCE,BytecodeScheduler.Mode.BATCHED) + : List.of(BytecodeScheduler.Mode.BATCHED,BytecodeScheduler.Mode.REFERENCE); + for(var mode:order)rows.add(sample(program,expected,fixture,fork,repetition,mode)); + } + } + Files.write(output.resolve("samples.csv"),rows,StandardCharsets.UTF_8); + Files.writeString(output.resolve("conditions.md"),metadata,StandardCharsets.UTF_8); + } + + /** Ensures equivalence cannot pass by losing both a known serialized and a known failing path. + * @param fixture fixture identity + * @param observations independent instruction outcomes */ + private static void requireOutcomes(String fixture,Set observations) { + var kinds=observations.stream().map(BytecodeInstructionOracle.Observation::kind).collect(java.util.stream.Collectors.toSet()); + var expected=fixture.equals("two-lock") ? Set.of("COMPLETED","DEADLOCK") : Set.of("COMPLETED","CHECK_FALSE"); + if(observations.size()!=2 || !kinds.equals(expected))throw new AssertionError("Missing known fixture outcomes: "+fixture+" "+observations); + String cell=BytecodeInstructionOracle.cellKey(BytecodeState.FIXTURE,new BytecodeProgram.FieldId("Fixture","x","I")); + for(var outcome:observations) { + int value=outcome.kind().equals("COMPLETED") ? 2 : fixture.equals("two-lock") ? 0 : 1; + if(!new BytecodeState.Int(value).equals(outcome.fields().get(cell)))throw new AssertionError("Wrong shared observation: "+outcome); + if(outcome.kind().equals("DEADLOCK") && outcome.waits().size()!=2)throw new AssertionError("Missing concrete wait cycle"); + } + } + + /** Holds the actual visited-key store and concrete witnesses across post-run GC. + * @param program immutable interpreted fixture + * @param expected independently enumerated outcomes + * @param fixture fixture name + * @param fork fresh JVM identifier + * @param repetition measured repetition + * @param mode scheduling mode + * @return one CSV row + * @throws InterruptedException if measurement is cancelled */ + private static String sample(BytecodeProgram program,Set expected,String fixture,String fork,int repetition,BytecodeScheduler.Mode mode) throws InterruptedException { + retained=null;collect();long before=ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getUsed(); + long elapsed=runRetained(program,expected,mode); + long collections=gcCount();collect();long after=ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getUsed();long gc=gcCount()-collections; + var metrics=retained.result().metrics();var sharing=metrics.sharing(); + return String.join(",",fixture,fork,Integer.toString(repetition),mode.toString(),Long.toString(metrics.states()),Long.toString(metrics.transitions()), + Long.toString(metrics.opcodes()),Long.toString(metrics.instructions()),Long.toString(metrics.encodingCalls()),Long.toString(metrics.encodingBytes()), + Long.toString(metrics.encodingNanos()),Long.toString(metrics.retainedKeyBytes()),Long.toString(elapsed),Long.toString(before),Long.toString(after), + Long.toString(after-before),Long.toString(gc),Long.toString(metrics.checkInvocations()),Long.toString(metrics.checkInstructions()),Long.toString(sharing.traversals()),Long.toString(sharing.objects()),Long.toString(sharing.edges()), + Long.toString(sharing.promotions()),"0",Integer.toString(retained.result().witnesses().size())); + } + + /** Executes outside the GC sampler's stack frame, leaving only the explicit volatile retention root. + * Warmup and previous search locals therefore cannot contaminate the next baseline. + * @param program immutable fixture + * @param expected independent observations + * @param mode scheduling granularity + * @return elapsed search nanoseconds */ + private static long runRetained(BytecodeProgram program,Set expected,BytecodeScheduler.Mode mode) { + var explorer=new BytecodeExplorer(program,mode);long start=System.nanoTime();var result=explorer.explore(100000);long elapsed=System.nanoTime()-start; + if(!result.exhaustive() || !expected.equals(BytecodeBatchingOracleTest.independentProjection(result)))throw new AssertionError("Measured outcome mismatch"); + retained=new Held(explorer,result);return elapsed; + } + + /** Requests two synchronous full collections under the configured Serial GC and verifies progress. + * @throws InterruptedException if measurement is cancelled */ + private static void collect() throws InterruptedException { + long before=gcCount();System.gc();Thread.sleep(20);System.gc();Thread.sleep(20); + if(gcCount()<=before)throw new IllegalStateException("Explicit GC made no observable progress; retained-memory sample invalid"); + } + + /** Sums JVM-reported completed collector invocations. + * @return actual completed collections */ + private static long gcCount() {return ManagementFactory.getGarbageCollectorMXBeans().stream().mapToLong(bean->Math.max(0,bean.getCollectionCount())).sum();} + + /** Loads exactly the checked-in measurement source through the real compiler and interpreter loader. + * @param directory isolated compiler workspace + * @param name resource fixture name + * @return validated program with identical default limits in both modes + * @throws Exception for fixture failures */ + private static BytecodeProgram fixture(Path directory,String name) throws Exception { + String source; + try(var resource=BytecodeMeasurementTest.class.getResourceAsStream("/bytecode/concurrency/"+name+"/Fixture.java")) { + if(resource==null)throw new IllegalStateException("Missing measurement fixture "+name); + source=new String(resource.readAllBytes(),StandardCharsets.UTF_8); + } + return BytecodeLoader.load(BytecodeFixtures.compile(directory.resolve(name),26,source),"Fixture",BytecodeLimits.defaults()); + } + + /** Hashes exact source bytes without relying on filename or timestamps. + * @param bytes source payload + * @return SHA-256 hex + * @throws Exception if the required JDK digest is unavailable */ + private static String hex(byte[] bytes) throws Exception {return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes));} +} diff --git a/src/test/java/dev/samhb/interleave/bytecode/BytecodeSearchContractTest.java b/src/test/java/dev/samhb/interleave/bytecode/BytecodeSearchContractTest.java new file mode 100644 index 0000000..2dfa57f --- /dev/null +++ b/src/test/java/dev/samhb/interleave/bytecode/BytecodeSearchContractTest.java @@ -0,0 +1,124 @@ +/** Exact byte payload membership, checker interruptions and real internal witness choices. */ +package dev.samhb.interleave.bytecode; + +import java.nio.file.Path; +import java.util.*; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import static org.junit.jupiter.api.Assertions.*; + +class BytecodeSearchContractTest { + /** Different terminal int payloads collide under Arrays.hashCode and must remain distinct. + * @param directory compiler workspace + * @throws Exception for fixture failures */ + @Test void hashCollisionsStillCompareCompletePayloads(@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=31;} @Actor(id=1)public void second(){x=256;} + } + """); + var program=BytecodeLoader.load(classes,"Fixture",BytecodeLimits.defaults()); + var result=new BytecodeExplorer(program,BytecodeScheduler.Mode.REFERENCE).explore(100000); + assertTrue(result.exhaustive());assertEquals(2,result.witnesses().size()); + var first=result.witnesses().get(0).state().canonicalBytes();var second=result.witnesses().get(1).state().canonicalBytes(); + assertFalse(Arrays.equals(first,second));assertEquals(Arrays.hashCode(first),Arrays.hashCode(second)); + assertEquals(Set.of(31,256),result.witnesses().stream().map(w->((BytecodeState.Int)w.state().fixtureField("x")).value()).collect(java.util.stream.Collectors.toSet())); + // Seven stages per actor; the sixteen positions after both writes have two possible values:49+16=65. + // Independent Python stage enumeration also yields65 states and108 enabled edges. + assertEquals(65,result.metrics().states());assertEquals(108,result.metrics().transitions());assertEquals(109,result.metrics().encodingCalls()); + } + + /** Checker limits/cancellation stay external incomplete results, with no fabricated modeled cutoff. + * @param directory compiler workspace + * @throws Exception for fixture failures */ + @Test void externalStopsAreNotModeledCutoffs(@TempDir Path directory) throws Exception { + var program=load(directory); + for(var budget:List.of(new BytecodeExplorer.Budget(0,1000000),new BytecodeExplorer.Budget(10000,0),new BytecodeExplorer.Budget(1,1000000))) { + var result=new BytecodeExplorer(program,BytecodeScheduler.Mode.REFERENCE).explore(budget); + assertFalse(result.traversalComplete());assertFalse(result.exhaustive()); + var witness=result.witnesses().getLast();assertEquals(BytecodeExplorer.Kind.INTERRUPTED,witness.outcome().kind()); + assertNull(witness.outcome().cutoff());assertNull(witness.outcome().observer());assertNull(witness.outcome().fault()); + } + try { + Thread.currentThread().interrupt(); + var result=new BytecodeExplorer(program,BytecodeScheduler.Mode.REFERENCE).explore(10000); + assertEquals("CANCELLED",result.witnesses().getFirst().outcome().interruption());assertEquals(0,result.metrics().states()); + assertTrue(Thread.currentThread().isInterrupted()); + } finally {Thread.interrupted();} + assertThrows(IllegalArgumentException.class,()->new BytecodeExplorer.Budget(-1,1)); + assertThrows(IllegalArgumentException.class,()->new BytecodeExplorer.Budget(1,-1)); + } + + /** Returned schedules contain enabled original choices and reproduce their actual internal states. + * This is not the public strict replay format owned by94C. + * @param directory compiler workspace + * @throws Exception for fixture failures */ + @Test void internalWitnessesFollowActualEnabledChoices(@TempDir Path directory) throws Exception { + var program=load(directory);var initial=program.initialState().canonicalBytes(); + for(var mode:BytecodeScheduler.Mode.values()) { + var explorer=new BytecodeExplorer(program,mode);var result=explorer.explore(100000); + assertTrue(result.exhaustive()); + for(var witness:result.witnesses()) { + var scheduler=new BytecodeScheduler(program,mode);var state=program.initialState(); + for(var selection:witness.schedule()) { + assertTrue(scheduler.choices(state).contains(selection.actor())); + var next=scheduler.advance(state,selection.actor());assertEquals(selection.executed(),next.executed());state=next.state(); + } + assertArrayEquals(witness.state().canonicalBytes(),state.canonicalBytes()); + assertFalse(state.executions.containsKey(BytecodeState.OBSERVER)); + } + var again=explorer.explore(100000);assertEquals(result.metrics().states(),again.metrics().states()); + assertArrayEquals(initial,program.initialState().canonicalBytes()); + } + } + + /** A full state budget still permits edges to already-stored states. + * @param directory compiler workspace + * @throws Exception for fixture failures */ + @Test void exactStateBudgetAllowsRemainingDuplicateEdges(@TempDir Path directory) throws Exception { + var program=load(directory); + var explorer=new BytecodeExplorer(program,BytecodeScheduler.Mode.REFERENCE);long start=System.nanoTime();var result=explorer.explore(140);long elapsed=System.nanoTime()-start; + assertTrue(result.exhaustive());assertEquals(140,result.metrics().states());assertEquals(246,result.metrics().transitions()); + assertEquals(2,result.witnesses().size());assertEquals(178,result.metrics().instructions());assertEquals(178,result.metrics().opcodes()); + assertEquals(247,result.metrics().encodingCalls());assertEquals(118191,result.metrics().encodingBytes());assertEquals(66946,result.metrics().retainedKeyBytes()); + assertTrue(result.metrics().encodingNanos()>0);assertTrue(result.metrics().encodingNanos()<=elapsed); + assertEquals(0,result.metrics().checkInvocations());assertEquals(0,result.metrics().checkInstructions()); + assertEquals(new BytecodeSharing.Work(1,2,0,0),result.metrics().sharing()); + assertTrue(explorer.explore(new BytecodeExplorer.Budget(140,66946)).exhaustive()); + var shortKeys=explorer.explore(new BytecodeExplorer.Budget(140,66945));assertFalse(shortKeys.exhaustive()); + assertEquals("KEY_BYTES",shortKeys.witnesses().getLast().outcome().interruption()); + var shortStates=explorer.explore(139);assertFalse(shortStates.exhaustive());assertEquals(139,shortStates.metrics().states()); + assertTrue(explorer.explore(140).exhaustive(),"A prior interruption must not leak into a reused explorer"); + assertThrows(NullPointerException.class,()->explorer.explore((BytecodeExplorer.Budget)null)); + } + + /** Independent concurrent runs share metadata without target state or search-store interference. + * @param directory compiler workspace + * @throws Exception for fixture or worker failures */ + @Test void immutableProgramSupportsIndependentConcurrentRuns(@TempDir Path directory) throws Exception { + var program=load(directory);var initial=program.initialState().canonicalBytes(); + try(var workers=java.util.concurrent.Executors.newFixedThreadPool(2)) { + var reference=workers.submit(()->new BytecodeExplorer(program,BytecodeScheduler.Mode.REFERENCE).explore(100000)); + var batched=workers.submit(()->new BytecodeExplorer(program,BytecodeScheduler.Mode.BATCHED).explore(100000)); + try { + var first=reference.get(10,java.util.concurrent.TimeUnit.SECONDS);var second=batched.get(10,java.util.concurrent.TimeUnit.SECONDS); + assertTrue(first.exhaustive());assertTrue(second.exhaustive()); + assertEquals(BytecodeBatchingOracleTest.independentProjection(first),BytecodeBatchingOracleTest.independentProjection(second)); + assertArrayEquals(initial,program.initialState().canonicalBytes()); + } finally {reference.cancel(true);batched.cancel(true);} + } + } + + /** Loads a tiny shared-state model without observer callbacks. + * @param directory compiler workspace + * @return validated model + * @throws Exception for fixture failures */ + private static BytecodeProgram load(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++;} + } + """); + return BytecodeLoader.load(classes,"Fixture",BytecodeLimits.defaults()); + } +} diff --git a/src/test/java/dev/samhb/interleave/bytecode/BytecodeWorkProbe.java b/src/test/java/dev/samhb/interleave/bytecode/BytecodeWorkProbe.java new file mode 100644 index 0000000..a92aadc --- /dev/null +++ b/src/test/java/dev/samhb/interleave/bytecode/BytecodeWorkProbe.java @@ -0,0 +1,51 @@ +/** Child-JVM entry point for independently validating PIT-only bytecode progress assertions. */ +package dev.samhb.interleave.bytecode; + +import java.nio.file.Path; +import java.util.TreeSet; + +/** Never shipped in the production artifact or used as a model execution fallback. */ +public final class BytecodeWorkProbe { + /** Prevents construction of this child entry point. */ + private BytecodeWorkProbe() {} + /** Runs a real fixture through internal search, reporting assertion failures separately from verdicts. + * @param arguments fixture class directory + */ + public static void main(String[] arguments) { + try { + var program=BytecodeLoader.load(Path.of(arguments[0]),"Fixture",BytecodeLimits.defaults()); + if(arguments.length>1 && arguments[1].equals("cancel")){cancelAfterCommit(program);System.out.println("CANCELLATION_OWNED");return;} + var result=new BytecodeExplorer(program,BytecodeScheduler.Mode.REFERENCE).explore(100000); + if(!result.exhaustive())throw new IllegalStateException("Probe traversal incomplete"); + var kinds=new TreeSet();for(var witness:result.witnesses())kinds.add(witness.outcome().kind().toString()); + System.out.println("OUTCOMES "+kinds); + } catch(AssertionError exceeded) { + if(exceeded.getMessage()==null || !exceeded.getMessage().startsWith("Bytecode logical"))throw exceeded; + System.out.println("BOUND_EXCEEDED"); + } + } + + /** Verifies cancellation injected after exactly one real local, shared-write or implicit-entry step. + * The replacement scheduler is test-only; no pause/callback is added to production code. + * @param program immutable cancellation fixture */ + private static void cancelAfterCommit(BytecodeProgram program) { + var scheduler=new BytecodeScheduler(program,BytecodeScheduler.Mode.BATCHED); + for(int scenario=0;scenario<3;scenario++) { + var parent=program.initialState();int actor=scenario==2 ? 1 : 0; + if(scenario==1)for(int local=0;local<2;local++)parent=OpcodeExecutor.step(program,parent,actor).state(); + byte[] before=parent.canonicalBytes(); + try {scheduler.advance(parent,actor);throw new AssertionError("Injected cancellation was ignored");} + catch(java.util.concurrent.CancellationException expected) { + if(!Thread.currentThread().isInterrupted() || !java.util.Arrays.equals(before,parent.canonicalBytes()))throw new AssertionError("Cancelled scratch work mutated its parent"); + } finally {Thread.interrupted();} + } + var initial=program.initialState();var before=initial.canonicalBytes(); + try { + var result=new BytecodeExplorer(program,BytecodeScheduler.Mode.BATCHED).explore(100000); + if(result.traversalComplete() || result.witnesses().size()!=1 || result.witnesses().getFirst().outcome().kind()!=BytecodeExplorer.Kind.INTERRUPTED + || !"CANCELLED".equals(result.witnesses().getFirst().outcome().interruption()) + || !java.util.Arrays.equals(before,result.witnesses().getFirst().state().canonicalBytes()))throw new AssertionError("Explorer did not preserve the external cancellation prefix"); + } finally {Thread.interrupted();} + } + +} diff --git a/src/test/java/dev/samhb/mutationharness/BytecodeWorkBudgetTest.java b/src/test/java/dev/samhb/mutationharness/BytecodeWorkBudgetTest.java new file mode 100644 index 0000000..3250eef --- /dev/null +++ b/src/test/java/dev/samhb/mutationharness/BytecodeWorkBudgetTest.java @@ -0,0 +1,131 @@ +/** Real-definition and child-JVM checks for bytecode DFS/observer logical-work assertions. */ +package dev.samhb.mutationharness; + +import java.lang.classfile.*; +import java.lang.classfile.instruction.*; +import java.nio.file.*; +import java.util.*; +import java.util.concurrent.TimeUnit; +import javax.tools.ToolProvider; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import static org.junit.jupiter.api.Assertions.*; + +class BytecodeWorkBudgetTest { + /** Child replacement workspace. */ + @TempDir Path directory; + + /** Original definitions preserve lost-update detection and normal completion with/without instrumentation. + * @throws Exception for child/fixture failures */ + @Test void preservesRealSearchAndObserverOutcomes() throws Exception { + assertEquals("OUTCOMES [CHECK_FALSE, COMPLETED]",run(null,null,false)); + assertEquals("OUTCOMES [CHECK_FALSE, COMPLETED]",run(null,null,true)); + } + + /** Interrupts deterministically after an actual primitive commit, including a shared write and method entry. + * @throws Exception for class/child failures */ + @Test void cancellationAfterPrimitiveCommitKeepsParentOwned() throws Exception { + var file=classFile();int[] checkpoints={0}; + var changed=file.transformClass(file.parse(bytes("BytecodeScheduler")),ClassTransform.transformingMethodBodies( + method->method.methodName().equalsString("advance"),(code,element)->{ + code.with(element); + if(element instanceof InvokeInstruction call && call.owner().asInternalName().equals("dev/samhb/interleave/bytecode/OpcodeExecutor") && call.name().equalsString("step")) { + checkpoints[0]++;var thread=java.lang.constant.ClassDesc.of("java.lang.Thread"); + code.invokestatic(thread,"currentThread",java.lang.constant.MethodTypeDesc.of(thread)) + .invokevirtual(thread,"interrupt",java.lang.constant.MethodTypeDesc.of(java.lang.constant.ConstantDescs.CD_void)); + } + })); + assertEquals(2,checkpoints[0]);assertEquals(List.of(),file.verify(changed)); + assertEquals("CANCELLATION_OWNED",run("BytecodeScheduler",changed,false,"cancel")); + } + + /** Removing the actual deque pop must fail a finite graph-work assertion, never a wall-clock oracle. + * @throws Exception for class/child failures */ + @Test void catchesRemovedDfsPop() throws Exception { + var file=classFile();int[] changed={0};var original=bytes("BytecodeExplorer"); + var mutant=file.transformClass(file.parse(original),ClassTransform.transformingMethodBodies( + method->method.methodName().equalsString("explore"),(code,element)->{ + if(element instanceof InvokeInstruction call && call.owner().asInternalName().equals("java/util/ArrayDeque") && call.name().equalsString("pop")) { + code.pop().aconst_null();changed[0]++; + } else code.with(element); + })); + assertEquals(1,changed[0]);assertEquals(List.of(),file.verify(mutant)); + assertEquals(List.of(),file.verify(BytecodeWorkBudget.instrument(mutant,true,getClass().getClassLoader()))); + assertEquals("BOUND_EXCEEDED",run("BytecodeExplorer",mutant,true)); + } + + /** A real root-return size removal is stopped by the independent per-invocation event bound. + * @throws Exception for class/child failures */ + @Test void catchesObserverRootReturnRegression() throws Exception { + var file=classFile();int[] changed={0}; + var mutant=file.transformClass(file.parse(bytes("BytecodeChecks")),ClassTransform.transformingMethodBodies( + method->method.methodName().equalsString("evaluate"),(code,element)->{ + if(element instanceof InvokeInstruction call && call.owner().asInternalName().equals("java/util/ArrayList") && call.name().equalsString("size")) { + code.pop().iconst_0();changed[0]++; + } else code.with(element); + })); + assertEquals(1,changed[0]);assertEquals(List.of(),file.verify(mutant)); + assertEquals("BOUND_EXCEEDED",run("BytecodeChecks",mutant,true)); + } + + /** Binding/checkpoint drift fails closed rather than silently omitting the instrumentation. + * @throws Exception for class-file failures */ + @Test void rejectsMethodAndCheckpointDrift() throws Exception { + var file=classFile(); + for(String name:List.of("BytecodeExplorer","BytecodeChecks")) { + var original=bytes(name);String method=name.equals("BytecodeExplorer") ? "explore" : "evaluate"; + var missing=file.transformClass(file.parse(original),ClassTransform.dropping(element->element instanceof MethodModel m && m.methodName().equalsString(method))); + assertThrows(IllegalArgumentException.class,()->BytecodeWorkBudget.instrument(missing,false,getClass().getClassLoader())); + var noCheckpoint=file.transformClass(file.parse(original),ClassTransform.transformingMethodBodies(m->m.methodName().equalsString(method),(code,element)->{ + if(element instanceof InvokeInstruction call && (call.name().equalsString("peek") || call.name().equalsString("currentThread"))) { + if(call.name().equalsString("peek"))code.pop();code.aconst_null(); + } else code.with(element); + })); + assertThrows(IllegalArgumentException.class,()->BytecodeWorkBudget.instrument(noCheckpoint,false,getClass().getClassLoader())); + assertEquals(List.of(),file.verify(BytecodeWorkBudget.instrument(noCheckpoint,true,getClass().getClassLoader()))); + } + } + + /** Resolves checker implementation types, never application model classes. + * @return class-file service for host checker verification */ + private static ClassFile classFile(){return ClassFile.of(ClassFile.ClassHierarchyResolverOption.of(ClassHierarchyResolver.ofClassLoading(BytecodeWorkBudgetTest.class.getClassLoader())));} + + /** Reads the real compiled checker definition. + * @param name checker class name + * @return original bytes + * @throws Exception for missing/failed resources */ + private static byte[] bytes(String name) throws Exception { + try(var source=BytecodeWorkBudgetTest.class.getResourceAsStream("/dev/samhb/interleave/bytecode/"+name+".class")) {assertNotNull(source);return source.readAllBytes();} + } + + /** Launches a bounded child and always reaps it; the timeout is only process-startup safety. + * @param name optional replacement checker class + * @param replacement optional actual mutant + * @param agent whether the existing test-only agent is active + * @param modes optional deterministic cancellation probe mode + * @return stripped successful child output + * @throws Exception for fixture/process failures */ + private String run(String name,byte[] replacement,boolean agent,String... modes) throws Exception { + Path classes=Files.createTempDirectory(directory,"classes");String classpath=System.getProperty("interleave.testRuntimeClasspath"); + Path source=classes.resolve("Fixture.java");String body=modes.length==0 ? """ + import dev.samhb.interleave.bytecode.*; + @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;}} + """ : """ + import dev.samhb.interleave.bytecode.*; + @Model public class Fixture {public int x;public Fixture(){} + @Actor(id=0)public void first(){x=1;} @Actor(id=1)public synchronized void second(){}} + """; + Files.writeString(source,body); + assertEquals(0,ToolProvider.getSystemJavaCompiler().run(null,null,null,"--release","26","-classpath",classpath,"-d",classes.toString(),source.toString())); + if(replacement!=null) {Path target=classes.resolve("dev/samhb/interleave/bytecode/"+name+".class");Files.createDirectories(target.getParent());Files.write(target,replacement);} + var command=new ArrayList();command.add(Path.of(System.getProperty("java.home"),"bin","java").toString()); + if(agent)command.add("-javaagent:"+System.getProperty("interleave.mutationHarnessJar")); + command.addAll(List.of("-cp",classes+java.io.File.pathSeparator+classpath,"dev.samhb.interleave.bytecode.BytecodeWorkProbe",classes.toString())); + command.addAll(List.of(modes)); + Path output=Files.createTempFile(directory,"child",".log");var child=new ProcessBuilder(command).redirectErrorStream(true).redirectOutput(output.toFile()).start(); + try {assertTrue(child.waitFor(15,TimeUnit.SECONDS),"Bytecode harness child did not terminate");String text=Files.readString(output);assertEquals(0,child.exitValue(),text);return text.strip();} + finally {if(child.isAlive()){child.destroyForcibly();assertTrue(child.waitFor(5,TimeUnit.SECONDS),"Bytecode child could not be reaped");}} + } +} diff --git a/src/test/resources/bytecode/concurrency/lost-update/Fixture.java b/src/test/resources/bytecode/concurrency/lost-update/Fixture.java new file mode 100644 index 0000000..15757a8 --- /dev/null +++ b/src/test/resources/bytecode/concurrency/lost-update/Fixture.java @@ -0,0 +1,12 @@ +/** Two explicit actors race through separate shared read/write bytecodes. */ +@Model public class Fixture { + public int x; + /** Starts with x=0 and no actor allocations. */ + public Fixture() {} + /** Reads and writes the shared counter. */ + @Actor(id=0) public void first() { x++; } + /** Competes with the first actor's increment. */ + @Actor(id=1) public void second() { x++; } + /** Declares the final shared counter property; deadlocked prefixes do not run FINAL checks. */ + @Check public boolean valid() { return x==2; } +} diff --git a/src/test/resources/bytecode/concurrency/two-lock/Fixture.java b/src/test/resources/bytecode/concurrency/two-lock/Fixture.java new file mode 100644 index 0000000..55c9b9c --- /dev/null +++ b/src/test/resources/bytecode/concurrency/two-lock/Fixture.java @@ -0,0 +1,14 @@ +/** Opposing setup-allocated monitors admit a wait cycle and successful serialized schedules. */ +@Model public class Fixture { + public final Object left=new Object(); + public final Object right=new Object(); + public int x; + /** Creates both distinct lock identities during interpreted setup. */ + public Fixture() {} + /** Acquires left before right. */ + @Actor(id=0) public void first() { synchronized(left) { synchronized(right) { x++; } } } + /** Acquires right before left. */ + @Actor(id=1) public void second() { synchronized(right) { synchronized(left) { x++; } } } + /** Declares the final shared counter property; deadlocked prefixes do not run FINAL checks. */ + @Check public boolean valid() { return x==2; } +}