Squirrel architecture¶
This page documents Squirrel's internal design decisions for developers working on or extending the module. For what Squirrel does and how to use it, see the Squirrel guide.
Layout¶
| Package | Role |
|---|---|
api/v1/ |
HTTP routes. They validate input, call a service, and enqueue jobs |
services/ |
Domain logic: SnapshotService, PvService, TagService |
data/ |
SQLAlchemy models (the squirrel Postgres schema) and repositories |
adapters/epics_io.py |
EpicsIO, batch EPICS reads and writes over the shared connector |
restore_hooks/ |
The RestoreHook interface, the built-in hooks, and the registry |
tasks.py |
The Arq tasks the worker runs for capture and restore |
gateway.py |
The read-only surface other Canopy modules may import |
Services own no transaction. A request commits through the request session,
and a worker task commits through its own session_scope, so each caller
decides what is atomic.
Why capture and restore are jobs¶
Both touch every PV in a snapshot, which can mean thousands of EPICS operations, so they take longer than a request should. They also need the EPICS connector, which only the worker builds. So the route enqueues an Arq job and returns its id, and the worker does the work and reports progress to Redis. The Jobs module serves that progress to clients without knowing anything about Squirrel.
Everything else (listing, editing, comparing) runs in the request.
Capture¶
SnapshotService.create_snapshot is the hot path.
- One read per address. Only setpoint addresses are unique; several PVs can share a readback. Capture maps each address to the list of PVs using it and reads it once, instead of once per PV.
- A failed read never fails the batch.
EpicsIOturns any per-PV exception into a disconnected value, and capture stores no value for it. The snapshot keeps a row for the PV either way. - Bulk insert with
COPY. Values are written with PostgreSQLCOPYon the session's own connection, in the same transaction as the snapshot row, so a snapshot is saved complete or not at all, and a retried job never finds a half-written one. - Values are JSON blobs. Each setpoint and readback reading is stored as
JSONB (
value,status,severity,timestamp,units,precision), so more metadata can be captured later without a migration. Units, precision and limits come from a separate EPICS describe call, so v1 leaves them empty.
Restore¶
SnapshotService.restore_snapshot plans everything before writing anything:
- Build the write set: saved setpoints only, never readbacks.
- Ask every hook for its extra writes. A
RestoreHookErrorremoves that PV from the write set, so a PV a hook can't handle is never partly restored. - Write the setpoints, then each hook's writes, as separate batches.
Each batch is a RestorePhase, reported to the job's phases. A failure
row's phase names the batch that failed, and a PV that fails in one phase
is skipped by later ones. A restore reads the database but never writes to
it.
Paging¶
The snapshot list and the paged PV search use keyset paging: each page continues after the last row of the previous one instead of skipping a count of rows, so rows created or deleted between pages can't make a later page repeat or skip one.
- Snapshots sort by
(created_at, id), newest first. The continuation token is that pair, base64-encoded. A token that doesn't decode is rejected with400rather than reaching the database. - PVs sort by
id, and the token is the last id.
GET /pvs/search uses offset paging instead, for clients that need page
numbers.
PV identity¶
A PV is identified by its first address in the order setpoint, readback,
config. Only setpoint_address has a unique constraint in the database. The
rest of the rule is enforced in PvService, so that a PV with a setpoint
never collides with a readback-only PV that shares its readback.
Restore hooks across processes¶
Hooks are resolved from CANOPY_SQUIRREL__RESTORE_HOOKS separately in each
process. Restores run in the worker, but the API is what operators can
query. So the worker publishes its resolved hooks to Redis when it starts,
and GET /squirrel/v1/health/restore-hooks shows that report next to the
API's own view. The report has no expiry: each worker start replaces it, and
it carries the time and host it came from, so a stale one can be recognised.
Module reference¶
Gateway¶
canopy.squirrel.gateway
¶
Public surface of the Squirrel module for in-process callers.
Other Canopy modules import only from this file; the rest of canopy.squirrel.*
is private implementation. Unlike formula_engine/converter — whose gateways hand back a
service singleton bound at startup — Squirrel's services are request/session
scoped (there is nothing to bind), so each call here opens a short-lived read
session via session_scope and builds the service from it.
Today nothing imports Squirrel across a module boundary: the frontend talks to it
over HTTP at /squirrel/v1. This file defines the intended public read surface
now so the first in-process consumer (and the boundary linters on the roadmap) has
one stable entry point instead of reaching into the internals.
get_snapshot(snapshot_id, *, limit=None, offset=0)
async
¶
Return a stored snapshot with its values (optionally paginated), or None if absent.
Read-only: the snapshot is loaded and mapped to a DTO inside a short-lived session that is disposed before returning.
get_pv(pv_id)
async
¶
Return a registered PV by id, or None if no such PV. Read-only.
Services¶
SnapshotService¶
canopy.squirrel.services.snapshot_service
¶
Snapshot domain service: create / restore / compare + listing.
SnapshotService(session, epics_io=None, restore_hooks=None, facility_scope=None)
¶
Snapshot operations with EPICS integration. Owns no transaction — the caller
(request dep or worker session_scope) commits.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
session
|
AsyncSession
|
The caller's session; the service owns no transaction. |
required |
epics_io
|
EpicsIO | None
|
Required only for create/restore (run in the worker, which builds the connector). The read endpoints construct the service without it. |
None
|
restore_hooks
|
list[RestoreHook] | None
|
Hooks to run during a restore. |
None
|
facility_scope
|
set[str] | None
|
The calling key's granted facility ids, hierarchy-expanded, resolved per
request by |
None
|
list_snapshots(title=None, tag_ids=None, start=None, end=None, page_size=100, continuation_token=None, facility=None)
async
¶
List snapshots one keyset page at a time, newest first, optionally filtered.
Each page continues from the sort position the previous page ended on, so snapshots created or deleted between requests cannot make a later page repeat or skip a row the way an offset would.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
title
|
str | None
|
Case-insensitive substring match against the snapshot title. |
None
|
tag_ids
|
list[str] | None
|
Tag IDs; a snapshot matches when it holds a PV carrying any of them. |
None
|
start
|
datetime | None
|
Lower bound on creation time, inclusive. Converted with |
None
|
end
|
datetime | None
|
Upper bound on creation time, inclusive. Converted the same way as |
None
|
page_size
|
int
|
Maximum number of summaries on the page. |
100
|
continuation_token
|
str | None
|
Token from the previous page's result; |
None
|
facility
|
str | None
|
A facility slug to additionally narrow the search to, resolved against the
calling key's own facility scope by |
None
|
Returns:
| Type | Description |
|---|---|
PagedResult[SnapshotSummaryDTO]
|
The page's summaries, the token for the next page ( |
Raises:
| Type | Description |
|---|---|
BadRequest
|
When a bound falls outside |
FacilityNotFound
|
When |
snapshot_exists(snapshot_id)
async
¶
Existence check used before enqueueing a restore. Gated on the snapshot's own
facility, the same rule as get_by_id: a snapshot the key can't view doesn't
exist for it, so it can't be restored either.
get_by_id(snapshot_id, limit=None, offset=0)
async
¶
Get a snapshot with its values (values optionally paginated).
update_snapshot_metadata(snapshot_id, title=None, description=None)
async
¶
Update a snapshot's title and/or description.
create_snapshot(data, created_by=None, progress_callback=None, facility_id=None, pv_cache=None)
async
¶
Create a snapshot by reading PVs from EPICS (the hot read path).
A facility snapshot captures only the PVs assigned to that facility or one of its descendants; unassigned PVs are left out. A snapshot with no facility captures every registered PV.
facility_id lets a caller that already resolved data.facility pass the id
straight through. The route does that — it has to resolve the slug anyway to gate
the write, and passing the id over the job queue avoids re-resolving it.
With pv_cache, values the worker's PV cache can vouch for are taken from it
and only the rest are read live. The stored snapshot has the same shape either
way, but a cached value is the PV's last monitor update, which can trail a live
read by up to the record's monitor deadband (MDEL).
plan_restore(snapshot_id, pv_ids=None)
async
¶
Narrow a restore's write set to what the calling key may actually write.
Returns (pv_ids_to_restore, skipped_pv_ids), where a None first element
keeps the "restore everything in the snapshot" meaning pv_ids=None already has.
This runs in the route, not the worker: no caller identity crosses the Arq boundary, so the write set has to be narrowed before the job is queued.
The route has already gated on the snapshot's own facility, and capture only takes that facility's PVs, so this normally keeps everything. It catches PVs whose facility assignment changed after capture, and snapshots taken before capture was facility-scoped.
restore_snapshot(snapshot_id, request=None, progress_callback=None)
async
¶
Restore a snapshot's setpoints to EPICS (the hot write path).
Setpoints only, never readbacks. Every hook derives its extra writes up front,
before anything is written; a hook error drops that PV from the write set so the
system is never left half-restored. The setpoints go out as one batch, then each
hook's extras as a batch of its own, in configured order, restricted to the PVs
whose setpoint and earlier hook writes all succeeded. A failed extra write marks
its primary address failed, with phase naming that hook, and later hooks skip
the PV.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
snapshot_id
|
str
|
The snapshot to restore. |
required |
request
|
RestoreRequestDTO | None
|
Restores only |
None
|
progress_callback
|
Callable | None
|
Async sink called as |
None
|
Returns:
| Type | Description |
|---|---|
RestoreResultDTO
|
Totals plus a |
compare_snapshots(snapshot1_id, snapshot2_id)
async
¶
Compare two stored snapshots (setpoint + readback) under each PV's tolerances.
Loads every value row for both snapshots into memory (no pagination) and runs on the request path, so comparing two very large (~100k-PV) snapshots is a sizeable synchronous allocation. Fine at current scale; a known v1 limit to revisit (stream/paginate the diff) if snapshot sizes grow.
delete_snapshot(snapshot_id)
async
¶
Delete a snapshot and all its values (DB cascade).
RestorePhase(name, total, current=0, status='pending', failures=0)
dataclass
¶
One stage of a restore: the setpoint writes, or one restore hook's derived writes.
Reported to the job poller as a JobPhaseDTO, beside the restore-wide percent.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
str
|
|
total |
int
|
Writes the phase will attempt. A hook phase starts at every write it derived and drops to the writes it actually attempts once it starts, leaving out PVs whose setpoint or an earlier hook failed. |
current |
int
|
Writes done so far. |
status |
{'pending', 'running', 'completed', 'skipped'}
|
|
failures |
int
|
PVs that failed in this phase, matching the failure rows with this |
PvService¶
canopy.squirrel.services.pv_service
¶
PV registry + meta-PV domain service.
PvService(session, facility_scope=None)
¶
PV registry + meta-PV management. Owns no transaction — the caller commits.
unrestricted, which is what the worker gets.
create(data)
async
¶
Register a single PV.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
NewPVElementDTO
|
Wire payload for the new PV. |
required |
Returns:
| Type | Description |
|---|---|
PVElementDTO
|
The created PV. |
Raises:
| Type | Description |
|---|---|
BadRequest
|
If no address is given, or a tag ID is unknown. |
PvAlreadyExists
|
If another PV already holds the same identifying address. |
create_many(data_list)
async
¶
Register many PVs in one import.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data_list
|
list[NewPVElementDTO]
|
Wire payloads for the PVs to import. |
required |
Returns:
| Type | Description |
|---|---|
list[PVElementDTO]
|
The created PVs, in input order. |
Raises:
| Type | Description |
|---|---|
BadRequest
|
If a row has no address, a tag ID is unknown, or two rows in the import share an identifying address. |
PvAlreadyExists
|
If a row's identifying address is already held by a registered PV. |
import_many(data_list, on_conflict)
async
¶
Import many PVs, skipping or updating rows whose PV is already registered.
POST /v1/pvs/import. create_many (POST /v1/pvs/multi) refuses an import
with any registered row; this skips or updates those rows instead.
A row matches a registered PV by the same identity rule as create_many (see
_identity). Rows that match nothing are created exactly as create_many
creates them. Duplicate identities within the import are still a BadRequest.
Every row is facility-gated as a new row before anything is looked up, exactly as
in create_many, so whether a refused row's address is registered never shows.
A skipped row's response entry only echoes the request (row, identity kind and
address), which reveals no more than create_many's PvAlreadyExists does.
With on_conflict="update", a matched PV is changed the way update changes
one: only fields the row explicitly provides with a non-null value are applied,
tags replaces the tag list, and addresses are never changed (a differing
non-identifying address is reported in address_mismatches and kept as stored).
Facilities are never changed either: a matched row's facilities only has to
pass the create gate, and the PV keeps its assignments, which change through
update alone. A client may fill a default facility into every row (a CSV
import does, for rows that name none), and the gate needs a facility on every row
from a restricted key, so applying them would move or strip PVs no row meant to
reassign. The key must be allowed to write every matched PV (_can_write), or
the whole import is refused. The refusal names the rows, but not the facilities
of a PV the key cannot write. Unlike a created row, an update row naming an
unknown tag ID is refused rather than having that tag dropped, since dropping it
would remove a stored tag.
Nothing is written until every check has passed, and all of it happens in the caller's transaction.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data_list
|
list[NewPVElementDTO]
|
Wire payloads for the PVs to import. |
required |
on_conflict
|
('skip', 'update')
|
What to do with a row whose PV is registered. |
"skip"
|
Returns:
| Type | Description |
|---|---|
PVImportResultDTO
|
Created, updated and skipped rows, and address mismatches, each in input order. |
Raises:
| Type | Description |
|---|---|
BadRequest
|
If a row has no address, two rows share an identifying address, or an update row names an unknown tag ID. |
InsufficientFacilityAccess
|
If a row names no facility the key holds, or ( |
PvAlreadyExists
|
If a concurrent write registers one of the new rows' addresses first. |
search_filtered(q=None, devices=None, tag_ids=None, limit=100, offset=0, facility=None)
async
¶
Offset-paginated, server-side filtered search (the source's live-value join is dropped).
get_all_devices()
async
¶
All distinct device names, for the frontend's device filter.
Restore hooks¶
canopy.squirrel.restore_hooks.base
¶
Plugin for site-specific writes that must accompany a snapshot restore.
Some labs need extra puts beyond the snapshot's setpoint write — e.g. magnets that
require a TRIM put to a CTRL PV before they physically move. A lab implements
:class:RestoreHook, registers the subclass in
canopy.squirrel.restore_hooks.registry.RESTORE_HOOK_PROVIDERS, and selects it via
CANOPY_SQUIRREL__RESTORE_HOOKS — a comma-separated list of provider keys, each
applied in the order given.
RestoreHook
¶
Bases: ABC
Abstract base class for restore-time hooks.
derive_extra_writes(address, value)
abstractmethod
¶
Return additional puts to send after the snapshot's write to address succeeds.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
address
|
str
|
The setpoint PV address being restored. |
required |
value
|
Any
|
The value the restore writes to |
required |
Returns:
| Type | Description |
|---|---|
list[tuple[str, Any]]
|
Ordered |
Raises:
| Type | Description |
|---|---|
RestoreHookError
|
When the hook recognises the address but cannot derive the extras (e.g. a malformed name). The restore then treats this PV as failed without attempting the primary write. |
RestoreHookError
¶
Bases: Exception
Raised by a hook when an address it recognises is malformed.
Treated by SnapshotService.restore_snapshot as a per-PV failure: the primary
setpoint write is skipped and the error is surfaced in the restore result's
failures (so the system is never left in an inconsistent state).
canopy.squirrel.restore_hooks.registry
¶
Restore-hook plugin registry.
get_restore_hooks returns the hooks named by CANOPY_SQUIRREL__RESTORE_HOOKS
(comma-separated provider keys, applied in the order given) — an empty list when
nothing is selected. The module:Class dotted-path escape hatch for out-of-tree
lab hooks is a Phase-2 addition.
RESTORE_HOOK_PROVIDERS = {'magnet_trim': _build_magnet_trim, 'write_to_con': _build_write_to_con}
module-attribute
¶
get_restore_hooks()
¶
Return the configured hook singletons, built once per provider list.
Returns:
| Type | Description |
|---|---|
list[RestoreHook]
|
Hook instances in configured order. Unregistered provider keys are logged and skipped, so a typo disables only that hook. Empty when nothing is configured. |
describe_restore_hooks()
¶
Report configured versus registered restore hooks, for diagnostics.
Read-only: builds and caches nothing, so an operator can confirm that the
CANOPY_SQUIRREL__RESTORE_HOOKS they set reached the process and resolved to
known providers without triggering a restore.
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
|
EPICS adapter¶
canopy.squirrel.adapters.epics_io
¶
Squirrel's EPICS I/O adapter.
Bridges the squirrel domain (batch-native and metadata-rich — it speaks
get_many/put_many returning EpicsValue / (ok, err)) to Canopy's
per-PV canopy.epics connector (get() -> PVValue / put(pv, value)).
Why this layer exists: snapshot_service was written against a batch EPICS
service. Rather than rewrite it, we rebuild that batch surface over the connector —
fanning out per-PV get/put with bounded concurrency, reporting chunked
progress, and re-normalizing per-PV exceptions into the dict contracts the
create/restore code consumes (a read failure never breaks the batch).
A single PVValue read carries value, alarm severity, alarm status, timestamp and
connection state. Units, precision and the control limits live in PVMeta via
describe(), so v1 snapshots leave them None; since they live inside the
JSONB value blob, enriching later needs no migration.
EpicsIO(connector, *, concurrency=64, chunk_size=500, timeout=None)
¶
Batch EPICS reads/writes over a canopy.epics connector.
At most concurrency reads or writes are in flight at once. Reads run as one
pool, refilled as each read finishes; writes go chunk by chunk under a semaphore,
each chunk finishing before the next starts. Progress is reported every
chunk_size items either way. The connector is shared and already started
(typically the one the worker builds at startup and stashes in the Arq context).
get_many_with_progress(pv_names, progress_callback=None)
async
¶
Read every PV, at most concurrency at a time.
All reads share one pool rather than running chunk by chunk, so a PV that only answers with a timeout (disconnected, retired, misspelled) holds up its own slot and nothing else. Chunked, every chunk waited for its slowest read, and a few dead PVs scattered through a large facility cost a full timeout per chunk.
progress_callback is awaited after every chunk_size completed reads and
once more at the end, in order, from this coroutine alone. If this coroutine is
cancelled (a job timing out), the reads still in flight are cancelled with it.
EpicsValue(value, status=None, severity=None, timestamp=None, units=None, precision=None, upper_ctrl_limit=None, lower_ctrl_limit=None, connected=True, error=None)
dataclass
¶
A single PV read, in the shape the snapshot domain consumes.
Ported from react-squirrel-backend's epics_types.EpicsValue. status
carries the EPICS alarm status code that accompanies severity, and is None
when the backend supplies none. units, precision and the control limits are
part of the contract but stay None in v1, since a single get() doesn't carry
them — they live in PVMeta behind a describe() pass. timestamp is a
timezone-aware datetime (never a float), avoiding the source's latent
.isoformat()-on-float bug on the CA path.
Configuration¶
canopy.squirrel.config
¶
Squirrel module configuration.
Sourced from env vars with prefix CANOPY_SQUIRREL__ (nested delimiter __),
mirroring the other Canopy modules. A fresh instance per get_squirrel_config()
call (no caching) so tests can vary the environment freely.
SquirrelConfig
¶
Bases: BaseSettings
Squirrel's environment-sourced settings.
restore_hooks_list
property
¶
Split restore_hooks into provider keys.
Returns:
| Type | Description |
|---|---|
list[str]
|
The comma-separated entries, stripped of surrounding whitespace, with empty entries dropped and configured order preserved. |