Instrument agent: commands

MicroscopeControl.Agent is the command machinery of the instrument-agent layer: how an instrument declares its commands, and how each is planned, confirmed by a person where it must be, and run, one serialized command at a time, with an abort and a STOP latch that act from any thread. The module is public and not exported, so using MicroscopeControl gains no name from it; load it with using MicroscopeControl.Agent. The body that boots an instrument and holds the operator's grant and STOP, and the call surface an agent uses, are not part of it yet: until then the grant command, :agent_may_act, throws.

An instrument package declares its commands once, at load time, in a table it owns. Every command has a pure plan (no device I/O, no side effects) that says what it would move and whether light leaves the instrument; the layer adds the command's name and its arguments to that plan. Arguments are values of a closed set of types (Bool, Int, Float64, String, Symbol, a Tuple or Vector of these, or Union{Nothing,T} of one; see CommandArg), so a plan holds them in an immutable form. A confirm-class command runs only with a Confirmation of the plan a person was shown, and that confirmation is refused once the plan, its arguments included, has changed:

using MicroscopeControl
using MicroscopeControl.Agent
const MC = MicroscopeControl

const COMMANDS = CommandTable()
register_command!(COMMANDS, :snap, CommandArg[], "One camera frame.", false,
    (sys, a) -> CommandPlan(; command=:snap, moves=["camera: one frame"]),
    (sys, a) -> (MC.capture(sys.cam); MC.getdata(sys.cam)))
register_command!(COMMANDS, :light_on, CommandArg[], "Light on.", true,
    (sys, a) -> CommandPlan(; command=:light_on, moves=["light on"], emits=true),
    (sys, a) -> (check_abort(sys); MC.light_on(sys.light)))       # a checkpoint before every light-on step
register_abort_command!(COMMANDS)

struct Scope <: MC.AbstractSystem
    core::CommandCore                     # immutable struct: the same core at every call (in a mutable one, `const`)
    cam::SimCamera
    light::SimLight
    inhibit::Threads.Atomic{Bool}         # the beam-safe line: light leaves only while it is clear; no command clears it
end
MicroscopeControl.Agent.command_core(s::Scope) = s.core
# Set the inhibit: one atomic store, safe from any thread and beside a command that is switching the source, so a
# light-on step that runs after it lets no light out. On hardware it drives a shutter or interlock line of its own.
MicroscopeControl.Agent.make_safe!(s::Scope) = (s.inhibit[] = true; nothing)
# A person's reset, never a command: the source off first, so clearing the inhibit lets no light out.
reset_inhibit!(s::Scope) = (MC.light_off(s.light); s.inhibit[] = false; nothing)

sys = Scope(CommandCore(; table=COMMANDS), SimCamera(; exposure_time=0.0), SimLight(), Threads.Atomic{Bool}(false))
frame = run_command(sys, :snap)                      # free: it runs
plan = run_command(sys, :light_on; dry_run=true)     # confirm-class: show this plan to a person
run_command(sys, :light_on; confirmed=Confirmation("operator", plan))

The trust boundary

What arrives from a mind (a Claude session, through the call surface a later part of this layer adds) is untrusted, and the layer defends against anything it can send: an unknown command or keyword, a value of the wrong type (a Bool is never a number), a confirmation of another plan, a command that STOP forbids. The instrument's own code (its plans, executes, hooks and command_core) is trusted, but it may fail: the layer survives its throws and interrupts, and when a serialized command ends abnormally it makes the instrument safe, or latches STOP when make_safe! fails (an unserialized command has no cleanup). What the layer cannot check, the instrument promises, and the hooks below say what each promise is.

One path, and hooks

Every system holds a CommandCore and implements command_core, returning that same core at every call (a mutable system holds it in a const field), and make_safe!. command_core is a read that never blocks and is safe from any thread: an abort sent from another thread reaches its command only after it returns. Every command runs through the layer's run_command, which asks for the core once per call. An instrument defines no method of run_command, and nothing of its own writes the core's STOP latch or its slot: only the layer, and a person who clears STOP, do. Julia cannot seal a function, so these two rules are the instrument's to keep; the instrument's body, a later part of this layer, refuses a system with a method of run_command of its own or a core that changes between calls.

An instrument changes what happens around its commands through hooks with defaults, dispatched on its system type:

  • after_execute, on the end of each serialized command: it may stop what the command left running and report an abort that arrived after the last checkpoint by throwing Aborted. It runs after the layer has classified what execute returned, so it cannot turn an aborted result into a normal one, and it must not change how that result classifies (it never mutates the fields is_aborted reads), since a caller may classify it again.
  • is_aborted, for an abort a command reports by its result. A classifier has no side effects: it reads the value it is given and nothing else. The layer counts its own Aborted whatever the classifier says.
  • make_safe! itself, which must work in any state, leaves the latch and the slot alone, returns nothing once the instrument is safe, and runs with interrupts deferred, so it must return promptly.

