Repository navigation
Agent layer, part 1: the command machinery - #99
Conversation
Adds MicroscopeControl.Agent, a public submodule that is not exported, so `using MicroscopeControl` gains no name from it. It holds what lets an instrument declare its commands and run them one serialized command at a time, with an abort and a STOP latch that act from any thread: - CommandTable, CommandArg, CommandPlan, Command, register_command! and describe_commands: an instrument's own table of commands, each with a pure plan (what it would move, and whether light leaves the instrument) and an execute. register_abort_command! and register_grant_command! add the layer's own :abort and :agent_may_act. - run_command dry-runs a command to its plan, refuses a confirm-class command without a Confirmation, and binds every confirmation, of free commands too, to the requested command, its arguments, moves and emits flag as they are now, so a confirmation of a plan that has since changed is refused. Arguments convert by a closed rule (convert_arg; a Bool is never a number). - AbortFlags holds two atomics, abort and the STOP latch, so request_abort! and check_abort work from any thread with no lock. check_stopped refuses an unserialized command whose plan emits (it would run beside another command), and, while STOP is latched, everything but :abort, the grant turning off and reads. - EventLog, CommandRunner and start_job! belong to the body thread, thread 1 in a sticky task: a non-dry run_command, log_event! and start_job! throw OffThread anywhere else, including in a spawned task that happens to run on thread 1, since it can move to another thread at its next yield. - The system contract: a system holds a CommandCore, or has its own run_command and implements abort_flags; either way it implements make_safe!, whose fallback throws. The body that holds the operator's grant and STOP is not part of this change; until it exists, :agent_may_act throws. Adds Observables as a direct dependency (already loaded through Makie). The version stays 0.2.7-DEV: additions only. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
test/agent_fixture.jl holds two systems, one per mode of the system contract: SimScope (a SimCamera, a SimStage2d and a SimLight behind a CommandCore) and OwnScope (a SimLight, its own run_command and its own AbortFlags). test/agent_commands.jl checks, in both modes where the mode matters: - the unserialized rule and the STOP latch: an emitting unserialized command is refused; while latched, a read, :abort and the grant turning off get through and everything else is refused, and the stale-abort clear is never reached; - a command that turns light on stops at its next checkpoint once STOP latches from another thread; - confirmations bound to the plan as it is now, for confirm-class and free commands, its emits flag, and the requested command name; - ArgError kinds, and convert_arg's rule that a Bool is never a number; - one serialized command at a time, the abort, and the stale-abort clear; - OffThread from another thread and from a non-sticky task on thread 1; - request_abort! from another thread beside logging on thread 1; - the grant toggle running beside a job, the path a revoke takes; - the event log's tee and escaping, the job runner, and showerror of every exception. The Interface Contract testset gains an "Agent layer" check: the submodule is public and not exported, its exports resolve beside MicroscopeControl's with no clash, it has no method ambiguities, and the contract's required functions throw. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
docs/src/api/agent.md introduces the command machinery with an example on simulated devices, names every exported and public name of the submodule, and takes its other docstrings in an Internals section, so the build's docstring coverage check passes. CHANGELOG.md: one Added entry under Unreleased. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
Local checks on b6ee818 (Julia 1.13):
|
The command machinery's checks are tightened so that none depends on an instrument getting something else right: - make_safe! runs whenever a serialized command ends abnormally: by any exception (an abort, or a failure such as a camera timeout after a light came on) or by a result is_aborted reports, before that end is logged. An unserialized command, which can never emit, never calls it. - An abort is never lost: the layer's :abort sets the flag before it logs, and a failure to write the event log is reported with @error and never stops a command, its abort or its make_safe!. A stale abort is cleared before a command is published as running, so an abort aimed at the running command is kept for its first checkpoint. - A confirmation binds what executes: the layer sets the plan's command and arguments from the request (the converted arguments execute receives) and refuses a plan function that names another command, or a table entry held under another name. The plan shown is a snapshot (Confirmation and the plan constructor copy it; execute gets a copy of the caller's values), and arguments compare by type and value at every level, so true is not 1 and 0.0 is not -0.0. - The thread rule holds in both modes: run_command checks the body thread first, dry runs included, since plan and confirm functions read the instrument's state; check_stopped starts with the same check, so a system with its own run_command gets it too. - check_stopped runs before a confirmation is asked for, so nothing invites a confirmation of a command that cannot run; under STOP the grant turning on is refused whatever its plan's moves. - convert_arg's Bool rule holds inside a tuple or array that is already of the declared type. - An argument may not be named dry_run or confirmed, run_command's own keywords. - start_job! rolls a start back when a busy listener throws, keeps the slot free when one throws as a job ends, and returns the task it created. Tests: each of these checks has a test that fails when that check alone is removed (shown by a mutation sweep of 27 mutations in a scratch copy). The cross-thread STOP test holds the command at a known point with events instead of a sleep and checks which thread latched STOP; the fixture's make_safe! closes a shutter held in an atomic, the channel independent of the light the command switches. The test file runs in its own module. Checked on simulated devices at --threads=1,0, 2,1 and 4,1. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
Round 1 fixes in 140b5a2 (both reviews; every blocking and should-fix finding). Local checks on 140b5a2 (Julia |
A system with its own run_command had to copy safety rules the layer
keeps internal, and the copies drifted. That mode is gone: every system
holds a CommandCore, run_command is the layer's one method, and an
instrument changes what happens around its commands through hooks with
defaults, dispatched on its system type:
- after_execute(sys, c, args, result) runs after execute returns, while
the command holds the slot; it may throw Aborted for an abort that
arrived after the last checkpoint (stop a focusing phase first).
- is_aborted(sys, x) classifies a result or an exception.
- make_safe!(sys), required, as before.
abort_flags, check_stopped and AbortFlags are internal now. The docs page
shows the hooks on an instrument with a focusing phase.
Arguments are values of a closed set of types: Bool, Int, Float64,
String, Symbol, a concrete Tuple or Vector of these, or Union{Nothing,T}
of one. Registration refuses anything else and says what to use;
convert_arg converts by a closed rule in which a Bool is never a number
at any level and an Int becomes a Float64 only exactly. Plans hold each
argument in a canonical immutable form, and each callback gets its own
value of the declared type.
Also:
- A confirmation binds an immutable form of the plan (command, arguments
by type and value, moves, emits), made by every constructor and
independent of c.plan, its display copy.
- STOP is checked again at admission, after the confirmation is bound,
with nothing that can yield between that check and the claim.
- An unserialized command, :abort included, runs before anything on its
path is logged, so an abort reaches its flag first.
- A serialized command that ends abnormally (any exception from execute
or after_execute, an aborted result, a classifier that throws) runs
make_safe! before anything is classified or logged; a late abort is
logged as such only after a normal end.
- The event log's write guard never swallows an interrupt; a failed write
is still a record failure that never stops a command.
Tests: the second fixture is an instrument with a focusing phase on the
one path; the fixtures' make_safe! sets an inhibit no light-on step can
clear, tested with STOP latched before and after a checkpoint. A
mutation sweep of 38 mutations in a scratch copy fails at least one test
for every check. Checked on simulated devices at --threads=1,0, 2,1 and
4,1.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
Round 2 fixes in 607b6a9. Most round 2 findings came from one class: a system with its own Local checks on 607b6a9 (Julia 1.13): the full suite passes, with the same 3 known broken tests as main; the agent |
…very end The layer now states its trust boundary: what a mind sends is untrusted, and the instrument's own code (plans, executes, hooks, command_core) is trusted but may fail. Against that: - Admission is publish, then check. A serialized command clears a stale abort, claims the slot and only then reads the STOP latch, so a STOP on another thread either refuses it or finds it running and stops it at its next checkpoint. The abort and STOP flags and the running slot are sequentially consistent atomics: a Threads.Atomic's acquire and release orders let a store and a later load of the other flag pass each other. - run_command asks the system for its core once and uses that core throughout; no instrument code runs between the busy check and the claim. - The layer owns :abort and :agent_may_act. register_command! refuses both names, the abort command sets the abort flag itself before it calls the instrument's on_abort, and STOP's exemptions recognize the layer's two commands by what they are, not by their names. - The layer counts its own Aborted whatever is_aborted says, classifies a result before after_execute runs (so the hook cannot undo an abort), and runs make_safe! at any end where the abort or STOP flag is still set, so a command that honors an abort by returning partial work leaves the instrument safe. - A make_safe! that fails, or is interrupted, latches STOP. - If a serialized command throws after its execute began, make_safe! has run, interrupts included (during completion logging, classification, or make_safe! itself), and a terminal event is recorded where it can be. - A Confirmation reads its plan once and derives both what it shows and what it binds from that read. Commands are immutable, with a Tuple of arguments; the binding includes each argument's declared type, so the old confirmations of a re-declared command bind nothing; two arguments of one name are refused. - Vector inputs are read by iteration into dense one-based storage, so arrays with other indices convert and bind as their values; non-finite Float64 arguments are refused. - The test fixture's reset turns the source off before it clears the inhibit. - The docs page and the module docstring state the trust boundary and the hook obligations: classifiers have no side effects, hooks leave the core's flags alone, an instrument defines no run_command method and returns the same core at every call, and a plan that depends on state binds an absolute target or re-checks it at the hardware action. The worked example says which outputs its inhibit covers. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
Round 3 fixes in 4ec016a. The layer now states a trust boundary: what a mind sends is untrusted, and the Local checks on 4ec016a (Julia 1.13): the full suite passes (5683 passed, the same 3 known broken tests as main); the |
…slot A real Ctrl-C (an OS SIGINT) could land between a command's failure and its cleanup, or inside the handling of a failed cleanup before STOP latched, and an abort sent just as a command ended could later be cleared as stale. Now: - Interrupts are deferred (Base.disable_sigint) from the moment a serialized command claims the slot until it frees it, except inside its execute and the hooks that classify or follow it. An interrupt in the layer's own steps (the cleanup, the STOP latch after a failed cleanup, the terminal event, the release) is delivered once they are done; one that arrives after the end of a command that needed no cleanup makes the layer run make_safe! (logged :interrupted) before it is let through. make_safe! itself runs deferred, so an instrument's make_safe! must return promptly. - An abort is part of the slot: request_abort! and the layer's :abort mark the command in the slot in one atomic step, and the command's end takes that mark in another, after which no abort reaches it. An abort either reaches the command before its end, which then makes the instrument safe, or finds it ended (request_abort! returns nothing; :abort logs that it arrived after the end). An abort sent while nothing runs reaches nothing, so no abort is ever left over for a later command. Admission claims the slot in one atomic step that is also the busy check, then reads the STOP latch. The slot is freed only after the end's cleanup. - When execute returns an aborted result, run_command returns that result, whatever after_execute returns. - The records are truthful: one terminal event per call where the log can be written; an abort the command did not report is noted with whether the instrument was made safe; an exception whose showerror throws or is interrupted is recorded by its type's name. - The docs say command_core must be a non-blocking, thread-safe read (a const field in a mutable system), that the abort is armed before on_abort runs, that an unserialized command admitted just before STOP still runs, and the introductory example shows an independent inhibit that only a person's reset clears. Tests send a real SIGINT to the test process at each point of a command's end: in execute, as it fails before its cleanup, inside a make_safe! that then fails, and in the last steps of a command that needed no cleanup. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
Round 4 fixes in e0f2ed0. Interrupts are now deferred ( Local checks on e0f2ed0 (Julia 1.13): the full suite passes (5721 passed, the same 3 known broken tests as main); the |
A reporting failure at a command's end could leave its slot held forever, a forced interrupt (Julia's repeated Ctrl-C, which passes Base.disable_sigint) could skip the cleanup or the STOP latch, and the layer's :abort could run its instrument action after its command had ended, reaching the next one. Now: - The slot is released in a finally once the end's cleanup step is settled (no cleanup was needed, make_safe! returned, or it failed and STOP is latched), whatever the event log's reporting does. A logger that fails while reporting a failed tee write is ignored. If a forced interrupt cuts the end short before its cleanup is settled, the release latches STOP first; at every step before that the slot is still held. A forced interrupt can leave the instrument unsafe, but never leaves the layer accepting commands. An abnormal end calls a make_safe! that was cut short again. - The layer's :abort marks the command and counts its on_abort in one atomic step on the slot, records the arrival, runs on_abort only for a command it reached, and uncounts it in a finally. The slot is freed by whichever finishes last, the command's end or its on_abort, so an on_abort cannot act on a later command; a blocking on_abort keeps the layer refusing commands. run_command(sys, :abort) returns what request_abort! returns: the name of the command reached, or nothing. - An abort that marks a command which STOP then refuses at admission is recorded. - The docs say what the after-end interrupt recovery covers (an interrupt delivered to the command's own task), that a host process must make Ctrl-C catchable, that after_execute must not change how execute's result classifies, and that each device call in make_safe! needs its own timeout. The real-SIGINT tests now run in a child Julia process with the parent's flags, project and threads, killed after a timeout, on Unix only, and add one as the :abort records its arrival. A forced interrupt at each of the layer's own steps is stood in for by an internal test point, a no-op inlined away in normal use, that the tests redefine; a real forced interrupt is not sent, since Julia throws it from its signal handler at whatever instruction runs, which can deadlock the process. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
Round 5 fixes in 579489f. The slot is now released in a Local checks on 579489f (Julia 1.13): the full suite passes (5762 passed, the same 3 known broken tests as main); the |
Each recovery step added for an interrupt opened a new window for a forced interrupt (Julia's repeated Ctrl-C, which passes Base.disable_sigint): a command whose end needed no cleanup could be given one by a late report and then released without it, the recovery after a command's end began with the slot already free, and a cleanup retried after a failed make_safe! could clear its record. The layer now keeps one rule for a forced interrupt: at every instruction boundary of its own code the slot is held, or STOP is latched, or the cleanup the command needed has returned. It can leave the instrument unsafe, or a slot held after its call has unwound; inside the instrument's own code it is the instrument's. Now: - Once a command's end has decided its cleanup (none needed, make_safe! returned, or it did not and STOP is latched), nothing after it creates a new one: the terminal event is reported by a step that never throws, a held interrupt is rethrown after the release, and the command's result stands, as for an abort that arrives after the end. Only a throw before the decision makes the end call make_safe!. - The recovery that ran make_safe! for an interrupt delivered after a command's end is removed. Such an interrupt reaches the caller. - The end marks a make_safe! attempt before calling it. An end that finds an attempt that did not return latches STOP before anything else, records it, and does not call make_safe! again, so no retry can settle the end as clean. - The release records why it latched STOP when an end was cut short. - The command's claim, and the :abort's count of its on_abort, are taken inside the region whose finally undoes them; only the one instruction between the atomic step and its record is left, and an interrupt there leaves the slot held. - on_abort must return only once its action has completed or can no longer affect a later command, and must return nothing. From its call until it has returned nothing its action counts as outstanding: one that throws (an acknowledgement timeout), returns anything else (a task still running), or whose return a forced interrupt kept the layer from reading latches STOP, in the finally that undoes its count and before that step, and is logged. An interrupt held while reporting an on_abort failure reaches the caller. Tests: two :abort calls whose on_aborts are held and released in either order, an on_abort that returns a task or throws, forced-interrupt stand-ins after the claim, after a failed make_safe! at a normal end, after the end's decision, after the :abort's count and after on_abort returns, and an interrupt during the terminal report that makes no new cleanup. The child process that runs the real-SIGINT checks is sent SIGKILL if it is still running ten seconds after SIGTERM at its deadline, so a stuck child fails the test instead of hanging the suite. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
Round 6 fixes, on top of 579489f. They make one rule for a forced interrupt (Julia's repeated Ctrl-C, which passes
Local checks on the final code (Julia 1.13):
|
…records Two abort paths broke the layer's promises. An abort that request_abort! had acknowledged could be dropped when a forced interrupt (Julia's repeated Ctrl-C) cut the command's admission short: the release freed the slot, recorded the abort as one STOP refused although STOP was clear, and the next command ran with no cleanup. And while the layer's :abort waited for its on_abort (an actuator stop, say), an unserialized movement could start, and the stop then reached it. Now: - A claim never admitted is closed to aborts and its mark read while the slot is still held. An abort that reached it is recorded as STOP refused only when STOP is latched; otherwise the release latches STOP and records that the abort reached a command whose admission was cut short. - An unserialized command whose plan moves is refused, with the new AbortInFlight, while an on_abort is outstanding. Reads, the :abort and the grant turning off still run. A failing on_abort latches STOP before its exception or return value is formatted. - The layer recognizes its own Aborted itself, with interrupts still deferred, so a Ctrl-C cannot turn a known abort into a failure record. - Interrupts are now deferred by a helper that ends the deferral in a finally. Base.disable_sigint leaves an exceptional exit to the handler that catches it, which delivers a pending interrupt as it is entered, past the caller's catch. - An interrupt held while the release reports reaches the caller on every path, a refused claim's included. - make_safe! must return nothing. Any other return (a pending Task) latches STOP and is recorded, never as "made safe". - An interrupt delivered as the :abort reopens interrupts, before on_abort is entered, no longer marks on_abort outstanding. It is recorded as the interrupt, and STOP stays clear. - A STOP the release latches for an end cut short is logged :stop_latched unless make_safe! was called and did not return. - The forced-interrupt rule is stated once, in a "Forced interrupts" section of the API page, and the docstrings point to it. The docs show an on_abort that ends with nothing, since a driver call may return a status. _make_safe!'s unused Bool return is gone. Tests cover each change. The real-SIGINT child process adds a check for an Aborted interrupted in make_safe!, and its check of an :abort interrupted at its arrival now expects STOP clear and a record of the interrupt. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
Round 7 fixes, on top of a769616. They close two abort paths.
Smaller fixes, from both reviews:
One more change, beyond the brief. Interrupts are now deferred by a helper that ends the deferral in a The forced-interrupt rule is stated once, in the API page's "Forced interrupts" section. Local checks on the final code (Julia 1.13):
|
…ecords An abort's on_abort (a stage stop, say) may act on a whole actuator. The layer already refused a movement admitted while an on_abort was outstanding. But a movement admitted just before could yield inside its execute, issue its move while the on_abort ran, be stopped by it, and still end with a success record. Now: - Every unserialized command whose plan moves, and whose run overlaps an on_abort, is treated as reached by it. Whatever its execute returned, run_command throws Aborted for it and records :command_aborted, saying an abort's on_abort ran while it moved. One whose execute throws keeps its failure record, with the overlap noted. Reads, the grant and the layer's :abort are unaffected. - The mechanism is a count of on_abort calls begun, kept in the CommandCore. A movement reads it at admission, before its slot check, and compares it at its end, together with the slot's outstanding count. The :abort counts its call in the slot, then raises the count, both before on_abort is entered. A comment states the order. - on_abort's outstanding mark is now the last step before it is entered. The call is prepared first, and on_abort is called directly rather than through the command's execute. An interrupt in the window left, or inside on_abort, is recorded as interrupted as it was called or while it ran, never as a throw. It latches STOP, since the layer cannot tell whether the action is done. - A result execute returned that the layer classified as aborted keeps that classification. A later abnormal end (an interrupt in after_execute) is recorded :command_aborted, not :command_failed. - on_abort's throw is tracked apart from the value thrown. A throw(nothing) is a throw: STOP latched, recorded, and an interrupt held while reporting it reaches the caller. The two rethrows of a held interrupt in the :abort are now one. - The API page's "Forced interrupts" section says to restart Julia after a forced interrupt. In plain Julia 1.13, with no package loaded, a later Ctrl-C ends the process with a segmentation fault. - Comments say that _is_abort runs only inside a deferral, and which Base internals _deferred relies on. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
Round 8 fixes, on top of 60a2dc6. The blocking case. An abort's
The should-fix items.
Verification note. After a caught forced interrupt, a later Ctrl-C ends plain Julia 1.13 with a segmentation Local checks on the final code (Julia 1.13):
|
One ordinary Ctrl-C after a movement's execute returned, while the layer decided its overlap with an abort's on_abort or logged its end, could leave no record of the movement at all. And a forced interrupt (a repeated Ctrl-C) between the :abort's slot count and its raise of the count of on_abort calls begun could erase a counted overlap. Now: - An unserialized command runs with interrupts deferred except inside its execute, as a serialized command's end does. Its overlap decision and its one terminal record (:command_done, :command_aborted or :command_failed) always happen. An interrupt that arrived meanwhile, or that the record's report met, reaches the caller after the record. - The :abort raises the count of on_abort calls begun again in its finally, before the uncount. Any movement whose run overlaps the slot count then sees a change; an interrupt between that raise and the uncount leaves the slot counted, which fails closed. The comment at _watches_on_abort states what carries the order: run_command runs only on the body thread, with no yield between the paired steps, and the slot clause is a second defense. - The :abort records its success after the uncount, so a slow report no longer holds the slot. Failure records stay before it. - Records say what the layer saw. A movement's overlap record says an abort's on_abort was counted (begun, or about to begin) while it moved. An interrupt before the layer read on_abort's return says it "was interrupted before the layer saw it return nothing", also when a second forced interrupt cut the catch short. - With the default on_abort, which has no action, the :abort counts nothing, refuses no movement and treats none as reached. - The Command docstring and the API page say that a movement's execute returns only when its motion has ended (or has been stopped), as the N-472 move does by waiting until every axis is on target. The overlap rule's window ends there. - The unused call method of the :abort's execute is gone; the layer calls on_abort directly. Tests: an interrupt at each of a movement's terminal records; a real SIGINT in the child process as an overlapping movement decides its overlap; a forced-interrupt stand-in between the :abort's slot count and its count raise; a slow :abort success report; and the default on_abort beside a movement. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
Round 9 fixes, on top of acfd77a. The blocking case. An unserialized command now runs with interrupts deferred except inside its The should-fix items.
The rest.
Local checks on the final code (Julia 1.13):
|
A reporter (the event log's tee, or the logger an @error reaches) that called run_command from inside an unserialized command's deferred end started a serialized command whose execute ran with the outer deferral still in force. One Ctrl-C did not stop it: the light stayed on, it recorded done, and the next command ran. Now: - run_command refuses, before it does anything else, a call from inside the layer's own deferred steps (make_safe!, or a report of the event log), with the new ReentryRefused. A per-task flag in task-local storage marks those steps. _deferred sets it and _interruptible clears it for its body, so an execute (and the hooks that classify or follow it, and on_abort) may run another command. Julia keeps the interrupt deferral per task, and a task spawned from inside those steps inherits neither the deferral nor the flag. The docs say make_safe! and on_abort call the instrument's drivers directly and a reporter never runs a command. - An unserialized command's final admission checks (STOP, the read of the on_abort change counter and the AbortInFlight slot check) now run inside its deferred region, in the same order, and its arguments are prepared inside the try that records a failure. An admitted command always leaves its record. - on_aborts is now described as a change counter. The :abort changes it once, in its finally, before the uncount. Its first raise, before on_abort, was redundant and is gone. A movement's end reads the slot before the counter, so the argument holds on any thread. The comment at _watches_on_abort states which step covers which window. - The movement docs give the same task qualification as the serialized section: a Ctrl-C reaches the task running then. They also say that a movement's execute checks the driver's status and throws when completion is unknown. The N-472 move returns FALSE when its on-target query fails while the motion may continue. Tests: reentry from a reporter refused on the unserialized path, the serialized path and the :abort, and from make_safe! (STOP latched); an execute that runs another command, and a task spawned from a reporter, unaffected; an error while arguments are prepared, recorded. Two real-SIGINT checks in the child: a reporter's run_command for a confirmed light-on, which is refused and the light never comes on, and a SIGINT at an unserialized command's final admission checks, after which its record is kept. Three tests that observed the slot by reentering from a reporter or from make_safe! now read the state directly or act from another task. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
Round 10 fixes, on top of 3f23dbf. The blocking case.
The should-fix items.
Local checks on the final code (Julia 1.13):
|
…ts try The layer's :abort made its final STOP check before it entered its deferred region, so one ordinary Ctrl-C between the two could erase an abort with no record: the command it was sent for ran on, unaborted. The check now runs inside the region, as an unserialized command's admission already does. An admitted :abort always takes its step and records its arrival, and an interrupt that arrived meanwhile reaches the caller after that record. The per-task flag behind ReentryRefused is now set inside the try whose finally restores it, so a forced interrupt (a repeated Ctrl-C) just after the set no longer leaves the task marked. The two windows left, inside that finally and in the restore that ends an interruptible step, are the forced-interrupt limit, and the API page states them. Docs: - an interrupt can reach another task before a movement's record exists when formatting a failure, or a report, yields before the record is appended; - ReentryRefused is enforced only inside the layer's deferred steps. A reporter of a refusal made before them (a confirmation required, say) is not checked by it, and the rule that a reporter never runs a command still holds for instrument authors; - the comment at _watches_on_abort names the window the slot read also covers: a forced interrupt in the :abort's finally before the counter changes. Tests, on simulated devices: - the :abort's admission point lies inside its deferred region; - a real SIGINT there, in the child process: the command's abort is armed and recorded, the interrupt comes after the records, and the command stops; - a stand-in forced interrupt just after each of the flag's two sets leaves the task unmarked, and the steps around an execute still marked as they unwind. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
Round 11 fixes, on top of 4521157. Both round 11 reviews found nothing blocking; this commit takes their should-fix The The reentry flag. The per-task flag behind Docs and comment.
The N-472 Local checks on the final code (Julia 1.13):
|
… flag The tests added for the :abort's admission and the reentry flag checked the test point beside each operation, not the operation itself. Moving only the :abort's final STOP read out of its deferred region, or only the flag's set out of the try whose finally restores it, passed every test. Two source-order checks now hold the real positions, as the tests already do for the order of admission and of a command's end: - the :abort's STOP read lies inside its deferred region, before the step that arms the abort; - the flag's set lies inside that try, before its finally. Docs and comments, no code change: - an interrupt that arrives at the :abort's admission is delivered after its arrival record. When a report of the arrival yields, it can reach another task, and the :abort runs on: its on_abort may still start and run, and the caller gets its result. The unserialized command's comment gets the same qualification; - a forced interrupt that leaves the reentry flag clear while the outer steps unwind matters only to code that also breaks its own rule and runs a command there. That is a reporter, or a make_safe! the unwinding reaches. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
Round 12 fixes, on top of 1b816b0. Both round 12 reviews found nothing blocking. This commit is two docs corrections Tests tied to the real positions. The round 11 tests checked the test point beside each operation, not the
The The forced-interrupt wording. A flag left clear while the outer steps unwind matters only to code that also breaks Local checks on the final code (Julia 1.13):
|
Docs and comments, no code change. The API page gains a section, "Where an interrupt lands", that states the rule once. Wherever the layer's own steps call code that may yield (the event log's tee, a logger, an exception's showerror, any report), an interrupt held there may be delivered in another task, before the record that step writes exists. The layer guarantees the cleanup and the record, not which task receives the interrupt or when it arrives relative to a record. Three reviews in a row had each found one more place this happens, and each fix named only that place. The passages that named those places (the :abort's guarantee, the movement text, the forced-interrupt sentence about code that breaks its rule and runs a command) now give examples and refer to the section. The run_command docstring and the comments on the serialized, unserialized and :abort paths no longer promise delivery after the record. The rule that code the layer calls never runs a command now names an exception's showerror beside the reporters. The two source-order checks added for the :abort's admission and the reentry flag matched source text. A harmless edit (a renamed local, a trailing comment) broke them, and two real defects passed them: interrupts reopened just around the STOP read, and an earlier try that holds the flag's set outside the restoring one. They now check the parsed code, matching only function names and the flag's key: - the :abort's STOP check sits in the body of the function passed to _deferred, inside no call that reopens interrupts; - every assignment to the flag's key other than the restore sits in the protected block of the try whose finally holds the restore, and in no other try. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
Round 13 fixes, on top of ccf00dd. Both round 13 reviews found nothing blocking. This commit changes docs, comments One rule for where an interrupt lands. The API page has a new section, "Where an interrupt lands", that states the The passages that named such places now give examples and refer to the section:
The Structural checks instead of text checks. The round 12 source-order checks matched source text. A renamed local or
Local checks on the final code (Julia 1.13):
|
… audited Two regression tests guard the :abort's final STOP read (it must run with interrupts deferred) and the reentry flag's write (a finally sure to restore it must cover it). Their test points sat beside each operation, so moving the operation alone left them behind. The structural checks that replaced them could be fooled, and they failed on correct code. Each operation is now a small function that holds its test point: - _admit_abort makes the :abort's final admission check, then hits the point; - _mark_layer_step! writes the flag, then hits the point. The existing behavioral checks at those points now go wherever the operation goes: a parent test and two real-SIGINT child checks at the read, and a forced stand-in just after the write. The structural checks and their helpers are deleted. Seven defects fail the behavioral checks: - either operation moved on its own; - interrupts reopened around the read through _interruptible, through a closure defined in the region, or by raw sigatomic calls; - an earlier try ... catch holding the write; - a restore made conditional on a flag set after the write. Four correct rewrites pass. Every statement in the API page, the docstrings, the comments, CHANGELOG.md and the pull request text about where or when an interrupt arrives, or about a result that stands, now agrees with "Where an interrupt lands": - only an interrupt thrown in the command's own task while it runs, which the layer catches and saves, is sure to reach the caller. One delivered in the layer's steps may reach another task, and the caller may then return normally; - a result stands only once the end has decided its cleanup. An interrupt between the claim and execute takes effect as interrupts reopen for execute, which then never runs, and the command fails, with its cleanup; - the release step is distinct from the slot becoming free: the slot stays held while an on_abort for the command still runs. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… at debug level Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
Round 14 fixes, on top of 853a6fe. Both round 14 reviews found nothing blocking. This commit closes the two Test points inside the guarded operations. Each operation is now a small function that holds its own test point:
The existing behavioral checks at those points (a parent test and two real-SIGINT child checks at the read, a forced One audit of every statement about delivery and results. I checked the API page, the docstrings, the comments in
Main merged in. After this commit, main is merged into the branch (f041459), bringing in pull request 98: the Local checks (Julia 1.13):
|
…antees The regression test for the :abort's final admission check put its interrupt after the whole check. Interrupts reopened around the check inside its helper, or only around the latch read, therefore passed every test, although one Ctrl-C there erases the abort. A test point now sits in _check_stopped immediately before the latch is read. The child process sends a real SIGINT there on the :abort's final check, so the signal is pending before the read. Correct code defers it until the abort's region ends, so a reopening anywhere from the read to the end delivers it early and fails the check. The parent test at the old point stays as the fallback where the child process cannot run. The flag test's forced interrupt now selects the write that clears the flag, not the second write, so a correct nested deferred scope passes. A restore made conditional on something set between the write and the test point, or an extra write of the flag outside _mark_layer_step!, is left to the statement-boundary sweep the next pull request commits; the test comment says so. The AbortInFlight message no longer claims the abort's on_abort "has not returned". The refusal holds while the abort is counted, which includes its reports. The API page, docstrings, comments, CHANGELOG and pull request text now state what is guaranteed and point to "Where an interrupt lands" for delivery: - an interrupt still pending as interrupts reopen for execute takes effect there, and execute never runs; one delivered earlier, at a yield, may reach another task while the command runs on; - only an interrupt that escapes into the layer is caught, saved and thrown to the caller; - once the end has decided its cleanup, no new cleanup is made, though an interrupt during classification still records the command as failed; - the slot stays held while the layer's :abort for the command is counted, from before its arrival report until after its on_abort and its reports end. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
Round 15 fixes, on top of f041459 (63bc206 plus the merge of main). Both round 15 reviews found nothing blocking and The
The flag test.
Promises cut to guarantees. The API page, docstrings, comments, CHANGELOG and pull request text now state only
Local checks on the final code (Julia 1.13):
|
…fined once The child-process checks for the :abort now cover both on_abort paths and look past the terminal report: - the SIGINT before the final STOP read is chosen by the read's role, the first STOP read inside the layer's steps, not by its position; - a second check sends it with an on_abort of the instrument's; - a third sends it after that on_abort returned; - a writable tee must receive the abort's terminal record before the interrupt arrives. Edits that reopen interrupts only when the instrument registered an on_abort, around the uncount, around reading on_abort's return, or for the success report's tee write now fail them. Code moved ahead of its test point, such as the latch read cached in a local before the point, is outside what any one test point can see; the test comment names this limit. This corrects two claims in the previous commit's message. The STOP-read check did not catch every reopening up to the region's end: it covered only the default on_abort, and nothing looked after the terminal report. The abort's count does not last until its reports end: it is undone before the success report. Docs and comments, no code change: - the count's span is defined once, on the API page: the slot is held from before the :abort's arrival report until its on_abort has returned and any failure is recorded, and it is free during the success report. The other places point there. The comment that said a slow report cannot hold the slot now says this holds for the success report only; - a yield is a point where another task may receive an interrupt, not a point where it is delivered; - an interrupt that escapes into the layer reaches the caller: saved and thrown after the release step for a serialized command, rethrown as it is for an unserialized one. Nothing promises that an interrupt in execute ends the command abnormally; - an overlapped movement is recorded :command_aborted, and its caller gets Aborted, or a Ctrl-C that arrived while its end ran; - the terminal event's kind comes from the instrument's classification; only an interrupt that escapes the classification of an exception records the command as failed; - before the slot is released, cleanup has succeeded or STOP is latched. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
Round 16 fixes, on top of eafd9c9. Both round 16 reviews found nothing blocking and no code defect. This commit The
The count, defined once. The API page now defines the span once. The slot is held from before the Promises cut to the guarantees.
Local checks on the final code (Julia 1.13):
|
Docs, docstrings, comments and test comments only. With comments and docstrings removed, the code is the same as in the previous commit. What a caller reads now matches what the code does: - Abnormal end. The instrument is made safe, or STOP is latched when make_safe! fails. The module docstring, the API page's trust-boundary summary and its account of an abort reaching a command no longer promise successful cleanup alone. - The slot. Undoing an abort's count is one condition of the slot becoming free; the command must also have ended. The _Run docstring says the slot is freed only once both have finished. - While an abort is counted, STOP is still checked first. With STOP latched, a movement is refused Stopped whatever the count, and reads pass. The registration docstring now lists reads among what runs under STOP. - on_abort. The signature no longer shows sys -> nothing as a default. Leaving the keyword out selects no extra action and no count. Supplying any on_abort, even one that does nothing, selects the counted path, so a movement it overlaps is treated as reached by it. - The record. One terminal event is recorded per admitted execution. A dry run or an unknown command records nothing, and a refusal records :command_refused. An overlapped movement is recorded :command_aborted, or :command_failed with the overlap noted when its execute throws. The Aborted docstring says what the unserialized path does with an Aborted: it is not classified, it is recorded :command_failed when thrown and :command_done when returned, and no make_safe! runs. - Classification. The layer classifies its own Aborted, and the instrument's is_aborted classifies anything else. - Re-registration. A re-declared command's old confirmations bind nothing once a bound field changes; re-registering with the same bound fields keeps them valid. This corrects two claims in the previous commit's message: - The slot is not free during an abort's success report unless the command has also ended. - The child checks do not cover both on_abort paths whole. They run the default on_abort and an instrument's that returns nothing. The failure branch of an instrument's on_abort is not run with a pending signal. The test comments and the pull request text now say the same. The list of work owed by the next pull request gains that fourth case, a stricter tee check, a selector that cannot pick the preliminary STOP read, wording that tells an interrupt's first delivery from its delivery to the caller, and the three named limits. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
Round 17 fixes, on top of efc9ea7: text only. Both round 17 reviews found nothing blocking. This commit corrects the What a caller reads now matches the code.
Coverage claims. The test comments and the pull request text now name the cases the child checks run: the default The owed list gains these items:
Local checks on the final code (Julia 1.13):
|
Docs, docstrings and comments only. With comments and docstrings removed, the code is the same as in the previous commit. - Cleanup on an abnormal end applies to serialized commands: the instrument is made safe, or STOP is latched when make_safe! fails. An unserialized command has no cleanup. Corrected in the module docstring and the API page's trust-boundary summary. - The slot is nothing only when no serialized command runs and no counted :abort for an ended one is still outstanding (_Run docstring). - Under STOP only the :abort, the grant turning off and unserialized reads run; every serialized command is refused Stopped. The admission checks run in order: STOP, then confirmation, then the count. So AbortInFlight refuses a movement that passed the earlier checks, while a latched STOP refuses it Stopped first. - What a call that does not run records. A refusal by an admission rule records :command_refused: STOP or the emit rule, confirmation, busy, or AbortInFlight. A dry run records nothing, and so does a call that fails before those rules decide, for its reentry, thread, name or arguments, or for a plan or confirm function that fails. - An unserialized execute that returns Aborted is recorded :command_done and returned, unless a counted on_abort overlapped the movement. Then it is recorded :command_aborted and run_command throws Aborted. This corrects the previous commit's message. Besides a dry run and an unknown command, every call that fails before the admission rules decide records nothing. An unserialized Aborted that execute returns is recorded :command_aborted when a counted on_abort overlapped the movement. The pull request text no longer says the child checks see the record reach the tee before the interrupt: they compare the event kinds in the tee after the writer is closed. The list of work owed by the next pull request adds the unserialized path's distinction between an interrupt from execute, rethrown directly, and one from a report, saved and thrown after the record. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
Round 18 fixes, on top of b7af798: text only, and only in the sentences the brief named. Both round 18 reviews found
The commit message corrects b7af798's on the records of calls that do not run and on an unserialized returned Local checks on the final code (Julia 1.13):
|
…ments While the layer's :abort for a command is counted, AbortInFlight refuses an unserialized movement that passed STOP and confirmation; a serialized command is refused CommandBusy instead, since the slot is still held, and the count refuses no unserialized read. The entry said "a movement" without the distinction. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The child process copied the parent's thread counts as --threads=N,M. Under Julia 1.11 the parent has no interactive thread (M = 0), and 1.11 refuses an interactive count of 0, so the child never started and the test failed. On 1.11 the child now gets --threads=N, which there means N,0; 1.12 and later keep --threads=N,M, since there --threads=N adds an interactive thread. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
First code change of the instrument-agent layer: a shared part of this package through which a Claude session can
operate a microscope. It reads state and runs a short, per-instrument list of approved actions only while a person
allows it, and proposes anything else for a person to confirm. This change adds only the command machinery the rest
builds on; the body that holds a person's grant and STOP, the call surface, the transports and the workspace follow in
later pull requests.
What it adds
A new submodule,
MicroscopeControl.Agent, declaredpublicand not exported, sousing MicroscopeControlgains noname from it.
CommandTable,CommandArg,CommandPlan,Command,register_command!,describe_commands: each instrument owns its table; each command, immutable once made, has a pure plan (what itwould move, and whether light leaves the instrument) and an execute. The layer's own
:abortand:agent_may_actcome only from
register_abort_command!andregister_grant_command!;register_command!refuses both names.it can send. The instrument's own code (its plans, executes, hooks and
command_core) is trusted but may fail: thelayer survives its throws and interrupts, and the docs state each hook's obligations.
Bool,Int,Float64,String,Symbol, a concreteTupleorVectorof these, orUnion{Nothing,T}of one. Registration refuses anything elseand says what to use, and refuses two arguments of one name.
convert_argconverts by a closed rule (aBoolisnever a number, at any level; an
Intbecomes aFloat64only exactly; aFloat64is finite; a vector is read byiteration, whatever its indices), and the layer holds each argument in a canonical immutable form.
run_commandis the only way a command runs, and it asks the system for itsCommandCoreonce percall. Every system holds one and implements
command_coreandmake_safe!; what an instrument adds goes throughhooks with defaults, dispatched on its type:
after_execute(after the result is classified; may throwAborted)and
is_aborted(an abort reported by a result; side-effect free). The docs page shows them on an instrument witha focusing phase, and says which outputs its inhibit covers.
request and the declaration, refuses a plan function that names another command or a table entry held under another
name, and binds every confirmation (free commands' too) to an immutable form of the plan it was given: the command,
the arguments by type and value at every level, their declared types (so a re-declared command's old confirmations
bind nothing once a bound field changes, a declared argument type included; re-registering with the same bound
fields keeps them valid), the moves and the emits flag. Every
Confirmationconstructor reads the plan once andderives both what it shows and what it binds from that one read.
slot, in one atomic step that is also the busy check, and only then reads the STOP latch, on sequentially
consistent atomics, so a STOP on another thread either refuses it or finds it in the slot and stops it at its next
checkpoint. While STOP is latched, only the layer's
:abort, its grant turning off, and reads run (the twoexemptions known by identity, not by name); an unserialized command whose plan emits is always refused.
request_abort!and the layer's:abortmark the command in the slot in oneatomic step (both return its name), and the command's end takes that mark in another, its ordering point, after
which no abort reaches it. So an abort either reaches the command before its end, which then makes the instrument
safe (or latches STOP when
make_safe!fails), or finds it ended and says so; an abort sent while nothing runsreaches nothing, and none is ever left over to be cleared as stale; one that marks a command STOP then refuses at
admission is recorded. The slot is freed only after the end's cleanup. The
:abort'son_abortruns only for acommand it reached, its arrival is recorded first, and while the
:abortis counted (the API page's "STOP, abortand the body thread" defines the span once) the command's slot is not freed to another command and, the checks
running in order (STOP, then confirmation, then the count),
AbortInFlightrefuses an unserialized movement thatpassed the earlier checks (a serialized command is refused
CommandBusy, since the slot is held), while a latchedSTOP refuses it
Stoppedfirst; the count refuses none of unserialized reads, the:abortand the grant turningoff. An
on_abortmay act on a whole actuator, and the layer cannot know which, so anunserialized movement whose run overlaps one in the other order (admitted before it was counted) is treated as
reached by it: whatever its
executereturned, it is recorded:command_aborted("an abort's on_abort was counted(begun, or about to begin) while it moved") and the caller gets
Aborted, or a Ctrl-C that arrived while its endran; one whose
executethrew keeps its failure record, with the overlap noted. The movement reads a change counter(
on_aborts) at admission, then checks the slot; at its end it reads the slot, then the counter. The:abortchanges the counter in its
finally, before the uncount. The comment at_watches_on_abortstates which stepcovers which window: the admission check refuses an
on_abortalready counted; the slot read at the end sees onestill counted, including one a forced interrupt left counted for good; and the counter sees one uncounted before the
end. A movement's run ends where its
executereturns, so theCommanddocs require a movement to return only whenits motion has ended, and to check the driver's status and throw when completion is unknown (the N-472
movewaitsuntil every axis is on target, but returns
FALSEwhen its on-target query fails while the motion may continue).Without an
on_abort(the keyword left out),:abortcounts nothing, refuses no movement and treats none asreached; supplying one, even one that does nothing, selects the counted path.
make_safe!on any exception fromexecuteorafter_execute, interrupts included (first, before anything is classified or logged), on an aborted result (thelayer's own
Abortedcounts whateveris_abortedsays and is recognized with interrupts still deferred,after_executecannot undo it, that result is whatrun_commandreturns, and a later abnormal end, an interrupt inafter_executesay, keeps the classification), on a classifier that throws, and on an abort or STOP that reached itbefore its end. So if it throws after its
executebegan and before its end settled its cleanup,make_safe!hasrun, or STOP is latched.
make_safe!returnsnothingonce the instrument is safe; one that fails, does notreturn, or returns anything else (a pending
Task) latches STOP, is not called again, and no record then claims theinstrument was made safe.
executeand the hooksthat classify or follow it (an unserialized command, the layer's
:abortincluded, is deferred the same way fromits final admission checks to its terminal record, so an admitted command always leaves its record), so a Ctrl-C
cannot land between a failure and its cleanup, or between a failed cleanup and the STOP latch. A deferred interrupt
stays pending until the first reopening for the instrument's code (where the layer takes it as that step's failure)
or the end of the layer's steps (an ordinary throw, on a throw as well as a return:
Base.disable_sigintalonewould deliver it past the caller's
catch); at a yield, another task may receive it first, while the command runson. One still pending as interrupts reopen for
executetakes effect there, andexecutenever runs: the commandfails, with its cleanup. Once the end has decided its cleanup, no new cleanup is made, so which task receives the
interrupt no longer matters to the instrument; the terminal event's kind still comes from classification (the layer
classifies its own
Aborted, and the instrument'sis_abortedclassifies anything else); an interrupt that escapesthe classification of an exception records the command as failed. An interrupt that escapes into the layer (from
execute, a hook,make_safe!or a report) is thrown to the caller: caught, saved (_End.held) and thrown afterthe release step on a serialized command, rethrown as it is on an unserialized one; instrument code that catches its
own interrupt decides what follows.
make_safe!runs deferred, so it must return promptly. The API page states thedelivery rule once, in "Where an interrupt lands", and the other passages point to it: the layer guarantees the
cleanup and the record, not which task receives an interrupt or when relative to a record. A host must make Ctrl-C
catchable (
Base.exit_on_sigint(false)); the body's startup will.finallyruns the release step, once the end hassettled its cleanup (none needed,
make_safe!returned, or it did not and STOP is latched), whatever the eventlog's reporting does: a tee or a logger that fails cannot strand the slot. The slot is free then, unless the layer's
:abortfor the command is still counted; the last of those frees it. A forced interrupt (a Ctrl-C pressedrepeatedly) fails closed, by the rule the API page states once, in its "Forced interrupts" section; among its cases,
an abort that reached a claim whose admission it cut short latches STOP, since
request_abort!had acknowledged it.The section also says to restart Julia after a forced interrupt: in plain Julia 1.13, with no package loaded, a
later Ctrl-C ends the process with a segmentation fault when the forced interrupt landed in running Julia code
(reproduced; not when it landed in a blocking C call; no Julia issue reports it).
:command_done,:command_abortedor:command_failed)where the log can be written (a refusal by an admission rule, STOP and the emit rule, confirmation, busy or
AbortInFlight, records:command_refused; a dry run records nothing, and so does a call that fails before thoserules decide, for its reentry, thread, name or arguments, say, or for a plan or confirm function that fails); an
exception whose
showerrorfails or is interrupted is recorded by its type's name. A STOP the layer latches sayswhy:
:make_safe_failedonly whenmake_safe!was called and failed,:stop_latchedfor an end or an admissioncut short, and "STOP refused" only when STOP refused.
on_abort. It returns only when its action has completed or can no longer affect a later command, and returnsnothing(the docs showsys -> (stopmotion(sys.stage); nothing): a driver call may return a status). From insideits call until it has returned
nothingits action counts as outstanding: one that throws or returns anything else(a
Task) latches STOP before its failure is formatted and before its count is undone, and is logged; athrow(nothing)is a throw. The outstanding mark is the last step beforeon_abortis entered: an interruptdelivered as
:abortreopens interrupts, before it, is recorded as what it is and latches nothing; one at or afterthe call that comes before the layer read
on_abort's return is recorded as "was interrupted before the layer sawit return
nothing", never as a throw, and latches STOP, since the layer cannot tell. A failure is recorded beforethe uncount, a success after it, so a slow success report cannot hold the slot.
run_commandrefuses, before anything else, a call from inside thelayer's own deferred steps (
make_safe!, or a report of the event log: its tee, or a logger an@errorreaches)with
ReentryRefused, since a command started there would run with the layer's deferral still in force and oneCtrl-C would not stop it. A per-task flag in task-local storage marks those steps;
_interruptibleclears it for anexecuteand the hooks, so anexecutemay run another command, and a task spawned from inside the steps inheritsneither the flag nor the deferral (Julia keeps the deferral per task). The flag is set inside the
trywhosefinallyrestores it. The runtime refusal applies only inside those steps: a reporter of a refusal made before them(STOP before a confirmation, a confirmation required or not matching) is not checked by it, and the API page keeps
the rule for instrument authors there too.
make_safe!andon_abortcall the instrument's drivers directly.request_abort!andcheck_abortare atomic operations, safe from any thread, given acommand_corethat is a non-blocking read. The layer's:abortarms the abort before itson_abortruns andbefore anything is logged; any unserialized command runs before anything on its path is logged.
run_command(dry runs too: plan functions read the instrument's state),log_event!and
start_job!run only on thread 1 in a sticky task; elsewhere they throwOffThread.EventLog(tab-separated, escaped so no message can forge a line; a record, not an interlock: a failure to writeit is reported and never stops a command),
CommandRunnerandstart_job!(abusylistener that throws rolls astart back;
start_job!returns the task it created),JobRecord.Until the body exists (next pull request),
:agent_may_actthrows "no body holds this system".Tests (simulated devices only)
test/agent_fixture.jlholds two systems on simulated devices, both on the one path: one with a camera, a stage anda light and only the required contract, and one with a laser, a lamp and a focusing phase that exercises the hooks
(and can be set to misbehave: a classifier that throws, is interrupted or knows only its own records, an
after_executethat drops the result, amake_safe!that fails or is interrupted). Light leaves either only whileits source is on and its inhibit, an atomic that
make_safe!sets from any thread and no command clears, is clear;a person's reset turns the source off before it clears the inhibit. A test holds a running command at a known point
with events, never a sleep.
test/agent_commands.jl, in its own module, covers:declarations; the canonical argument form;
thread where there is one), at admission, and by a failed
make_safe!or one that returns a task;make_safe!on each abnormal end, interrupts included, and on an abort that reached a command that ended normally;no-op inlined away in normal use), including after the claim with an abort already acknowledged, after the end's
decision, after the count of the
:abort'son_abortand afteron_abortreturns, each with the record itleaves;
abort STOP refused, which is saved and reaches the caller;
:abort: twoon_aborts held and released in either order; anon_abortthat returns a task, throws,throws
nothingor is interrupted, one whose exception is shown only after STOP is latched, and ones whose failurereport is interrupted;
on_abortheld at a wait while its command ends, with an unserialized movement refusedmeanwhile and a read, a second
:abortand the grant turning off let through; its final admission check made insideits deferred region;
on_abortin the other order: admitted and paused before its stage call, then anon_abortthat is still outstanding at the movement's end, or that begins and returns while it is paused (both endAborted); one whoseexecutethrows during the overlap (its failure kept, the overlap noted); a read pausedacross an
on_abort(done); a movement admitted after theon_abortreturned (done); a forced interrupt betweenthe
:abort's slot count and its raise of the count (the movement still endsAborted); an interrupt that each ofa movement's three terminal records meets (the record kept, the interrupt after it); a slow
:abortsuccess report(the slot already free, a movement admitted); and the default
on_abort(nothing counted, the movement done);Abortedended abnormally by an interrupt inafter_execute, still recorded:command_aborted;run_commandrefused on the unserialized path, the serializedpath and the
:abort, and frommake_safe!(STOP latched, recorded); anexecutethat runs another command, and atask spawned from a reporter, unaffected; an error while an unserialized command's arguments are prepared
(recorded); a forced interrupt just after the per-task flag is set, at the set that opens the layer's steps (the
task left unmarked) and at the one that opens an
execute(the steps around it still marked as they unwind);SIGTERM, then SIGKILL after ten seconds): in
execute, as it fails before its cleanup, insidemake_safe!(completing, failing, and after
executethrew the layer's ownAborted, which is still recorded as an abort), inthe last steps of a command that needed no cleanup, as the
:abortrecords its arrival (recorded as the interrupt,with STOP clear), as an overlapping movement's end decides its overlap (its
:command_abortedrecord kept, theinterrupt after it), as a reporter of an unserialized command calls
run_commandfor a confirmed light-on (refused;the light never comes on), as an unserialized command passes its final admission checks (its record kept, the
interrupt after it), and three on the
:abortwith a command held and a writable tee: immediately before it readsthe STOP latch in its final admission check (chosen by its role, the first STOP read inside the layer's steps), with
the default
on_abortand with one of the instrument's, and after the instrument'son_abortreturned. Each timethe abort arms the command's abort and records its arrival and its end (a failure where the interrupt arrives as
interrupts reopen for
on_abort), the tee receives both records, the interrupt comes after, and the command stops.A real forced interrupt is not sent: Julia throws it from its signal handler at whatever instruction runs, which can
deadlock the process;
execution, and an exception whose
showerrorfails;:abortarming its abort before its instrument's code; one core per call; the latch and the slot beingsequentially consistent atomics;
no instrument callback run there); the job runner; and
showerrorof every exception.The Interface Contract testset gains an "Agent layer" check: the submodule is public and not exported, its exports
resolve beside MicroscopeControl's with no clash, there are no method ambiguities, the required contract functions
throw, the hooks have defaults, and
run_commandhas one method.Beyond the committed tests, a statement-boundary sweep (an interrupt thrown before each of 164 statements of the
layer's end, abort, admission and flag functions, singly and in pairs, in 16 scenarios, one judged by the overlap
rule's letter) found no boundary at which the layer admitted a command with a needed cleanup missing, or let an
overlapping movement end with a success record. Committing such a sweep is listed for the next pull request.
Each safety check has a test that fails when that check alone is removed: a sweep of 159 mutations in a scratch copy
(tried, not committed), one full pass on the code as it now stands (round 16 changed only comments, docstrings and
tests, and every row still finds its anchor), failed at least one test for 146 of the 147 meant to fail (the other 12,
ten correct rewrites and two named limits, are expected to pass, and they do), including mutations of the interrupt
deferral and its delivery (for unserialized commands and the
:aborttoo, from their admission), of the refusal of acommand from inside the layer's own steps and of the flag behind it being set inside its
try, of the end's orderingpoint and its decision, of the release rule, of an abort owed at a cut-short admission, of the movement refusal while
the
:abortis counted and of a movement overlapping one, of the change counter and the slot read that cover thatoverlap, of the
make_safe!andon_abortreturn and throw rules, and of the count of the:abort'son_abort. Theone that passes, freezing a vector by making a tuple from a generator over it rather than reading it into dense
storage first, is equivalent in this process: OffsetArrays, which MicroscopeControl loads through Makie, already gives
such a tuple the vector's values. The order of admission (the claim, then the STOP read) and of the end (the ordering
point, the cleanup and the terminal event, then the release; in a release, a claim never admitted read before it is
freed; in an abnormal end, the STOP latch for a
make_safe!that did not return before anything else) is held by asource-order check, since no task can run between those steps. The
:abort's final STOP read is guarded at the read:a test point in
_check_stopped, immediately before the latch is read, where the child process sends a real SIGINT onthe
:abort's final check (chosen by its role, the first STOP read inside the layer's steps), with the defaulton_abortand with one of the instrument's; a third child check sends it after the instrument'son_abortreturned,and each compares the event kinds in a writable tee, read after the writer is closed. These run three cases: the
default
on_abort, and an instrument's that returnsnothing, with the SIGINT at the final STOP read or after thaton_abortreturned; the failure branch of an instrument'son_abortis not run with a pending signal (owed by thenext pull request); code moved ahead of its test point (the latch read cached in a local before the point) is outside
what any one test point can see. A parent test at
:abort_admittedis the fallback where the child is skipped. Thereentry flag's write holds its test point inside
_mark_layer_step!, and the forced stand-in there selects the firstwrite that clears the flag. Round 16's own run: sixteen defects fail these checks (among them interrupts reopened only
when the instrument registered an
on_abort, around the uncount, around readingon_abort's return, and for thesuccess report's tee write), twelve correct rewrites pass (among them the
:abort's pre-confirmation check skipped,or split into a helper without the point), and three named limits pass, as expected: a restore made conditional on
something set between the flag's write and its point, an extra write of the flag outside
_mark_layer_step!(bothclosed by the next pull request's committed sweep), and the latch read cached ahead of its point.
Other
docs/src/api/agent.md: an API page with an example run on simulated devices and a worked example of the hooks;the docs' coverage check passes.
run_commandof the instrument's own and a
command_corethat returns another core at a second call (Julia cannot seal afunction, so this part can only document both rules);
clear_stop!, a person's clear of the latch (there is noabort flag to clear); a
stop!that latches STOP and then callsrequest_abort!;Base.exit_on_sigint(false)atthe body's startup, so a Ctrl-C is catchable; a close that reports a
nothingfromrequest_abort!as an abortthat reached nothing; a person's way to clear a slot held after its call unwound (after
make_safe!); the body'sother tasks (the heartbeat, the hop drainer, the transport) surviving a Ctrl-C, or SIGINT routed to
stop!; theheartbeat's count of event-log write failures; and a committed statement-boundary sweep (a forced interrupt before
each statement of the layer's functions, one at a time, in the child process, including the two transitions of the
per-task flag behind
ReentryRefused: one inside thefinallythat restores it, which leaves the task marked, andone in the restore that ends an interruptible step, which leaves it clear while the outer steps unwind; it also
closes what one test point after the flag's write cannot see: a restore made conditional on something set between
the write and the point, or an extra write of the flag outside
_mark_layer_step!), so the tests cover the wholeclass of forced-interrupt windows rather than named points.
Also owed, from the round 17 reviews:
on_abort: a SIGINT at:returnedwith anon_abortthat returns a value, expecting[:abort_requested, :command_failed]in the log and the tee, STOPlatched, and the slot freed once the command has ended;
or late line fails it;
own;
on_abort) from itsdelivery to the caller, on both paths, and on the unserialized path that an interrupt from
executeis rethrowndirectly, while one from a report is saved and thrown after the record;
(M164), an extra write of the flag outside
_mark_layer_step!(M165), and the latch read cached ahead of:stop_read(M172).Checked: the full local suite and the docs build on Julia 1.13, the agent tests at
--threads=1,0,2,1and4,1(results in the comment below), and the lab test record on Julia 1.13 and on the 1.11 floor (thelab/testsstatus on the head), where the child-process SIGINT checks run too.
🤖 Generated with Claude Code