diff --git a/CONTEXT.md b/CONTEXT.md new file mode 100644 index 0000000..c944ae6 --- /dev/null +++ b/CONTEXT.md @@ -0,0 +1,23 @@ + +# Interleave + +Vocabulary for explicit-state checking across existing models and the selected bytecode profile. + +## Language + +**Actor**: A fixed modeled participant whose actions the checker schedules. In the bytecode profile an actor is an annotation-declared method invocation on the shared fixture. + +**Scheduling transition**: One selected actor's observable operation and any justified local computation around that operation. It is distinct from an executed opcode. +_Avoid_: instruction when referring to a scheduler choice. + +**Instruction fuel**: The remaining allowance for interpreted opcodes in one actor's execution, setup, or one check invocation. +_Avoid_: transition limit. + +**Cutoff**: An omitted modeled operation that ends one bounded execution prefix. It does not freeze the actor for continued execution of that prefix. + +**Resource interruption**: An external checker stop, such as a deadline or global memory safeguard. It establishes incompleteness without asserting a reproducible modeled cutoff. + +**Sharedness history**: Irreversible knowledge that an object has become shared during an execution, even if its current references later change. + +**Bytecode location**: An artifact-bound class, method descriptor and bytecode index, optionally accompanied by a compiler line number. +_Avoid_: source span for bytecode evidence. diff --git a/README.md b/README.md index 930fb8c..14b223c 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,10 @@ 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 next workstream is [#12 bounded Java bytecode checking](docs/plans/bytecode-contract.md), +currently **specification only**. Its first public release follows internal interpreter/concurrency +milestones; no bytecode CLI or runtime support 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. ## What it does diff --git a/docs/plans/bytecode-contract.md b/docs/plans/bytecode-contract.md new file mode 100644 index 0000000..e30593a --- /dev/null +++ b/docs/plans/bytecode-contract.md @@ -0,0 +1,440 @@ + +# #12 — Bounded Java bytecode checking + +## Objective and status + +**Selected; specification only.** 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. + +Planning baseline: remote main `2a242c4`, freshly fetched during authoring. B10 is complete through +PRs #136/#137 and its closure commit. Sam explicitly selected #12 after that stopping point; #11 +and parked conditional/deferred tasks remain unselected. No bytecode implementation or runtime +measurement is established by this PR. [Vocabulary](../../CONTEXT.md) owns domain terms; this document +owns common behavior, interface seams, verification and phase boundaries. + +## Sequential delivery and ownership + +One specification PR followed by **ten implementation PRs**, sequentially into main. Split further +only for a distinct reviewable behavior or correctness argument. Each phase owns its affected callers, +tests, fixtures, documentation and consumers. A spec merge enables no capability. + +| Phase | Specification | Complete delivery and release boundary | +|---|---|---| +| 94A | [Interpreter foundation](../specs/active/94A-bytecode-foundation.md) | Internal loader, owned state, single-actor execution/faults, fuel and setup lock references; JVM differential cases | +| 94B | [Concurrent execution](../specs/active/94B-bytecode-concurrency.md) | Internal actors, monitors/cleanup, exact DFS, checks, reference/batching and measured feasibility gate | +| 94C | [Initial public release](../specs/active/94C-bytecode-release.md) | BYTECODE evidence, strict replay, library/CLI, reports/viewer and complete lost-update/deadlock examples | +| 95 | [Objects, arrays and dispatch](../specs/active/95-bytecode-heap.md) | Actor allocations, aliases, arrays, hierarchy/dispatch, publication and accounting | +| 96 | [Exceptions](../specs/active/96-bytecode-exceptions.md) | General supported catch/finally, ordered handlers, unwinding, suppression and restricted try-with-resources | +| 97 | [Primitives and core library](../specs/active/97-bytecode-core-library.md) | Remaining primitives, exact descriptor allowlist, deterministic intrinsic semantics | +| 98 | [CBS](../specs/active/98-bytecode-cbs.md) | Exact context bounds, cost dominance, evidence and all consumers | +| 99 | [Restricted DPOR](../specs/active/99-bytecode-dpor.md) | Admission/resource analysis, dependency/observation summaries, preservation argument, fallback and measured reduction | +| 100 | [Narrow atomics](../specs/active/100-bytecode-atomics.md) | Integer/Boolean/Reference construction, get/set and strong CAS; cyclic retry fallback | +| 101 | [Bitstate and completion](../specs/active/101-bytecode-bitstate.md) | One-filter approximate DFS/CBS/DPOR, full consumers, compiler/JPF evidence and scope closure | + +Do not expose public bytecode selectors before 94C. Internal 94A/B remain testable without installing +public partial entry points. Do not implement a synthetic list of fuel-limit steps or append cutoff +sentinels. Later phases extend the profile version and admission registry together with strict replay. + +## Loading and public interfaces + +Use JDK 26 `java.lang.classfile`, with a metadata-only hierarchy resolver. +The checker already requires JDK26+ (build.gradle.kts toolchain/release=26, README requirements and +CI setup-java=26); this adds no runtime-floor or packaging change. Input class-file floor17 is +distinct from the checker runtime requirement. Parse target bytes; never +reflectively load/instantiate/invoke target classes, execute initializers, or fall back to JDK methods. +The [Class-File API](https://docs.oracle.com/en/java/javase/26/docs/api/java.base/java/lang/classfile/package-summary.html) +provides class models; parsing alone is not this profile's bytecode verifier. + +Accept non-preview Java 17–26 class files (major 61–70, minor 0) from **one directory classpath**. +No JAR discovery, automatic compilation or ambient host application classpath. Resolve binary names +under the canonical root, reject escapes/symlink escapes, duplicate/conflicting identities and missing +metadata. Bound reads before allocation: 64 application classes, 1 MiB/class, 8 MiB total. Include +all application classes used by the closed reachable hierarchy, not merely initially called methods. +Use explicit trusted metadata for supported platform classes; missing/unknown metadata rejects. +Validate access, descriptors, stack/local types, branch/handler targets, constructor initialization, +return types and reachable opcode/call support before exploration. Inspect all branch alternatives +and possible dispatch targets; runtime values do not excuse unsupported reachable code. Unreachable +methods may remain unsupported unless hierarchy validity or class initialization requires inspection. +No filesystem access or resolution occurs during exploration/replay after loading the frozen artifact. + +Reject application `` with executable behavior; an absent or return-only initializer is allowed. +Supported ConstantValue fields initialize without execution; otherwise static fields have JVM default +values. Ordinary static Object locks, static arrays, enum machinery and assertion-status initialization +usually need executable `` and reject. Initialize instance locks in the fixture constructor and +use declared checks instead of Java assertions. This remains true in later phases; no initializer allowlist. + +94C introduces `dev.samhb.interleave.format.BytecodeProgramLoader`: + +```java +public static BytecodeProgram load(Path classDirectory, String modelClass); +public static BytecodeProgram load(Path classDirectory, String modelClass, BytecodeLimits limits); +// InterleaveRunner: a distinct name keeps existing run(Program), including null calls, compatible. +public TestResult runBytecode(BytecodeProgram program); +// TraceReplayer: validate and return an immutable record with actual replay snapshots/observations. +public TraceRecord replayBytecode(BytecodeProgram program, TraceRecord record); +``` + +`BytecodeProgram` is immutable, retaining bytes/metadata, profile identity, validated declarations, +limits and interpreted setup snapshot. Returned instances cannot be forged by public construction. +All three public types BytecodeProgram/BytecodeLimits/BytecodeLoadException live in +`dev.samhb.interleave.bytecode`; the facade alone lives in `format`. BytecodeProgram has no public +constructor and exposes `artifactDigest()`, `profileVersion()` and `limits()` read-only accessors. +BytecodeLoadException extends IllegalArgumentException and exposes a stable diagnostic category plus +optional bytecode location; no target throwable is loaded on the host. + +```java +public record BytecodeLimits(int actorInstructions, int actorAllocations, int actorHeapCells, + int maxCallDepth, int maxArrayLength, int maxStringLength, int setupInstructions, + int setupAllocations, int setupHeapCells, int checkInstructions) { + public static BytecodeLimits defaults(); +} +``` + +The canonical constructor validates every component against the table below; no public mutable builder +or unvalidated bypass. Internal execution mode is +REFERENCE or BATCHED; the production default is BATCHED only after 94B's gate. Evidence records mode. +`load` rejects invalid/null input and setup failure with an actionable loading diagnostic containing +class/method/BCI when available; no search verdict is emitted. Diagnostics must distinguish malformed +input, unsupported behavior, missing metadata, limits and interpreted setup fault. Independent repeated +and concurrent runs share immutable metadata and start from isolated state. +`runBytecode` uses declared interpreted checks and owned storage only. Reject a non-null builder +Invariant, explicit generic stateStore/stateStoreFactory, or symmetry-specific configuration before +execution; do not invoke arbitrary model/property/store callbacks or silently ignore them. Strategy, +maxStates/maxTime and supported CBS options retain their existing meanings. Default bytecode storage +is EXACT. In101 add `Builder.bytecodeBitstate(int bits, int hashFunctions)` for an owned one-filter +selection with positive validated arguments; reject this configuration on ordinary run(Program). +CLI keeps its existing exact|bitstate flags and routes to the corresponding owned bytecode selection. +No caller-supplied StateStore adapter is admitted merely because it has a familiar class name. + +Annotations live in `dev.samhb.interleave.bytecode` and are parsed as metadata: +`@Model` on one concrete fixture class; `@Actor(id = 0)` on public instance `()V` methods; dense unique IDs +0..n-1, 1..8 actors; `@Check(when = ALWAYS | FINAL)` on public instance `()Z` methods, default FINAL. +Use CLASS retention, TYPE/METHOD targets respectively. `Actor.id()` is int without a default; +`Check.when()` returns the nested public enum `Check.When { ALWAYS, FINAL }` with default FINAL. In the first profile the fixture directly extends +Object; static helpers have exact known targets. Inherited annotated entry points are rejected; 95 +allows internal inheritance/dispatch without silently changing entry-point discovery. One annotation +role per method. Sort checks by declaring binary class, name, descriptor for deterministic failure order. +Construct the shared fixture via interpreted public `()V` constructor. All actor receivers are this same +fixture, with independent stacks. Checks may be absent. Setup finishes before actors/checks begin. + +CLI: `--bytecode --class-path `, mutually exclusive with built-in/all/file +selection; require both exactly once. Reuse strategy/store/bound options and defaults subject to +phase admission: 94C–97 exact DFS only; 98 adds CBS; 99 adds DPOR with reported fallback; 101 adds +BITSTATE for supported strategies. Omitted strategy selects only currently supported bytecode +strategies. Explicit static POR, symmetry, unavailable storage/strategy or incompatible source-only +options reject before search; do not silently substitute them. No new CLI resource flags are required; +use documented BytecodeLimits defaults. Library callers can select immutable custom limits. Omitted store selects EXACT before101; +101 may run the existing exact/bitstate selection matrix. Legacy input-mode defaults remain unchanged. + +## First-release language and execution seams + +94A/B/C support int/boolean values and field/static access, constants, local loads/stores, integer +arithmetic/bitwise/shifts/conversions i2b/i2c/i2s, comparisons, conditional/unconditional branches, +tableswitch/lookupswitch, loops, known static application helpers, constructor invokespecial, return, +reference locals/fields/null/identity comparisons needed for fixture lock wiring, and synchronized +blocks/methods. Stack operations must obey verifier categories, including wide local-index forms. +Only setup allocates: one fixture plus distinct plain Object monitors via Object.`()V`; no +arbitrary application helper-object construction, actor `new`, arrays, general virtual/interface calls, +explicit user `athrow` or general user handlers until their owning phases. String ConstantValue metadata +may be retained initially; executable String operations/constants requiring modeled String storage +reject until 96 introduces immutable exception-message constants and 97 the remaining String profile. Class literals for arbitrary application use reject; internal +class-monitor identity for static synchronized helpers is supported without reflection. + +Every run owns a bytecode state: heap/statics, actor frames (method/BCI, locals, operand stack), pending +exception/unwind/terminal events, monitors and counters. Instruction decoding is immutable. Define one +opcode executor used by both modes; selection/classification must be pure and return executable next +choice, blocked monitor or pending terminal event without charging fuel or committing effects. +Bytecode branches/backedges update real continuations, never source scheduling ordinals. + +Internal seam (94A/B; names describe obligations, not new public extension points): frozen metadata + +state + actor + mode → isolated transition result containing committed state, executed opcode locations, +observable effects, or pending terminal/cutoff evidence. Search and replay call this same executor. +A bytecode-specific search adapter owns enabledness and canonical keys. Reuse stores and result types +where honest; do not force bytecode into source Forward SourceStep lists or weaken existing source +validation. An exceptional terminal snapshot may preserve earlier committed bytecode effects; legacy +StepTransition's no-successor failure contract remains unchanged for source/JSON. + +## Scheduling, batching and observations + +Every executed opcode costs one unit of its execution owner's instruction fuel, including a faulting +opcode. Calls cost their invoke opcode plus executed callee opcodes. Implicit operations/intrinsics +have explicit additional costs specified below; probes and disabled monitor attempts cost zero. +From94A, trusted Object.()V costs invoke1 plus intrinsic1; it adds no payload fields. Class-monitor +entry/exit and initial pending VM-fault metadata propagation cost zero; actual cleanup opcodes cost1. +Insufficient fuel for an existing next opcode creates a selectable cutoff event before testing that +opcode's dynamic blocking/fault conditions. Thus zero-fuel monitor entry is exhaustion, not deadlock; +a disabled monitor attempt with sufficient fuel still consumes nothing. A pending normal termination +has no next opcode and can complete at zero fuel. Counters measure executed work, not scheduling transitions. For unit-cost opcodes, exactly N instructions are permitted; +normal return at N succeeds, the attempted next opcode yields a cutoff before N+1. +Multi-unit intrinsics from94A onward preflight invoke plus intrinsic cost and may cutoff with positive +remaining allowance, omitting the entire invoke without fuel/payload/identity charges. The omitted +location is the invoke BCI; record total required work and remaining allowance. Pure preflight can +inspect fault conditions to select the fixed fault cost; probes never execute callbacks. + +Required boundaries: shared field/static/array accesses, monitor acquire/release, reference publication, +atomic operations, termination, exception delivery/terminal failure and actual exhaustion. Shared `x++` +retains distinct read and write choices. Local prefixes may be batched only when they cannot change +another actor's enabledness, check value/error, dependency, resource outcome or terminal outcome. +Reference mode offers a choice at every opcode boundary and evaluates ALWAYS after every executed +opcode. BATCHED executes at most one observable operation plus justified local work and stops before +the next observable or terminal event. Initial/pure-local prefixes are permitted under the same rule. + +**Yield before terminal events**, even if a local sequence discovers a fault or budget exhaustion. +Save a pending event at an actual BCI, yield, then let a scheduler selection deliver it. Never charge or +mutate state in a classification probe. Reference mode uses compatible pending-event semantics so +another actor can run before termination, uncaught failure or cutoff is selected. Implicit synchronized +entry/exit and exception propagation are explicit events with real invoke/return/throw locations; +extra events have zero opcode fuel, and every enabled zero-cost event strictly advances pending-event +state. Cleanup opcodes still consume fuel. If cleanup exhausts fuel, end the prefix INCOMPLETE at the +omitted cleanup opcode; never claim monitors were released or the exception fully delivered. + +Sharedness: derive exclusive actor reachability transitively from statics, the shared fixture and +all actor roots, including frame references/pending values. Fixture/statics are shared roots. Unknown +ownership means shared. Before reference publication, promote the reachable subgraph; publication +is observable even if the containing object had been local. Once shared, remain shared for that +execution, and encode this history. Aliases/cycles require a terminating visited-object traversal; +account its cost in instrumentation. No heap renumbering, GC or reuse. Lock semantics and errors +remain observable regardless of object locality. + +Verify each check's entire reachable call graph against a pure allowlist. Reads and pure supported +operations are allowed; target mutation/allocation/synchronization, I/O, host callbacks and inspection +of actor frames/history/resource counters reject before search. Observer scratch frames are separate +and cannot escape. ALWAYS runs initially and at property-relevant boundaries, including cleanup and +exception effects; batching can omit checks only when both value and error are invariant. FINAL runs +only when every actor has normally terminated. False → VIOLATION/CHECK_FALSE. Check exception or +instruction/depth exhaustion → INCOMPLETE/OBSERVER_ERROR or OBSERVER_LIMIT. An exception raised during +an observer aborts that invocation immediately; observer execution does not enter target exception +handlers or allocate a target Throwable. This restriction remains explicit after96. Check fuel resets per +invocation; setup/actor fuel is unchanged. Evaluate ordered ALWAYS checks at a committed position +before deadlock/completion and before selecting a competing pending terminal. Never turn an observer +failure into PASS. An earlier established finding remains recorded if a later branch is incomplete. + +## Faults, monitors and verdicts + +Model null field/monitor access as NullPointerException and integer divide/remainder zero as +ArithmeticException. Preserve prior instruction effects; the faulting opcode follows JVM semantics +and consumes fuel. Required cleanup/unwinding runs, then an uncaught actor exception is +VIOLATION/UNCAUGHT_EXCEPTION, distinct from CHECK_FALSE. Capture actor, exception type, throwing +class/method/descriptor/BCI, and interpreted frames; do not use a host stack as target evidence. +Setup fault/limit is a load diagnostic; observer fault/limit is INCOMPLETE. Unsupported user handlers +reject before exploration until 96; compiler cleanup catch-all handlers are recognized by verified +control/data flow in 94A/B, not a compiler-name heuristic or arbitrary catch-all exemption. + +Monitor state is identity → owner/depth; reentrant acquisition increments, release decrements, final +release enables competitors. Disabled acquisition has no effects/fuel. Model null/nonowner release +faults; malformed structured-lock behavior rejects at validation. Synchronized method entry must +acquire before body execution, including static helpers' stable class monitors. Normal/abrupt return +releases the method monitor exactly once; nested compiler cleanup and method cleanup do not duplicate +release. A deadlock is a nonterminal state with blocked actors and no runnable opcode/pending event; +record concrete ownership and wait-for relationships. Do not call a fuel cutoff or all-asleep DPOR +position a deadlock. No fairness/liveness claim. + +A cutoff ends that prefix, explores sibling alternatives and records actor/reason/omitted location/ +limit and last committed state. Never freeze exhausted actors and continue that execution. Any +unexplored bound or resource interruption prevents an exhaustive absence verdict; retain genuine +positive findings with incompleteness metadata. Busy loops/retries may exhaust fuel, while bounded +terminating loops can succeed. Equal values with different remaining budgets are different states. + +## Limits, cells and identity + +Defaults are provisional settings; 94B measurements must review them before 94C. + +| Resource | Default | Hard ceiling | Scope | +|---|---:|---:|---| +| Actor instruction fuel | 256 | 4096 | Each actor, entire execution | +| Allocations | 128 | 4096 | Each allocating actor | +| Heap cells | 8192 | 65536 | Each allocating actor | +| Call depth | 32 | 256 | Each actor | +| Array length | 64 | 4096 | Each array | +| String UTF-16 length | 256 | 4096 | Each String | +| Setup instruction fuel | 4096 | 65536 | Setup only | +| Check instruction fuel | 1024 | 16384 | Each invocation | + +Setup has separate allocation/cell allowances with actor defaults/ceilings and separate depth using +actor depth limits. Check depth uses the same ceiling/value on private observer frames. Positive +integer limits at or below ceilings are accepted; zero/negative/overflow/excess values reject. +Allocation/cell charges are permanent to setup/allocating actor even after escape; per-resource checks +occur before object creation. Charge one cell for an object header plus one per inherited instance +field (long/double still one modeled cell), or array header plus length elements. String payload costs +header plus its declared modeled fields plus UTF-16 units; StringBuilder costs header/fields plus +logical capacity units. Throwable suppression/reference payloads and atomic value cells count too. +Do not duplicate charges for aliases or double-charge payloads backed by an already charged modeled +array. Static slots and built-in constants/caches belong to a separate bounded setup-owned table, +charged once against setup heap cells; deterministic materialization cannot depend on actor scheduling. +Constant-table entries do not consume setup's application-allocation count: their identities occupy a +separate tagged namespace, bounded by registry/input caps and setup cells. Count actual interpreted +setup new/array allocations normally. Each class-monitor constant costs one header cell; static slots +cost one cell apiece. Thus deterministic eager wrapper caches do not exhaust the default128 setup +application allocations merely by containing more cached values. 97's registry fixes +payload field/capacity counts and cache identities before enabling those descriptors. + +A cutoff identifies the selected executing actor; allocation/cell cutoffs additionally identify +the charged budget owner (setup or original allocator), including mutation of escaped modeled payloads. +Cell limits bound modeled storage, not JVM bytes. Metadata/input caps and a global checker safety +abort protect implementation overhead; report external safety aborts honestly as INCOMPLETE. Allocation, +cell and depth cutoffs name the omitted allocation/invoke location, reason and configured limit. +For simultaneous failures use fuel first, then opcode dynamic validity (e.g. negative length), then +array/String length, allocation count, cells, depth as applicable. Failed allocations charge no cells +or identities; an executed allocating opcode consumes fuel even if it cannot allocate. No exception +object allocation is required for initial modeled VM faults: bounded pending-fault metadata belongs +to actor state, with no fabricated user-visible Throwable before 96. + +Identity = `(setup | actor-id, allocation-sequence)`; sequences start at zero in each namespace and increase only on successful allocation. +The setup fixture is sequence0; subsequent setup allocations follow interpreted order. +Built-in class monitors/caches use distinct tagged deterministic constant namespaces. Encode every +future-relevant heap/alias/static/frame/BCI/stack/pending-event/monitor/sharedness/counter/sequence +value with typed length-delimited versioned keys. Exclude diagnostics that cannot affect execution. +Retain allocator charge histories even after objects become unreachable; no state merging by values +alone or identity renaming. Evidence and replay retain actual identities. + +## Exact search, CBS and DPOR + +DFS exact state enumeration is the execution reference; EXACT membership must compare full canonical payloads after hash filtering. CBS in 98 +uses the production scheduling granularity, last actor and minimum preemption cost per complete state. +A preemption is switching away from a runnable previous actor, not a switch forced by blocking or +termination. Minimum-cost dominance for positive behavior does not establish cutoff-equivalence: +retain uncovered cost-context obligations for prefix cutoffs before pruning a dominated position. +No dominated path may turn a bounded/incomplete traversal into an exhaustive absence claim. Compare to independent exhaustive enumeration at the same mode and bound. + +99 owns optimized bytecode DPOR. Admission requires acyclic reachable control flow **and** call graphs, +conservative resource upper bounds within selected limits, complete dependencies and check observations. +Include setup, all dispatch alternatives, intrinsic/implicit costs, exceptional cleanup, errors and +observer execution, including repeated ALWAYS invocations when bounding total checker work. Unknown cost/dependency/metadata or possible exhaustion selects exhaustive DFS +traversal; report requested DPOR, effective DFS and reason. Loops, including later CAS retries, remain +usable through DFS/CBS and DPOR fallback. Do not infer independence from separate actor fuel/budgets. + +Independence must preserve enabledness, commutation, observations and terminal outcomes, including +publication, constructor effects and allocation identities. Actual terminal cutoffs are conservatively +dependent with competing choices. Do not append sentinels; detect exhaustion from state when next +execution is attempted. Never reuse source's forward future-step scan for dynamic continuations +without bytecode-specific justification. Retain sleep context in exact visited products, and use a +written preservation argument, not tests alone. An eligible acyclic disjoint-write fixture must show +actual reduction versus DFS; labels without reduction fail 99 acceptance. Broader cyclic DPOR remains +research beyond this set. + +## Evidence, replay and consumers + +94C owns a distinct `BYTECODE` program/evidence discriminator, never SOURCE spans. Artifact identity +is SHA-256 of a versioned, sorted, length-prefixed manifest of binary names and exact class bytes plus +trusted intrinsic/profile version. Record selected limits and execution mode separately and validate +all on replay; changing debug bytes changes artifact identity. Hash the frozen closure, including +setup/check/dispatch metadata. Host directory paths are not semantic identity. + +Evidence records the selected modelClass binary name and validated actor/check entry-point mapping +separately from the artifact digest. Replay must match modelClass and declaration mapping even when +two selections have identical class manifests and even for empty-choice root/interrupted records. +Evidence contains actor choices, actual method/descriptor/BCI and optional compiler line, executed +opcode range/list per scheduling transition, outcomes, immutable snapshots, failure/check/deadlock/ +cutoff details and profile/limits. No invented source columns. Implicit events identify their causing +real BCI and event kind. Root check failure accepts empty choices. Strict replay rejects artifact/modelClass/declaration, +profile, limits/mode mismatch; disabled/foreign choices; changed outcomes/monitor ownership/checks; +trailing choices after earlier terminal observations; wrong omitted cutoff/limit; and fabricated +completion/deadlock. Replay captured external interruptions only as authenticated prefixes, retaining +original interruption and separate observations; do not reproduce wall-clock deadlines as model events. + +Use tagged lossless integer/long and floating raw-bit encodings (including NaN payload and signed zero) +when those types arrive. Viewer uses text-safe labels and caps; no numeric coercion through JavaScript +Number for 64-bit values. Extend TraceRecord/TestResult/reporting compatibly with optional bytecode +payloads or version native serialization when shape requires; do not pin old UIDs or relabel legacy +JSON/source. Minimization/source cutoff helpers remain source-only unless separately specified. +From 94C onward, all supported phase additions ship with strict replay, library, CLI, report, +normalization and browser fixtures in the same PR. Internal phases 94A and 94B expose no public +consumers and are exempt from this public-consumer requirement; their own internal verification gates +still apply. Requested/effective strategy and fallback reason are visible in all public consumers. + +## Library profile and exclusions + +97 defines the finite descriptor registry, modeled payloads, instruction costs and fault semantics; +100 owns narrow atomics. Supported user callbacks are interpreted through validated dispatch, never +executed by host JDK library code. Integer caching is exactly -128..127; other caches are explicit. +Volatile reads/writes have ordinary SC visible-access behavior with preserved metadata, without JMM +claims. Collections, wait/notify, dynamic threads, reflection, I/O, native/JDK fallback, lambdas, +unsupported bootstraps, bytecode static POR/symmetry and weak memory stay deferred. String concat +bootstrap support is restricted to 97's exact recipe; no general invokedynamic support. + +## Verification and measurement gates + +Each implementation starts with a fresh fetched merged-main SHA and baseline; historical test/PIT +counts are not baselines. Full build, tests and strict Javadoc; affected mutation census and unchanged +default PIT gate; relevant built-jar/CLI/report/replay/browser compatibility checks are mandatory. +Preserve inherited kills and distinct regressions. Report scoped versus default totals, surviving +fingerprints and NO_COVERAGE separately; uncovered/timeouts/run errors are not killed mutants. +All local Gradle runs include `--max-workers=1 -PpitestThreads=1`; CI stays parallel. + +Independent oracles: targeted JVM sequential differential fixtures and fixed-seed generated bounded +sequential programs with shrinking/saved regressions. JVM identity-hash integers and implicit message text are implementation-specific: compare their +specified consistency/type/effect contracts rather than requiring host numeric/text identity. +JVM execution is a **test oracle process only**, +never a production fallback. Concurrent reference enumeration is test-only and independent of batch +classification, optimized admission and canonical encoding. Compare normalized sets of violation/fault +identity, relevant final shared observations, deadlock ownership/wait relationships and cutoff +actor/reason/omitted location/limit. Do not demand equal traces, transition counts or local snapshots. + +94B early gate: same lost-update/two-lock programs and limits in REFERENCE/BATCHED; equal normalized +observable outcome sets required. Measure unique states, executed transitions, key-encoding calls and +bytes/time, elapsed time, retained memory, sharedness traversal frequency/objects/edges and states +differing only in historical flags. Record hardware/JDK/compiler/flags, source+artifact SHA, seeds, +warmup/forks, raw runs and variability; do not invent percentage targets or silently substitute heap +allocation for retained memory. 94B must report actual zero/not-applicable history-only metrics if the setup-only heap cannot exercise +nontrivial publication; it must not construct unsupported fixtures to obtain nonzero results. 95 owns +the nontrivial actor-local graph/publication/allocator adversarial cases and repeats those measurements. +Costs/proof gaps require investigation before 94C; changing approved +semantics to improve numbers requires a new decision. Measure normalized terminal pending-event +outcomes, not just verdict strings. + +Mandatory adversarial corpus: exhaustion competing with a violation, pure local infinite computation, +fuel-sensitive shared branches, exact-limit return, cyclic/aliased publication, reversed actor +allocation ordering, charges after escape, heap exhaustion, nested/reentrant cleanup and unknown +metadata. Apply each case when its behavior becomes supported: 94B covers terminal/fuel/monitor/check +cases; 95 adds allocation/publication/history cases. Add general exceptions, primitive edge values, +observers and atomics at their owning phases. + +Compiler compatibility: keep fixture sources, explicit compiler/release commands and expected +support in Git; generated class files live under build/test outputs, not committed binary artifacts. +Maintain supported/rejected Java 17/21/26 fixtures for string switches, enums, +array clone, nestmates, assertions, try-with-resources, records and pattern switches. Rejection is valid +where it matches phase support; a class-file version alone promises no unsupported construct. 101 +pins an actual JPF revision, probes accepted versions/required constructs, then chooses a mutual +compilation release without lowering Interleave's Java 17 input floor. Compare normalized outcomes +and explain scheduler/SC differences. If incompatible, record JPF gate **blocked** and scope not fully +accepted; no fabricated compatibility claim. jcstress/Lincheck may supplement, never replace exact +reference. This is future implementation evidence, not an authoring prerequisite. + +## Source-inspection evidence and proof obligations + +[verified, planning main] `core/Program` is final and distinguishes source by digest; `SourceStep` and +`Configuration.successorAt` enforce forward source continuations. `TransitionExecutor.execute` +special-cases SourceStep and generic failures produce no successor. `dpor/DporExplorer.dporDfs` +scans later list steps before sleeping competitors; its unknown-observation path uses exhaustive DFS. +These facts establish integration constraints, not bytecode compatibility. No `.codegraph` index or +existing domain authority was present in the isolated tree during inspection. + +[approved decision] Interpret target code only; use owned bytecode continuations and one opcode +executor. Batching requires a stuttering/observation argument covering resource and terminal events; +99 additionally needs an independence/sleep-coverage preservation argument. Each names assumptions, +state relation, event matching, counterexample tests and limits. A green suite alone is not a proof. + +[unverified] All bytecode performance/sharedness measurements, optimized reduction and JPF compatibility. +[deferred research] Frozen exhausted actors, fuel-free cycle detection, broader cyclic DPOR and +initializer allowlists. None is a release requirement or implied optimization opportunity. + +## Authoring and implementation workflow + +The [specification review record](bytecode-specification-review.md) separates actual authoring +checks, reader findings and CodeRabbit outcomes from future runtime acceptance. + +Follow the repository's spec template: objective, scope, non-goals, invariants, requirements, edge +cases, acceptance, baseline/rollback, design, current state, tests, constraints and skills. Reuse this +contract rather than duplicate semantics. Each milestone includes intended paths; new names are +planned, not claims of existing classes. Run actual CodeRabbit after completing each specification, +independently review dependencies/PR size/claims, and use fresh-reader testing from doc-coauthoring. +Record actual completion or quota/error status through agent-setup; ordinary review cannot stand in +for required CodeRabbit. Never use paid credits or change account/configuration to force reviews. + +This specification-only PR validates documentation/links/structure and records review evidence; no +production tests/PIT/interpreter benchmark claims. Each later implementation PR publishes its own +`docs/measurements/-bytecode-*.md` ledger, updates phase status and support matrix, includes +`Co-authored-by: Codex `, reports its PR link and stops. Sam supplies CI/review/merge +updates; do not watch CI or begin the next milestone before that update. diff --git a/docs/plans/bytecode-specification-review.md b/docs/plans/bytecode-specification-review.md new file mode 100644 index 0000000..c720d41 --- /dev/null +++ b/docs/plans/bytecode-specification-review.md @@ -0,0 +1,145 @@ + +# #12 specification authoring review + +## Scope and evidence boundary + +Planning base: freshly fetched remote main `2a242c4`. Authored one +[shared contract](bytecode-contract.md), ten sequential milestone specs (94A–94C,95–101), root +vocabulary and current roadmap pointers. No production/test/configuration code changes. +The original dirty checkout and existing context-store staged work were preserved. + +## Independent reader testing + +Two fresh readers received only named repository documents, without conversation history. One read +contract/94A–96; one read contract/97–101. They answered public-release, fuel/cleanup, setup/observer, +seam/measurement, intrinsic/cell, CBS/DPOR/bitstate and JPF questions and searched for contradictions. +Their findings and revisions: + +- Moved minimal immutable exception-message String storage to96; broader computation stays97. +- Marked nontrivial publication/history/allocator adversarial measurements as95 work;94B reports +actual zero/not-applicable costs where its setup-only profile cannot exercise them. +- Specified public types/limits/annotation shapes and selected existing EXACT rather than accidental +symmetry-backend expansion. A final local compatibility pass uses runBytecode to preserve run(Program). +- Defined full-cost intrinsic preflight, omitted invoke identity and unchanged counters on insufficient +allowance; qualified ordinary unit-opcode N/N+1 rules. Reader rechecks found these decisions clear. +- Removed cause-only Throwable constructors that could trigger an unmodeled overridden toString; +explicit message/cause constructors remain. Added finite descriptor/layout/cost contracts. +- Selected one101 ledger path and a deterministic modeled identity hash; readers found no remaining +material contradictions in their revised document subsets. This is document testing, not an interpreter proof. + +Local connected-source/ponytail review additionally checked loader/runner/store seams, DPOR future +scan, source forward validation, terminal ordering, resource ownership and all phase dependencies. +94B is a coherent concurrency/preservation gate;97 and101 are broad but can split only for distinct +behavior/correctness arguments under the approved target, without enabling partial consumers. + +## Actual CodeRabbit CLI invocations + +CLI0.8.1, existing Homebrew installation. Each invocation occurred after the named specification was +complete and reviewed the available integrated set with: + +```sh +coderabbit review --agent --uncommitted --include-untracked +``` + +No paid-credit flag, account changes or invented substitute review. Raw per-invocation NDJSON remains +local as `/private/tmp/interleave-bytecode--coderabbit.ndjson`; the outcome table below is the +portable result summary. Later reviews include revisions to the prior set; a heartbeat is not completion. + +| Completed document | Actual invocation result | Finding events | +|---|---|---| +| 94A | complete: review_completed | major, major | +| 94B | complete: review_completed | minor, major | +| 94C | complete: review_completed | major | +| 95 | complete: review_completed | major | +| 96 | complete: review_completed | minor, major | +| 97 | complete: review_completed | major, major, major, major, major | +| 98 | complete: review_completed | minor, major | +| 99 | complete: review_completed | major, major | +| 100 | complete: review_completed | major, major, major, major, major | +| 101 | complete: review_completed | major, major | +| contract | complete: review_completed | major, major | + +## Validated dispositions + +- 94A review, Major runtime requirement: verified Gradle toolchain/release26, README JDK26+ and CI +setup-java26. Contract now states the already-supported runtime and distinguishes Java17 input floor; +no runtime compatibility change was made. +- 94A review, Major CBS dominance:98 now requires independent two-actor/two-action cost/cutoff enumeration, +including cutoff obligations below dominated states. Minimum-cost positive coverage cannot erase +incompleteness or imply cutoff-equivalence. +- 94B review, Major Throwable cause constructor: independently confirmed the reader's callback concern; +cause-only descriptors explicitly reject. Non-null message/cause support needs no implicit callback. +- 94B review, Minor stale follow-up summary: marked completed A/B/C and selected later bundles historical; +current selected work points to12 and parked scope remains parked. +- 94C review, Major artifact versus model selection: retained digest definition and separately bound +selected modelClass and entry-point declarations in strict replay, including empty interrupted traces. + +- 95 review, Major String ownership:96 now directly owns literal/message layout and intern-table +semantics;97 explicitly retains and extends that prior representation rather than owning its definition. + +- 96 review, Minor actor syntax: Java annotation example now uses explicit `@Actor(id = 0)`. +- 96 review, Major StringBuilder atomicity: atomic shared append would mask real races. Restrict the +selected builder profile to conservatively proven nonescaping builders; unknown/shared escape rejects +before search. Immutable String results may publish. Add a shared-two-append/final-length negative +case rather than a false serialized PASS. General shared-builder microsteps are not claimed. + +- 97 review: five Major findings. Running/uninvoked status rows are updated from actual NDJSON at +publication, never upgraded speculatively. StringBuilder finding repeats the prior snapshot and is +resolved by the nonescape restriction. Pinned OpenJDK26 source independently confirmed boolean +String.valueOf literal identity, getSuppressed shared-empty identity and constructor fillInStackTrace +callback. Specs now preserve literal/empty-array identities and setup charges; reachable Throwable +fillInStackTrace overrides reject before search with an explicit negative/differential fixture. + +- 98 review: Minor review-table status is finalized from actual logs. Major shared array clone finding +is valid: a bulk snapshot can omit mixed copies. Restrict admitted cloning to sources conservatively +proven free of concurrent element mutation; unknown/racy sources reject before search. Immutable +String copy remains supported. Negative two-write/clone and positive local/readonly cases are required. + +- 99 review: Major array-clone finding repeats98's prior snapshot and is resolved by source-mutation +admission restrictions. Major status-table concern is resolved only by final actual-outcome refresh. +- 100 review: five Major findings. Status table remains actual-outcome-only. Implicit exception messages +cannot be replaced with null when target code can inspect them; such unsupported/unknown-origin reads +now reject before search. Pinned Throwable source confirms initCause overwrite can invoke user toString; +this descriptor is excluded, preserving explicit message+cause constructors. Synchronized Throwable +intrinsics require observable receiver-monitor entry/body/exit and competing-monitor tests. Pinned +StringBuilder source confirms empty toString returns the interned empty literal; identity and no-allocation +semantics plus exact-budget tests are specified. No runtime differential experiment is claimed here. + +- 101 review: two Major findings repeat the prior Throwable monitor/initCause snapshot.96 now states +entry/body/exit, reentrance, blocked zero-charge and release-on-fault rules; initCause is excluded. +No nonexistent implementation evidence was asserted to answer either finding. + +- Contract review: two Major administrative findings required actual101 outcome and both99 +findings in the record. Final refresh records completed101 analysis plus both99 dispositions above. +These are specification review outcomes; every implementation and runtime gate remains pending. + +All eleven required invocations completed actual analysis; none was quota-limited, skipped or replaced +with ordinary review. All substantive findings are resolved in the contracts or explicit admission +restrictions. Administrative status corrections reflect the final NDJSON rather than future claims. + +Final focused reader pass also found a synchronized-cost sequencing ambiguity.96 now recomputes +suppression-dependent cost at actual monitor entry, freezes the plan under the held monitor, and +rechecks current allocation/cell counters at body execution. Blocked attempts cache no stale cost. +97 explicitly inherits this entry/body/exit exception to its atomic-body wording. This focused +clarification and final administrative status refresh received local review after the completed CLI +analyses; no additional CLI completion is claimed for them. + +## Validation and deliberate skips + +PR #138 follow-up: independently validated and patched all three Minor inline comments: public +consumer fixtures apply from 94C, the 94C Scope ledger uses docs/measurements, and String.equals +has explicit operand-length/null/type/fault costs with literal exact/insufficient-fuel acceptance +cases. Also corrected the review's stale #12 stop-status nit while retaining #11/deferred exclusions. +Documentation/link/table and whitespace checks were rerun. No additional CodeRabbit CLI or runtime +tests were run for these minor specification clarifications; the prior eleven analyses remain +historical authoring evidence, not a new review of this patch. + +Documentation validation checks the ten canonical milestone sections and sequential dependencies, +requirement/acceptance mappings, local Markdown files/anchors, table shape, spec-only changed paths and +whitespace. Context structural validation has zero errors and one preexisting external-link warning. +Validation scripts/raw review logs are local authoring tools, not new production infrastructure. + +No Gradle, PIT, browser or interpreter measurement was run: the change is specifications only and the +bytecode implementation does not exist.94B batching/sharedness measurements,99 genuine reduction and101 +pinned-JPF compatibility remain mandatory unverified implementation gates. No old baseline count was +reused as a fresh measurement. Sam supplies remote CI/review/merge status after publication; no watcher. diff --git a/docs/plans/future-work.md b/docs/plans/future-work.md index 0f94300..40a3825 100644 --- a/docs/plans/future-work.md +++ b/docs/plans/future-work.md @@ -43,10 +43,11 @@ items and unmet conditional recommendations remain parked and do not become impl commitments merely because their IDs are next. Do not ask for repeated selection of active items. 9-F2–F4 and 9-F9 are merged; the selected active follow-up backlog is complete. **#10 is complete**: symmetry reduction shipped in Specs 75–77 / PRs #117–119, with final exact-strategy composition -merged in PR #119 at `d8ad49e`. Sam's selected stopping point is reached; **stop before #11/#12**. +merged in PR #119 at `d8ad49e`. The earlier stop-before-#11/#12 boundary was subsequently superseded for explicitly selected +[#12 bounded bytecode checking](bytecode-contract.md). #11 remains unselected. Parked work includes 9-V5 representation changes, 9-V6 research, conditional 9-F1, 9-F5–F8, -conditional 9-F10 and deferred 9-F11. Items #11–12 remain separate future workstreams -under the prerequisite above. Count overlapping mutation cases once and shared groundwork once. **Separate workstream** means staged, coherent +conditional 9-F10 and deferred 9-F11. Items #11–12 remain separate workstreams; only #12 is now selected. +The prerequisite active backlog is complete. Count overlapping mutation cases once and shared groundwork once. **Separate workstream** means staged, coherent PRs for a larger subsystem, rather than one PR per small helper or test family. If a complete feature is too large, separate compatible groundwork from the usable feature. @@ -159,13 +160,15 @@ Start these only after the active preceding follow-up backlog and bug fixes are Deferred and unmet conditional follow-ups remain parked under Sam's current active-items-only scope. The order below does not make these workstreams a substitute for completing active fixes. Keep symmetry reduction, relaxed memory models and actual Java input as separate workstreams. -Sam selected #10 as the stopping point: finish it, explicitly report completion, then stop before #11/#12. +The historical #10 stopping point was reached. Sam subsequently selected #12's +[bounded interpreter contract](bytecode-contract.md), with one spec PR and ten sequential implementation +milestones (94A–94C, 95–101). #11 and deferred/conditional work remain unselected. | # | Item | LOE | Spec Needed? | Why | PR grouping / boundary | |---|---|---|---|---|---| -| 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; stop before #11/#12 and deferred/conditional work. | +| 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 | Real Java bytecode instrumentation | Very High | Spec-set | Entirely new subsystem with external deps (ASM/Javassist) | Stage supported-bytecode ingestion and rejection rules; execution/lowering with source identities and replay; CLI/library integration and differential corpus verification. Group broader bytecode coverage by supported capability, not individual opcodes. Exact PR count follows the selected Java subset. | +| 12 | Bounded Java bytecode checking — selected, specification only | 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. Target ten sequential implementation PRs; measurements remain pending. | ## Deferred @@ -198,8 +201,11 @@ planned. **PR grouping:** none while deferred; do not bundle with active visuali 9. **Concurrent-program parser** — Shipped in [PR #57](https://github.com/SamuelIVX/interleave/pull/57), with all implementation PR checks passing. [Spec 16](../specs/active/16-concurrent-program-parser/README.md) records measured acceptance and review evidence. Readable source models compile into finite forward control flow with atomic interiors, explicit loop cutoffs and shared execution/reduction machinery. Actual Java project ingestion remains item #12; follow-up candidates are grouped above. -10. **Symmetry reduction — complete** — Specs 75–77 merged in PRs #117–119; final exact DFS/POR/DPOR/CBS composition merged at `d8ad49e`. Checked source eligibility, original-identity evidence and separate preservation arguments are included. Sam's selected stopping point is reached: stop before #11/#12. +10. **Symmetry reduction — complete** — Specs 75–77 merged in PRs #117–119; final exact DFS/POR/DPOR/CBS composition merged at `d8ad49e`. Checked source eligibility, original-identity evidence and separate preservation arguments are included. The historical stopping point was reached; #12 is subsequently selected under its separate contract, while #11 stays unselected. 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. **Real Java bytecode instrumentation** — instead of hand-written `Step` objects, instrument real Java bytecode so the checker can analyze actual concurrent programs. Requires bytecode analysis (ASM/Javassist), thread detection, and mapping bytecode to atomic steps. +12. **Bounded Java bytecode checking — selected, specification only** — [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. Initial public release follows internal 94A/B gates; no bytecode runtime, +batching/sharedness measurements, optimized reduction or JPF acceptance is established by these specs. diff --git a/docs/plans/post-task10-follow-ups.md b/docs/plans/post-task10-follow-ups.md index 3f85204..cddca93 100644 --- a/docs/plans/post-task10-follow-ups.md +++ b/docs/plans/post-task10-follow-ups.md @@ -3,14 +3,18 @@ ## TL;DR -Task #10 remains complete. This document plans only the leftover report JSON escaping defect, +Task #10/B9/B10 remain complete. Sam subsequently selected +[#12 bounded bytecode checking](bytecode-contract.md) as a separate workstream; #11 and parked tasks +remain unselected. The older exclusions below describe this follow-up inventory's scope, not a new +stop instruction for the selected #12 work. This document plans only the leftover report JSON escaping defect, the narrower boundaries identified in the post-#10 audit, and its two highlighted verification gaps. It does not activate the explicitly deferred/conditional roadmap work. -Start with three independently reviewable bundles: **A — report JSON escaping**, **B — focused -symmetry assurance**, then **C — explorer residual triage**. B combines V1/B2 below; those rows do -not require separate PRs. The other rows are proposed support expansions or contract checks, -not confirmed bugs or approved implementation promises. +Historical sequence: **A — report JSON escaping**, **B — focused symmetry assurance**, then +**C — explorer residual triage**, followed by the separately selected boundary expansions through B10. +All selected bundles are complete, as recorded below; do not repeat them. B combined V1/B2 in one +bundle. Unselected/deferred/conditional rows remain parked; current selected work is only the separate +#12 contract linked above. **Planning baseline:** main `2a53ffc`, after PR #119 and the task-#10 completion-table update. Recheck the cited symbols and specs before implementation; this is a planning inventory, not an @@ -51,7 +55,7 @@ execution spec. No implementation is included in this document. | **10 / B7** | Offer a stronger shortest-cutoff witness guarantee | Legacy `--simplify-cutoff` stays deletion-1-minimal. Specs 85/86 add bounded library and opt-in CLI search for shortest length among the supplied witness’s subsequences, with best-found output and explicit proof/work metadata. This does not search every legal schedule or turn INCOMPLETE into PASS. | **L: 1–2 weeks for a bounded, precisely defined mode. High cost/completeness risk.** | Define the search domain and length metric first. Preserve the entire omitted cutoff value and nonterminal/property contract. Add an opt-in exact search with an explicit work budget; report proven shortest length only when every shorter candidate is excluded or the empty lower bound is reached. If stopped early, retain an honest best-found result with `shortestProven` false; it need not be deletion-1-minimal. Test tiny independently enumerated optima and resource stops. | **2 PRs — I1/I2:** I1 bundles bounded library search, immutable proof/work result, authentication, tests and evidence. I2 bundles opt-in CLI proof/work presentation and consumer/schema validation; legacy CLI behavior remains unchanged. | **Spec-set:** optimization domain/optimality plus resource and result semantics. | **I1 merged PR #127 at `fc10c62` — [Spec 85](../specs/active/85-shortest-cutoff-subsequence.md). I2 CLI proof/work presentation and consumer validation completed under [Spec 86](../specs/active/86-shortest-cutoff-cli.md), merged PR #128 at `2f578cf`. B7 is complete.** | [Spec 74 algorithm](../specs/active/74-source-cutoff-witness-simplification.md), [CutoffSimplifier](../../src/main/java/dev/samhb/interleave/minimize/CutoffSimplifier.java), [legacy simplifier tests](../../src/test/java/dev/samhb/interleave/minimize/CutoffSimplifierTest.java), [shortest-subsequence tests](../../src/test/java/dev/samhb/interleave/minimize/ShortestCutoffSubsequenceTest.java). | | **11 / B8** | Capture, replay and present resource-limited prefixes safely | `CutoffSimplifier` accepts reproducible loop/preemption cutoffs and rejects resource-only incomplete results. A host deadline, state limit or memory stop is not automatically an omitted modeled action that replay can reproduce. | **L: 1–2 weeks for a useful bounded prefix feature. High evidence-classification risk.** | Define a separate resource-result contract: authenticate/replay the committed prefix and preserve its external stop classification. Do not fabricate a LOOP_LIMIT/PREEMPTION_BOUND witness, reproduce a wall-clock deadline as model behavior, or label a shorter prefix PASS. Capture the actual interrupted prefix and authenticate its committed execution; expose replay observations separately from the original resource stop. Carry provenance through Java/JSON/viewer validation. Choice A is the complete selected scope; shortening and a new CLI mode remain unselected. | **2 PRs — J1/J2:** actual capture/authenticated replay under Spec 87, then Java JSON/viewer presentation under Spec 88. Publish sequentially; no shortening stages. | **Spec-set:** reproducible prefix versus external stop, simplification and compatibility/reporting. | **Choice A approved — [contract](resource-prefix-contract.md).** J1 capture/replay under [Spec 87](../specs/active/87-resource-prefix-evidence.md) merged in PR #129 at `9abbc4f` (1,852 tests/build/strict Javadoc, 60/60 new-module K and default mutation gate pass). J2 JSON/viewer presentation under [Spec 88](../specs/active/88-resource-prefix-presentation.md) merged in PR #130 at `1db7870` (1,862 tests/build/strict Javadoc, 97/97 resource-module K, unchanged default gate, 135 browser checks). B8 is complete. | [Spec 74 input contract](../specs/active/74-source-cutoff-witness-simplification.md), [trace/minimization contract](../specs/active/16-concurrent-program-parser/06-traces-replay-and-minimization.md), [CutoffSimplifier](../../src/main/java/dev/samhb/interleave/minimize/CutoffSimplifier.java). | | **12 / B9** | Combine symmetry with approximate bitstate storage | Exact symmetry supports all four strategies; approximate DFS/static POR, CBS and DPOR merged in K1/K2/K3. An approximate orbit store can introduce collisions on top of symmetry pruning, while CBS and DPOR retain additional scheduling context. Exact-store absence guarantees cannot simply be reused. | **L–XL: 2–4 weeks across the selected strategies. High assurance/reporting risk.** | Define the approximation contract and complete orbit/context encoding. Preserve CBS cost semantics and DPOR sleep-context requirements, report approximate status explicitly, retain the symmetry marker, and prevent exhaustive-absence claims. Validate collision behavior and independent verdict/witness oracles before enabling each supported strategy. Do not combine this with generic custom-backend support by default. | **3 complete PRs — K1/K2/K3:** shared membership with DFS/static POR and consumers; CBS cost/deepening and consumers; DPOR complete product membership and final all-strategy consumers. | **Spec-set:** approximate storage, strategy applicability and result/attestation guarantees. | **Complete: K1/K2/K3 merged in PRs #132–134; final merge `3d5c09e`.** [B9 spec set](approximate-symmetry-contract.md): all four strategies, library/CLI/reports, one shared CBS Bloom budget and approximate complete DPOR context. Specs 89–91 define sequential K1/K2/K3; no whole-process memory or speed guarantee. | [Spec 77 exclusions](../specs/active/77-source-symmetry-strategy-composition.md), [BitstateStore](../../src/main/java/dev/samhb/interleave/state/BitstateStore.java), [StateStore](../../src/main/java/dev/samhb/interleave/search/StateStore.java). | -| **13 / B10** | Certify declarative JSON symmetry | Selected extension: trusted format: declarative JSON through DslLoader. Certified source/declarative eligibility, checked DPOR routing and precision consumers now support the selected matrix without admitting typed/registered models or arbitrary callbacks. JSON execution and evidence remain distinct from source. | **XL; high assurance risk. Two coherent implementation phases; re-estimate from each measured base.** | Add loader-held certification and model-wide admission checks; preserve structural grouping, ordered effects/errors and original owners. L1 delivers all exact strategies/backends with consumers and strict positive-witness checks; L2 reuses B9 complete products and one Bloom budget with truthful approximate reports. | **1 spec-only PR, then 2 implementation PRs — L1/L2:** complete exact certification/integration; complete approximate matrix and consumers. | **Spec-set:** [contract](declarative-symmetry-contract.md), [Spec 92](../specs/active/92-certified-declarative-symmetry.md), [Spec 93](../specs/active/93-approximate-declarative-symmetry.md). | **Completed — specs PR #135; L1 PR #136 at `013c963`; L2 PR #137 at `aebb919`. B10 is complete.** All four strategies support exact HASHED/ORDERED and approximate BITSTATE with truthful precision and original-owner evidence. Stop before #11/#12 and deferred/conditional work. | [SourceSymmetry.groups](../../src/main/java/dev/samhb/interleave/format/dsl/SourceSymmetry.java), [Spec 76](../specs/active/76-source-symmetry-exact-search.md), [Spec 77](../specs/active/77-source-symmetry-strategy-composition.md). | +| **13 / B10** | Certify declarative JSON symmetry | Selected extension: trusted format: declarative JSON through DslLoader. Certified source/declarative eligibility, checked DPOR routing and precision consumers now support the selected matrix without admitting typed/registered models or arbitrary callbacks. JSON execution and evidence remain distinct from source. | **XL; high assurance risk. Two coherent implementation phases; re-estimate from each measured base.** | Add loader-held certification and model-wide admission checks; preserve structural grouping, ordered effects/errors and original owners. L1 delivers all exact strategies/backends with consumers and strict positive-witness checks; L2 reuses B9 complete products and one Bloom budget with truthful approximate reports. | **1 spec-only PR, then 2 implementation PRs — L1/L2:** complete exact certification/integration; complete approximate matrix and consumers. | **Spec-set:** [contract](declarative-symmetry-contract.md), [Spec 92](../specs/active/92-certified-declarative-symmetry.md), [Spec 93](../specs/active/93-approximate-declarative-symmetry.md). | **Completed — specs PR #135; L1 PR #136 at `013c963`; L2 PR #137 at `aebb919`. B10 is complete.** All four strategies support exact HASHED/ORDERED and approximate BITSTATE with truthful precision and original-owner evidence. The later #12 selection is tracked separately; #11 and deferred/conditional work remain parked. | [SourceSymmetry.groups](../../src/main/java/dev/samhb/interleave/format/dsl/SourceSymmetry.java), [Spec 76](../specs/active/76-source-symmetry-exact-search.md), [Spec 77](../specs/active/77-source-symmetry-strategy-composition.md). | ## Recommended PR sequence and dependencies @@ -139,10 +143,10 @@ and final returns merged in PR #125** at `a0b45b9` under [Spec 83](../specs/acti **B6 / H certified backend selection merged in PR #126** at `7c0072d` under [Spec 84](../specs/active/84-certified-symmetry-backends.md). **B7 / I1 bounded shortest-subsequence library search** merged PR #127 at `fc10c62` under [Spec 85](../specs/active/85-shortest-cutoff-subsequence.md). -I2 CLI proof/work presentation and consumer validation merged PR #128 at `2f578cf` under [Spec 86](../specs/active/86-shortest-cutoff-cli.md); **B7 is complete**. **B8 / J1 capture/replay merged in PR #129 at `9abbc4f`** under [Spec 87](../specs/active/87-resource-prefix-evidence.md); J2 JSON/viewer presentation merged in PR #130 at `1db7870` under [Spec 88](../specs/active/88-resource-prefix-presentation.md); B8 is complete. B9 planning is captured in the [B9 spec set](approximate-symmetry-contract.md), with K1/K2/K3 merged in PRs #132–134 and **B9 complete**. Sam subsequently selected **B10 declarative JSON certification** under the [new spec set](declarative-symmetry-contract.md): Specs 92/93 merged in PR #135; L1 exact implementation merged in PR #136 at `013c963`. L2 approximate support merged in PR #137 at `aebb919`. **B10 is complete**, delivered in two implementation PRs after the spec-only PR. Stop here before #11/#12 and deferred/conditional work. Other B5 capabilities and arbitrary third-party +I2 CLI proof/work presentation and consumer validation merged PR #128 at `2f578cf` under [Spec 86](../specs/active/86-shortest-cutoff-cli.md); **B7 is complete**. **B8 / J1 capture/replay merged in PR #129 at `9abbc4f`** under [Spec 87](../specs/active/87-resource-prefix-evidence.md); J2 JSON/viewer presentation merged in PR #130 at `1db7870` under [Spec 88](../specs/active/88-resource-prefix-presentation.md); B8 is complete. B9 planning is captured in the [B9 spec set](approximate-symmetry-contract.md), with K1/K2/K3 merged in PRs #132–134 and **B9 complete**. Sam subsequently selected **B10 declarative JSON certification** under the [new spec set](declarative-symmetry-contract.md): Specs 92/93 merged in PR #135; L1 exact implementation merged in PR #136 at `013c963`. L2 approximate support merged in PR #137 at `aebb919`. **B10 is complete**, delivered in two implementation PRs after the spec-only PR. Sam subsequently selected #12 under its [separate contract](bytecode-contract.md); #11 and deferred/conditional work remain unselected. Other B5 capabilities and arbitrary third-party backends remain unselected. This approval does not activate excluded roadmap work or require combining independent capabilities. The main [future-work table](future-work.md) retains its existing parked decisions and #10-complete status. This separate inventory must not be interpreted as reopening the completed prerequisite -backlog or as permission to start #11/#12. +backlog or as permission to start #11. The separate #12 contract governs that selected workstream. diff --git a/docs/specs/active/100-bytecode-atomics.md b/docs/specs/active/100-bytecode-atomics.md new file mode 100644 index 0000000..0c448fe --- /dev/null +++ b/docs/specs/active/100-bytecode-atomics.md @@ -0,0 +1,141 @@ + +# Spec 100: Narrow sequentially consistent atomic variables + +## Objective + +Deliver narrow sequentially consistent atomic variables as one coherent stage of bounded Java bytecode checking. +**Type: delta. Status: specified, not implemented or measured.** 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 100 only. + +## Scope + +Extend bytecode IntrinsicRegistry/heap/value/fault/sharedness/dependency/resource metadata for the +exact AtomicInteger/AtomicBoolean/AtomicReference descriptors below. Update DPOR analysis, strict +replay, library/CLI/report/viewer and supported examples. Add BytecodeAtomicTest/BytecodeCasLoopTest +and measurements/100-bytecode-atomics.md. No weak-memory or broader atomic methods. + +## Non-Goals + +No expansion beyond this milestone's behavior. No host execution of target code, executable application +initializers, dynamic actors, collections, wait/notify, weak memory, bytecode static POR/symmetry, +frozen exhausted actors or fuel-free cycle detection. Later-phase support stays rejected until its +complete implementation and consumers merge. + +## Invariants + +- Existing explicit/source/JSON/replay/symmetry behavior, validation and mutation policy remain intact. +- Owned state and deterministic identities preserve aliases, resource counters and sharedness history. +- Cutoffs end prefixes; external stops and observer errors remain honestly incomplete. +- All executed target behavior stays interpreted; no host fallback or forged source locations. +- Public selection follows the phase release boundary and never advertises partial consumer support. + +## Requirements + +1. **R1 — Atomic descriptors.** WHEN allowed atomic constructors/get/set/strong compareAndSet execute, +THE SYSTEM SHALL use modeled payloads with SC atomic visible transitions, exact old-value tests and +specified return values. Failed CAS SHALL still read/observe and consume its intrinsic work. +2. **R2 — Identity/publication.** WHEN AtomicReference CAS compares expected with current, THE SYSTEM +SHALL compare modeled identity, including null, never equals. Successful set/CAS SHALL promote +transitive referenced objects before publication; failed CAS SHALL not publish the replacement. +3. **R3 — Bounds and DPOR.** WHEN retry loops occur, THE SYSTEM SHALL allow DFS/CBS within fuel and +fall back exhaustively for DPOR due to cyclic control flow. Acyclic atomic programs SHALL require a +fresh complete cost/dependency proof for optimized admission; unknown effects SHALL fall back. +4. **R4 — Coverage and consumers.** WHEN this profile is selected, THE SYSTEM SHALL extend replay, +snapshots/dependency identities/reports/viewer and JVM/reference oracles. Unsupported weak CAS, +getAndUpdate/callback variants, lazySet, acquire/release/opaque operations and fences SHALL reject. + +## Failure Modes & Edge Cases + +- WHEN metadata, descriptors or reachable behavior is unsupported, THE SYSTEM SHALL reject before +exploration with actionable identity/location diagnostics; dynamic supported faults SHALL remain runtime behavior. +- WHEN actor/setup/observer budgets fail, THE SYSTEM SHALL preserve their separate ownership and the +shared priority, exact-limit semantics and omitted operation. A check/setup failure SHALL not become an actor violation. +- WHEN a run stops externally, THE SYSTEM SHALL retain original INCOMPLETE classification and genuine +already-recorded findings. It SHALL not manufacture a reproducible modeled resource cutoff. +- WHEN this milestone exposes new payload/state, THE SYSTEM SHALL include every future-relevant field +in keys and replay validation, including pending terminal events and permanent allocation charges. + +## Acceptance Criteria + +- R1: `java/util/concurrent/atomic/AtomicInteger` `()V`, `(I)V`, `get()I`, `set(I)V`, +`compareAndSet(II)Z`; AtomicBoolean analogous Z descriptors; AtomicReference `()V`, +`(Ljava/lang/Object;)V`, `get()Ljava/lang/Object;`, `set(Ljava/lang/Object;)V`, +`compareAndSet(Ljava/lang/Object;Ljava/lang/Object;)Z`. Constructor initializes one payload field; +header+field costs two cells, normal new allocation charging. Invoke costs one opcode plus one +intrinsic fuel unit; constructors/get/set/CAS each execute atomically. Null receiver faults as usual. +- R1/R2: success/failure/no-change CAS, equal-valued distinct reference objects, null expected/current, +publication chains and failed-publication negatives match independent expected outcomes. No spurious +failure for strong CAS; volatile metadata does not claim a Java Memory Model implementation. +- R3: bounded terminating CAS retries can succeed; contention/spin paths can cutoff, preserving exact +actor/reason/location/limit. DPOR fallback is visible; sufficient acyclic programs use only justified +summaries. Re-run earlier DPOR resource certificates against newly supported registry entries. +- R4: strict replay rejects changed expected/current identity and return result; fresh producer artifacts +render atomic objects and fallback without hiding incompleteness. Unsupported overload fixtures reject. + +## Refactor Baseline & Rollback + +- Pre-change baseline: fetch and record actual merged-main SHA at implementation start; [99](99-bytecode-dpor.md) merged, plus the shared contract. +Record fresh full build/strict Javadoc/tests and affected/default PIT fingerprints before production edits. +The authoring SHA and older counts are historical context, never fresh implementation baselines. +- Call-site migration: all paths listed in Scope, plus their existing connected tests and exports; +new profile state reaches executor, encoder, replay and consumers in this same milestone where exposed. +- Preserve existing public signatures/semantics, source forward validation, mutation operators/floors, +resource settings and CI parallelism. No hidden compatibility adapter may bypass validation. +- Roll back/restrict the newly admitted profile coherently if normalized reference outcomes diverge, +state/replay identity omits future behavior, cleanup/evidence is fabricated or legacy compatibility fails. +Do not weaken tests, change bounds to conceal a counterexample or silently enable a later phase. + +## Design + +Use the shared contract's deep loader/executor/search seams: immutable validated metadata and program, +owned execution state, one opcode executor and mode-aware scheduler, then existing result/consumer +adapters where contracts permit. Keep bytecode continuation identity separate from source forward PCs. +Do not add a generic backend/framework for hypothetical languages. Internal names in Scope are planned; +choose existing equivalent modules at implementation after connected-source inspection. + +## Current State + +- [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. + +## Tests + +`strongCasMatchesValueOrReferenceIdentity` (R1/R2), `casPublicationIsTransitiveOnlyOnSuccess` (R2), +`casRetryLoopsUseBoundedExhaustiveFallback` (R3), `atomicDescriptorsAndConsumersStayClosed` (R4). +Kill equals-for-reference-CAS, spurious failure, failed-CAS publication and cyclic optimized admission. +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. + +## Constraints + +- Dependencies: [99](99-bytecode-dpor.md) merged, plus the shared contract; sequential publication into main, with Sam's merge update before the next stage. +- Backward compatibility: all existing explicit/source/declarative inputs, results and stores retain +behavior; source evidence is never manufactured for bytecode and native-stream changes are versioned. +- Oracle contract: [shared verification/measurement gates](../../plans/bytecode-contract.md#verification-and-measurement-gates). +- All local Gradle commands include `--max-workers=1 -PpitestThreads=1`. Full strict Javadoc/build/tests, +affected mutation census plus unchanged default PIT gate, and relevant consumers are mandatory during +implementation. NO_COVERAGE is not a kill; report scoped/default totals and inherited residual identities. +- Create `docs/measurements/100-bytecode-atomics.md` with implementation: fresh baseline/final evidence, +independent checks, raw measurement conditions, review dispositions and limits. Authoring evidence belongs +in the specification-set record, not a fabricated runtime ledger. + +## Relevant Skills and Review + +- doc-coauthoring: requirements/acceptance completeness and fresh-reader testing. +- domain-modeling / codebase-design: reuse [domain vocabulary](../../../CONTEXT.md) and the shared +small owned interfaces; do not create a competing glossary or source-shaped bytecode abstraction. +- tdd: establish failing behavioral regressions before new production behavior; fixed-seed/shrinking +oracles supplement targeted cases. owasp-security: fail-closed untrusted class metadata and replay input. +- ponytail / ponytail-review: smallest coherent implementation and connected-source review. +- code-review: actual CodeRabbit after this completed specification and before substantial implementation +publication; record completed/quota/error status through agent-setup without inventing completion. +- 94B/95/96/97: review the batching preservation argument for every newly admitted behavior; 99/100/101: +review reduction admission/resource/product obligations in addition to runtime tests. + +The specification-only PR runs document/link/structure validation, reader review and required actual +CodeRabbit invocations. It does not run Java/PIT/browser feature checks for code that does not exist. +After publishing this milestone's implementation PR, report its link and stop; do not watch CI. diff --git a/docs/specs/active/101-bytecode-bitstate.md b/docs/specs/active/101-bytecode-bitstate.md new file mode 100644 index 0000000..86d1e9d --- /dev/null +++ b/docs/specs/active/101-bytecode-bitstate.md @@ -0,0 +1,151 @@ + +# Spec 101: Bitstate storage and selected-scope completion + +## Objective + +Deliver bitstate storage and selected-scope completion as one coherent stage of bounded Java bytecode checking. +**Type: delta. Status: specified, not implemented or measured.** 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 101 only. + +## Scope + +Extend bytecode search/store integration for complete DFS/CBS/DPOR products with one owned Bloom +filter, reusing existing BitstateStore primitives without hidden exact production maps. Wire runner (including the owned Builder.bytecodeBitstate selection), +CLI, TestResult/report/attestation/strict replay/viewer and final supported-profile documentation. +Add BytecodeBitstateProductTest/collision fixtures, complete compiler matrix, pinned JPF comparison +harness/evidence and docs/measurements/101-bytecode-bitstate.md. No new language or reduction semantics. + +## Non-Goals + +No expansion beyond this milestone's behavior. No host execution of target code, executable application +initializers, dynamic actors, collections, wait/notify, weak memory, bytecode static POR/symmetry, +frozen exhausted actors or fuel-free cycle detection. Later-phase support stays rejected until its +complete implementation and consumers merge. + +## Invariants + +- Existing explicit/source/JSON/replay/symmetry behavior, validation and mutation policy remain intact. +- Owned state and deterministic identities preserve aliases, resource counters and sharedness history. +- Cutoffs end prefixes; external stops and observer errors remain honestly incomplete. +- All executed target behavior stays interpreted; no host fallback or forged source locations. +- Public selection follows the phase release boundary and never advertises partial consumer support. + +## Requirements + +1. **R1 — One approximate store.** WHEN BITSTATE is selected, THE SYSTEM SHALL encode complete typed +bytecode state and strategy context into one filter: value domain, CBS last actor/cost product and DPOR +continuation/sleep context as applicable. It SHALL retain no exact visited/context shadow in production; +filter budget SHALL not be presented as total JVM memory. +2. **R2 — Precision.** WHEN approximate exploration finds no failure, THE SYSTEM SHALL report +APPROXIMATE_PASS or INCOMPLETE as appropriate, never exact absence. Actual violations/deadlocks/cutoffs +SHALL retain concrete strictly replayable witnesses. Requested DPOR with effective DFS fallback SHALL +retain both fallback and approximate precision. +3. **R3 — Product verification.** WHEN exact/approximate equality is asserted on a fixture, THE SYSTEM +SHALL independently establish zero false-positive decisions across that fixture's full relevant context +universe, including cross-domain interference. Deliberate collisions SHALL demonstrate possible missed +behavior without fabricating positive witnesses or claiming calibrated coverage. +4. **R4 — Compiler and cross-tool gate.** WHEN selected-scope acceptance is evaluated, THE SYSTEM +SHALL publish Java17/21/26 supported/rejected compiler fixtures and a pinned JPF experiment: probe actual +class version/construct support, choose mutually supported compilation release and compare normalized +outcomes with scheduling/semantic differences. Incompatibility SHALL mark that gate blocked and SHALL +not silently lower Interleave's Java17 input floor or claim complete acceptance. +5. **R5 — Integration and closure.** WHEN 101 completes, THE SYSTEM SHALL verify all supported strategy/ +store/profile consumers, preserve exact/source/JSON/symmetry behavior and honest mutation evidence, +update roadmap status only to demonstrated acceptance, and stop after publishing its PR. + +## Failure Modes & Edge Cases + +- WHEN metadata, descriptors or reachable behavior is unsupported, THE SYSTEM SHALL reject before +exploration with actionable identity/location diagnostics; dynamic supported faults SHALL remain runtime behavior. +- WHEN actor/setup/observer budgets fail, THE SYSTEM SHALL preserve their separate ownership and the +shared priority, exact-limit semantics and omitted operation. A check/setup failure SHALL not become an actor violation. +- WHEN a run stops externally, THE SYSTEM SHALL retain original INCOMPLETE classification and genuine +already-recorded findings. It SHALL not manufacture a reproducible modeled resource cutoff. +- WHEN this milestone exposes new payload/state, THE SYSTEM SHALL include every future-relevant field +in keys and replay validation, including pending terminal events and permanent allocation charges. + +## Acceptance Criteria + +- R1: independently enumerate finite state/context bytes, domain separation, CBS cost/last actor, +DPOR sleep continuations, filter insertion/query semantics, clear/copy/concurrent run isolation and +cross-domain collisions. Test-only exact shadows cannot leak into production configuration. +- R2/R3: tiny-filter forced collision may miss a real outcome; every found witness still replays. +Known zero-collision finite fixtures agree with exact normalized observations. Fallback+bitstate rows +remain approximate and excluded from exact agreement; root/later resource stops remain incomplete. +- R4: pin JPF repository revision/toolchain/configuration and store probe commands/results before choosing +compiler target. Lost-update and deadlock comparisons use actual compiled common supported fixtures; +explain missing outcomes due to scheduling/semantics without forcing misleading equality. If no mutual +release >=17 supports the required constructs, record blocked evidence and leave completion unaccepted. +- R5: built-jar, CLI, JSON/Markdown, attestation, strict replay, normalization/browser exercise DFS/CBS/ +DPOR admitted and fallback with EXACT and approximate BITSTATE. Bytecode static POR, +symmetry and weak-memory requests continue rejecting. Full gates preserve default and scoped mutation +accounting; no NO_COVERAGE-as-kill or inherited baseline assumptions. + +## Refactor Baseline & Rollback + +- Pre-change baseline: fetch and record actual merged-main SHA at implementation start; [100](100-bytecode-atomics.md) merged, plus the shared contract. +Record fresh full build/strict Javadoc/tests and affected/default PIT fingerprints before production edits. +The authoring SHA and older counts are historical context, never fresh implementation baselines. +- Call-site migration: all paths listed in Scope, plus their existing connected tests and exports; +new profile state reaches executor, encoder, replay and consumers in this same milestone where exposed. +- Preserve existing public signatures/semantics, source forward validation, mutation operators/floors, +resource settings and CI parallelism. No hidden compatibility adapter may bypass validation. +- Roll back/restrict the newly admitted profile coherently if normalized reference outcomes diverge, +state/replay identity omits future behavior, cleanup/evidence is fabricated or legacy compatibility fails. +Do not weaken tests, change bounds to conceal a counterexample or silently enable a later phase. + +## Design + +Use the shared contract's deep loader/executor/search seams: immutable validated metadata and program, +owned execution state, one opcode executor and mode-aware scheduler, then existing result/consumer +adapters where contracts permit. Keep bytecode continuation identity separate from source forward PCs. +Do not add a generic backend/framework for hypothetical languages. Internal names in Scope are planned; +choose existing equivalent modules at implementation after connected-source inspection. + +## Current State + +- [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. + +## Tests + +`bytecodeBitstateEncodesCompleteStrategyProducts` (R1), `collisionsNeverInventWitnesses` (R2/R3), +`independentZeroCollisionUniverseMatchesExact` (R3), `compilerAndPinnedJpfEvidenceIsHonest` (R4), +`allSupportedBytecodeConsumersKeepPrecision` (R5). Kill incomplete product keys, exact-shadow routing, +precision upgrades, context-cost omission and unconditional completion claims. +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. + +## Constraints + +- Dependencies: [100](100-bytecode-atomics.md) merged, plus the shared contract; sequential publication into main, with Sam's merge update before the next stage. +- Backward compatibility: all existing explicit/source/declarative inputs, results and stores retain +behavior; source evidence is never manufactured for bytecode and native-stream changes are versioned. +- Oracle contract: [shared verification/measurement gates](../../plans/bytecode-contract.md#verification-and-measurement-gates). +- All local Gradle commands include `--max-workers=1 -PpitestThreads=1`. Full strict Javadoc/build/tests, +affected mutation census plus unchanged default PIT gate, and relevant consumers are mandatory during +implementation. NO_COVERAGE is not a kill; report scoped/default totals and inherited residual identities. +- Create `docs/measurements/101-bytecode-bitstate.md` with implementation: fresh baseline/final evidence, +independent checks, raw measurement conditions, review dispositions and limits. Authoring evidence belongs +in the specification-set record, not a fabricated runtime ledger. + +## Relevant Skills and Review + +- doc-coauthoring: requirements/acceptance completeness and fresh-reader testing. +- domain-modeling / codebase-design: reuse [domain vocabulary](../../../CONTEXT.md) and the shared +small owned interfaces; do not create a competing glossary or source-shaped bytecode abstraction. +- tdd: establish failing behavioral regressions before new production behavior; fixed-seed/shrinking +oracles supplement targeted cases. owasp-security: fail-closed untrusted class metadata and replay input. +- ponytail / ponytail-review: smallest coherent implementation and connected-source review. +- code-review: actual CodeRabbit after this completed specification and before substantial implementation +publication; record completed/quota/error status through agent-setup without inventing completion. +- 94B/95/96/97: review the batching preservation argument for every newly admitted behavior; 99/100/101: +review reduction admission/resource/product obligations in addition to runtime tests. + +The specification-only PR runs document/link/structure validation, reader review and required actual +CodeRabbit invocations. It does not run Java/PIT/browser feature checks for code that does not exist. +After publishing this milestone's implementation PR, report its link and stop; do not watch CI. diff --git a/docs/specs/active/94A-bytecode-foundation.md b/docs/specs/active/94A-bytecode-foundation.md new file mode 100644 index 0000000..7e3aa3b --- /dev/null +++ b/docs/specs/active/94A-bytecode-foundation.md @@ -0,0 +1,152 @@ + +# Spec 94A: Interpreter foundation + +## Objective + +Deliver interpreter foundation as one coherent stage of bounded Java bytecode checking. +**Type: delta. Status: specified, not implemented or measured.** 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 94A only. + +## Scope + +Internal `src/main/java/dev/samhb/interleave/bytecode/`: planned BytecodeProgram, BytecodeLimits, +BytecodeLoader, BytecodeState, BytecodeFrame, OpcodeExecutor and metadata verifier. Reserve the future +format/BytecodeProgramLoader facade for 94C. Add corresponding package tests and +src/test/resources/bytecode/foundation fixtures, including separately compiled 17/21/26 inputs. +Before94C, compile fixture sources against test-only annotation declarations with the approved binary +names; publish those annotations in the main artifact only with94C. No public runner/CLI/report/viewer selectors; 94B owns concurrent search/checks and full monitor behavior. + +## Non-Goals + +No expansion beyond this milestone's behavior. No host execution of target code, executable application +initializers, dynamic actors, collections, wait/notify, weak memory, bytecode static POR/symmetry, +frozen exhausted actors or fuel-free cycle detection. Later-phase support stays rejected until its +complete implementation and consumers merge. + +## Invariants + +- Existing explicit/source/JSON/replay/symmetry behavior, validation and mutation policy remain intact. +- Owned state and deterministic identities preserve aliases, resource counters and sharedness history. +- Cutoffs end prefixes; external stops and observer errors remain honestly incomplete. +- All executed target behavior stays interpreted; no host fallback or forged source locations. +- Public selection follows the phase release boundary and never advertises partial consumer support. + +## Requirements + +1. **R1 — Closed loading.** WHEN bytes are loaded, THE SYSTEM SHALL enforce the shared contract's +version/input bounds, annotations, hierarchy/access/stack verification, reachable support and executable +initializer rejection using JDK 26 Class-File API and metadata only. Missing classes, untrusted platform +calls, malformed branches/handlers, wrong method roles and target-path escape SHALL reject before execution. +2. **R2 — Setup and ownership.** WHEN a fixture loads, THE SYSTEM SHALL interpret its public no-arg +constructor and known helper calls, allocate fixture/Object monitors in setup identity space and freeze +an isolated snapshot. Setup faults/limits SHALL yield loading diagnostics. All runs/copies SHALL be independent. +3. **R3 — Execution.** WHEN one actor executes internally, THE SYSTEM SHALL implement the first-profile +int/boolean/reference instruction subset and real branches/calls/stacks with one deterministic opcode +executor. Unsupported actor allocations/arrays/dispatch/general handlers SHALL reject before exploration. +4. **R4 — Budgets.** WHEN work reaches a limit, THE SYSTEM SHALL charge executed opcodes, permanent +allocator cells and identities exactly as the contract specifies. It SHALL permit return at N and omit +N+1, distinguish setup/actor accounting and preserve canonical counters/frames/pending-event state. +5. **R5 — Dynamic faults and cleanup recognition.** WHEN null access or divide/remainder zero occurs, +THE SYSTEM SHALL produce interpreted fault state with real BCI/stack, preserving prior effects and +charging the throwing opcode. It SHALL validate compiler monitor-cleanup handler shapes now, permit +required astore/aload/athrow cleanup instructions only in that verified context, and retain pending +unwind metadata. Concurrent/reentrant release semantics are completed in 94B, not claimed here. +6. **R6 — Independent evidence.** WHEN foundation acceptance runs, THE SYSTEM SHALL compare generated +and targeted sequential executions with a separate JVM process, saving seeds, shrunk failures and +unsupported fixtures. Test oracle execution SHALL never become a production loader fallback. + +## Failure Modes & Edge Cases + +- WHEN metadata, descriptors or reachable behavior is unsupported, THE SYSTEM SHALL reject before +exploration with actionable identity/location diagnostics; dynamic supported faults SHALL remain runtime behavior. +- WHEN actor/setup/observer budgets fail, THE SYSTEM SHALL preserve their separate ownership and the +shared priority, exact-limit semantics and omitted operation. A check/setup failure SHALL not become an actor violation. +- WHEN a run stops externally, THE SYSTEM SHALL retain original INCOMPLETE classification and genuine +already-recorded findings. It SHALL not manufacture a reproducible modeled resource cutoff. +- WHEN this milestone exposes new payload/state, THE SYSTEM SHALL include every future-relevant field +in keys and replay validation, including pending terminal events and permanent allocation charges. + +## Acceptance Criteria + +- R1: Java 17/21/26 class majors accepted for supported code; preview/newer/older/malformed inputs, +missing superclass, wrong static/instance invocation, invalid stacks, duplicate/gapped actor IDs, +9 actors, zero actors, static/argument/nonvoid actors and impure annotations rejected. Boundary input +sizes use bounded byte reads; no reflection/classloader invocation even for setup. +- R2/R3: constructor-wired distinct Object locks, int overflow/shifts, local branches/loops, static +helpers and exact-limit normal return match independent JVM values. Concurrent calls to internal +fresh-state construction cannot leak heap/frame mutations. +- R4/R5: N versus N+1, call-depth crossing, disabled-attempt no-charge seam, setup quota isolation, +reversed identity construction, null field and division after an earlier write preserve exact state. +Cleanup handler impostors reject; recognized javac cleanup metadata survives loading. +- R6: fixed-seed bounded sequential generator with shrinking and persisted minimal regression; independent +oracle does not call OpcodeExecutor/encoder to compute expected values. Record compiler/toolchain hashes. + +## Refactor Baseline & Rollback + +- Pre-change baseline: fetch and record actual merged-main SHA at implementation start; approved shared contract/specification PR and freshly fetched main. +Record fresh full build/strict Javadoc/tests and affected/default PIT fingerprints before production edits. +The authoring SHA and older counts are historical context, never fresh implementation baselines. +- Call-site migration: all paths listed in Scope, plus their existing connected tests and exports; +new profile state reaches executor, encoder, replay and consumers in this same milestone where exposed. +- Preserve existing public signatures/semantics, source forward validation, mutation operators/floors, +resource settings and CI parallelism. No hidden compatibility adapter may bypass validation. +- Roll back/restrict the newly admitted profile coherently if normalized reference outcomes diverge, +state/replay identity omits future behavior, cleanup/evidence is fabricated or legacy compatibility fails. +Do not weaken tests, change bounds to conceal a counterexample or silently enable a later phase. + +## Design + +Use the shared contract's deep loader/executor/search seams: immutable validated metadata and program, +owned execution state, one opcode executor and mode-aware scheduler, then existing result/consumer +adapters where contracts permit. Keep bytecode continuation identity separate from source forward PCs. +Do not add a generic backend/framework for hypothetical languages. Internal names in Scope are planned; +choose existing equivalent modules at implementation after connected-source inspection. + +## Current State + +- [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. + +## Tests + +`loadsOnlyClosedSupportedMetadata` (R1), `setupNeverExecutesOnHost` (R1/R2), +`integerAndReferenceExecutionMatchesJvm` (R3/R6), `exactFuelReturnAndFaultCharge` (R4/R5), +`isolatedCopiesRetainAllocatorIdentity` (R2/R4), `monitorCleanupShapeIsVerified` (R5). +Kill inverted limit boundaries, missing fuel charge, omitted state fields, shared copy aliases and +validation bypasses. Monitor concurrency tests belong to 94B. +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. + +## Constraints + +- Dependencies: approved shared contract/specification PR and freshly fetched main; sequential publication into main, with Sam's merge update before the next stage. +- Backward compatibility: all existing explicit/source/declarative inputs, results and stores retain +behavior; source evidence is never manufactured for bytecode and native-stream changes are versioned. +- Oracle contract: [shared verification/measurement gates](../../plans/bytecode-contract.md#verification-and-measurement-gates). +- All local Gradle commands include `--max-workers=1 -PpitestThreads=1`. Full strict Javadoc/build/tests, +affected mutation census plus unchanged default PIT gate, and relevant consumers are mandatory during +implementation. NO_COVERAGE is not a kill; report scoped/default totals and inherited residual identities. +- Create `docs/measurements/94A-bytecode-foundation.md` with implementation: fresh baseline/final evidence, +independent checks, raw measurement conditions, review dispositions and limits. Authoring evidence belongs +in the specification-set record, not a fabricated runtime ledger. + +## Relevant Skills and Review + +- doc-coauthoring: requirements/acceptance completeness and fresh-reader testing. +- domain-modeling / codebase-design: reuse [domain vocabulary](../../../CONTEXT.md) and the shared +small owned interfaces; do not create a competing glossary or source-shaped bytecode abstraction. +- tdd: establish failing behavioral regressions before new production behavior; fixed-seed/shrinking +oracles supplement targeted cases. owasp-security: fail-closed untrusted class metadata and replay input. +- ponytail / ponytail-review: smallest coherent implementation and connected-source review. +- code-review: actual CodeRabbit after this completed specification and before substantial implementation +publication; record completed/quota/error status through agent-setup without inventing completion. +- 94B/95/96/97: review the batching preservation argument for every newly admitted behavior; 99/100/101: +review reduction admission/resource/product obligations in addition to runtime tests. + +The specification-only PR runs document/link/structure validation, reader review and required actual +CodeRabbit invocations. It does not run Java/PIT/browser feature checks for code that does not exist. +After publishing this milestone's implementation PR, report its link and stop; do not watch CI. diff --git a/docs/specs/active/94B-bytecode-concurrency.md b/docs/specs/active/94B-bytecode-concurrency.md new file mode 100644 index 0000000..fceb33e --- /dev/null +++ b/docs/specs/active/94B-bytecode-concurrency.md @@ -0,0 +1,161 @@ + +# 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 +[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. + +## Scope + +Internal bytecode scheduler/transition and exact-search adapter in bytecode/; extend OpcodeExecutor, +BytecodeState and verifier for full monitor/cleanup/check execution. Reuse the complete-payload membership policy of state/HashingStateStore.java through an owned +bytecode key adapter; it currently accepts Configuration, so do not claim direct bytecode reuse or +weaken its existing encoding. Use an independent sorted-key set in tests, not a new public backend. +Do not adapt via source forward PCs. Add BytecodeConcurrencyTest, BytecodeBatchingOracleTest and BytecodeMeasurementTest with +src/test/resources/bytecode/concurrency fixtures and docs/measurements/94B-bytecode-concurrency.md. +Public loader/runner/CLI/report/viewer remains 94C ownership. + +## Non-Goals + +No expansion beyond this milestone's behavior. No host execution of target code, executable application +initializers, dynamic actors, collections, wait/notify, weak memory, bytecode static POR/symmetry, +frozen exhausted actors or fuel-free cycle detection. Later-phase support stays rejected until its +complete implementation and consumers merge. + +## Invariants + +- Existing explicit/source/JSON/replay/symmetry behavior, validation and mutation policy remain intact. +- Owned state and deterministic identities preserve aliases, resource counters and sharedness history. +- Cutoffs end prefixes; external stops and observer errors remain honestly incomplete. +- All executed target behavior stays interpreted; no host fallback or forged source locations. +- Public selection follows the phase release boundary and never advertises partial consumer support. + +## Requirements + +1. **R1 — Concurrent state.** WHEN fixed actors run, THE SYSTEM SHALL enumerate enabled choices with +exact DFS over complete owned states, including real BCIs/frames, monitors, sharedness history, budgets +and pending events. EXACT enumeration SHALL agree with the independent reference on normalized outcomes. Backedges SHALL not weaken +Configuration.successorAt's existing forward-source validation. +2. **R2 — Monitor behavior.** WHEN blocks or synchronized methods acquire/release, THE SYSTEM SHALL +honor identity, owner/depth, static class locks, disabled-attempt no fuel, reentrance and normal/abrupt +cleanup. Nonowner/null release SHALL fault. A blocked acquire SHALL remain blocked until enabled. +3. **R3 — Checks and verdicts.** WHEN checks execute, THE SYSTEM SHALL enforce transitive purity, +initial/ALWAYS/FINAL timing, separate observer fuel and false/fault/exhaustion classifications. It SHALL +classify deadlock only with actual blocked actors and no executable/pending choices, and preserve +uncaught-fault versus false-check identity. +4. **R4 — Two modes.** WHEN REFERENCE/BATCHED executes, THE SYSTEM SHALL share OpcodeExecutor and +retain observable read/write/publication/monitor/terminal boundaries. It SHALL yield before terminal +failure/cutoff/termination and perform pure classification. Unknown locality or observation effects +SHALL prevent batching; conservative sharedness SHALL propagate transitively and irreversibly. +5. **R5 — Preservation.** WHEN batching is proposed for release, THE SYSTEM SHALL supply a written +state relation and event/observation argument covering errors, fuel, observer evaluation, cleanup and +terminal competition. Every allowed local segment SHALL justify omitted interleavings; equivalence of +verdict strings alone SHALL not suffice. +6. **R6 — Measurement gate.** WHEN 94B completes, THE SYSTEM SHALL measure both modes on identical +lost-update and two-lock fixtures/limits using all common-contract metrics, raw repetitions and +conditions. It SHALL compare normalized outcome sets, document default-limit suitability and investigate +regressions before 94C. No benchmark proxy SHALL be reported as interpreter evidence. + +## Failure Modes & Edge Cases + +- WHEN metadata, descriptors or reachable behavior is unsupported, THE SYSTEM SHALL reject before +exploration with actionable identity/location diagnostics; dynamic supported faults SHALL remain runtime behavior. +- WHEN actor/setup/observer budgets fail, THE SYSTEM SHALL preserve their separate ownership and the +shared priority, exact-limit semantics and omitted operation. A check/setup failure SHALL not become an actor violation. +- WHEN a run stops externally, THE SYSTEM SHALL retain original INCOMPLETE classification and genuine +already-recorded findings. It SHALL not manufacture a reproducible modeled resource cutoff. +- WHEN this milestone exposes new payload/state, THE SYSTEM SHALL include every future-relevant field +in keys and replay validation, including pending terminal events and permanent allocation charges. + +## Acceptance Criteria + +- R1/R2: actual `x++` produces lost-update final x=1 and nonlost x=2; two opposing Object locks produce +real wait-cycle evidence as well as terminating schedules. Nested/reentrant blocks, synchronized +instance/static methods and exception cleanup release exactly their held depths. Null monitor faults. Zero-fuel blocked entry exposes the prior fuel cutoff; +a sufficiently fueled disabled entry changes nothing and consumes zero. +- R3: initially false ALWAYS, transient shared false, final-only false, absent checks, check arithmetic +error and observer fuel/depth stop have distinct expected outcomes. Reject checks that allocate or +mutate through helper/dispatch paths; FINAL never runs on deadlock/exception/cutoff. +- R4/R5: independent opcode-choice enumerator agrees on normalized observations, including cutoff +actor/reason/omitted BCI/limit, with batching for targeted/generated tiny programs. Pure local infinite +loop, fuel-sensitive branch and exhaustion competing with another actor's violation cannot disappear. +Fault discovered after a local prefix yields before delivery; unselected probe leaves fuel/state untouched. +- R4: canonical encoding retains history even when fixture fields are rewired; frame-root reachability +and unknown metadata rejection are covered. Until 95 fixtures cannot introduce unsupported allocations +or object graphs. Nontrivial cyclic publication/history/allocator adversarial cases are 95 acceptance; +94B reports genuine zero/not-applicable metrics when its setup-only profile cannot produce those states. +- R6: publish states/transitions/encoding/elapsed/retained-memory/sharedness/history-only-state data +with reproducible commands and variability. Correctness or unexplained cost gaps block the public release; +no fixed percentage speed target and no claim of prior measured performance. + +## Refactor Baseline & Rollback + +- Pre-change baseline: fetch and record actual merged-main SHA at implementation start; [94A](94A-bytecode-foundation.md) merged, plus the shared contract. +Record fresh full build/strict Javadoc/tests and affected/default PIT fingerprints before production edits. +The authoring SHA and older counts are historical context, never fresh implementation baselines. +- Call-site migration: all paths listed in Scope, plus their existing connected tests and exports; +new profile state reaches executor, encoder, replay and consumers in this same milestone where exposed. +- Preserve existing public signatures/semantics, source forward validation, mutation operators/floors, +resource settings and CI parallelism. No hidden compatibility adapter may bypass validation. +- Roll back/restrict the newly admitted profile coherently if normalized reference outcomes diverge, +state/replay identity omits future behavior, cleanup/evidence is fabricated or legacy compatibility fails. +Do not weaken tests, change bounds to conceal a counterexample or silently enable a later phase. + +## Design + +Use the shared contract's deep loader/executor/search seams: immutable validated metadata and program, +owned execution state, one opcode executor and mode-aware scheduler, then existing result/consumer +adapters where contracts permit. Keep bytecode continuation identity separate from source forward PCs. +Do not add a generic backend/framework for hypothetical languages. Internal names in Scope are planned; +choose existing equivalent modules at implementation after connected-source inspection. + +## Current State + +- [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. + +## 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. + +## Constraints + +- Dependencies: [94A](94A-bytecode-foundation.md) merged, plus the shared contract; sequential publication into main, with Sam's merge update before the next stage. +- Backward compatibility: all existing explicit/source/declarative inputs, results and stores retain +behavior; source evidence is never manufactured for bytecode and native-stream changes are versioned. +- Oracle contract: [shared verification/measurement gates](../../plans/bytecode-contract.md#verification-and-measurement-gates). +- All local Gradle commands include `--max-workers=1 -PpitestThreads=1`. Full strict Javadoc/build/tests, +affected mutation census plus unchanged default PIT gate, and relevant consumers are mandatory during +implementation. NO_COVERAGE is not a kill; report scoped/default totals and inherited residual identities. +- Create `docs/measurements/94B-bytecode-concurrency.md` with implementation: fresh baseline/final evidence, +independent checks, raw measurement conditions, review dispositions and limits. Authoring evidence belongs +in the specification-set record, not a fabricated runtime ledger. + +## Relevant Skills and Review + +- doc-coauthoring: requirements/acceptance completeness and fresh-reader testing. +- domain-modeling / codebase-design: reuse [domain vocabulary](../../../CONTEXT.md) and the shared +small owned interfaces; do not create a competing glossary or source-shaped bytecode abstraction. +- tdd: establish failing behavioral regressions before new production behavior; fixed-seed/shrinking +oracles supplement targeted cases. owasp-security: fail-closed untrusted class metadata and replay input. +- ponytail / ponytail-review: smallest coherent implementation and connected-source review. +- code-review: actual CodeRabbit after this completed specification and before substantial implementation +publication; record completed/quota/error status through agent-setup without inventing completion. +- 94B/95/96/97: review the batching preservation argument for every newly admitted behavior; 99/100/101: +review reduction admission/resource/product obligations in addition to runtime tests. + +The specification-only PR runs document/link/structure validation, reader review and required actual +CodeRabbit invocations. It does not run Java/PIT/browser feature checks for code that does not exist. +After publishing this milestone's implementation PR, report its link and stop; do not watch CI. diff --git a/docs/specs/active/94C-bytecode-release.md b/docs/specs/active/94C-bytecode-release.md new file mode 100644 index 0000000..b7d7421 --- /dev/null +++ b/docs/specs/active/94C-bytecode-release.md @@ -0,0 +1,155 @@ + +# Spec 94C: Initial public bytecode release + +## Objective + +Deliver initial public bytecode release as one coherent stage of bounded Java bytecode checking. +**Type: delta. Status: specified, not implemented or measured.** The +[shared #12 contract](../../plans/bytecode-contract.md) is normative for common semantics, limits, +interface signatures, profile exclusions, phase ownership and verification. This spec owns 94C only. + +## Scope + +Create format/BytecodeProgramLoader.java and public annotation/limits/program interfaces defined in +the contract. Modify InterleaveRunner.java, TestResult.java, TraceRecord.java, core evidence types, +search/TraceReplayer.java, cli/Main.java and report/{BenchmarkHarness,BenchmarkResult,SoundnessAttestation}.java +through explicit bytecode routes. Update docs/visualizer.js, normalization/browser checks, README.md, +examples/bytecode/ and API docs. Add built-jar/CLI/replay/report tests and +docs/measurements/94C-bytecode-release.md. Static POR/CBS/DPOR/bitstate/symmetry remain unavailable until their +owning phases; no source/JSON behavior rewrite. + +## Non-Goals + +No expansion beyond this milestone's behavior. No host execution of target code, executable application +initializers, dynamic actors, collections, wait/notify, weak memory, bytecode static POR/symmetry, +frozen exhausted actors or fuel-free cycle detection. Later-phase support stays rejected until its +complete implementation and consumers merge. + +## Invariants + +- Existing explicit/source/JSON/replay/symmetry behavior, validation and mutation policy remain intact. +- Owned state and deterministic identities preserve aliases, resource counters and sharedness history. +- Cutoffs end prefixes; external stops and observer errors remain honestly incomplete. +- All executed target behavior stays interpreted; no host fallback or forged source locations. +- Public selection follows the phase release boundary and never advertises partial consumer support. + +## Requirements + +1. **R1 — Public selection.** WHEN the loader, runBytecode entry point or CLI selects bytecode, THE SYSTEM +SHALL expose exactly the shared signatures/annotation/limits contract and exact DFS selection, reject +incompatible arguments before search, and start fresh independent states. Generic Invariant/store callbacks and symmetry-specific +builder settings SHALL reject before invocation; the bytecode path SHALL use only declared checks +and owned exact storage. It SHALL keep public bytecode +selection absent before this phase's complete release. +2. **R2 — Identity and evidence.** WHEN execution emits a record, THE SYSTEM SHALL tag BYTECODE and +retain frozen artifact/profile/limit/mode identity, original actor choices, real method/descriptor/BCIs, +optional lines, transitions, immutable snapshots, monitor relationships and classified terminal evidence. +It SHALL neither fabricate SOURCE spans nor publish tentative host execution. +3. **R3 — Strict replay.** WHEN replay is requested, THE SYSTEM SHALL validate identity, enabled choices, +executed operations, outcomes, checks, monitors, pending terminals and exact cutoffs. Earlier failure, +false check or cutoff SHALL forbid trailing choices. External interruptions SHALL authenticate only +their captured prefix and preserve original incompleteness separately from replay observations. +4. **R4 — Consumers.** WHEN library/CLI emits JSON/Markdown and viewer data, THE SYSTEM SHALL preserve +precision, requested/effective strategy, real faults/checks/deadlocks/cutoffs and absence limits. Native +serialization SHALL explicitly version/reject incompatible shapes. Source/JSON serializers/replay and +source forward validation SHALL retain existing behavior. +5. **R5 — Usable release.** WHEN 94C is accepted, THE SYSTEM SHALL demonstrate independently compiled +lost-update and opposing-two-lock examples end to end, document supported/rejected constructs including +clinit restrictions, and incorporate reviewed 94B measurement/proof/default decisions. + +## Failure Modes & Edge Cases + +- WHEN metadata, descriptors or reachable behavior is unsupported, THE SYSTEM SHALL reject before +exploration with actionable identity/location diagnostics; dynamic supported faults SHALL remain runtime behavior. +- WHEN actor/setup/observer budgets fail, THE SYSTEM SHALL preserve their separate ownership and the +shared priority, exact-limit semantics and omitted operation. A check/setup failure SHALL not become an actor violation. +- WHEN a run stops externally, THE SYSTEM SHALL retain original INCOMPLETE classification and genuine +already-recorded findings. It SHALL not manufacture a reproducible modeled resource cutoff. +- WHEN this milestone exposes new payload/state, THE SYSTEM SHALL include every future-relevant field +in keys and replay validation, including pending terminal events and permanent allocation charges. + +## Acceptance Criteria + +- R1/R5: a separate Java built-jar consumer loads and runs both examples; actual CLI `--bytecode` +with `--class-path` produces the same normalized findings with the existing EXACT store selection. Missing/duplicate flags, +foreign model modes, invalid limits, unavailable strategies/stores and source-only simplify flags reject. +- R2/R3: reload at another directory with identical bytes replays; changed class bytes, debug bytes, +profile, limits/mode, selected modelClass/declaration map, BCI, actor, outcome, monitor, check identity and cutoff fields reject. Two fixtures sharing the same frozen class manifest cannot replay each other, including empty +interrupted/root records. Empty root +false-check replay succeeds; fabricated empty deadlock/completion and trailing choices fail. +- R3/R4: real runtime fault after committed write, cleanup-fuel cutoff and global stop retain honest +snapshots and classifications; observer failure remains INCOMPLETE. JSON round trips cannot turn them +into PASS. Existing source/declarative exact/approximate/symmetry fixtures stay compatible. +- R4: feed fresh Java artifacts to normalization and browser, including no-line-table classes, long +labels/untrusted text, initial failure, deadlock and resource interruption. Numeric schema reserves +lossless tagged wide types for 97. Document native-stream upgrade boundary where required. +- R5: link the 94B actual measurement ledger and preservation argument; release is blocked if equivalent +observable outcomes/default review is unresolved. Runtime examples are compiled externally; loader does not compile. + +## Refactor Baseline & Rollback + +- Pre-change baseline: fetch and record actual merged-main SHA at implementation start; [94B](94B-bytecode-concurrency.md) merged, plus the shared contract. +Record fresh full build/strict Javadoc/tests and affected/default PIT fingerprints before production edits. +The authoring SHA and older counts are historical context, never fresh implementation baselines. +- Call-site migration: all paths listed in Scope, plus their existing connected tests and exports; +new profile state reaches executor, encoder, replay and consumers in this same milestone where exposed. +- Preserve existing public signatures/semantics, source forward validation, mutation operators/floors, +resource settings and CI parallelism. No hidden compatibility adapter may bypass validation. +- Roll back/restrict the newly admitted profile coherently if normalized reference outcomes diverge, +state/replay identity omits future behavior, cleanup/evidence is fabricated or legacy compatibility fails. +Do not weaken tests, change bounds to conceal a counterexample or silently enable a later phase. + +## Design + +Use the shared contract's deep loader/executor/search seams: immutable validated metadata and program, +owned execution state, one opcode executor and mode-aware scheduler, then existing result/consumer +adapters where contracts permit. Keep bytecode continuation identity separate from source forward PCs. +Do not add a generic backend/framework for hypothetical languages. Internal names in Scope are planned; +choose existing equivalent modules at implementation after connected-source inspection. + +## Current State + +- [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. + +## Tests + +`publicBytecodeLoaderAndRunnerWorkFromJar` (R1/R5), `bytecodeCliRejectsUnsupportedSelections` (R1), +`strictReplayAuthenticatesEveryBytecodeOutcome` (R2/R3), `bytecodeReportsRetainPrecisionAndLocations` (R4), +`bytecodeViewerUsesFreshProducerArtifacts` (R4), `legacyProfilesRemainCompatible` (R4). +Kill missing identity/limit/choice checks, false SOURCE routing, premature completion and precision upgrades. +These are intended behavioral contracts/test names, not tests already implemented or executed. +Use independent expected values/oracles, preserve distinct regression cases and save generated seeds. + +## Constraints + +- Dependencies: [94B](94B-bytecode-concurrency.md) merged, plus the shared contract; sequential publication into main, with Sam's merge update before the next stage. +- Backward compatibility: all existing explicit/source/declarative inputs, results and stores retain +behavior; source evidence is never manufactured for bytecode and native-stream changes are versioned. +- Oracle contract: [shared verification/measurement gates](../../plans/bytecode-contract.md#verification-and-measurement-gates). +- All local Gradle commands include `--max-workers=1 -PpitestThreads=1`. Full strict Javadoc/build/tests, +affected mutation census plus unchanged default PIT gate, and relevant consumers are mandatory during +implementation. NO_COVERAGE is not a kill; report scoped/default totals and inherited residual identities. +- Create `docs/measurements/94C-bytecode-release.md` with implementation: fresh baseline/final evidence, +independent checks, raw measurement conditions, review dispositions and limits. Authoring evidence belongs +in the specification-set record, not a fabricated runtime ledger. + +## Relevant Skills and Review + +- doc-coauthoring: requirements/acceptance completeness and fresh-reader testing. +- domain-modeling / codebase-design: reuse [domain vocabulary](../../../CONTEXT.md) and the shared +small owned interfaces; do not create a competing glossary or source-shaped bytecode abstraction. +- tdd: establish failing behavioral regressions before new production behavior; fixed-seed/shrinking +oracles supplement targeted cases. owasp-security: fail-closed untrusted class metadata and replay input. +- ponytail / ponytail-review: smallest coherent implementation and connected-source review. +- code-review: actual CodeRabbit after this completed specification and before substantial implementation +publication; record completed/quota/error status through agent-setup without inventing completion. +- 94B/95/96/97: review the batching preservation argument for every newly admitted behavior; 99/100/101: +review reduction admission/resource/product obligations in addition to runtime tests. + +The specification-only PR runs document/link/structure validation, reader review and required actual +CodeRabbit invocations. It does not run Java/PIT/browser feature checks for code that does not exist. +After publishing this milestone's implementation PR, report its link and stop; do not watch CI. diff --git a/docs/specs/active/95-bytecode-heap.md b/docs/specs/active/95-bytecode-heap.md new file mode 100644 index 0000000..cce1c69 --- /dev/null +++ b/docs/specs/active/95-bytecode-heap.md @@ -0,0 +1,147 @@ + +# Spec 95: Objects, arrays and dispatch + +## Objective + +Deliver objects, arrays and dispatch as one coherent stage of bounded Java bytecode checking. +**Type: delta. Status: specified, not implemented or measured.** 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 95 only. + +## Scope + +Extend bytecode/ metadata verifier, heap/state/encoder, OpcodeExecutor and sharedness analysis for +application allocations, arrays and general closed dispatch. Update public BytecodeProgram profile, +replay/snapshots, CLI help, reports/viewer fixtures, examples/bytecode and README supported matrix. +Add BytecodeHeapTest/BytecodeDispatchTest/BytecodePublicationTest and heap compiler resources. +General exception handlers belong to 96; remaining primitive/library operations to 97. + +## Non-Goals + +No expansion beyond this milestone's behavior. No host execution of target code, executable application +initializers, dynamic actors, collections, wait/notify, weak memory, bytecode static POR/symmetry, +frozen exhausted actors or fuel-free cycle detection. Later-phase support stays rejected until its +complete implementation and consumers merge. + +## Invariants + +- Existing explicit/source/JSON/replay/symmetry behavior, validation and mutation policy remain intact. +- Owned state and deterministic identities preserve aliases, resource counters and sharedness history. +- Cutoffs end prefixes; external stops and observer errors remain honestly incomplete. +- All executed target behavior stays interpreted; no host fallback or forged source locations. +- Public selection follows the phase release boundary and never advertises partial consumer support. + +## Requirements + +1. **R1 — Heap behavior.** WHEN actors allocate application objects/arrays, THE SYSTEM SHALL interpret +constructors, inherited fields, null/alias cycles, reference operations, checkcast/instanceof and virtual/ +interface dispatch over every validated closed-hierarchy target. It SHALL preserve JVM field hiding, +overrides, access/nestmate rules and constructor initialization, without target class loading. +2. **R2 — Arrays.** WHEN array opcodes execute, THE SYSTEM SHALL support primitive/reference and +multidimensional arrays, length and bounds/store/type/null faults, and exact rank/component metadata. +Each allocated dimension SHALL receive a real identity and budget charge in deterministic JVM order. +Long/float/double elements may exist with default values; their computations remain rejected until 97. +3. **R3 — Publication.** WHEN a reference escapes, THE SYSTEM SHALL promote reachable objects before +publication is observable, retain sharedness history and make shared array/field accesses schedulable. +Unknown roots SHALL be shared; path-sensitive locality SHALL never be inferred from allocator alone. +4. **R4 — Accounting.** WHEN objects escape or become unreachable, THE SYSTEM SHALL retain allocator +namespace, sequences and permanent allocation/cell charges. Length/count/cell/depth checks SHALL follow +the shared failure priority, preserving prior committed instructions and explicit partial multidimensional +allocation effects when a later component hits a budget. No GC/renumbering SHALL occur. +5. **R5 — Complete extension.** WHEN this broader profile is selected, THE SYSTEM SHALL extend strict +replay/evidence/consumers and the two-mode preservation argument with dynamic allocation, dispatch and +publication cases. New dynamic VM faults SHALL follow initial unwind/uncaught semantics; user catch remains rejected. + +## Failure Modes & Edge Cases + +- WHEN metadata, descriptors or reachable behavior is unsupported, THE SYSTEM SHALL reject before +exploration with actionable identity/location diagnostics; dynamic supported faults SHALL remain runtime behavior. +- WHEN actor/setup/observer budgets fail, THE SYSTEM SHALL preserve their separate ownership and the +shared priority, exact-limit semantics and omitted operation. A check/setup failure SHALL not become an actor violation. +- WHEN a run stops externally, THE SYSTEM SHALL retain original INCOMPLETE classification and genuine +already-recorded findings. It SHALL not manufacture a reproducible modeled resource cutoff. +- WHEN this milestone exposes new payload/state, THE SYSTEM SHALL include every future-relevant field +in keys and replay validation, including pending terminal events and permanent allocation charges. + +## Acceptance Criteria + +- R1: inherited/hidden fields, abstract/interface alternatives, invokevirtual/invokeinterface/invokespecial, +null receiver, failed casts, missing targets, nestmate private calls and unknown metadata have independent +expected behavior. Malformed linkage rejects before search; dynamic null/cast/array faults do not. +- R2/R4: zero/max/max+1 lengths, negative length, index bounds, reference covariance/store failure, +multidimensional partial construction, inherited field cells and per-allocator exact budget crossings. +No partial object identity is committed for an allocation that fails before creation; earlier successful +component allocations remain charged in terminal state. JVM differential testing covers non-budget semantics. +- R3/R4: cyclic publication, reference retained only on operand stack, two actors publishing to each +other, reversed allocation interleavings and post-publication allocator exhaustion retain identities, +charges and history. Compare reference/batching normalized outcomes; do not assert equal local snapshots. +- R5: strict replay of published aliases/array failures/resource cutoffs and browser references uses +fresh artifacts. All former initial-profile examples and legacy/source symmetry runs remain stable. + +## Refactor Baseline & Rollback + +- Pre-change baseline: fetch and record actual merged-main SHA at implementation start; [94C](94C-bytecode-release.md) merged, plus the shared contract. +Record fresh full build/strict Javadoc/tests and affected/default PIT fingerprints before production edits. +The authoring SHA and older counts are historical context, never fresh implementation baselines. +- Call-site migration: all paths listed in Scope, plus their existing connected tests and exports; +new profile state reaches executor, encoder, replay and consumers in this same milestone where exposed. +- Preserve existing public signatures/semantics, source forward validation, mutation operators/floors, +resource settings and CI parallelism. No hidden compatibility adapter may bypass validation. +- Roll back/restrict the newly admitted profile coherently if normalized reference outcomes diverge, +state/replay identity omits future behavior, cleanup/evidence is fabricated or legacy compatibility fails. +Do not weaken tests, change bounds to conceal a counterexample or silently enable a later phase. + +## Design + +Use the shared contract's deep loader/executor/search seams: immutable validated metadata and program, +owned execution state, one opcode executor and mode-aware scheduler, then existing result/consumer +adapters where contracts permit. Keep bytecode continuation identity separate from source forward PCs. +Do not add a generic backend/framework for hypothetical languages. Internal names in Scope are planned; +choose existing equivalent modules at implementation after connected-source inspection. + +## Current State + +- [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. + +## Tests + +`heapAliasesAndDispatchMatchJvm` (R1/R2), `arrayFaultsRemainDynamic` (R2), +`transitivePublicationPrecedesVisibleEscape` (R3), `escapeRetainsAllocatorCharges` (R4), +`reversedAllocationsKeepNamespacedIdentity` (R4), `heapProfileReplaysAcrossConsumers` (R5). +Kill omitted inherited cells, actor-global allocation sequence, reversible sharing and alias-copy errors. +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. + +## Constraints + +- Dependencies: [94C](94C-bytecode-release.md) merged, plus the shared contract; sequential publication into main, with Sam's merge update before the next stage. +- Backward compatibility: all existing explicit/source/declarative inputs, results and stores retain +behavior; source evidence is never manufactured for bytecode and native-stream changes are versioned. +- Oracle contract: [shared verification/measurement gates](../../plans/bytecode-contract.md#verification-and-measurement-gates). +- All local Gradle commands include `--max-workers=1 -PpitestThreads=1`. Full strict Javadoc/build/tests, +affected mutation census plus unchanged default PIT gate, and relevant consumers are mandatory during +implementation. NO_COVERAGE is not a kill; report scoped/default totals and inherited residual identities. +- Create `docs/measurements/95-bytecode-heap.md` with implementation: fresh baseline/final evidence, +independent checks, raw measurement conditions, review dispositions and limits. Authoring evidence belongs +in the specification-set record, not a fabricated runtime ledger. + +## Relevant Skills and Review + +- doc-coauthoring: requirements/acceptance completeness and fresh-reader testing. +- domain-modeling / codebase-design: reuse [domain vocabulary](../../../CONTEXT.md) and the shared +small owned interfaces; do not create a competing glossary or source-shaped bytecode abstraction. +- tdd: establish failing behavioral regressions before new production behavior; fixed-seed/shrinking +oracles supplement targeted cases. owasp-security: fail-closed untrusted class metadata and replay input. +- ponytail / ponytail-review: smallest coherent implementation and connected-source review. +- code-review: actual CodeRabbit after this completed specification and before substantial implementation +publication; record completed/quota/error status through agent-setup without inventing completion. +- 94B/95/96/97: review the batching preservation argument for every newly admitted behavior; 99/100/101: +review reduction admission/resource/product obligations in addition to runtime tests. + +The specification-only PR runs document/link/structure validation, reader review and required actual +CodeRabbit invocations. It does not run Java/PIT/browser feature checks for code that does not exist. +After publishing this milestone's implementation PR, report its link and stop; do not watch CI. diff --git a/docs/specs/active/96-bytecode-exceptions.md b/docs/specs/active/96-bytecode-exceptions.md new file mode 100644 index 0000000..0781f20 --- /dev/null +++ b/docs/specs/active/96-bytecode-exceptions.md @@ -0,0 +1,220 @@ + +# Spec 96: General supported exceptions + +## Objective + +Deliver general supported exceptions as one coherent stage of bounded Java bytecode checking. +**Type: delta. Status: specified, not implemented or measured.** 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 96 only. + +## Scope + +Extend bytecode/ handler verifier, OpcodeExecutor, frame/unwind/pending state and Throwable payloads. +Add interpreted supported Throwable hierarchy metadata and exception registry entries, preserving narrow +compiler-cleanup support. Update strict replay, TestResult/TraceRecord/report/viewer failures, examples +and compiler support table. Add BytecodeExceptionTest and try-with-resources resources. +General core-library widening belongs to 97; no class initialization expansion. This phase owns the +minimal immutable UTF-16 String literal/message representation needed for non-null exception messages: +ldc String constants, identity/reference passing and message access only, without String computation. +This phase defines String cells as one header, one length field and one cell per UTF-16 unit, +with identical literal contents interned in a deterministic setup-owned table. String length/heap/fuel +limits apply now;97 references and extends this representation without replacing it. + +## Non-Goals + +No expansion beyond this milestone's behavior. No host execution of target code, executable application +initializers, dynamic actors, collections, wait/notify, weak memory, bytecode static POR/symmetry, +frozen exhausted actors or fuel-free cycle detection. Later-phase support stays rejected until its +complete implementation and consumers merge. + +## Invariants + +- Existing explicit/source/JSON/replay/symmetry behavior, validation and mutation policy remain intact. +- Owned state and deterministic identities preserve aliases, resource counters and sharedness history. +- Cutoffs end prefixes; external stops and observer errors remain honestly incomplete. +- All executed target behavior stays interpreted; no host fallback or forged source locations. +- Public selection follows the phase release boundary and never advertises partial consumer support. + +## Requirements + +1. **R1 — Handler order.** WHEN a supported exception is thrown, THE SYSTEM SHALL select the first +matching exception-table entry for the throwing BCI and modeled type, transfer the exception to handler +stack, or unwind with exact throwing/invocation locations. User athrow(null) SHALL produce modeled NPE. +2. **R2 — Cleanup.** WHEN return/throw crosses synchronized/finally paths, THE SYSTEM SHALL execute +compiled cleanup in order and release held method monitors exactly once. Handler/finally faults SHALL +replace the propagating exception per JVM semantics while earlier committed effects remain. +3. **R3 — Throwable support.** WHEN supported application exceptions/Throwable methods execute, THE +SYSTEM SHALL model constructor/message/cause/suppression state, bounded identities and cells. It SHALL +support restricted try-with-resources with interpreted AutoCloseable.close callbacks; unsupported +callback bodies or platform descriptors SHALL reject before exploration. +4. **R4 — Terminal behavior.** WHEN an exception escapes an actor, THE SYSTEM SHALL emit uncaught +VIOLATION with original throw site and interpreted stack; observer failure SHALL remain INCOMPLETE and +setup failure a load diagnostic. Exhaustion during unwinding SHALL end a cutoff prefix without +inventing completed cleanup. All pending exception/handler/cause/suppression state SHALL enter keys. +5. **R5 — Consumers and oracles.** WHEN exception support is enabled, THE SYSTEM SHALL extend strict +replay/evidence/viewer and reference/batching comparison to caught, replaced, suppressed and uncaught +exceptions, with independent JVM sequential cases and generated shrinking regressions. + +## Failure Modes & Edge Cases + +- WHEN metadata, descriptors or reachable behavior is unsupported, THE SYSTEM SHALL reject before +exploration with actionable identity/location diagnostics; dynamic supported faults SHALL remain runtime behavior. +- WHEN actor/setup/observer budgets fail, THE SYSTEM SHALL preserve their separate ownership and the +shared priority, exact-limit semantics and omitted operation. A check/setup failure SHALL not become an actor violation. +- WHEN a run stops externally, THE SYSTEM SHALL retain original INCOMPLETE classification and genuine +already-recorded findings. It SHALL not manufacture a reproducible modeled resource cutoff. +- WHEN this milestone exposes new payload/state, THE SYSTEM SHALL include every future-relevant field +in keys and replay validation, including pending terminal events and permanent allocation charges. + +## Acceptance Criteria + +- R1/R2: overlapping handlers preserve class-file order, superclass catches, rethrow, nested finally, +normal return through cleanup and exceptions within catch/finally match the JVM. No Java-source rewrite +of handlers or host catch invocation substitutes for interpreted bytecode. +- R3: explicit registry for Throwable/Exception/RuntimeException and modeled VM fault types includes +`()V`, `(String)V`, `(String,Throwable)V` constructors where declared, getMessage/getCause, +addSuppressed/getSuppressed plus protected Throwable `(String,Throwable,ZZ)V` for supported +subclasses. Return arrays allocate/charge; self-suppression/null and suppression-disabled +cases match semantics. Stack-trace mutation/printing, cause-only platform `(Throwable)V` constructors (which may call overridden +toString), and arbitrary JDK exception helpers reject. The selected profile does not enable that callback +constructor in97 either; supported message+cause constructors provide explicit message semantics. +- R3: Throwable has header plus message, cause, causeInitialized, suppressionEnabled and +writableStackTrace fields, plus one cell per suppressed reference (six base cells). Interpreted stack +metadata is separately bounded by depth and captured at throw; stack trace APIs stay unsupported. +All supported Throwable methods add one intrinsic unit to invoke fuel; getSuppressed instead +charges max(1,count) intrinsic units. For zero suppressed exceptions or suppression disabled, +getSuppressed returns one deterministic shared empty Throwable[] constant with no call-time allocation +or cell charge. Charge its one array-header cell to setup once, in constant namespace8/sequence0. +For nonempty results allocate a fresh array with header+count cells charged to the calling actor. +Repeated empty calls on the same or different exceptions preserve that shared identity; nonempty +calls return distinct arrays. This follows [OpenJDK26 Throwable.getSuppressed](https://github.com/openjdk/jdk/blob/jdk-26-ga/src/java.base/share/classes/java/lang/Throwable.java). Reject reachable application Throwable subclasses overriding fillInStackTrace()Ljava/lang/Throwable; +before exploration: base constructors can invoke it and an atomic intrinsic would omit its effects. +A JVM fixture whose override writes a field demonstrates the behavior; loader rejection prevents a +false effect-free constructor result. Other supported application callbacks still interpret normally. +Constructors without that override validate then assign within one atomic intrinsic. Shared full-cost preflight applies now: insufficient total fuel omits the entire +invoke at its BCI with no charges, stack change or allocation; exactly sufficient fuel succeeds. Each runtime fault becomes a modeled Throwable with allocator charges when +materialized for handlers; allocation failure yields a cutoff at its original throwing BCI, never a +fake OutOfMemoryError or missing exception. Bootstrap initial-profile faults remain bounded metadata +until materialization is needed. Messages/getMessage return the same modeled String reference. +- R3: two resources close in reverse order, one/two close failures, body failure, suppressed ordering +and suppression disabled are independently checked; callbacks execute on the interpreter, never host. +- R4/R5: exact fuel limit in a cleanup handler and exception replacing an earlier pending fault retain +real BCIs/charges/monitor state. Replay rejects altered suppression or handler order; browser distinguishes +caught continuation from terminal violation and check failure. Re-run the 94B normalized mode gate, including exact/insufficient intrinsic fuel on getSuppressed. + +## Refactor Baseline & Rollback + +- Pre-change baseline: fetch and record actual merged-main SHA at implementation start; [95](95-bytecode-heap.md) merged, plus the shared contract. +Record fresh full build/strict Javadoc/tests and affected/default PIT fingerprints before production edits. +The authoring SHA and older counts are historical context, never fresh implementation baselines. +- Call-site migration: all paths listed in Scope, plus their existing connected tests and exports; +new profile state reaches executor, encoder, replay and consumers in this same milestone where exposed. +- Preserve existing public signatures/semantics, source forward validation, mutation operators/floors, +resource settings and CI parallelism. No hidden compatibility adapter may bypass validation. +- Roll back/restrict the newly admitted profile coherently if normalized reference outcomes diverge, +state/replay identity omits future behavior, cleanup/evidence is fabricated or legacy compatibility fails. +Do not weaken tests, change bounds to conceal a counterexample or silently enable a later phase. + +## Design + +Use the shared contract's deep loader/executor/search seams: immutable validated metadata and program, +owned execution state, one opcode executor and mode-aware scheduler, then existing result/consumer +adapters where contracts permit. Keep bytecode continuation identity separate from source forward PCs. +Do not add a generic backend/framework for hypothetical languages. Internal names in Scope are planned; +choose existing equivalent modules at implementation after connected-source inspection. + +### Exact Throwable profile + +Resolve these descriptors only on the declared trusted Throwable/Exception/RuntimeException hierarchy +and supported VM exception metadata; subclass user constructors are interpreted. Do not synthesize a +constructor that a platform class does not declare. + +| Owner | Allowed descriptor | +|---|---| +| java/lang/Throwable and declared supported subclasses | `()V`, `(Ljava/lang/String;)V`, `(Ljava/lang/String;Ljava/lang/Throwable;)V` where declared | +| java/lang/Throwable (protected subclass call) | `(Ljava/lang/String;Ljava/lang/Throwable;ZZ)V` | +| java/lang/Throwable | `getMessage()Ljava/lang/String;`, `getCause()Ljava/lang/Throwable;`, `addSuppressed(Ljava/lang/Throwable;)V`, `getSuppressed()[Ljava/lang/Throwable;` | +| java/lang/AutoCloseable | `close()V` only through validated application implementations, interpreted with ordinary opcode costs | + +Supported VM types include NullPointerException, ArithmeticException, IllegalMonitorStateException, +ClassCastException, NegativeArraySizeException, ArrayIndexOutOfBoundsException and ArrayStoreException; +IllegalArgumentException/IllegalStateException support the specified Throwable validation faults. +Include their metadata superclasses and IndexOutOfBoundsException. Explicit application-provided messages retain modeled UTF-16 contents. An implicit VM exception +message may remain a tagged unavailable value only when whole-program conservative analysis proves +no reachable getMessage/other admitted operation can expose it to execution. Unsupported implicit +message inspection, including unknown receiver origin, rejects before exploration; never substitute +null or normalize a value used by application branches. A catch block testing getMessage()!=null for +an implicit fault requires a supported exact message rule or loader rejection. Host stack formatting +alone may normalize in differential comparisons; message-dependent target behavior may not. +This initial profile rejects initCause on all receivers: its cause-overwrite error can call the +replacement cause's overridden toString and cannot be an effect-free atomic fault. Include a JVM +fixture where that callback writes a field and a matching loader-negative test. Explicit message+cause +constructors provide supported cause wiring without this hidden callback. +No getStackTrace/fillInStackTrace/printing/toString/cause-only constructor is admitted by this table. + +### Synchronized intrinsic calls + +Honor trusted declaration synchronization: Throwable.getCause, addSuppressed and getSuppressed acquire +the receiver monitor, block while owned by another actor and release it on normal/abrupt completion. +Use separate entry/body/exit continuation events at the causing invoke BCI; successful acquisition and +release are observable, reentrant and zero opcode fuel. Disabled entry changes nothing and costs zero. +Recompute full-cost fuel preflight from current state whenever entry is actually selected; a blocked +attempt caches neither count nor cost. Successful entry freezes the body plan/count/fuel cost under +the held receiver monitor; the selected body debits invoke+intrinsic work once. Recheck allocation/cell +availability at body execution against current counters, since other actors may charge the allocator +through other escaped payloads. Never reuse a pre-blocking suppression count. Retain +pending call/monitor-release state in canonical keys and replay. Atomicity describes the body while +holding the monitor, not an uninterruptible acquisition-through-return shortcut. An actor explicitly +holding the exception monitor can therefore block another actor's getSuppressed/getCause call. Add that +competing-monitor regression, including a real lock cycle and cleanup. These synchronizing descriptors +are forbidden in checks even when a particular call would not allocate. Throwable constructor internal +fillInStackTrace uses its new unescaped receiver monitor; model required entry/exit events and reject +application overrides as above, rather than invoking target code on the host. + +## Current State + +- [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. + +## Tests + +`exceptionTableOrderMatchesJvm` (R1), `nestedUnwindReleasesExactMonitorDepth` (R2), +`tryWithResourcesKeepsPrimaryAndSuppressed` (R3), `unwindCutoffDoesNotInventRelease` (R4), +`exceptionIdentityAndConsumersReplayStrictly` (R5). Kill handler-order changes, duplicate release, +missing suppression cells, missing pending state and observer-fault-as-violation 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. + +## Constraints + +- Dependencies: [95](95-bytecode-heap.md) merged, plus the shared contract; sequential publication into main, with Sam's merge update before the next stage. +- Backward compatibility: all existing explicit/source/declarative inputs, results and stores retain +behavior; source evidence is never manufactured for bytecode and native-stream changes are versioned. +- Oracle contract: [shared verification/measurement gates](../../plans/bytecode-contract.md#verification-and-measurement-gates). +- All local Gradle commands include `--max-workers=1 -PpitestThreads=1`. Full strict Javadoc/build/tests, +affected mutation census plus unchanged default PIT gate, and relevant consumers are mandatory during +implementation. NO_COVERAGE is not a kill; report scoped/default totals and inherited residual identities. +- Create `docs/measurements/96-bytecode-exceptions.md` with implementation: fresh baseline/final evidence, +independent checks, raw measurement conditions, review dispositions and limits. Authoring evidence belongs +in the specification-set record, not a fabricated runtime ledger. + +## Relevant Skills and Review + +- doc-coauthoring: requirements/acceptance completeness and fresh-reader testing. +- domain-modeling / codebase-design: reuse [domain vocabulary](../../../CONTEXT.md) and the shared +small owned interfaces; do not create a competing glossary or source-shaped bytecode abstraction. +- tdd: establish failing behavioral regressions before new production behavior; fixed-seed/shrinking +oracles supplement targeted cases. owasp-security: fail-closed untrusted class metadata and replay input. +- ponytail / ponytail-review: smallest coherent implementation and connected-source review. +- code-review: actual CodeRabbit after this completed specification and before substantial implementation +publication; record completed/quota/error status through agent-setup without inventing completion. +- 94B/95/96/97: review the batching preservation argument for every newly admitted behavior; 99/100/101: +review reduction admission/resource/product obligations in addition to runtime tests. + +The specification-only PR runs document/link/structure validation, reader review and required actual +CodeRabbit invocations. It does not run Java/PIT/browser feature checks for code that does not exist. +After publishing this milestone's implementation PR, report its link and stop; do not watch CI. diff --git a/docs/specs/active/97-bytecode-core-library.md b/docs/specs/active/97-bytecode-core-library.md new file mode 100644 index 0000000..8b17fd7 --- /dev/null +++ b/docs/specs/active/97-bytecode-core-library.md @@ -0,0 +1,259 @@ + +# Spec 97: Primitive and descriptor-level core library + +## Objective + +Deliver primitive and descriptor-level core library as one coherent stage of bounded Java bytecode checking. +**Type: delta. Status: specified, not implemented or measured.** 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 97 only. + +## Scope + +Extend bytecode/ OpcodeExecutor/value/heap/encoder and IntrinsicRegistry (planned internal name). +Create descriptor/cost/payload table in this spec's implementation ledger, bounded String/wrapper/builder +storage, exact bootstrap validation and pure-check admission metadata. Update snapshots/replay/report JSON, +viewer lossless values, README/examples/compiler fixtures and BytecodePrimitiveTest/BytecodeIntrinsicTest. +Atomics remain 100; no arbitrary JDK callbacks or host execution. + +## Non-Goals + +No expansion beyond this milestone's behavior. No host execution of target code, executable application +initializers, dynamic actors, collections, wait/notify, weak memory, bytecode static POR/symmetry, +frozen exhausted actors or fuel-free cycle detection. Later-phase support stays rejected until its +complete implementation and consumers merge. + +## Invariants + +- Existing explicit/source/JSON/replay/symmetry behavior, validation and mutation policy remain intact. +- Owned state and deterministic identities preserve aliases, resource counters and sharedness history. +- Cutoffs end prefixes; external stops and observer errors remain honestly incomplete. +- All executed target behavior stays interpreted; no host fallback or forged source locations. +- Public selection follows the phase release boundary and never advertises partial consumer support. + +## Requirements + +1. **R1 — Primitives.** WHEN admitted opcodes execute, THE SYSTEM SHALL implement byte/short/char/int/ +long/float/double/boolean conversions, category-2 stack/local rules, overflow/shifts, comparisons, +NaNs/infinities/signed-zero and narrowing per JVM semantics. Floating arithmetic SHALL preserve SC +visibility and lossless raw-bit snapshots, not JavaScript rounded representations. +2. **R2 — Finite intrinsics.** WHEN a platform call occurs, THE SYSTEM SHALL admit only the exact +owner/name/descriptors below, with explicit atomicity, effects, fault, fuel and payload accounting. +Unsupported overloads/bootstraps SHALL reject during loading; an implementation whitelist alone SHALL +not define the documented contract. +3. **R3 — Identity and storage.** WHEN strings/wrappers/builders are created, THE SYSTEM SHALL enforce +UTF-16 limits/cells, deterministic bounded constants/caches and observable allocation/publication. +Integer cache SHALL be exactly -128..127. Each user callback SHALL execute as interpreted application +code; host toString/equals/hashCode SHALL never substitute. +4. **R4 — Bootstrap and checks.** WHEN javac string concatenation is encountered, THE SYSTEM SHALL +admit only StringConcatFactory.makeConcatWithConstants with validated recipe/constant types and exact +invocation descriptor. It SHALL lower its specified cost/effects deterministically, reject lambdas/other +bootstraps, and reject allocating/mutating intrinsics in checks. +5. **R5 — Verification and consumers.** WHEN widened values/library support is released, THE SYSTEM +SHALL extend strict replay, lossless JSON/native snapshots, browser rendering and normalized two-mode +oracles. JVM differential tests SHALL cover boundaries and intrinsic faults rather than host fallback. + +## Failure Modes & Edge Cases + +- WHEN metadata, descriptors or reachable behavior is unsupported, THE SYSTEM SHALL reject before +exploration with actionable identity/location diagnostics; dynamic supported faults SHALL remain runtime behavior. +- WHEN actor/setup/observer budgets fail, THE SYSTEM SHALL preserve their separate ownership and the +shared priority, exact-limit semantics and omitted operation. A check/setup failure SHALL not become an actor violation. +- WHEN a run stops externally, THE SYSTEM SHALL retain original INCOMPLETE classification and genuine +already-recorded findings. It SHALL not manufacture a reproducible modeled resource cutoff. +- WHEN this milestone exposes new payload/state, THE SYSTEM SHALL include every future-relevant field +in keys and replay validation, including pending terminal events and permanent allocation charges. + +## Acceptance Criteria + +- R1: category-2 dup/pop variants, wide locals, signed shifts, MIN/-1 divide/remainder, NaN compares, +float-to-integral saturation/truncation and raw-bit round trips. Literal expected boundary bits derive +outside the interpreter; canonical keys distinguish future-relevant signed zero/raw representations. +- R2/R3: every admitted descriptor has positive/negative tests including null/type/length/fuel/cells, +cache edges and uncached allocation identity. Shared/possibly escaping StringBuilder models, +including two concurrent appends with final length2 check, reject before search; local builders and +publication of their immutable toString results succeed. Deterministic cache/constant materialization precedes actors. +- R2: `stringEqualsFuelBoundaries` uses the literal costs in the equality table below, checking exact +allowance success and one-unit-short cutoff for every row. Verify true/false/NPE outcomes, unchanged +state/fuel on an omitted invocation, and the invoke BCI/required work/remaining allowance in evidence. +- R4: Java17/21/26 string switches, primitive concat and unsupported Object-concat/callback cases; +unsupported variants reject with descriptor/bootstrap diagnostic. No enum/assertion clinit exemption. +- R5: long extrema, signed zero, infinities and NaN payloads survive Java→JSON→viewer→replay fixtures. +Re-run sequential generator and reference/batched normalized outcomes on new operations. + +## Refactor Baseline & Rollback + +- Pre-change baseline: fetch and record actual merged-main SHA at implementation start; [96](96-bytecode-exceptions.md) merged, plus the shared contract. +Record fresh full build/strict Javadoc/tests and affected/default PIT fingerprints before production edits. +The authoring SHA and older counts are historical context, never fresh implementation baselines. +- Call-site migration: all paths listed in Scope, plus their existing connected tests and exports; +new profile state reaches executor, encoder, replay and consumers in this same milestone where exposed. +- Preserve existing public signatures/semantics, source forward validation, mutation operators/floors, +resource settings and CI parallelism. No hidden compatibility adapter may bypass validation. +- Roll back/restrict the newly admitted profile coherently if normalized reference outcomes diverge, +state/replay identity omits future behavior, cleanup/evidence is fabricated or legacy compatibility fails. +Do not weaken tests, change bounds to conceal a counterexample or silently enable a later phase. + +## Design + +Use the shared contract's deep loader/executor/search seams: immutable validated metadata and program, +owned execution state, one opcode executor and mode-aware scheduler, then existing result/consumer +adapters where contracts permit. Keep bytecode continuation identity separate from source forward PCs. +Do not add a generic backend/framework for hypothetical languages. Internal names in Scope are planned; +choose existing equivalent modules at implementation after connected-source inspection. + +### Descriptor registry and intrinsic cost model + +This finite table is the selected library profile. Internal generated equivalent owner names do not +widen it; inheritance uses resolved declaring owner. Admitted calls are one SC intrinsic operation; mutable StringBuilder calls are admitted only for +proven actor-local builders (or setup-local builders discarded before actors), as specified below. +Except for96's synchronized Throwable entry/body/exit protocol, other methods have one SC intrinsic body, +with one invoke-opcode fuel plus the additional units stated here. Dynamic faults consume the invoke +opcode and work already completed; no partial target mutation on failed validation. Reads/writes/ +allocations remain observable even inside intrinsics; non-atomic interpreted user code is not folded +into a host call. Length-dependent costs use input logical UTF-16 units/elements (u); max(1,u) units +in addition to invoke fuel. An intrinsic requiring more total fuel (invoke plus additional units) than remains omits the entire +invocation: no opcode/work/cell/identity charge and no payload change, with a cutoff at the invoke BCI +recording required work and remaining allowance. Thus an expensive intrinsic can cutoff with positive +remaining fuel; the ordinary N/N+1 rule still applies to unit-cost opcodes. Pure preflight validates +operands to determine the normal or fault cost; failed dynamic preconditions cost invoke plus one +intrinsic unit, if available. Costs are debited together only after selection, never by a probe. +Normal completion at exactly the last unit succeeds. String copies read immutable UTF-16 contents. Array clone is admitted only when whole-program +conservative analysis proves its source elements cannot mutate concurrently (actor-exclusive source +or no actor writes after setup, through every alias/dispatch alternative). Unknown proof rejects +before search. Do not treat a concurrently mutable shared array clone as an atomic snapshot. +A two-actor fixture with two ordered source writes and cloning must reject rather than falsely exclude +mixed copied values; an equivalent source-proven-readonly fixture and local array cloning succeed. +General racy cloning requires separately scheduled copy-read semantics and is not enabled here. + +| Owner | Exact names/descriptors | Additional fuel and modeled effects | +|---|---|---| +| java/lang/Object | `()V`, `equals(Ljava/lang/Object;)Z`, `hashCode()I` | 1; constructor no payload, equals identity, hash deterministic from identity with specified stable encoding | +| java/lang/String | `()V`, `(Ljava/lang/String;)V`, `length()I`, `isEmpty()Z`, `charAt(I)C`, `equals(Ljava/lang/Object;)Z`, `hashCode()I`, `toString()Ljava/lang/String;` | Scalars 1, copy/hash max(1,u); equality cost defined below; UTF-16 payload, Java polynomial hash, toString returns this | +| java/lang/String | `concat(Ljava/lang/String;)Ljava/lang/String;`, `valueOf(I)Ljava/lang/String;`, `valueOf(J)Ljava/lang/String;`, `valueOf(Z)Ljava/lang/String;`, `valueOf(C)Ljava/lang/String;` | max(1,result units); deterministic text; Z overload returns interned true/false literals with no call-time allocation; concat(empty) returns receiver; I/J/C results allocate | +| java/lang/Integer | `valueOf(I)Ljava/lang/Integer;`, `intValue()I`, `equals(Ljava/lang/Object;)Z`, `hashCode()I` | 1; exact -128..127 cache; header+one field otherwise | +| java/lang/Boolean | `valueOf(Z)Ljava/lang/Boolean;`, `booleanValue()Z`, `equals(Ljava/lang/Object;)Z`, `hashCode()I` | 1; exactly two cached identities | +| java/lang/Byte, Short, Long, Character | valueOf primitive → matching wrapper and matching primitiveValue getter; equals(Object)Z, hashCode()I | 1; Byte all values, Short/Long -128..127, Character 0..127 cached; no extended caches | +| java/lang/Float, Double | valueOf primitive → matching wrapper and matching primitiveValue getter; equals(Object)Z, hashCode()I | 1; no caches; wrapper NaN canonical equality/hash, signed zero distinct per Java wrapper semantics | +| java/lang/Math | `abs(I)I`, `abs(J)J`, `min(II)I`, `max(II)I`, `min(JJ)J`, `max(JJ)J` | 1; Java overflow (including MIN abs); floating/transcendental overloads reject | +| java/util/Objects | `requireNonNull(Ljava/lang/Object;)Ljava/lang/Object;`, `requireNonNull(Ljava/lang/Object;Ljava/lang/String;)Ljava/lang/Object;`, `isNull(Ljava/lang/Object;)Z`, `nonNull(Ljava/lang/Object;)Z` | 1; NPE for null requireNonNull; supplier/callback overloads reject | +| java/lang/StringBuilder | `()V`, `(I)V`, `(Ljava/lang/String;)V`, `append(I)Ljava/lang/StringBuilder;`, `append(J)Ljava/lang/StringBuilder;`, `append(Z)Ljava/lang/StringBuilder;`, `append(C)Ljava/lang/StringBuilder;`, `append(Ljava/lang/String;)Ljava/lang/StringBuilder;`, `length()I`, `toString()Ljava/lang/String;` | Scalars 1, construction/append/copy max(1,result units); mutable UTF-16 logical capacity and length, bounds as String; append null String writes "null"; empty toString returns interned empty literal without allocation | +| array receiver | `clone()Ljava/lang/Object;` with array owner descriptor | max(1,length); source proven free of concurrent mutation; shallow array of identical component/rank, fresh identity and header+elements charge | +| Throwable family | Only descriptors established in 96 | Scalars 1; suppression copy max(1,count); allocated exception/header fields and returned arrays charged | + +For `String.equals(Ljava/lang/Object;)Z` with a non-null receiver and a String argument, +`u = max(receiver UTF-16 length, argument UTF-16 length)` and additional intrinsic fuel is `max(1,u)`. +Use this fixed cost even for identical references, unequal lengths or an early content mismatch; +the result is true exactly when UTF-16 contents match. A null or non-String argument returns false +with one intrinsic unit. A null receiver raises NPE with one intrinsic unit under the existing fault +rule. Every case additionally costs the invoke opcode's one unit and uses full-cost preflight. +These are profile fuel charges, not measured host-JVM work. + +| Receiver | Argument | Outcome with sufficient fuel | Total fuel | One-unit-short allowance | +|---|---|---|---:|---:| +| `"abc"` | `"abc"` | true | 4 | 3 | +| `"ab"` | `"ac"` | false | 3 | 2 | +| `"ab"` | `"abcd"` | false | 5 | 4 | +| `"abcd"` | `"ab"` | false | 5 | 4 | +| `""` | `""` | true | 2 | 1 | +| `"abc"` | null | false | 2 | 1 | +| `"abc"` | plain Object | false | 2 | 1 | +| null | `"abc"` | NPE | 2 | 1 | + +The totals are independently specified literals: the invoke contributes one unit, the longest +two/three/four-unit String contributes two/three/four, and empty/null/type/fault cases contribute one. +Each one-unit-short case omits the whole invocation without charges, including the null-receiver case. + +For wrapper shorthand above, exact primitive/getter pairs are Byte B/byteValue()B, Short S/shortValue()S, +Long J/longValue()J, Character C/charValue()C, Float F/floatValue()F and Double D/doubleValue()D; +valueOf returns `Ljava/lang/;`. No constructor/numeric-conversion widening is implied. +When StringBuilder.toString() is reachable, preinstall the interned empty String in setup. Empty +builders return it with no call-time allocation/cells; nonempty results allocate a fresh immutable +String. Fuel remains invoke1+max(1,result units). Test empty identity against "", repeated calls and an +exhausted allocation budget (empty success versus nonempty cutoff). This follows +[OpenJDK26 StringBuilder.toString](https://github.com/openjdk/jdk/blob/jdk-26-ga/src/java.base/share/classes/java/lang/StringBuilder.java). +Object.getClass, clone on arbitrary Object, String.intern, Object-argument String.valueOf/append, +reflection, system clocks/identityHashCode and all other overloads reject. + +Retain96's String representation: modeled header plus one length field plus UTF-16 units (no hidden backing-array double +charge). Builders have header plus length/capacity fields plus capacity units; default capacity 16, +explicit capacity n, String constructor capacity length+16. Growth uses max(2*old+2, required), checked +against String length cap and cell budget before mutation; negative/oversized capacities fault or cutoff +as specified by the shared priority. Growth charges incremental cells permanently to the builder's allocator. This initial StringBuilder +profile requires conservative whole-program nonescape proof: builders cannot reach the fixture, +statics, another actor or a published object, including through helper/dispatch alternatives. Unknown +escape rejects during loading; setup-created builders retained by the fixture therefore reject. +Only immutable String results may publish. Do not treat racy shared append as an atomic success or +use a runtime "unsupported" verdict after exploration. General shared StringBuilder support would +require separately specified internal scheduling, pending operations and race/fault semantics; it is +not enabled by this registry. This restriction does not weaken generic application-object publication +or permanent allocator charging. A model with two actors appending to one builder and a final length +check must reject before search rather than falsely pass because both appends were serialized. +Wrapper payload is one field. Throwable payload layout is fixed in 96's registry and encoded explicitly. +String constants are interned by identical UTF-16 contents in a bounded setup-owned deterministic table; +when String.valueOf(Z) is reachable, preinstall both "true" and "false" with ordinary literal setup +cell/length accounting. Calls return those same literal identities without allocation; their fuel cost +remains max(1,result units). Add JVM differential identity cases for both boolean results against literals. +This follows [OpenJDK26 String.valueOf](https://github.com/openjdk/jdk/blob/jdk-26-ga/src/java.base/share/classes/java/lang/String.java); +class monitors and wrapper caches have tagged stable identities, charged to setup cells before actors. +Record exact cache/table cost on setup and reject a setup limit rather than lazily charging whichever +actor first touches a constant. Object hashCode is FNV-1a-32 (offset 2166136261, prime 16777619, modulo 2^32) over one namespace tag +byte (setup=0, actor=1, constant=2), big-endian signed 32-bit owner/subnamespace and big-endian 64-bit +sequence. Setup owner=0; actor owner=id; constants use stable subnamespace IDs 0=class-monitor, +1=String, 2=Integer, 3=Boolean, 4=Byte, 5=Short, 6=Long, 7=Character, 8=empty-Throwable-array, with sequence from sorted class +names, sorted UTF-16 contents or ascending cached values. Hash may collide and is unchanged by +publication; keying/equality never relies on hash uniqueness. This modeled deterministic hash is not +required to equal the host JVM's unspecified identity hash. + +Concat accepts only primitive/String operands and primitive/String constants in a verified +makeConcatWithConstants recipe; Object conversions/callbacks reject. Recipe cost is max(1, output +units) plus one per operand conversion; result String allocation obeys cells/count/length caps. Any +interpreted callback elsewhere must have an explicit registered descriptor and scheduling/cost +contract before admission; this table enables no additional callback-taking intrinsic. + +## Current State + +- [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. + +## Tests + +`allPrimitiveEdgesMatchIndependentJvmCases` (R1/R5), `intrinsicDescriptorsAreClosed` (R2), +`cacheIdentityAndPayloadBudgetsAreDeterministic` (R3), `concatRecipesNeverCallHostCallbacks` (R4), +`wideValuesRoundTripWithoutNumericCoercion` (R5). Kill descriptor broadening, cache-boundary shifts, +missing payload charges, NaN comparison inversion and lossy long/raw-bit conversion. +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. + +## Constraints + +- Dependencies: [96](96-bytecode-exceptions.md) merged, plus the shared contract; sequential publication into main, with Sam's merge update before the next stage. +- Backward compatibility: all existing explicit/source/declarative inputs, results and stores retain +behavior; source evidence is never manufactured for bytecode and native-stream changes are versioned. +- Oracle contract: [shared verification/measurement gates](../../plans/bytecode-contract.md#verification-and-measurement-gates). +- All local Gradle commands include `--max-workers=1 -PpitestThreads=1`. Full strict Javadoc/build/tests, +affected mutation census plus unchanged default PIT gate, and relevant consumers are mandatory during +implementation. NO_COVERAGE is not a kill; report scoped/default totals and inherited residual identities. +- Create `docs/measurements/97-bytecode-core-library.md` with implementation: fresh baseline/final evidence, +independent checks, raw measurement conditions, review dispositions and limits. Authoring evidence belongs +in the specification-set record, not a fabricated runtime ledger. + +## Relevant Skills and Review + +- doc-coauthoring: requirements/acceptance completeness and fresh-reader testing. +- domain-modeling / codebase-design: reuse [domain vocabulary](../../../CONTEXT.md) and the shared +small owned interfaces; do not create a competing glossary or source-shaped bytecode abstraction. +- tdd: establish failing behavioral regressions before new production behavior; fixed-seed/shrinking +oracles supplement targeted cases. owasp-security: fail-closed untrusted class metadata and replay input. +- ponytail / ponytail-review: smallest coherent implementation and connected-source review. +- code-review: actual CodeRabbit after this completed specification and before substantial implementation +publication; record completed/quota/error status through agent-setup without inventing completion. +- 94B/95/96/97: review the batching preservation argument for every newly admitted behavior; 99/100/101: +review reduction admission/resource/product obligations in addition to runtime tests. + +The specification-only PR runs document/link/structure validation, reader review and required actual +CodeRabbit invocations. It does not run Java/PIT/browser feature checks for code that does not exist. +After publishing this milestone's implementation PR, report its link and stop; do not watch CI. diff --git a/docs/specs/active/98-bytecode-cbs.md b/docs/specs/active/98-bytecode-cbs.md new file mode 100644 index 0000000..f709e63 --- /dev/null +++ b/docs/specs/active/98-bytecode-cbs.md @@ -0,0 +1,147 @@ + +# Spec 98: Exact bytecode context-bounded search + +## Objective + +Deliver exact bytecode context-bounded search as one coherent stage of bounded Java bytecode checking. +**Type: delta. Status: specified, not implemented or measured.** 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 98 only. + +## Scope + +Extend bytecode exact-search adapter and cb/ContextBoundedExplorer.java only through a narrow owned +bytecode route, preserving existing source/JSON paths. Wire InterleaveRunner/CLI strategy selection, +reports/attestation/replay/viewer and CBS iteration/resource prefixes; add BytecodeCbsOracleTest, +built-jar/CLI/browser fixtures and measurements/98-bytecode-cbs.md. +DPOR analysis belongs to 99; bitstate to 101. + +## Non-Goals + +No expansion beyond this milestone's behavior. No host execution of target code, executable application +initializers, dynamic actors, collections, wait/notify, weak memory, bytecode static POR/symmetry, +frozen exhausted actors or fuel-free cycle detection. Later-phase support stays rejected until its +complete implementation and consumers merge. + +## Invariants + +- Existing explicit/source/JSON/replay/symmetry behavior, validation and mutation policy remain intact. +- Owned state and deterministic identities preserve aliases, resource counters and sharedness history. +- Cutoffs end prefixes; external stops and observer errors remain honestly incomplete. +- All executed target behavior stays interpreted; no host fallback or forged source locations. +- Public selection follows the phase release boundary and never advertises partial consumer support. + +## Requirements + +1. **R1 — Cost product.** WHEN CBS explores, THE SYSTEM SHALL retain complete bytecode state plus +last actor and minimum preemption cost. Switching from a runnable prior actor SHALL cost one; forced +switch after blocking/termination SHALL cost zero. Pending terminal event enabledness SHALL follow the +shared scheduler, never host-thread status. +2. **R2 — Bounds.** WHEN another preemption would exceed the selected bound, THE SYSTEM SHALL emit +a prefix-ending PREEMPTION_BOUND cutoff at the omitted bytecode/event location, continue alternatives +and preserve fuel/allocation counters without executing the omitted choice. It SHALL not freeze actors. +Cost dominance SHALL not suppress uncovered cutoff obligations: retain/revisit distinct cost contexts +until their omitted-operation outcomes are covered, even when a lower-cost visit covers positive +behavior. A completed lower-cost path SHALL not erase bounded incompleteness on a higher-cost path. +3. **R3 — Reference agreement.** WHEN compared at a context bound, THE SYSTEM SHALL match independent +exhaustive enumeration at the same production scheduling granularity. Instruction-reference CBS SHALL +be evaluated at its own granularity; changing granularity SHALL not be assumed to preserve context costs. +4. **R4 — Isolation and consumers.** WHEN iterative/repeated/concurrent CBS runs occur, THE SYSTEM +SHALL use fresh per-bound membership and immutable bindings, preserve real evidence, and expose +requested/effective strategy, bound and precision through library/CLI/reports/viewer. Discovered failure +bound SHALL not imply a globally shortest schedule or a proven minimum after interruption. + +## Failure Modes & Edge Cases + +- WHEN metadata, descriptors or reachable behavior is unsupported, THE SYSTEM SHALL reject before +exploration with actionable identity/location diagnostics; dynamic supported faults SHALL remain runtime behavior. +- WHEN actor/setup/observer budgets fail, THE SYSTEM SHALL preserve their separate ownership and the +shared priority, exact-limit semantics and omitted operation. A check/setup failure SHALL not become an actor violation. +- WHEN a run stops externally, THE SYSTEM SHALL retain original INCOMPLETE classification and genuine +already-recorded findings. It SHALL not manufacture a reproducible modeled resource cutoff. +- WHEN this milestone exposes new payload/state, THE SYSTEM SHALL include every future-relevant field +in keys and replay validation, including pending terminal events and permanent allocation charges. + +## Acceptance Criteria + +- R1/R3: independent tiny-state enumerator validates bounds 0,1,2; running versus blocked switches, +reentrant monitors, local computation, pending failure/cutoff and termination. Same values at different +last actor/cost remain distinct where future costs differ; lower cost dominates only soundly. +- R2/R3: two actors with two independent abstract actions each, bound2, include reachable prefixes +B1,A1,A2 and A1,B1,A2 and their full continuations. Independently enumerate last-actor/cost and +preemption omissions before applying dominance; retain the first actual bound-prune witness and +INCOMPLETE status. Extend with a case where the omitted choice lies below a dominated state. +- R2: strict replay authenticates owner/location/limit/omitted choice for preemption cutoff and rejects +an executed over-bound action. Instruction fuel cutoff competing with preemption uses fuel only when +that actor is selected; a preemption-disallowed choice is not executed or charged. +- R3/R4: iterative CBS equals fresh single-bound results, interrupted search remains INCOMPLETE and +real violations/deadlocks retain their original witnesses. Built-jar/CLI and fresh browser artifacts +exercise explicit/omitted selection and invalid bound handling; old source CBS regressions remain. + +## Refactor Baseline & Rollback + +- Pre-change baseline: fetch and record actual merged-main SHA at implementation start; [97](97-bytecode-core-library.md) merged, plus the shared contract. +Record fresh full build/strict Javadoc/tests and affected/default PIT fingerprints before production edits. +The authoring SHA and older counts are historical context, never fresh implementation baselines. +- Call-site migration: all paths listed in Scope, plus their existing connected tests and exports; +new profile state reaches executor, encoder, replay and consumers in this same milestone where exposed. +- Preserve existing public signatures/semantics, source forward validation, mutation operators/floors, +resource settings and CI parallelism. No hidden compatibility adapter may bypass validation. +- Roll back/restrict the newly admitted profile coherently if normalized reference outcomes diverge, +state/replay identity omits future behavior, cleanup/evidence is fabricated or legacy compatibility fails. +Do not weaken tests, change bounds to conceal a counterexample or silently enable a later phase. + +## Design + +Use the shared contract's deep loader/executor/search seams: immutable validated metadata and program, +owned execution state, one opcode executor and mode-aware scheduler, then existing result/consumer +adapters where contracts permit. Keep bytecode continuation identity separate from source forward PCs. +Do not add a generic backend/framework for hypothetical languages. Internal names in Scope are planned; +choose existing equivalent modules at implementation after connected-source inspection. + +## Current State + +- [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. + +## Tests + +`bytecodeCbsMatchesIndependentBoundedEnumeration` (R1/R3), +`forcedSwitchAndPendingTerminalCostsAreExact` (R1), `preemptionCutoffOmitsUnexecutedChoice` (R2), +`iterativeBytecodeCbsIsIsolated` (R4), `cbsConsumersRetainLimitsAndPrecision` (R4). +Kill last-actor omission, wrong runnable-switch cost, strict-versus-nonstrict bound and per-bound reuse. +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. + +## Constraints + +- Dependencies: [97](97-bytecode-core-library.md) merged, plus the shared contract; sequential publication into main, with Sam's merge update before the next stage. +- Backward compatibility: all existing explicit/source/declarative inputs, results and stores retain +behavior; source evidence is never manufactured for bytecode and native-stream changes are versioned. +- Oracle contract: [shared verification/measurement gates](../../plans/bytecode-contract.md#verification-and-measurement-gates). +- All local Gradle commands include `--max-workers=1 -PpitestThreads=1`. Full strict Javadoc/build/tests, +affected mutation census plus unchanged default PIT gate, and relevant consumers are mandatory during +implementation. NO_COVERAGE is not a kill; report scoped/default totals and inherited residual identities. +- Create `docs/measurements/98-bytecode-cbs.md` with implementation: fresh baseline/final evidence, +independent checks, raw measurement conditions, review dispositions and limits. Authoring evidence belongs +in the specification-set record, not a fabricated runtime ledger. + +## Relevant Skills and Review + +- doc-coauthoring: requirements/acceptance completeness and fresh-reader testing. +- domain-modeling / codebase-design: reuse [domain vocabulary](../../../CONTEXT.md) and the shared +small owned interfaces; do not create a competing glossary or source-shaped bytecode abstraction. +- tdd: establish failing behavioral regressions before new production behavior; fixed-seed/shrinking +oracles supplement targeted cases. owasp-security: fail-closed untrusted class metadata and replay input. +- ponytail / ponytail-review: smallest coherent implementation and connected-source review. +- code-review: actual CodeRabbit after this completed specification and before substantial implementation +publication; record completed/quota/error status through agent-setup without inventing completion. +- 94B/95/96/97: review the batching preservation argument for every newly admitted behavior; 99/100/101: +review reduction admission/resource/product obligations in addition to runtime tests. + +The specification-only PR runs document/link/structure validation, reader review and required actual +CodeRabbit invocations. It does not run Java/PIT/browser feature checks for code that does not exist. +After publishing this milestone's implementation PR, report its link and stop; do not watch CI. diff --git a/docs/specs/active/99-bytecode-dpor.md b/docs/specs/active/99-bytecode-dpor.md new file mode 100644 index 0000000..b976cfa --- /dev/null +++ b/docs/specs/active/99-bytecode-dpor.md @@ -0,0 +1,154 @@ + +# Spec 99: Conservatively admitted bytecode DPOR + +## Objective + +Deliver conservatively admitted bytecode dpor as one coherent stage of bounded Java bytecode checking. +**Type: delta. Status: specified, not implemented or measured.** 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 99 only. + +## Scope + +Create internal bytecode admission/resource/dependency/observation analysis and dynamic continuation +sleep-context representation; integrate dpor/DporExplorer.java through a justified bytecode path or +small bytecode-specific explorer, preserving source future-list semantics. Update requested/effective +selection and fallback consumers in runner/CLI/report/replay/viewer. Add BytecodeDporAdmissionTest, +BytecodeDporOracleTest, BytecodeDporReductionTest and measurements/99-bytecode-dpor.md with written +preservation argument. No static POR, symmetry, cyclic optimization or bitstate. + +## Non-Goals + +No expansion beyond this milestone's behavior. No host execution of target code, executable application +initializers, dynamic actors, collections, wait/notify, weak memory, bytecode static POR/symmetry, +frozen exhausted actors or fuel-free cycle detection. Later-phase support stays rejected until its +complete implementation and consumers merge. + +## Invariants + +- Existing explicit/source/JSON/replay/symmetry behavior, validation and mutation policy remain intact. +- Owned state and deterministic identities preserve aliases, resource counters and sharedness history. +- Cutoffs end prefixes; external stops and observer errors remain honestly incomplete. +- All executed target behavior stays interpreted; no host fallback or forged source locations. +- Public selection follows the phase release boundary and never advertises partial consumer support. + +## Requirements + +1. **R1 — Admission.** WHEN DPOR is requested, THE SYSTEM SHALL require acyclic reachable control and +call graphs, conservative resource bounds within selected limits and complete dependency/observation +summaries. Analysis SHALL include setup, dispatch alternatives, constructors, intrinsics, implicit +monitor/unwind/error events and all check executions. Unknown metadata SHALL already reject loading; +unknown analysis costs/effects or possible exhaustion SHALL select exhaustive traversal with reason. +2. **R2 — Runtime cutoff.** WHEN execution reaches an actual limit, THE SYSTEM SHALL determine it +from runtime state and preserve prefix-ending cutoffs, conservatively dependent with competing choices. +It SHALL append no sentinel or future pseudo-cutoff and SHALL infer no independence from actor-local +fuel/allocation ownership alone. Runtime exhaustion contradicting an admission certificate SHALL be +a failed correctness gate, with safe exhaustive rerun or INCOMPLETE analysis-error result, never trusted +reduced absence. +3. **R3 — Independence.** WHEN actions are pruned, THE SYSTEM SHALL establish enabledness preservation, +commutation, check/error observations and terminal-outcome preservation, including publication, +allocation identity and monitor ownership. Dynamic continuations and complete sleep contexts SHALL +enter visited coverage; list indices/Step identity from source SHALL not masquerade as bytecode actions. +4. **R4 — Argument and measurement.** WHEN optimization is accepted, THE SYSTEM SHALL provide a written +preservation argument and genuine measured reduction on an acyclic disjoint-write fixture versus exact +DFS at identical mode/limits. It SHALL exercise fallback/terminal behavior separately; a DPOR label or +all-path exhaustive run SHALL not count as reduction evidence. +5. **R5 — Consumers.** WHEN DPOR falls back, THE SYSTEM SHALL report requested DPOR, effective DFS and +specific reason in library/CLI/reports/viewer/replay metadata. Loops SHALL remain usable via exhaustive +fallback. Existing source/JSON DPOR and check contracts SHALL remain intact. + +## Failure Modes & Edge Cases + +- WHEN metadata, descriptors or reachable behavior is unsupported, THE SYSTEM SHALL reject before +exploration with actionable identity/location diagnostics; dynamic supported faults SHALL remain runtime behavior. +- WHEN actor/setup/observer budgets fail, THE SYSTEM SHALL preserve their separate ownership and the +shared priority, exact-limit semantics and omitted operation. A check/setup failure SHALL not become an actor violation. +- WHEN a run stops externally, THE SYSTEM SHALL retain original INCOMPLETE classification and genuine +already-recorded findings. It SHALL not manufacture a reproducible modeled resource cutoff. +- WHEN this milestone exposes new payload/state, THE SYSTEM SHALL include every future-relevant field +in keys and replay validation, including pending terminal events and permanent allocation charges. + +## Acceptance Criteria + +- R1: bound every path through dispatch and exceptions with saturating arithmetic; compute actor fuel, +allocations/cells/depth and per-observer-invocation demand plus setup, including payload growth +charged to an original allocator when other actors mutate escaped modeled objects. Setup/check error possibilities +and intrinsic payload costs are included. Known dynamic faults cannot be treated as invisible locals. +Unknown observation or possible resource exhaustion falls back; simple separate budgets do not admit. +- R2/R3: exact-limit return, exhaustion versus another actor's violation, null fault versus release, +publication/aliases and complete sleep coverage match independent exhaustive normalized sets. Test +all-asleep handling without calling it deadlock; no synthetic sentinel appears in future summaries. +- R3/R4: argument states admitted domain, complete state relation, action identity, observation visibility, +terminal cases, sleep product coverage and exhaustive fallback. Review counterexamples before acceptance. +Acyclic independent writes to distinct unobserved fields with FINAL checks absent or justified must +reduce actual states/transitions and preserve final observations; publish raw counts, not invented targets. +- R5: cyclic loops, unknown costs and insufficient limits show distinct fallback reasons in actual jar, +CLI/report/browser output. Effective DFS is exact with exact storage; source DPOR tests still pass. + +## Refactor Baseline & Rollback + +- Pre-change baseline: fetch and record actual merged-main SHA at implementation start; [98](98-bytecode-cbs.md) merged, plus the shared contract. +Record fresh full build/strict Javadoc/tests and affected/default PIT fingerprints before production edits. +The authoring SHA and older counts are historical context, never fresh implementation baselines. +- Call-site migration: all paths listed in Scope, plus their existing connected tests and exports; +new profile state reaches executor, encoder, replay and consumers in this same milestone where exposed. +- Preserve existing public signatures/semantics, source forward validation, mutation operators/floors, +resource settings and CI parallelism. No hidden compatibility adapter may bypass validation. +- Roll back/restrict the newly admitted profile coherently if normalized reference outcomes diverge, +state/replay identity omits future behavior, cleanup/evidence is fabricated or legacy compatibility fails. +Do not weaken tests, change bounds to conceal a counterexample or silently enable a later phase. + +## Design + +Use the shared contract's deep loader/executor/search seams: immutable validated metadata and program, +owned execution state, one opcode executor and mode-aware scheduler, then existing result/consumer +adapters where contracts permit. Keep bytecode continuation identity separate from source forward PCs. +Do not add a generic backend/framework for hypothetical languages. Internal names in Scope are planned; +choose existing equivalent modules at implementation after connected-source inspection. + +## Current State + +- [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. + +## Tests + +`admissionIncludesImplicitAndObserverCosts` (R1), `possibleExhaustionFallsBackWithoutSentinel` (R1/R2), +`dynamicSleepProductsMatchExactEnumeration` (R3), `acyclicDisjointWritesActuallyReduce` (R4), +`allConsumersReportRequestedAndEffectiveTraversal` (R5). Kill omitted dispatch alternatives, +underestimated intrinsic/unwind costs, fuel-only independence, lost sleep context and false optimized labels. +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. + +## Constraints + +- Dependencies: [98](98-bytecode-cbs.md) merged, plus the shared contract; sequential publication into main, with Sam's merge update before the next stage. +- Backward compatibility: all existing explicit/source/declarative inputs, results and stores retain +behavior; source evidence is never manufactured for bytecode and native-stream changes are versioned. +- Oracle contract: [shared verification/measurement gates](../../plans/bytecode-contract.md#verification-and-measurement-gates). +- All local Gradle commands include `--max-workers=1 -PpitestThreads=1`. Full strict Javadoc/build/tests, +affected mutation census plus unchanged default PIT gate, and relevant consumers are mandatory during +implementation. NO_COVERAGE is not a kill; report scoped/default totals and inherited residual identities. +- Create `docs/measurements/99-bytecode-dpor.md` with implementation: fresh baseline/final evidence, +independent checks, raw measurement conditions, review dispositions and limits. Authoring evidence belongs +in the specification-set record, not a fabricated runtime ledger. + +## Relevant Skills and Review + +- doc-coauthoring: requirements/acceptance completeness and fresh-reader testing. +- domain-modeling / codebase-design: reuse [domain vocabulary](../../../CONTEXT.md) and the shared +small owned interfaces; do not create a competing glossary or source-shaped bytecode abstraction. +- tdd: establish failing behavioral regressions before new production behavior; fixed-seed/shrinking +oracles supplement targeted cases. owasp-security: fail-closed untrusted class metadata and replay input. +- ponytail / ponytail-review: smallest coherent implementation and connected-source review. +- code-review: actual CodeRabbit after this completed specification and before substantial implementation +publication; record completed/quota/error status through agent-setup without inventing completion. +- 94B/95/96/97: review the batching preservation argument for every newly admitted behavior; 99/100/101: +review reduction admission/resource/product obligations in addition to runtime tests. + +The specification-only PR runs document/link/structure validation, reader review and required actual +CodeRabbit invocations. It does not run Java/PIT/browser feature checks for code that does not exist. +After publishing this milestone's implementation PR, report its link and stop; do not watch CI.