Repository navigation
Cooperative scheduler for PChecker, with value-semantics and lowering fixes - #1008
Open
ankushdesai wants to merge 51 commits into
Open
ankushdesai wants to merge 51 commits into
ankushdesai wants to merge 51 commits into
Conversation
Each state machine used to run on its own thread, and the scheduler serialized them by parking and waking threads at every scheduling point. Goto and raise unwound handlers with exceptions. Scheduling points are now awaitables: they complete inline when the current machine keeps running, otherwise they park its continuation and a single run loop resumes whichever machine the strategy picks. Send, create and receive are awaited in generated code, and callers check for a pending transition after calls that may goto or raise instead of relying on exceptions. Scheduling decisions are unchanged, so strategies, replay and schedule files behave as before. Claude-Session: https://claude.ai/code/session_01VEcvJ4X55JReamZATsUWmK
The ids are only dictionary keys, so hashing them bought nothing and ran a SHA-256 for every logged send and receive in every schedule. Claude-Session: https://claude.ai/code/session_01VEcvJ4X55JReamZATsUWmK
Building the text and JSON traces dominated exploration, yet only the trace of a failing schedule is ever written. Explore without them and replay the failing schedule with tracing enabled to produce its traces. Verbose and replay runs trace as before. Claude-Session: https://claude.ai/code/session_01VEcvJ4X55JReamZATsUWmK
Collecting activity coverage takes about a third of exploration time. --no-coverage skips it for runs that do not read the coverage report. Claude-Session: https://claude.ai/code/session_01VEcvJ4X55JReamZATsUWmK
The same machine states and event links recur throughout a schedule, and rebuilding their string ids for every event dominated coverage collection. Claude-Session: https://claude.ai/code/session_01VEcvJ4X55JReamZATsUWmK
They were never removed, so every goto and raise grew the list that each dequeue scans, and a later event of the same type could be linked to a stale entry. Claude-Session: https://claude.ai/code/session_01VEcvJ4X55JReamZATsUWmK
Event coverage state ids depend only on their inputs, and timeline tokens only need formatting the first time a pair of deliveries is seen. Claude-Session: https://claude.ai/code/session_01VEcvJ4X55JReamZATsUWmK
Sends, announces, raises and machine creation formatted their error messages on every call, whether or not the check failed. Claude-Session: https://claude.ai/code/session_01VEcvJ4X55JReamZATsUWmK
Every scheduling step filtered the operations into a new list and looked up priorities through LINQ closures. Claude-Session: https://claude.ai/code/session_01VEcvJ4X55JReamZATsUWmK
Tuples copied their field names and values on every construction and clone, and immutable values (primitives, machine references) were cloned and re-boxed on every read. Tuples of a type now share one names array and keep their values in an array, and copies share immutable values. Claude-Session: https://claude.ai/code/session_01VEcvJ4X55JReamZATsUWmK
Announce looked up and invoked the event constructor through reflection on every call; compile it once per event type instead. Claude-Session: https://claude.ai/code/session_01VEcvJ4X55JReamZATsUWmK
Every goto searched the machine's states for the target and formatted its qualified name. Claude-Session: https://claude.ai/code/session_01VEcvJ4X55JReamZATsUWmK
Event values were created with a default payload that is replaced right away, or never read at all. Claude-Session: https://claude.ai/code/session_01VEcvJ4X55JReamZATsUWmK
Temporaries are always assigned before they are read, so defaulting tuple- and collection-typed ones only allocated. Claude-Session: https://claude.ai/code/session_01VEcvJ4X55JReamZATsUWmK
Every send copies the sender's clock. Machine ids are small and dense, so an array copies far cheaper than a dictionary. Claude-Session: https://claude.ai/code/session_01VEcvJ4X55JReamZATsUWmK
The trace records every scheduling step, and the linked-list pointers between steps were unused. Claude-Session: https://claude.ai/code/session_01VEcvJ4X55JReamZATsUWmK
The cooperative scheduler turned StateMachine.SendEvent and CreateInterface into awaitable scheduling points. Foreign C# code calls them synchronously and cannot await, so the awaitable was dropped: when the scheduler switched operations, the rest of the send (the enqueue) was parked on the operation while the P handler kept running as if it were still scheduled. Events were lost or the checker reported bogus bugs such as "X invoked SendEvent on behalf of Y", and code calling CreateInterface no longer compiled. Restore master's synchronous signatures for foreign code. They do the same checks, announce and vector clock work, then enqueue or create right away without a scheduling point, so there is no continuation to lose and no randomness is consumed. They must be called on the state machine that is executing (checked), so they cannot act from the test entry or on behalf of another machine. Generated code now calls the awaitable SendEventAsync / CreateInterfaceAsync instead, so P sends and creates remain scheduling points. Add regression tests with C# foreign functions that send and create through the machine (they pass on master), let the regression and Phase1Dormancy harnesses build ForeignFunctions.cs files next to the P files, and document how foreign code interacts with the runtime. Co-Authored-By: Claude Code <noreply@anthropic.com>
On master, RaiseEvent and goto threw an exception that unwound foreign C# frames and every P caller. The cooperative scheduler replaced that with a pending transition plus an `if (HasPendingTransition) return` check after calls that may raise, but the check was never emitted after calls to foreign functions. So when foreign code raised or went to a state (directly or by calling back into a P function that does), the P code after the call kept running: assertions after the call failed spuriously and a second raise tripped the dangling-transition check. Treat a foreign function, and every function that transitively calls one, as possibly leaving a pending transition, so the check follows the call both as a statement and in an assignment (calls in expressions are lifted to temporaries). The set is computed per compilation from the call graph and kept on the CompilationContext, since the code generator instance is shared between concurrent compilations. Monitors get the same check through Monitor.HasPendingTransition. The cost is one field read per foreign call. Add regression tests for a foreign raise, a raise through a P helper, a raise in an assignment, a goto from a local foreign function, a foreign callback into a P goto, and the same in a spec monitor. They pass on master. Co-Authored-By: Claude Code <noreply@anthropic.com>
If code drops the awaitable of a scheduling point (e.g. foreign code
calling SendEventAsync without awaiting it), it keeps running after the
scheduler switched to another operation, and its parked continuation
is later overwritten or discarded. Before, this showed up as a bogus
program bug ("X invoked SendEvent on behalf of Y") or silently lost
work.
The operation the scheduler picked always has a parked continuation
until the run loop resumes it, so any call into the scheduler (or a
runtime check of the calling machine) while the scheduled operation
still has one means the caller runs outside of the scheduler. Detect
that, stop the schedule and record it as an internal error with a
pointer to the likely cause, instead of a bug: it is not counted or
traced as a bug, later assertion failures in the corrupted schedule
are ignored, the run stops, the message is printed and `p check` exits
with the internal-error code. The check is one field read per
scheduling point.
The in-process regression runner now also fails on internal errors,
which it used to ignore. Add a unit test with a foreign function that
drops SendEventAsync.
Co-Authored-By: Claude Code <noreply@anthropic.com>
The test entry method now runs synchronously inside the run loop, so it cannot be suspended. Its Create scheduling point could still pick an already created machine, which reported the false bug "The test entry method can only create a single state machine." (C# tests creating more than one machine, which work on master). Take the Create scheduling point only while the test entry is the only enabled operation, where it cannot switch away; this keeps the usual single create of a generated P test, and its schedule trace, unchanged. Later creates register and enable the machine without a scheduling point, so the machines start once the test entry returns. This is deterministic; it only drops interleavings where a machine runs before the test entry has created its siblings. A create from foreign code inside a handler (allowed on master) is done on behalf of the executing machine, without a scheduling point. Also drop the duplicate hasTaskInputParameters check in TestMethodInfo and say in its error message that async test methods are no longer supported. Add a unit test with a C# test entry creating four machines, under random and PCT with several seeds. Co-Authored-By: Claude Code <noreply@anthropic.com>
`p check` reuses an existing PGenerated dll. A dll compiled by an older P binds to runtime members whose signature or meaning changed: it either fails with a MissingMethodException that is reported as a bug in the model, or, now that the synchronous SendEvent and CreateInterface are back for foreign code, silently runs every send without a scheduling point and misses bugs (1 timeline instead of 2 on a small race). Generated code now stamps its assembly with [assembly: GeneratedCodeVersion(GeneratedCodeVersionAttribute.Current)]. When the checker loads a test assembly that has another stamp, or no stamp but the types every P project contains, it stops before running with "re-run 'p compile'" and the internal-error exit code (2). C# tests that use the checker directly are not stamped and still run. As a backstop, a MissingMemberException or TypeLoadException thrown by the code under test (e.g. foreign code built against another runtime) stops the schedule as an internal error with the same advice, instead of a bug. Native library load failures are still reported as before. Refresh the PChecker golden snapshot, which also picks up codegen changes from earlier commits on this branch (the test only runs on Linux). Co-Authored-By: Claude Code <noreply@anthropic.com>
The cooperative scheduler removed public PCheckerCore members that C# harnesses and foreign code may use. Bring back the ones that can still be honest: - PNonStandardReturnException and NonStandardReturn, as [Obsolete] types that are never thrown, so foreign code that catches them still compiles. The doc says that a raise or goto now only records the transition, so foreign code must return right after it. - ControlledRuntime.SendEvent(StateMachineId, Event), [Obsolete]. As on master it sends on behalf of the executing state machine without the send checks or monitor announcement; it now enqueues without a scheduling point, like the foreign StateMachine.SendEvent. Called from the test method it fails with a clear assertion (on master it threw a NullReferenceException). The PChecker.Tasks namespace, async test methods, TestingEngine.Create(config, Func<Task>), SendEventAndExecuteAsync and CreateStateMachineAndExecuteAsync need the removed multi-threaded task layer and stay removed. A harness built against them cannot load its types; test discovery used to report only "Failed to get test method", and now lists the missing types, asks to recompile and, for PChecker.Tasks, says that test methods must be synchronous. Co-Authored-By: Claude Code <noreply@anthropic.com>
Traces said "Main(1) was created by task '1'": a machine created by the test method has no creator, and the formatters fell back to Task.CurrentId. With one thread for the whole run this is the id of the testing task, which means nothing; on master it was the id of the test's controlled task, which also varied between schedules and runs (2, 4, 6, 12, ...). Print a fixed label instead, "Main(1) was created by the test." in the text and JSON traces, and creatorName/senderName "test" with type "test" in the XML trace (also for random choices and monitor events without a state machine caller), so traces of the same schedule are identical across runs. Co-Authored-By: Claude Code <noreply@anthropic.com>
Schedules are explored without tracing, and a failing one is replayed to build its .txt and .trace.json. Nothing checked that the replay found the same bug, so the traces could miss the ErrorLog that PeasyAI and users look for, while the console still reported the bug: - Under --fail-on-maxsteps the replay strategy never reached the steps bound, so the replay ended silently. - When the program depends on state that the schedule does not control, such as a static counter in foreign code, the replay took another path. The replay now reaches the steps bound where the explored schedule did, and is compared with the explored schedule (bug report and number of steps). If it diverges, the checker prints a warning, puts it at the top of the text trace, and still ends both traces with the bug that exploration found. It never exits the process on a divergence, and it runs the per-schedule dispose method of the test like any schedule. The JSON trace again describes the strategy that found the bug, e.g. random[seed '7'], instead of "replay". With --explore, traces are never emitted, yet every schedule after the first bug was replayed: this doubled the cost and, by rerunning foreign code, changed which later schedules failed. Traces are now built only for a schedule that found a bug, and never by a replay under --explore (only the reproducible schedule of the first bug is kept, so a later schedule no longer overwrites it). The tests compare the replayed traces with those built by tracing every schedule, which is how master built them, for assertion, steps-bound, hot-state-at-termination and liveness-temperature bugs. Co-Authored-By: Claude Code <noreply@anthropic.com>
When a schedule is not traced, RegisterLog skips the text and JSON trace formatters that generated code registers. It matched them with 'is', so it also dropped any user log derived from these public formatters (registered by foreign code or through CustomStateMachineRuntimeLogType), which then silently saw no events during exploration. Match the exact types instead. Document that a custom log observes every explored schedule, but not the replay that traces a failing schedule (so it does not see that schedule twice). Co-Authored-By: Claude Code <noreply@anthropic.com>
Generated code guards print with IsTraceEnabled, so that schedules that are not traced skip their messages. But IRTransformer lifted the format(...) call itself into a temporary before the print, with a clone of every argument, so the guard only skipped a string concatenation (which LogLine already skips). A formatted message now stays inline in the print statement. Everything in its arguments that can have side effects or fail (calls, choose, map and sequence accesses) is still lifted before the print and always runs, so skipping the formatting cannot change the schedule. A variable argument is no longer cloned unless a later argument runs statements that could change it before the message is formatted. Messages with arguments whose ToString can be foreign code (foreign, any or data values) keep the old form. The PChecker and PEx golden snapshots change accordingly (PObserve's does not). The new regression tests check that calls and choices in print arguments still run, and still fail, when the schedule is not traced. Co-Authored-By: Claude Code <noreply@anthropic.com>
A tuple field, map value or sequence element passed to a function, put in a tuple or sent with an event was not copied: IRTransformer stored the access in a temporary and then moved that temporary into the call, assuming every temporary holds a fresh value. The callee, the tuple or the receiver of the event then shared the element with its container, so changing one side changed the other. The same held for choose from a collection, and announce passed even plain variables to monitors without a copy. These are bugs on master too (master only got unnamed tuples with several fields right, because the PTuple constructor cloned its arguments). Call and constructor arguments, tuple fields and event payloads now go through SimplifyRvalue, which clones accesses and choose, as assignment already did, and announce clones its payload like send and raise. The generated code of other expressions is unchanged. The new regression test changes each such value after passing, storing, sending, raising or announcing it; master fails it. Co-Authored-By: Claude Code <noreply@anthropic.com>
The PTuple and PNamedTuple constructors kept the caller's array as the tuple's storage, and PTuple wrote clones back into it. Foreign code that reuses an array for several tuples got tuples that change together, and checked models reported bugs that master does not. All named tuples of a type also share one field names array, which was a public string[] that one write could rename for every tuple of the type. The public constructors copy their arrays again, as on master: a PTuple of several values stores copies of them, one of a single value stores it as is, and a PNamedTuple stores its values as is. Generated code always passes a new array of fresh values (since the previous commit, also for fields read out of other values), so it now calls new FromOwnedValues factories that keep the array without copying it. This also drops the second clone that the PTuple constructor made of every field of a P tuple expression. The arrays are private. fieldValues is an IReadOnlyList<IPValue> view of the array, and fieldNames a ReadOnlyCollection<string> made once per names array and cached outside the tuple, so neither can be written, even through a cast, and .Count, indexing, IndexOf and foreach still compile as with the old List fields. Code that grew tuples with Add (after the removed parameterless constructors) cannot work with fixed-size tuples, so those constructors stay removed. The change is listed in ChangeList.md. Co-Authored-By: Claude Code <noreply@anthropic.com>
Copies of a machine reference now share one PMachineValue, since machine references are immutable. But its Permissions was a public List<string>, so a change made through one variable (e.g. by foreign code) showed in every copy; on master each copy had its own list. Permissions is now a ReadOnlyCollection<string> over a private copy of the list the reference was created with, and the copy constructor shares it. The runtime only reads it, and Contains, Count and indexing still compile. Co-Authored-By: Claude Code <noreply@anthropic.com>
Building default payloads lazily made every event created with the parameterless constructor return the default value of its payload type when its payload was read. On master that constructor left the payload null, and only the events of P event expressions got a default payload. Foreign code and tools that create events without a payload now saw a payload (e.g. in their own logs), and ran the default constructor of a foreign payload type. The parameterless constructor leaves the payload null again. Generated event classes get an internal constructor taking a LazyDefaultPayload tag, which builds the default payload when first read, and P event expressions use it. The halt event (PHalt) keeps its own constructor: the special case for it matched the name "Halt", which only a user event can have (master wrote new PHalt() for such an event, which does not compile), so it now matches "PHalt". Being internal, it is not picked up by announce, which looks for the public payload constructor. Clone goes back to the parameterless constructor. Generated code built for version 2 of the runtime would now create event values without default payloads, so the generated code version is 3. Co-Authored-By: Claude Code <noreply@anthropic.com>
Generated functions are async when they can reach a scheduling point, and that was decided from CanSend, which announce statements set too. But an announce is delivered to monitors synchronously and is not a scheduling point, so every handler that announced, and everything calling it, paid for an async state machine with no await in it, and lost the synchronous OnFailure handling of actions. Track sends to machines in a separate CanSendToMachine flag, propagated to callers like the other capabilities, and decide async from it. CanSend keeps covering announce for the spec and global-function restrictions and for the monitor overload of global functions. Co-Authored-By: Claude Code <noreply@anthropic.com>
The option only skips activity coverage (the .coverage.txt and .sci reports), but its name suggests it also turns off scenario coverage, which it does not. Name it after what it skips, say in the help text that scenario coverage is still collected, and document it with the coverage reports in the getting-started guide. The old name was never released. Co-Authored-By: Claude Code <noreply@anthropic.com>
Memoizing coverage links by their HandledBy value returned a cached link without updating its attributes. When events between the same two states were handled in different states, the link kept the first HandledBy instead of the latest one, so .sci reports differed from earlier versions (e.g. Tutorial/Common/SharedMemory testRWLB_1). Memoize only the link lookup and set its attributes on every call. Also pin the earlier change that removes handled raised events from the coverage inbox. It fixes a misattribution: a raised event left in the inbox was matched with a later event of the same type sent by another machine, so the link from the sender was dropped and the raise link got the HandledBy of the later event. Co-Authored-By: Claude Code <noreply@anthropic.com>
Since values taken out of fields and elements are copied before they are passed on, the value of an add or insert statement and the arguments of a format string were copied too. PSeq, PMap and PSet already clone every value they store, and formatting only reads its arguments, so that copy was a wasted allocation on every such statement. These now simplify their operands as master did. The regression test also checks that a sequence element added from a tuple field and a map value inserted from a sequence element do not alias their source. Co-Authored-By: Claude Code <noreply@anthropic.com>
PCTStrategy is sealed, so declaring the buffer private protected only produced warning CS0628. The buffer is not used outside the class. Co-Authored-By: Claude Code <noreply@anthropic.com>
ForeignTupleCopies and ForeignEventPayloads implement their foreign functions only in C#. The PEx backend calls PExForeignCode for foreign functions, which these tests do not provide, so their generated Java does not compile and TestPEx would report them as failures. Exclude them next to the other C#-only foreign tests. The other regression directories added on this branch (EventNamedHalt, announceOnly, PrintFormatArgs, PrintFormatFailingCall, PrintFormatMissingKey, ValueCopiesOfElements) give the expected results under PEx. Co-Authored-By: Claude Code <noreply@anthropic.com>
On master, StateMachine.SendEvent and CreateInterface called from foreign code were scheduling points, like a P send or new. The cooperative scheduler made them synchronous without one, so other machines could no longer run right before a foreign send, and bugs that need that interleaving were silently missed (e.g. Other sending eB before the first foreign eA: master finds it at schedule 4 with seed 7, the branch found none in 10000 schedules). Foreign code cannot be suspended, so these calls now check for misuse right away and record the send or create. Generated code brackets every foreign call with BeginForeignCall / EndForeignCallAsync, which takes the Send or Create scheduling point of each recorded operation in order and then performs it, before a pending raise or goto unwinds the caller. The checker explores the same schedules as for the equivalent P code (same seed, same trace). Announces made while foreign code runs are deferred too, so monitors observe them in order with the sends. Functions that call foreign code are now async; monitor code is not bracketed. Foreign code can call back P functions that send or create again: while a foreign call runs their sends and creates are deferred the same way, so the task they return has already completed. Receiving there, or using a machine other than the one passed to the foreign code, stops the checker with an internal error, checked before anything is announced or the vector clock moves. Also make ForeignCreate fail when the machine created by foreign code never takes part, and exclude the new C#-only tests from PEx. Co-Authored-By: Claude Code <noreply@anthropic.com>
Every P function that sends or creates is now an async method, and the
checker runs every operation on one thread pool thread. Each level of a
recursion of such functions costs several frames, on the way down and
again when the suspended operation is resumed and the calls complete
back up. With the 1.5 MB stack of a thread pool thread on macOS, a
recursion of about 500 levels that sends at the bottom made .NET move
the remaining continuations to another thread, which the checker
reported as a bug in the model ("invoked a runtime method outside of
the scheduler"), and about 1000 levels overflowed the stack. Master
handles about 2800 levels of the same program.
Run the testing loop on a dedicated background thread with a 256 MB
stack instead. Only the used pages are committed, the thread is created
once per run, and the schedules stay on one thread, so exploration is
as deterministic and as fast as before (same .schedule as master for a
seeded deep-recursion bug; same throughput on 2_TwoPhaseCommit). The
same program now passes at 300000 levels. The timeout still cancels
the wait on the thread as it did on the task.
The two thread-hop messages now also mention deep recursion as a cause.
Co-Authored-By: Claude Code <noreply@anthropic.com>
…ys that find another bug The announceOnly regression programs pass both with and without the change that keeps functions that only announce synchronous: announcements reach monitors synchronously either way, and a failure is reported as a bug either way. The one behavioural difference is that the exception of a synchronous action reaches OnFailure from the action's exception filter, before its stack unwinds. The DynamicError program now fails with a runtime error in an announce-only handler, and AnnounceOnlyFailureTest runs it and checks that OnFailure first sees an ActionExceptionFilterException while the handler's frames are still on the stack. It fails with the previous codegen (IsAsync from CanSend). The Correct program now says it is a semantic check. BugTraceTest only covered a replay that finds no bug. tcCounterInBug fails on every schedule with the foreign counter in its message, so the replay always finds another bug. The test pins the warning and the trace layout: the replay's bug is logged first where the replay hit it, and the trace ends with the explored bug, in both the text and the JSON trace. Co-Authored-By: Claude Code <noreply@anthropic.com>
…list The change list only covered the tuple and machine reference changes, so users upgrading had no notice that they must re-run p compile, that the PChecker.Tasks layer, async test methods and the *AndExecuteAsync and Func<Task> entry points are gone, that ReceiveEventAsync returns a ValueTask, that raise and goto no longer unwind foreign code, that machines created by the test method start after it returns, or that traces now label them "created by the test" and are built by replaying the failing schedule. Add a section for these, verified against the code, and point foreign code users to the foreign functions manual. Also say that new PTuple() still compiles but makes an empty tuple, and update the sample trace in the foreign functions manual to the new label. Co-Authored-By: Claude Code <noreply@anthropic.com>
A create deferred from foreign code allocated the machine id when the foreign code requested it, before the scheduling points of the sends it had requested earlier. A P new, and a foreign create on master, allocate it after the Create scheduling point. Machines created by other operations at those points therefore got other ids, and since operations are ordered by id, the same seed explored another schedule and printed other machine names. The id of a deferred create is now unbound: it gets its value when the machine is created after its scheduling point, or when foreign code first hashes, compares or prints it. The parity test now has another machine create at those scheduling points and compares machine names. Co-Authored-By: Claude Code <noreply@anthropic.com>
PSet.Add and PMap.Add froze the value they were given and then stored a copy of it. Since bf0aa01 no longer copies the operand of an add statement, `st += (t.a)` froze the field t.a itself, and a later `t.a += (0, 2)` threw PFrozenMutationException. A map key inserted from a field or element (`m += (t.a, 1)`, `m[t.a] = 1`) froze its source on master already. Sets and maps now freeze the copy they store, which also protects the stored key from changes through an alias, and leave the caller's value mutable. This keeps the single copy that bf0aa01 aimed for. The map indexer copies a mutable key only when it adds it. Co-Authored-By: Claude Code <noreply@anthropic.com>
Sends and announces of foreign code are performed when the foreign call returns, and they kept a reference to their payload. Foreign code that changed the payload after sending or announcing it therefore changed what monitors observed, unlike on master, where monitors observed the payload at the call. StateMachine.SendEvent and a foreign Announce now copy the payload when they are called. This only allocates on the foreign path: sends of P functions that foreign code calls back already copy their payload and are deferred without another copy. Co-Authored-By: Claude Code <noreply@anthropic.com>
When the replay that traces a failing schedule hits another bug, the trace shows that bug where the replay hit it and ends with the bug that exploration found and reported (pinned by BugTraceTest). The PeasyAI fixer, the trace ranking of peasy-ai-fix-bug, PCheckerErrorParser and the legacy pipeline all took the first ErrorLog line, so they diagnosed the replay's bug instead of the reported one. They now take the last ErrorLog line, through a shared reported_error_message helper where they extract the message. Co-Authored-By: Claude Code <noreply@anthropic.com>
Since foreign sends and creates are deferred, the only regression test of the "scheduled to resume from a scheduling point" internal error became a correct program, and the message still blamed foreign code that does not await SendEventAsync or CreateInterfaceAsync, which no longer triggers it. A local foreign function that drops the awaitable of the protected CreateStateMachineAsync still reaches it: that scheduling point is not deferred. ForeignUnawaitedCreate now pins this, and the message and the docs name this cause instead. Co-Authored-By: Claude Code <noreply@anthropic.com>
Foreign code needs the value of a choice right away, so a RandomBoolean or RandomInteger it makes is taken before the scheduling points of the sends and creates it requested earlier in the same call, which are deferred until it returns. The equivalent P code, and master, take them in the opposite order. The reachable schedules are the same, but a seed can explore another schedule, and master .schedule files of such programs may not replay. This cannot be fixed without suspending foreign code. The change list, the foreign function docs and the parity test now say so, and a parity test checks that a foreign choice reaches exactly the traces of the equivalent P choice. Co-Authored-By: Claude Code <noreply@anthropic.com>
The full IR lowering puts every subexpression in a temporary and copies every value it stores or passes. That is required by the Java backends, but for C# it creates many temporaries and clones of values that are already fresh, on every step of the checker. Add LoweringMode.CSharp, used for PChecker output only. It keeps expressions inline and copies only values that are not fresh. It lifts a subexpression into a statement only when the generated C# needs that: - a call that may leave a pending transition, or that is foreign, so the generator can write the pending-transition check and the foreign-call prologue and epilogue after it; - a call that may change fields, when C# would otherwise read a field before it that the full lowering reads after it (e.g. x + f()); - a call assigned to a field-rooted lvalue when it may leave a pending transition, so the field is not set to default; - anything that the full lowering evaluates before a lifted part, so the order of evaluation and of side effects is unchanged; - print arguments that have side effects or may fail, before the trace guard, and the message of an assertion only when it fails. Foreach iterates natively over a snapshot of a non-fresh collection (a shallow one for sets and immutable elements), not by index, which was O(n^2) for sets. Raise and send build the event with its payload, which also fixes evaluating the event of raise twice. The generator now types inline accesses, == and other operators, and numeric coercions, and null owned values, since temporaries no longer do. Each backend of a job gets its own lowering (ScopeLowering swaps the lowered bodies), so PEx and PObserve output is byte-identical; their golden snapshots are unchanged. The PChecker snapshot is updated. Co-Authored-By: Claude Code <noreply@anthropic.com>
The map indexer stored a frozen copy of a new key only when the key was an IPMutableValue. Tuples and named tuples are not, but change in place, so `m[t] = 1; t.0 = 5;` changed the key stored in the map and left it in the wrong hash bucket: `(1, 2) in m` was false afterwards. This happened on master too, where the indexer froze the key instead of copying it, which does nothing for a tuple. The indexer now stores a frozen copy of every new key, as Add does. PSet.UnionWith also stores frozen copies and marks the set dirty, like Add; generated code does not call it, foreign code may. MapKeysAreCopies pins tuple and named tuple keys stored through the indexer and +=, and tuple elements of sets. It passes on PChecker and PEx. Co-Authored-By: Claude Code <noreply@anthropic.com>
3f23a66 copied the payloads of foreign sends and announces when they are made, but StateMachine.CreateInterface and the protected CreateStateMachine still kept a reference to theirs. Since the create is performed only when the foreign call returns, foreign code that changed the payload after the call changed what the new machine received. Both now copy the payload when they are called. ForeignPayloadSnapshot also creates a machine from foreign code and changes its payload after the call. Co-Authored-By: Claude Code <noreply@anthropic.com>
The full IR lowering, which PEx and PObserve use, emitted the statements that compute the event of a raise twice (raiseEventDeps was concatenated with itself), so `raise PickEvent(), p;` called PickEvent twice. The C# lowering of 2d70f40 fixed this for PChecker only, so the backends disagreed. The golden input has no raise, so no snapshot changes. LoweringEvaluationOrder pins the evaluation-order rules of the C# lowering against the full one: a call that changes a field is evaluated before the field is read on either side of +, print arguments are evaluated once, foreach over a set iterates over its elements at the start of the loop, and raise evaluates its event once, before its payload. It passes on PChecker and PEx, and fails on master. Co-Authored-By: Claude Code <noreply@anthropic.com>
Contributor
There was a problem hiding this comment.
🟡 Changes recommended
Unresolved critical issues cause quadratic vector-clock memory growth, failed map lookups after mutable-key changes, and retention of completed schedules’ machines and runtimes.
3 open issues
What changed in this PR
This PR moves PChecker toward cooperative, single-threaded execution, with compiler and runtime changes to preserve scheduling behavior and P value semantics.
Changes:
- Adds cooperative scheduling support, deferred foreign operations, and clearer runtime compatibility errors.
- Updates value copying, backend-specific lowering, activity coverage, and failing-schedule traces.
- Expands regression tests and documentation, and updates PeasyAI to identify the reported bug when replay diverges.
| File | Description |
|---|---|
| Tst/UnitTests/TypeChecker/Phase1DormancyTest.cs | Copies foreign C# sources into test output. |
| Tst/UnitTests/TupleValuesTest.cs | Tests tuple ownership, cloning, and immutable permissions. |
| Tst/UnitTests/TestEntryCreatesTest.cs | Tests synchronous entry methods creating multiple machines. |
| Tst/UnitTests/SchedulingPointCodegenTest.cs | Checks async generation and synchronous announce-only functions. |
| Tst/UnitTests/Runners/PCheckerRunner.cs | Reports internal errors with exit code 2. |
| Tst/UnitTests/GoldenTests/Expected/PEx.txt | Updates expected Java lowering output. |
| Tst/UnitTests/GoldenTests/Expected/PChecker.txt | Updates expected C# runtime and lowering output. |
| Tst/UnitTests/ForeignCodeMisuseTest.cs | Tests detection of foreign runtime misuse. |
| Tst/UnitTests/ForeignCallCodegenTest.cs | Checks foreign-call scheduling wrappers. |
| Tst/UnitTests/EventPayloadTest.cs | Tests lazy default event payloads. |
| Tst/UnitTests/CheckerOptionsTest.cs | Tests activity-coverage option parsing. |
| Tst/UnitTests/AnnounceOnlyFailureTest.cs | Checks synchronous failure reporting before stack unwinding. |
| Tst/UnitTests/ActivityCoverageGraphTest.cs | Tests raised-event links and cached link attributes. |
| Tst/RegressionTests/Integration/Traces/BugTraces/ForeignFunctions.cs | Supplies a counter that makes replay diverge. |
| Tst/RegressionTests/Integration/Traces/BugTraces/BugTraces.p | Exercises assertion, liveness, and replay-divergence traces. |
| Tst/RegressionTests/Integration/InternalError/ForeignUnawaitedCreate/ForeignUnawaitedCreate.p | Exercises an unawaited create scheduling point. |
| Tst/RegressionTests/Integration/InternalError/ForeignUnawaitedCreate/ForeignFunctions.cs | Implements the deliberately unawaited create. |
| Tst/RegressionTests/Integration/InternalError/ForeignSendOnOtherMachine/ForeignSendOnOtherMachine.p | Checks rejection of sends through another machine. |
| Tst/RegressionTests/Integration/InternalError/ForeignSendOnOtherMachine/ForeignFunctions.cs | Implements the invalid saved-machine send. |
| Tst/RegressionTests/Integration/InternalError/ForeignCallbackReceives/ForeignFunctions.cs | Calls a receiving P function from foreign code. |
| Tst/RegressionTests/Integration/InternalError/ForeignCallbackReceives/ForeignCallbackReceives.p | Exercises unsupported receive callbacks. |
| Tst/RegressionTests/Integration/InternalError/BindingFailure/ForeignFunctions.cs | Simulates a stale runtime binding failure. |
| Tst/RegressionTests/Integration/InternalError/BindingFailure/BindingFailure.p | Exercises binding-failure classification. |
| Tst/RegressionTests/Integration/DynamicError/ForeignSendInterleaving/ForeignSendInterleaving.p | Tests interleavings enabled by foreign sends. |
| Tst/RegressionTests/Integration/DynamicError/ForeignSendInterleaving/ForeignFunctions.cs | Implements the foreign send. |
| Tst/RegressionTests/Integration/Coverage/RaisedEventCoverage/RaisedEventCoverage.p | Exercises coverage attribution after a raised event. |
| Tst/RegressionTests/Integration/Correct/ForeignUnawaitedSend/ForeignUnawaitedSend.p | Checks delivery of deferred unawaited sends. |
| Tst/RegressionTests/Integration/Correct/ForeignUnawaitedSend/ForeignFunctions.cs | Drops a deferred send's awaitable. |
| Tst/RegressionTests/Integration/Correct/ForeignTupleCopies/ForeignTupleCopies.p | Checks tuple isolation across foreign calls. |
| Tst/RegressionTests/Integration/Correct/ForeignTupleCopies/ForeignFunctions.cs | Exercises reused tuple arrays and foreign mutation. |
| Tst/RegressionTests/Integration/Correct/ForeignSend/ForeignSend.p | Checks ordering between foreign and P sends. |
| Tst/RegressionTests/Integration/Correct/ForeignSend/ForeignFunctions.cs | Supplies the foreign send implementation. |
| Tst/RegressionTests/Integration/Correct/ForeignRaiseGotoMonitor/ForeignRaiseGotoMonitor.p | Checks monitor unwinding after foreign raises. |
| Tst/RegressionTests/Integration/Correct/ForeignRaiseGotoMonitor/ForeignFunctions.cs | Implements foreign monitor raises. |
| Tst/RegressionTests/Integration/Correct/ForeignRaiseGoto/ForeignRaiseGoto.p | Checks foreign and callback transition propagation. |
| Tst/RegressionTests/Integration/Correct/ForeignRaiseGoto/ForeignFunctions.cs | Implements foreign raises, gotos, and callbacks. |
| Tst/RegressionTests/Integration/Correct/ForeignPayloadSnapshot/ForeignPayloadSnapshot.p | Checks deferred operation payload snapshots. |
| Tst/RegressionTests/Integration/Correct/ForeignPayloadSnapshot/ForeignFunctions.cs | Mutates payloads after requesting operations. |
| Tst/RegressionTests/Integration/Correct/ForeignEventPayloads/ForeignFunctions.cs | Checks foreign event constructor compatibility. |
| Tst/RegressionTests/Integration/Correct/ForeignEventPayloads/ForeignEventPayloads.p | Checks event-value payload delivery. |
| Tst/RegressionTests/Integration/Correct/ForeignCreate/ForeignFunctions.cs | Creates a machine through foreign code. |
| Tst/RegressionTests/Integration/Correct/ForeignCreate/ForeignCreate.p | Checks participation of foreign-created machines. |
| Tst/RegressionTests/Integration/Correct/ForeignCallsBack/ForeignFunctions.cs | Exercises callbacks that send and create. |
| Tst/RegressionTests/Integration/Correct/ForeignCallsBack/ForeignCallsBack.p | Checks callback operation ordering. |
| Tst/RegressionTests/Integration/Correct/ForeignAnnounceOrder/ForeignFunctions.cs | Mixes foreign sends and announcements. |
| Tst/RegressionTests/Integration/Correct/ForeignAnnounceOrder/ForeignAnnounceOrder.p | Checks monitor observation order. |
| Tst/RegressionTests/Feature4DataTypes/Correct/ValueCopiesOfElements/ValueCopiesOfElements.p | Tests copying of fields, elements, and payloads. |
| Tst/RegressionTests/Feature4DataTypes/Correct/MapKeysAreCopies/MapKeysAreCopies.p | Tests isolation of stored tuple keys. |
| Tst/RegressionTests/Feature2Stmts/DynamicError/PrintFormatMissingKey/PrintFormatMissingKey.p | Checks print-argument failures without tracing. |
| Tst/RegressionTests/Feature2Stmts/DynamicError/PrintFormatFailingCall/PrintFormatFailingCall.p | Checks execution of failing print-argument calls. |
| Tst/RegressionTests/Feature2Stmts/DynamicError/announceOnly/announceOnly.p | Exercises synchronous announce-only failure. |
| Tst/RegressionTests/Feature2Stmts/Correct/PrintFormatArgs/PrintFormatArgs.p | Checks print-argument side effects and evaluation. |
| Tst/RegressionTests/Feature2Stmts/Correct/LoweringEvaluationOrder/LoweringEvaluationOrder.p | Tests evaluation order, set iteration, and raise evaluation. |
| Tst/RegressionTests/Feature2Stmts/Correct/DeepRecursiveSend/DeepRecursiveSend.p | Exercises deep recursive scheduling calls. |
| Tst/RegressionTests/Feature2Stmts/Correct/announceOnly/announceOnly.p | Checks announce ordering across synchronous and async calls. |
| Tst/RegressionTests/Feature1SMLevelDecls/Correct/EventNamedHalt/EventNamedHalt.p | Distinguishes user-defined Halt from built-in halt. |
| Tst/.gitignore | Allows regression foreign-source files to be tracked. |
| Src/PEx/src/test/java/pex/TestPEx.java | Excludes C#-only foreign integration programs. |
| Src/PeasyAI/tests/test_error_parsers.py | Tests selection of the final reported error. |
| Src/PeasyAI/src/ui/mcp/tools/fixing.py | Uses the reported error for analysis and prioritization. |
| Src/PeasyAI/src/core/modes/pipelines.py | Categorizes the last trace error. |
| Src/PeasyAI/src/core/compilation/checker_error_parser.py | Extracts the reported bug after replay divergence. |
| Src/PCompiler/PCommandLine/Options/PCheckerOptions.cs | Adds --no-activity-coverage. |
| Src/PCompiler/CompilerCore/TypeChecker/StatementVisitor.cs | Marks functions that send to machines. |
| Src/PCompiler/CompilerCore/TypeChecker/AST/Declarations/Function.cs | Separates machine sends from announcements. |
| Src/PCompiler/CompilerCore/TypeChecker/Analyzer.cs | Propagates machine-send capability through calls. |
| Src/PCompiler/CompilerCore/Compiler.cs | Selects lowering for each backend. |
| Src/PCompiler/CompilerCore/Backend/PChecker/CompilationContext.cs | Tracks foreign callers, monitor context, and field names. |
| Src/PCompiler/CompilerCore/Backend/ASTExt/CloneExpr.cs | Supports cloning inline expressions. |
| Src/PChecker/CheckerCore/Testing/TestingProcess.cs | Adds compatibility hints to discovery failures. |
| Src/PChecker/CheckerCore/Tasks/YieldAwaitable.cs | Removes the controlled-task yield wrapper. |
| Src/PChecker/CheckerCore/Tasks/TaskExtensions.cs | Removes controlled-task conversion extensions. |
| Src/PChecker/CheckerCore/Tasks/TaskAwaiter.cs | Removes controlled-task awaiters. |
| Src/PChecker/CheckerCore/Tasks/ConfiguredTaskAwaitable.cs | Removes configured controlled-task awaitables. |
| Src/PChecker/CheckerCore/SystematicTesting/Traces/ScheduleTrace.cs | Removes linked-step bookkeeping. |
| Src/PChecker/CheckerCore/SystematicTesting/Traces/ScheduleStep.cs | Stores schedule steps as readonly structs. |
| Src/PChecker/CheckerCore/SystematicTesting/TestMethodInfo.cs | Requires synchronous entries and explains incompatibility. |
| Src/PChecker/CheckerCore/SystematicTesting/Strategies/Special/ReplayStrategy.cs | Supports nonfatal replay for trace generation. |
| Src/PChecker/CheckerCore/SystematicTesting/Strategies/Probabilistic/RandomStrategy.cs | Reuses enabled-operation storage. |
| Src/PChecker/CheckerCore/SystematicTesting/Strategies/Probabilistic/ProbabilisticRandomStrategy.cs | Reuses enabled-operation storage. |
| Src/PChecker/CheckerCore/SystematicTesting/Strategies/Probabilistic/PCTStrategy.cs | Reduces filtering and lookup allocations. |
| Src/PChecker/CheckerCore/SystematicTesting/Strategies/Feedback/RandomScheduler.cs | Reuses enabled-operation storage. |
| Src/PChecker/CheckerCore/SystematicTesting/Strategies/Feedback/POSScheduler.cs | Reuses buffers and operation lookup helpers. |
| Src/PChecker/CheckerCore/SystematicTesting/Strategies/Feedback/PCTScheduler.cs | Reuses buffers and operation lookup helpers. |
| Src/PChecker/CheckerCore/SystematicTesting/Strategies/Feedback/Coverage/TimelineRepresentations.cs | Avoids formatting repeated coverage tokens. |
| Src/PChecker/CheckerCore/SystematicTesting/Strategies/EnabledOperations.cs | Adds reusable operation filtering and lookup helpers. |
| Src/PChecker/CheckerCore/SystematicTesting/SchedulingPoint.cs | Introduces a cooperative continuation awaitable. |
| Src/PChecker/CheckerCore/SystematicTesting/Resource.cs | Removes task-layer resource synchronization. |
| Src/PChecker/CheckerCore/SystematicTesting/Operations/TaskOperation.cs | Simplifies operations for synchronous test entry. |
| Src/PChecker/CheckerCore/SystematicTesting/Operations/AsyncOperation.cs | Stores parked cooperative continuations. |
| Src/PChecker/CheckerCore/SystematicTesting/GeneratedCodeVersionAttribute.cs | Detects incompatible generated assemblies. |
| Src/PChecker/CheckerCore/Runtime/VectorTime.cs | Replaces dictionary clocks with dense arrays. |
| Src/PChecker/CheckerCore/Runtime/Values/PValues.cs | Shares immutable values during cloning. |
| Src/PChecker/CheckerCore/Runtime/Values/PSet.cs | Stores frozen copies of inserted elements. |
| Src/PChecker/CheckerCore/Runtime/Values/PSeq.cs | Uses the shared cloning helper. |
| Src/PChecker/CheckerCore/Runtime/Values/PMap.cs | Copies new keys and updates cloning paths. |
| Src/PChecker/CheckerCore/Runtime/Values/PMachineValue.cs | Makes permissions read-only and shares references. |
| Src/PChecker/CheckerCore/Runtime/Values/MutabilityHelper.cs | Adds frozen-copy creation. |
| Src/PChecker/CheckerCore/Runtime/StateMachines/StateMachineId.cs | Defers ID allocation for foreign-created machines. |
| Src/PChecker/CheckerCore/Runtime/StateMachines/Managers/StateMachineManager.cs | Makes receive notifications awaitable. |
| Src/PChecker/CheckerCore/Runtime/StateMachines/Managers/IStateMachineManager.cs | Updates receive notification contracts. |
| Src/PChecker/CheckerCore/Runtime/StateMachines/EventQueues/IEventQueue.cs | Uses awaitable dequeue and receive operations. |
| Src/PChecker/CheckerCore/Runtime/StateMachines/EventQueues/EventQueue.cs | Integrates cooperative receive suspension. |
| Src/PChecker/CheckerCore/Runtime/Specifications/Monitor.cs | Records transitions without throwing and gates tracing. |
| Src/PChecker/CheckerCore/Runtime/Logging/PCheckerLogXmlFormatter.cs | Labels test-originated activity consistently. |
| Src/PChecker/CheckerCore/Runtime/Logging/PCheckerLogTextFormatter.cs | Updates origin labels and exception logging. |
| Src/PChecker/CheckerCore/Runtime/Logging/PCheckerLogJsonFormatter.cs | Updates origin labels and exception logging. |
| Src/PChecker/CheckerCore/Runtime/Logging/LogWriter.cs | Skips default trace formatters during exploration. |
| Src/PChecker/CheckerCore/Runtime/Logging/JsonWriter.cs | Removes hashing from send/receive correlation keys. |
| Src/PChecker/CheckerCore/Runtime/Exceptions/PNonStandardReturnException.cs | Deprecates exception-based transition unwinding. |
| Src/PChecker/CheckerCore/Runtime/Events/Event.cs | Adds lazy default payload construction. |
| Src/PChecker/CheckerCore/Random/Generator.cs | Removes the legacy random-generator wrapper. |
| Src/PChecker/CheckerCore/Coverage/ControlledRuntimeLogGraphBuilder.cs | Caches graph lookups and removes handled raised events. |
| Src/PChecker/CheckerCore/Coverage/ControlledRuntimeLogEventCoverage.cs | Caches coverage state identifiers. |
| Src/PChecker/CheckerCore/CheckerConfiguration.cs | Adds internal tracing control and documents custom logs. |
| Docs/docs/manual/foreigntypesfunctions.md | Documents deferred foreign operations and callback rules. |
| Docs/docs/getstarted/usingP.md | Explains activity reports and the opt-out option. |
| ChangeList.md | Documents scheduler migration and runtime API changes. |
Review effort: Balanced
Comment on lines
+115
to
+119
| if (!map.ContainsKey(key)) | ||
| { | ||
| // A new key is stored: store a frozen copy, as Add does. Tuples are not | ||
| // IPMutableValue but change in place, so every new key is copied. | ||
| key = MutabilityHelper.FrozenCopy(key); |
Comment on lines
+18
to
+19
| ownIndex = checked((int)stateMachineId.Value); | ||
| clock = new int[ownIndex + 1]; |
| public bool GetNextOperation(AsyncOperation current, IEnumerable<AsyncOperation> ops, out AsyncOperation next) | ||
| { | ||
| var enabledOperations = ops.Where(op => op.Status is AsyncOperationStatus.Enabled).ToList(); | ||
| var enabledOperations = EnabledOperations.Collect(ops, EnabledBuffer); |
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Cooperative scheduler for PChecker, plus fixes found while reviewing the branch. The branch has 50 commits on top of
master; the last three fix bugs found in review.d198e58c1), with schedules on a large-stack thread (1d87459bd). Foreign-call scheduling points, unawaited-point detection, and foreign create/send/announce ordering are covered by new integration programs andForeignSchedulingParityTest.choose, and announce are copied; tuples no longer share arrays; set elements and map keys are stored as frozen copies.LoweringMode.CSharplowers only what the C# backend needs (2d70f4041). PEx and PObserve keep the full lowering.--no-activity-coverage, and trace output only when replaying a failing schedule.0c3dc7aed: map indexer copies every new key, so tuple keys can't change under the map.c560a9f50: foreignCreateInterface/CreateStateMachinecopy their payload.ebbe35889: the full lowering (PEx/PObserve) evaluated araise's event twice.Testing
ScenarioCoverageBasic(Monitor NeverCoveredliveness bug), also fails onmasterat260da928f, so it's pre-existing and not from this branch.Feature4DataTypes/Correct/MapKeysAreCopies,Feature2Stmts/Correct/LoweringEvaluationOrder, and an extendedIntegration/Correct/ForeignPayloadSnapshot. Each new test fails without its fix and passes with it.Open items
ChangeList.mddoesn't yet list the large-stack thread, the new value copies, the new internal errors / exit code 2, or the announce-only sync rule.SchedulingPointCodegenTest, and a two-seed dependency inForeignSchedulingParityTest.d198e58c1,27d51c4be,f2dd19cc2.🤖 Generated with Claude Code