make_safe! and the :abort's on_abort call the instrument's drivers directly, never run_command, and neither a reporter (the event log's tee, or a logger an @error reaches) nor an exception's showerror runs a command. make_safe!, and a report of what the layer records in its own deferred steps, run inside those steps, where run_command refuses, before it does anything else, with ReentryRefused: a command started there would run with the layer's deferral still in force, so one Ctrl-C would not stop it. The refusal is enforced only inside those steps: the report of a refusal made before them (STOP before any confirmation, an unserialized command whose plan emits, a confirmation required or not matching) is not checked by it, and the rule holds there all the same. An execute may run another command, and so may a task spawned from inside those steps, which inherits neither the deferral nor the refusal. No hook runs a serialized command (it would be refused CommandBusy). A plan that depends on the instrument's state, such as a relative move, binds what the person saw only if the command then acts on the absolute target its plan quoted, or checks that state again at the hardware action: an unserialized command can change it between the confirmation and the move. Extend the hooks by qualified definitions (MicroscopeControl.Agent.make_safe!(s::Scope) = ...): an unqualified one defines a new function that the layer never calls.

Take an instrument with a focusing phase: its focus command turns a transmitted-light lamp on, runs a focus routine that cannot stop part way (no checkpoints), and leaves a focus lock running. An abort that arrives during the routine comes after the command's last checkpoint; its cleanup turns several devices safe; and its acquisition reports an abort by its result. Each is one hook:

# An abort that arrived while focusing: stop focusing, then report the abort. Any throw here ends the command
# abnormally, so make_safe! runs next.
function MicroscopeControl.Agent.after_execute(s::FocusScope, c::Command, args, result)
    s.phase === :focusing || return result
    try
        check_abort(s)
    catch
        stop_focusing!(s)
        rethrow()
    end
    return result
end

# The cleanup: beam safe first (an atomic line, safe from any thread, that stops the excitation laser whatever its
# source does), then, on the body thread, the lamp off and the phase reset. Every step is tried; the failures are
# thrown together, and the layer logs them as :make_safe_failed and latches STOP. It runs with interrupts deferred, so
# each device call in it (the lamp's, here) needs a timeout of its own: a Ctrl-C cannot stop a call that hangs.
function MicroscopeControl.Agent.make_safe!(s::FocusScope)
    s.beam_inhibit[] = true
    Threads.threadid() == 1 && current_task().sticky || return nothing
    failures = String[]
    try
        MC.light_off(s.lamp)
    catch e
        push!(failures, "lamp off: " * sprint(showerror, e))
    end
    s.phase = :idle
    isempty(failures) || error("make_safe! incomplete: " * join(failures, "; "))
    return nothing
end

# An acquisition that catches its abort and returns what it has, marked. No side effects.
MicroscopeControl.Agent.is_aborted(s::FocusScope, x) = x isa NamedTuple && get(x, :status, nothing) === :aborted

The inhibit covers the excitation laser only. The lamp, which this instrument does not count as light leaving it, is turned off by make_safe! on the body thread: at the end of a command, and when the body closes. A STOP from another thread while no command runs sets the inhibit and leaves the lamp on and the phase :focusing until a person clears STOP and ends the phase, since STOP refuses the serialized command that would.

When a serialized command ends, the layer runs make_safe! on any exception from execute or after_execute (interrupts included), on an aborted result, on a classifier that throws, and on an abort that reached the command or a STOP latched before its end, since it cannot tell whether the command honored them. On an exception it runs first, before anything is classified or logged. A returned result is classified first, since that is how the layer knows the end is abnormal, and make_safe! then runs after after_execute, the last of the instrument's code to touch the hardware; an aborted result is what run_command returns, whatever after_execute returns. The layer recognizes its own Aborted itself, with interrupts still deferred, and asks the instrument's is_aborted only about anything else, so a Ctrl-C cannot turn a known abort into a failure. That settles the end's cleanup: nothing after it, a report that fails or an interrupt delivered late, makes a new one. make_safe! settles it only by returning nothing: one that throws, or returns anything else (a pending Task, say), latches STOP, is not called again, and the log says so: no record claims the instrument was made safe when it was not. Each admitted execution records one terminal event, :command_done, :command_aborted or :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 those rules decide, for its reentry, thread, name or arguments, say, or for a plan or confirm function that fails); an exception whose showerror fails is recorded by its type's name. An unserialized command never calls make_safe!: it cannot emit, and the command beside it may be lighting the sample.

Interrupts (Ctrl-C) are deferred from the moment a serialized command claims the slot until its release step, except inside its execute and the hooks that classify or follow it. An interrupt that escapes from there ends the command abnormally, as any exception does. One that arrives during the layer's own steps is deferred, and Where an interrupt lands says where it is delivered. One still pending as interrupts reopen for execute takes effect there, and execute never runs: the command fails, with its cleanup; one delivered earlier, at a yield in a report, may reach another task, and the command then runs on. Once the end has decided its cleanup, no new cleanup is made, as for an abort that arrives after the end (a laser_on that ended normally leaves the light on, as it was asked to; STOP is the way to make the instrument dark at any time); the terminal event's kind still comes from classification (the layer classifies its own Aborted, and the instrument's is_aborted classifies anything else); an interrupt that escapes the 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 of the event log) is caught, saved and thrown to the caller after the release step; instrument code that catches its own interrupt decides what follows. The host process must make Ctrl-C catchable, with Base.exit_on_sigint(false): a Julia script that is not interactive exits on Ctrl-C by default, with no cleanup at all (the instrument's body, a later part of this layer, does this at its startup). make_safe! itself runs with interrupts deferred: it must return promptly and never block indefinitely, since only a repeated Ctrl-C, which Julia forces through, can cut it short.

The release step runs in a finally once the end has settled its cleanup (no cleanup was needed, make_safe! returned, or it did not and STOP is latched), whatever the event log's reporting does: a tee or a logger that fails cannot strand the slot. The slot is free then, unless the layer's :abort for the command is still counted (STOP, abort and the body thread gives the span); the last of those frees the slot as its count is undone.

Where an interrupt lands

An interrupt (Ctrl-C) that arrives while the layer's own steps run is deferred. It stays pending until one of these:

  • the layer reopens interrupts for the instrument's code (execute, a hook, on_abort): it is delivered there, and the layer takes it as that step's failure;
  • the layer's steps end: it is delivered there, as an ordinary throw.

A yield in those steps is a point where another task may receive it first: Julia defers interrupts per task, so wherever the steps call code that may yield (the event log's tee, a logger, an exception's showerror, any report), another task can run, with no deferral, and receive it, before the record that step writes exists, while the command runs on. If no task does, it stays pending.

An interrupt that escapes into the layer (from execute, a hook, make_safe! or a report) is thrown to the caller: on a serialized command it is caught, saved and thrown after the release step, and on an unserialized one it is rethrown as it is. Instrument code that catches its own interrupt decides what follows. So what the layer guarantees is the cleanup and the record (each record written where the log can be written), not which task receives a Ctrl-C, nor when it arrives relative to a record. The passages on this page that name such a step give examples, not a complete list.

Forced interrupts

A forced interrupt is Julia's repeated Ctrl-C, which passes the deferral. It can land at any instruction, so no code survives it in general, and the layer's promise for it is to fail closed: at every instruction boundary of the layer's own code, either the slot is held, or STOP is latched, or the cleanup the command needed has returned.

  • A command's claim and the :abort's count of its on_abort are each taken inside the region whose finally undoes them; only the one instruction between the atomic step and the record of it is left, and an interrupt there leaves the slot held.
  • An end it cuts short before its cleanup settled latches STOP in its release step, and that is recorded (:stop_latched, or :make_safe_failed when make_safe! was called and did not return).
  • An abort that reached a claim whose admission it cut short was acknowledged (request_abort! returned the command's name), so the release latches STOP and records it.
  • An on_abort counts as outstanding from inside its call until the layer has read that it returned nothing; one cut short in between latches STOP before its count is undone.

It can leave the instrument unsafe, or a slot held after its call has unwound (the instrument's body, a later part of this layer, gives a person a way to clear one), but never the layer accepting commands with a needed cleanup missing. Inside the instrument's own code (execute, the hooks, make_safe!, on_abort) it is the instrument's. The per-task flag behind ReentryRefused is set inside the try whose finally restores it; a forced interrupt inside that finally can leave it set, so that task refuses every later command until the restart below, or, in the restore that ends an execute or another interruptible step, leave it clear while the layer's steps around it unwind, which matters only to code that also breaks its own rule above and runs a command there (for example a reporter, a make_safe! the unwinding reaches, or an exception's showerror).

After a forced interrupt, restart the Julia process before the instrument is used again: in Julia 1.13 a later Ctrl-C can end the process with a segmentation fault, in plain Julia with no package loaded, when the forced interrupt landed in running Julia code (one that lands in a blocking C call has not done so). No Julia issue reports this case; the general problem of asynchronous exceptions is JuliaLang/julia#52291.

STOP, abort and the body thread

STOP latches: while it holds, check_abort throws at every checkpoint, no serialized command starts, and of the unserialized commands only the layer's :abort, its grant turning off and reads (plans with no moves) run; turning the grant on is refused. The two exemptions are the commands register_abort_command! and register_grant_command! make, known by what they are, not by their names; register_command! refuses both names. An unserialized command whose plan emits is always refused, since it would run beside another command. A command calls check_abort(sys) at its checkpoints and immediately before every step that turns light on.

run_command checks STOP before any confirmation is asked for. A serialized command is then admitted by claim, then check: it claims the slot, in one atomic step that is also the busy check, and only then reads the STOP latch, with 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. A command admitted before STOP latched runs to that checkpoint; so does an unserialized one, which runs to its end. 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, 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 (request_abort! returns nothing, and :abort logs that it arrived after the end, and the command's result stands); an interrupt delivered after the end's decision is the same: the layer makes no new cleanup for it (Where an interrupt lands). An abort sent while nothing runs reaches nothing, and no abort is ever left for a later command; one that marks a command STOP then refuses at admission is recorded. The slot is freed only after the end's cleanup, so no other serialized command starts in between.

The layer's :abort arms the abort before its on_abort runs and before anything is logged, records its arrival before on_abort runs, and returns the name of the command it reached, or nothing. Its final admission check is made inside its deferred region, so an admitted :abort always arms the abort of the command it reaches, if any, and records its arrival before a Ctrl-C that arrives meanwhile can be delivered (Where an interrupt lands); if that interrupt reaches another task, the :abort runs on, on_abort included. Its on_abort (an instrument's own action, stopping an actuator, say) runs only for a command the abort reached. The :abort's count is defined here: when the instrument supplied an on_abort (any, even one that does nothing), the :abort is counted against the command's slot from before its arrival report until its on_abort has returned and any failure of the :abort is recorded, and the count is undone before its success report. While it is counted, that command's slot is not freed to another command, nor does an unserialized command whose plan moves start: it is refused AbortInFlight, since the abort's action could stop it (reads, the :abort and the grant turning off still run). STOP is checked first: while it is latched a movement is refused Stopped, whatever the count, and reads still pass. An on_abort may act on a whole actuator (a stage stop stops every motion of that stage), and the layer cannot know which, so an unserialized movement whose run overlaps an on_abort in the other order, admitted before it was counted, is treated as reached by it: whatever its execute returns, it is recorded :command_aborted, saying an abort's on_abort was counted while it moved and it may have been stopped, and run_command throws Aborted for it, or a Ctrl-C that arrived while its end ran (Where an interrupt lands); one whose execute throws keeps its failure record, with the overlap noted. The run ends where execute returns, so a movement returns from execute only when its motion has ended (or has been stopped), and checks the driver's status, throwing when completion is unknown: this package's N-472 move waits until every axis is on target, but returns FALSE when its on-target query fails while the motion may continue, so a movement that calls it checks that status. One that returned while its stage still moved could be stopped short and recorded done. Without an on_abort (the keyword left out), the :abort counts nothing, refuses no movement and treats none as reached; supplying one, even one that does nothing, selects the counted path, so a movement it overlaps is treated as reached by it. A movement's own steps after its execute (the overlap decision and its terminal record), and its final admission checks before them, run with interrupts deferred, as a serialized command's end does: an admitted movement always leaves its record, wherever a Ctrl-C that arrives meanwhile is delivered (Where an interrupt lands). So on_abort returns only when its action has completed or can no longer affect a later command, returns nothing, and returns promptly. One that throws (an acknowledgement that timed out) or returns anything else (a Task still running) latches STOP before its failure is formatted, and is logged, since the layer cannot know its action is done. End it with nothing even when the driver call returns a value:

register_abort_command!(COMMANDS; on_abort = sys -> (MC.stopmotion(sys.stage); nothing))

A failure to write the event log is reported with @error without stopping a command, its abort or its make_safe!.

The body thread is thread 1 in a sticky task: the main task, an @async task or a Timer callback. run_command, dry runs included (plan and confirm functions read the instrument's state, so they never run beside a command on another thread), log_event! and start_job! run only there and throw OffThread anywhere else, including in a Threads.@spawn task that happens to run on thread 1. A handler on another thread hops to the body thread first. request_abort! and check_abort work from any thread.

The module

MicroscopeControl.Agent — Module
MicroscopeControl.Agent

The instrument-agent layer's command machinery: how an instrument declares its commands, and how they are planned, confirmed and run, one serialized command at a time, with an abort and a STOP latch that act from any thread.

  • An instrument declares its commands once, in a CommandTable it owns, with register_command!: each has a pure plan (a CommandPlan: what it would move, and whether light leaves the instrument) and an execute, and its arguments are values of a closed set of types (CommandArg). register_abort_command! and register_grant_command! add the layer's own :abort and :agent_may_act.
  • run_command is the one path every command runs through. It dry-runs a command to its plan, requires a person's Confirmation of a confirm-class plan and binds every confirmation to the plan as it is now, refuses what STOP forbids, runs one serialized command at a time, and on every abnormal end of a serialized command makes the instrument safe, or latches STOP when make_safe! fails (an unserialized command has no cleanup).
  • request_abort! and check_abort work from any thread, with no lock.
  • EventLog records what the commands did, on the body thread only; CommandRunner and start_job! give the one job slot.

The trust boundary: what arrives from a mind (a Claude session) is untrusted, and the layer defends against anything it can send, from an unknown name or a Bool given as a number to a command that STOP forbids. The instrument's own code (its plans, executes, hooks and command_core) is trusted but may fail: the layer survives its throws and interrupts, and the instrument keeps the obligations each hook's docstring states.

The system contract: a system holds a CommandCore and implements command_core, returning that same core at every call, and make_safe!. It changes what happens around its commands through hooks with defaults, dispatched on its type: after_execute and is_aborted, besides system_status, heartbeat_fields and heartbeat_tick!. It defines no method of run_command, and no hook writes the core's STOP latch or its slot: only the layer, and a person who clears STOP, do. The instrument's body, a later part of this layer, refuses a system with a method of run_command of its own or a core that changes between calls. Extend the contract by qualified definitions (MicroscopeControl.Agent.make_safe!(s::MySystem) = ...): an unqualified one defines a new local function that the layer never calls.

The body thread is thread 1 in a sticky task (the main task, an @async task, a Timer callback). run_command (dry runs too), start_job! and log_event! run only there and throw OffThread anywhere else, including in a Threads.@spawn task that happens to run on thread 1, since it can move at its next yield.

The module is public and not exported: using MicroscopeControl gains no name from it, and using MicroscopeControl.Agent brings in its exports.

source

Declaring commands

MicroscopeControl.Agent.CommandArg — Type
CommandArg(name, type, doc)
CommandArg(; name, type, doc="")

One declared keyword argument of a command: its name, the type a given value must convert to by convert_arg, and a line of doc for describe_commands.

Arguments are values. type is one of a closed set: Bool, Int, Float64, String, Symbol; a concrete Tuple or Vector of these (Tuple{Float64,Float64}, Vector{Int}); or Union{Nothing,T} of one of them. Registration refuses any other type. An instrument that needs a richer value (a file it loads, a preset) takes one of these, a name or an index, and converts it inside its execute. dry_run and confirmed are run_command's own keywords, so no command may declare them.

source
MicroscopeControl.Agent.CommandPlan — Type
CommandPlan(; command, args=Dict{Symbol,Any}(), moves=String[], emits=false, needs_confirmation=false, arg_types=())

What a command would do, made by its plan function without touching hardware. moves are human-readable lines of what changes; emits says whether light leaves the instrument, in the instrument's own judgment (the layer reads light only from this flag and infers nothing from device types, powers or names).

A plan function returns CommandPlan(; command=<its own name>, moves, emits). run_command then makes the plan it shows and binds from that: command and args from the request, each argument in its canonical immutable form (a scalar, a tuple for a Tuple or Vector, or nothing); arg_types, the command's declared arguments as (name, type) pairs sorted by name, so a confirmation binds the command's schema too; and needs_confirmation from the command's confirm rule. A plan function that names another command is refused.

A Confirmation binds the plan it was given, so moves may quote the state a command starts from (a stage position), which makes a confirmation stale once that state changes, but never a measured or time-varying value: no confirmation of such a plan could ever match. A plan that depends on state (a relative move) binds what the person saw only if its command acts on an absolute target, or re-checks that state at the hardware action: the state can change between the confirmation and the move.

source
MicroscopeControl.Agent.Command — Type
Command(; name, args=(), doc, confirm, confirm_rule=nothing, plan, execute, serialized=true)

One command of an instrument, immutable once made: its arguments are a Tuple of CommandArg.

  • confirm: true (confirm-class: it runs only with a person's Confirmation), false (free), or a function (sys, args) -> Bool, which then needs confirm_rule, the condition in words.
  • plan(sys, args) returns the CommandPlan, naming this command. It is pure: no device I/O, and it never yields.
  • confirm and plan run at every call, dry runs included, on the body thread: they must have no side effects.
  • execute(sys, args) does the work and returns its result. A long command calls check_abort at its checkpoints, and immediately before every step that turns light on. What it returns passes through after_execute.
  • serialized=false only for what must run while another command runs (a read, say). It runs past the one-command rule, so its plan may never emit. One whose plan moves returns from execute only when its motion has ended (or has been stopped), and checks the driver's status, throwing when completion is unknown (this package's N-472 move waits until every axis is on target, but returns FALSE when its on-target query fails while the motion may continue): the layer's rule for an abort's on_abort that overlaps it ends where execute returns (see register_abort_command!).

Each argument's type must be one of the closed set CommandArg lists, no two arguments may share a name, and none may be named dry_run or confirmed: every constructor refuses otherwise (ArgumentError). Usually made by register_command!.

source
MicroscopeControl.Agent.register_command! — Function
register_command!(table, name, args, doc, confirm, plan, execute; confirm_rule=nothing, serialized=true) -> Command

Add command name to table, under its own name, replacing one of the same name. The arguments are those of Command's keyword constructor, which refuses an argument type outside the closed set. :abort and :agent_may_act are the layer's own: register them with register_abort_command! and register_grant_command! (ArgumentError here).

source
MicroscopeControl.Agent.register_abort_command! — Function
register_abort_command!(table; [on_abort], doc=...) -> Command

Register the layer's :abort: no arguments, free and unserialized, so it runs beside the command it aborts and while STOP is latched. run_command arms the abort itself, as request_abort! does, in one atomic step before on_abort(sys) runs and before anything is logged; it then logs :abort_requested, naming the command the abort reached (none when nothing ran, or that it arrived after the command running had ended), and returns that name, or nothing, as request_abort! does.

on_abort(sys), an instrument's optional extra action (stopping an actuator, say), runs only for a command the abort reached, never for an empty slot or a command that has reached its end. While the :abort is counted (STOP, abort and the body thread gives the span), that command's slot is not freed to another command, and an unserialized command whose plan moves is refused AbortInFlight (or Stopped, checked first, while STOP is latched). It may act on a whole actuator (a stage stop stops every motion of that stage), and the layer cannot know which, so an unserialized movement already running when an on_abort is counted is treated as reached by it: whatever its execute returns, it is recorded :command_aborted, saying an abort's on_abort was counted while it moved, and run_command throws Aborted for it, or a Ctrl-C that arrived while its end ran (Where an interrupt lands); one whose execute throws keeps its failure record, with that noted. Such a movement's execute returns only when its motion has ended (see Command). Leave the keyword out for no extra action: then the :abort counts nothing, refuses nothing and overlaps nothing. Supplying any on_abort, even one that does nothing, selects the counted path, so a movement it overlaps is treated as reached by it. So on_abort returns only when its action has completed, or can no longer affect a later command, and returns nothing; it must return promptly, since a blocking one keeps every serialized command refused. The layer cannot know that an on_abort that throws (an acknowledgement that timed out, say), or returns anything else (a Task still running), has finished its action: either latches STOP, and is logged. End it with nothing even when the driver call returns a value (a stage's stopmotion may return its status), or every abort latches STOP:

register_abort_command!(table; on_abort = sys -> (stopmotion(sys.stage); nothing))

on_abort calls the instrument's drivers directly, never run_command.

Under STOP only this command, the grant turning off and unserialized reads run (every serialized command is refused Stopped), and only this registration makes this command: register_command! refuses the name.

source
MicroscopeControl.Agent.register_grant_command! — Function
register_grant_command!(table) -> Command

Register :agent_may_act(on::Bool), the operator's grant of the agent's act list: confirm-class to turn it on, free to turn it off, and unserialized, so a revoke never waits behind a running command and runs while STOP is latched (turning it on is refused then). Only this registration makes it: register_command! refuses the name. The grant itself is held by the instrument's body; for a system no body holds, the command throws.

source
MicroscopeControl.Agent.describe_commands — Function
describe_commands(table) -> Vector{Dict{String,Any}}

The table as plain data, sorted by name: each command's "name", "doc", "confirm" (its rule: "always", "never", or the condition in words) and "args" (each with "name", "type" and "doc").

source

Running commands

MicroscopeControl.Agent.run_command — Function
run_command(sys, name::Symbol; dry_run=false, confirmed=nothing, args...)

Run command name of the system's table: the one path every command of every instrument runs through. An instrument adds its own behavior through hooks dispatched on its system type, after_execute, is_aborted and make_safe!, and defines no method of run_command (the instrument's body, a later part of this layer, refuses a system that does).

Before anything else, it refuses a call from inside the layer's own deferred steps (make_safe!, or a report of the event log made in them) (ReentryRefused, not logged).

args are exactly the command's declared arguments, each converted by convert_arg (ArgError otherwise). Body thread only, dry runs included, checked next (OffThread): plan and confirm functions read the instrument's state, so they never run beside a command on another thread. A handler on another thread hops to the body thread first. command_core is called once, and that core is used throughout.

  • dry_run=true returns the CommandPlan, with needs_confirmation set, and does nothing else.
  • Otherwise it refuses, logging :command_refused, in this order: an unserialized command whose plan emits (ArgumentError); while STOP is latched, everything but the layer's :abort, its grant turning off and reads (Stopped), so nothing asks for a confirmation of a command that cannot run; a confirm-class plan without confirmed (ConfirmationRequired); any confirmed that does not bind the plan as it is now (ConfirmationMismatch); a serialized command while another runs (CommandBusy); an unserialized command whose plan moves while the layer's :abort for the running command is counted (AbortInFlight; STOP, abort and the body thread gives the span). An unserialized movement whose run overlaps an on_abort is treated as reached by it (see register_abort_command!).
  • An unserialized command runs at once, beside any other, after the STOP rules and the on_abort check are made again inside its deferred region (one admitted just before STOP latched still runs, as a serialized one runs to its next checkpoint): its execute before anything is logged on its path (the layer's :abort arms its abort before even that), then one event, :command_done, :command_aborted (a movement an on_abort overlapped) or :command_failed. It never calls make_safe!: it cannot emit, and the command beside it may be lighting the sample.
  • A serialized command claims the slot, in one atomic step that is also the busy check, and only then reads the STOP latch: set, it releases the slot and is refused Stopped; a STOP latched after that read finds it in the slot, and its next checkpoint stops it (a command admitted before STOP latched runs to that checkpoint). It logs :command_start, runs execute, classifies the result (an Aborted always counts, else is_aborted), then runs after_execute, which cannot undo that classification: an aborted result is what run_command returns. Its end's ordering point, one atomic step, takes any abort that reached it and closes it to later ones. It runs make_safe! on any exception from these, interrupts included (first, before anything is classified or logged), on an aborted result, on a classifier that throws, and on an abort that reached it or a STOP latched before that point; a failure there is logged :make_safe_failed and latches STOP. That settles the end's cleanup: nothing after it (a report that fails, an interrupt delivered late) makes a new one. Then it logs one terminal event, :command_aborted, :command_failed or :command_done (after :abort_ignored when an abort it did not report reached it, saying whether the instrument was made safe), and releases the slot: it is free then, unless the layer's :abort for the command is still counted (see STOP, abort and the body thread), and the last of those frees it. So if a serialized command throws after its execute began and before its end settled its cleanup, make_safe! has run, or STOP is latched, and a terminal event is recorded where it can be.
  • Interrupts are deferred from the claim to the release step, except inside execute and the hooks that classify or follow it. Where a deferred interrupt is delivered is stated once, in Where an interrupt lands. One still pending as interrupts reopen for execute takes effect there, and execute never runs: the command fails, with its cleanup. Once the end has decided its cleanup, no new cleanup is made; the terminal event's kind still comes from classification (the layer classifies its own Aborted, and the instrument's is_aborted classifies anything else); an interrupt that escapes the classification of an exception records the command as failed. make_safe! runs with interrupts deferred. The host process must make Ctrl-C catchable (Base.exit_on_sigint(false)): a script that is not interactive exits on it by default, with no cleanup.
  • The release step runs in a finally once the end has settled its cleanup, whatever the event log's reporting does. An interrupt that escapes into the layer (from execute, a hook, make_safe! or a report) is caught, saved and thrown to the caller after it; it is the only interrupt the layer is sure to give the caller. A forced interrupt (a Ctrl-C pressed repeatedly) fails closed, as Forced interrupts states.
  • The event log is a record, not an interlock: a failure to write it is reported with @error and never stops a command, its abort or its make_safe!; the event stays in memory. The instrument's body, a later part of this layer, counts these failures in its heartbeat.
source
MicroscopeControl.Agent.Confirmation — Type
Confirmation(by, plan)
Confirmation(by, at, plan)
Confirmation(; by, plan)

A person's confirmation of one plan: who (by), when (at, now unless given) and a copy of the CommandPlan they were shown, from a dry run. Every constructor reads the plan once, into an immutable form it binds, and builds its display copy c.plan from that same form: what it shows is what it binds, and changing the plan passed in, or c.plan, changes nothing. Pass it as run_command(sys, name; confirmed=c, args...): the command runs only if the plan made now names the same command, with the same arguments (the same types and values, at every level, under the same declared types), moves and emits flag (ConfirmationMismatch otherwise), for confirm-class and free commands alike.

A confirmation can be passed again while the plan stays the same, and at is a record, never checked: a caller that must confirm once per run builds one per run.

source
MicroscopeControl.Agent.convert_arg — Function
convert_arg(::Type{T}, v) -> T

Convert a given argument value v to a declared argument type T, one of the closed set CommandArg lists, by a closed rule: a Bool from a Bool only; an Int from an integer that is not a Bool; a finite Float64 from a Float64, or from an Int it holds exactly; a String from any string; a Symbol from a Symbol; a Tuple or a new Vector from a tuple or vector, read by iteration (so any indices become one-based), element by element by the same rules; nothing for Union{Nothing,T}. So a Bool is never a number, at any level. Anything else, and any other T, throws ArgumentError. Not extensible: an instrument converts a richer value inside its execute.

source
MicroscopeControl.Agent.request_abort! — Function
request_abort!(sys) -> Union{Nothing,Symbol}

Ask the serialized command running to stop at its next check_abort, in one atomic step on the slot: the name of the command the abort reached, or nothing when none was running or the one running had already reached its end (its end has decided whether to make the instrument safe). An abort sent while nothing runs reaches nothing, and is never left for a later command. From any thread: no log, no lock.

source

The system contract and its hooks

MicroscopeControl.Agent.CommandCore — Type
CommandCore(; table, events=EventLog())

What every system holds, for run_command: its CommandTable, its EventLog, the STOP latch, the slot (run: the serialized command running and whether an abort reached it, a sequentially consistent atomic; read it with running_command), and a change counter of the on_abort calls of the layer's :abort (on_aborts, also a sequentially consistent atomic: it changes before each counted on_abort is uncounted). The system implements command_core to return it; a mutable system holds it in a const field. Only the layer writes the latch, the slot and the counter.

source
MicroscopeControl.Agent.command_core — Function
command_core(sys) -> CommandCore

The CommandCore a system holds. Required: every system implements it, MicroscopeControl.Agent.command_core(s::MySystem) = s.core, returning the same core at every call (the instrument's body, a later part of this layer, refuses a system whose core changes between calls); in a mutable system, make that field const. It is a read that never blocks and is safe from any thread: request_abort! and check_abort call it from any thread, and an abort reaches its command only after it returns. run_command calls it once per call. The fallback throws.

source
MicroscopeControl.Agent.make_safe! — Function
make_safe!(sys)

Make sure no light leaves the instrument. Required: the fallback throws. run_command calls it on the body thread, first, whenever a serialized command ends abnormally: any exception from execute or after_execute (an abort, a failure such as a camera timeout after a light came on, an interrupt), an aborted result, a classifier that throws, or an abort or STOP that reached the command before its end. So if run_command throws after execute began and before its end settled its cleanup, make_safe! has run, or STOP is latched. It returns nothing, and only once the instrument is safe: a method that starts its cleanup and returns the task doing it has not made the instrument safe. It runs with interrupts deferred, so a Ctrl-C cannot cut it short: it must return promptly and never block indefinitely, and each device call in it needs a timeout of its own (see Forced interrupts for a Ctrl-C pressed repeatedly). If it throws, does not return, or returns anything but nothing, the layer latches STOP and logs :make_safe_failed, so nothing but the layer's :abort, its grant turning off and reads runs until a person clears it; it does not call it again. A method that makes several devices safe tries every one and then throws one error naming the failures. It calls the instrument's drivers directly, never run_command, which refuses inside the layer's own steps (ReentryRefused). The instrument's body also calls it at every close and failed boot, and from any thread at STOP. It must work in any state (before initialize, after shutdown, during a command), and it leaves the core's latch and slot alone. Called off the body thread, it acts through a channel no command holds across a yield or a blocking call (a shutter line of its own, a separate device handle), logs nothing, is idempotent and safe to run beside itself, and returns promptly.

source
MicroscopeControl.Agent.after_execute — Function
after_execute(sys, c::Command, args, result) -> result

A hook on the end of every serialized command: called with what execute returned, on the body thread, while the command still holds the slot, after the layer has classified that result. It returns the result (the default does nothing else), or throws: throwing Aborted reports an abort that arrived after the command's last checkpoint (stop what the command left running first, such as a focusing phase), and any throw ends the command abnormally, so make_safe! runs. It cannot turn an aborted result into a normal one: an abort execute reported stands, and that result is what run_command returns, whatever this returns. It must not change how that result classifies: it never mutates the fields is_aborted reads (a status in a mutable result, say), since the caller may classify the result again. Like every hook it leaves the core's latch and slot alone, and it never runs a serialized command.

source
MicroscopeControl.Agent.is_aborted — Function
is_aborted(sys, x) -> Bool

Whether a command's result or exception x means it was aborted, for an instrument whose commands report an abort by a result value. The layer counts an Aborted as an abort whatever this says; the default adds nothing. It is called inside a guard: one that throws, or returns something other than a Bool, makes the end abnormal. A classifier has no side effects: it reads x, nothing else.

source
MicroscopeControl.Agent.system_status — Function
system_status(sys) -> Dict{String,Any}

The instrument's own status fields, for status replies. No device I/O: it runs while commands run, so it reads cached fields. Default: none.

source
MicroscopeControl.Agent.heartbeat_tick! — Function
heartbeat_tick!(sys) -> nothing

Called on the body thread first in every heartbeat tick, from when the instrument is ready until it begins to close: the one hook allowed quick device I/O, such as a hardware watchdog reset. It must not block or yield for long, and must touch only a device or channel no command talks to across a yield. Default: nothing.

source

Exceptions

MicroscopeControl.Agent.ConfirmationMismatch — Type
ConfirmationMismatch(command, confirmed, planned)

run_command refused a confirmation that does not bind the plan made now (planned): confirmed (the confirmation's copy of what was shown) is for another command or other arguments, or its moves, its emits flag or its arguments' declared types changed since it was confirmed.

source
MicroscopeControl.Agent.AbortInFlight — Type
AbortInFlight(command, aborting)

An unserialized command whose plan moves, refused while the layer's :abort for the serialized command aborting is counted (STOP, abort and the body thread gives the span): that action (stopping an actuator, say) could stop it. Reads, the layer's :abort and the grant turning off are not refused. A movement already running when an on_abort begins is not refused; it is treated as reached by it (see register_abort_command!).

source
MicroscopeControl.Agent.ReentryRefused — Type
ReentryRefused(command)

run_command(sys, command) refused because it was called from inside the layer's own steps, where the layer defers interrupts: from make_safe!, or from a report of the event log made there (its tee, or the logger an @error reaches). A command started there would run with that deferral still in force, so one Ctrl-C would not stop it. make_safe! and on_abort call the instrument's drivers directly, and a reporter never runs a command, wherever it reports (this refusal checks only the deferred steps); an execute may run another command.

source
MicroscopeControl.Agent.Aborted — Type
Aborted()

Thrown by check_abort at a command's checkpoint when an abort was requested or STOP is latched, and by an after_execute method for an abort that arrived after the last checkpoint. On a serialized command the layer counts it as an abort, thrown or returned, whatever is_aborted says, and runs make_safe!. An unserialized command's result is not classified: an Aborted its execute throws is recorded :command_failed and reaches the caller, one it returns is recorded :command_done and returned, unless a counted on_abort overlapped the movement, when it is recorded :command_aborted and run_command throws Aborted; no make_safe! runs.

source
MicroscopeControl.Agent.Stopped — Type
Stopped(command)

command refused because STOP is latched; a person clears the latch. While it holds, no serialized command starts, and of the unserialized ones only the layer's :abort, its grant turning off, and reads (plans with no moves) run.

source
MicroscopeControl.Agent.OffThread — Type
OffThread(what)

what, a body-thread function, was called elsewhere. The body thread is thread 1 in a sticky task (the main task, an @async task, a Timer callback); a Threads.@spawn task never counts, even on thread 1, since it can move to another thread at its next yield.

source
MicroscopeControl.Agent.ArgError — Type
ArgError(kind, detail)

A command's arguments do not fit its declaration: kind is :unknown_command, :undeclared_keyword, :missing_keyword or :bad_args, and detail names the command, the keywords, or the value that did not convert.

source
MicroscopeControl.Agent.ConfirmRefused — Type
ConfirmRefused(id, why)

The operator's confirm or cancel of proposal id refused, for the reason why: id is not the pending proposal, it arrived too recently to have been read, or its plan changed since it was shown.

source

The event log

MicroscopeControl.Agent.EventLog — Type
EventLog()

An instrument's event log: events, a vector of (timestamp, kind, message) named tuples appended by log_event!, and tee, a Ref to an open IOStream (or nothing) that receives each event as one write_event_line line, flushed at once. The log is not thread-safe: only the body thread appends to it.

source
MicroscopeControl.Agent.log_event! — Function
log_event!(log::EventLog, kind::Symbol, message) -> nothing

Append one event, stamped now, and write it to the tee if one is set. Body thread only (thread 1, in a sticky task): the log is not thread-safe, so a call anywhere else throws OffThread and appends nothing.

source
MicroscopeControl.Agent.write_event_line — Function
write_event_line(io, seq::Int, e) -> nothing

Write event e (a (timestamp, kind, message) named tuple) as one line of four tab-separated fields: seq, the timestamp as yyyy-mm-ddTHH:MM:SS.sss, the kind, and the message escaped by escape_event.

source

Jobs

MicroscopeControl.Agent.CommandRunner — Type
CommandRunner()

One job slot on the body thread. busy is an Observable{Bool}, true while a job runs (a surface can listen to it); name, t0 and task describe the last job started, gen counts the jobs started, and once closed is set no job starts. Jobs start through start_job!.

source
MicroscopeControl.Agent.start_job! — Function
start_job!(runner, name::Symbol, job::Function) -> Union{Task,Symbol}

Run job() in a new task on the body thread, one job at a time: returns :closed once the runner is closed, :busy while a job runs, and otherwise the Task it created for this job, after yielding once so the job has started. A job that throws is logged with @error, never rethrown; runner.busy turns false when it ends either way. A busy listener that throws as the job starts rolls the start back (busy false again, nothing started, the listener's error rethrown); one that throws as it ends is logged and cannot keep the slot busy. Body thread only (OffThread elsewhere).

source
MicroscopeControl.Agent.JobRecord — Type
JobRecord(; id, name, args=Dict{Symbol,Any}(), t0=time(), t1=NaN, state=:running, message="")

One job's record, for status replies: its id, the command name and args, its start and end times t0 and t1 (NaN while it runs), its state (:running, then :done, :aborted or :failed) and a message saying why it failed or was aborted.

source

Internals

MicroscopeControl.Agent.StopLatch — Type
StopLatch()

The STOP latch every CommandCore holds: stopped, a sequentially consistent atomic safe from any thread. While it is set, no serialized command starts and check_abort throws, until a person clears it. Only the layer (which also latches it when make_safe! fails) and a person's clear of STOP write it; no instrument code does. An abort is not a flag of its own: it is part of the slot (_Run).

source
MicroscopeControl.Agent._End — Type
_End()

What a serialized command's end has done, for the layer's own bookkeeping: claimed (it holds the slot), admitted (it passed the STOP read, so its execute may have begun), attempted (make_safe! has been called), cleaned (and it returned), decided (the end has settled its cleanup: none was needed, make_safe! returned, or it did not and STOP is latched), aborted (the layer has classified what execute returned as aborted, which a later abnormal end keeps) and held, an interrupt thrown synchronously by code the end called, rethrown once the end is done.

source
MicroscopeControl.Agent._Flag — Type
_Flag(v)

A Bool safe from any thread, read f[] and written f[] = v, whose every load and store is sequentially consistent. A Threads.Atomic's are only acquire and release, which lets a store and a later load on one thread pass each other: two threads that each store one location and then load the other could both miss the other's store. Admission and STOP are exactly that pair.

source
MicroscopeControl.Agent._Run — Type
_Run(name, abort, ending, aborting, done)

The serialized command in a core's slot: its name; abort, set by an abort that reached it; ending, set at its end's ordering point, after which no abort reaches it; aborting, the number of the layer's :abort calls that reached it and are still counted (the API page's "STOP, abort and the body thread" gives the span); and done, set when its end has finished while such a call is counted. The slot is nothing when no serialized command runs and no counted :abort for one that has ended is outstanding (the API page defines the count), and every change to it is one sequentially consistent atomic step, so an abort and the command's end are ordered: the abort reaches the command before its end (which then makes the instrument safe, or latches STOP when make_safe! fails) or finds it ended, and an abort sent while nothing runs reaches nothing. No abort is ever left over for a later command, and the slot is freed only once both have finished, the command's end and every counted :abort for it, by whichever finishes last: an :abort's count undone while the command still runs leaves the slot held, so an abort's own action never reaches a later command.

source
MicroscopeControl.Agent._describe — Function

showerror's text for e, or its type's name when an instrument's showerror throws or is interrupted, so the failure is still recorded. An interrupt there is held in st (an _End) and rethrown when its end is done; with no st it is rethrown at once.

source
MicroscopeControl.Agent._test_point — Method
_test_point(step::Symbol)

A point in the layer's own steps where another thread could act, or where a forced interrupt (Julia's repeated Ctrl-C, which passes the deferral) could land: :claimed (after admission's claim, before its STOP read), :cleanup (before an end calls make_safe!), :latch (after a make_safe! threw, before STOP is latched), :decided (after a normal end decided its cleanup, before its terminal event), :release (before the release step), :counted (after the layer's :abort counted its on_abort in the slot), :returned (after on_abort returned, before the layer reads what it returned), :abort_caught (as the :abort's catch is entered), :abort_admitted (inside the function that makes the :abort's final admission check, after the check), :stop_read (in _check_stopped, immediately before it reads the STOP latch), :admitted (after an unserialized command's final admission checks), :arguments (before its arguments are prepared), :moved (after its execute ended, before its overlap decision and terminal record) and :flag_set (inside the function that writes the per-task flag ReentryRefused reads, after the write). A no-op, inlined away; the tests redefine it to act there.

source