Vole architecture¶
This page documents Vole's internal design decisions and component interactions for developers working on or extending the module.
Why Vole exists¶
Vole decouples the Formula Engine from direct dependencies on Hare (live broker) and Mole (archiver proxy). Without Vole, the Formula Engine would need to:
- Query Mole on every formula evaluation (network round-trip, latency)
- Maintain its own subscription management for live data
- Handle the complexity of merging live and historical data inline
Vole provides a single in-memory layer that:
- Absorbs live data from Hare continuously
- Seeds from Mole on first access (auto-provisioning)
- Serves the Formula Engine with sub-millisecond reads from memory
- Manages memory bounds and eviction independently
This separation means the Formula Engine only knows about the DataSource protocol — it doesn't know or care whether data came from a live broker, an archiver, or both.
Ring buffer model¶
PerPVRing¶
Each PV gets a dedicated PerPVRing instance — a bounded FIFO buffer backed by a sorted list of StoredSample namedtuples:
StoredSample(ts_ns: int, value: Any, severity: AlarmSeverity, source: "live" | "archive")
Key behaviors:
- Capacity: Hard ceiling at
max_points; oldest samples dropped on overflow - Ordering: Strict monotonic timestamps;
append()rejects out-of-order samples (returnsFalse) - Seeding:
seed()bulk-inserts archive samples, deduplicating against existing live data (live wins at same timestamp, archive samples at or after earliest live sample are skipped) - Slicing:
slice(t0_ns, t1_ns)returns samples in the[t0, t1]inclusive range using binary search - Pre-window lookup:
sample_before(ts_ns)enables forward-fill alignment by finding the last sample before a given time
PVStore¶
PVStore manages the collection of rings with lifecycle and concurrency control:
- Lazy creation:
get_or_create()instantiates rings on demand with optional per-PV capacity overrides - Per-PV locks: Each PV has its own
asyncio.Lockfor concurrent access safety - LRU tracking:
lru_candidates()returns rings sorted by last access time for eviction decisions - Stats aggregation:
total_bytes,total_points,ring_countfor introspection
Eviction policy¶
Vole uses a two-level capacity model:
- Per-ring cap (
max_points): FIFO within the ring — oldest samples silently drop - Global byte cap (
global_bytes_max): LRU across all rings — entire rings are removed
LRU eviction algorithm¶
When total_bytes > global_bytes_max:
1. Sort all rings by last_access_ns ascending (oldest access first)
2. Drop the least-recently-accessed ring entirely
3. Call on_evict callback (unsubscribes from Hare)
4. Repeat until total_bytes <= global_bytes_max
Eviction removes whole rings, not individual samples. This is intentional — partial eviction would leave fragmented data that produces misleading formula results. A fully evicted PV can be cleanly re-provisioned later.
Access time tracking¶
Both reads and writes update last_access_ns:
append()andseed()touch the ring (write path)read_window()andread_aligned()touch the ring (read path)
This means actively-queried PVs stay warm even if they receive data infrequently.
ChangeNotifier pattern¶
ChangeNotifier implements push-based pub/sub for PV data changes:
BufferService.append(pv, sample)
│
├── Appends to ring
└── notifier.notify(pv)
│
├── asyncio.create_task(callback_1(pv))
├── asyncio.create_task(callback_2(pv))
└── ... (fire-and-forget)
Design decisions:
- Fire-and-forget: Callbacks are launched as independent asyncio tasks. Failures are logged but don't block the data path or affect other callbacks.
- Unsubscribe function:
subscribe()returns a callable that removes the callback. This avoids the need for callback identity tracking by callers. - Single PV granularity: Subscriptions are per-PV, not per-ring or global. The Formula Engine registers one callback per PV per shared eval loop.
DataSource protocol boundary¶
The Formula Engine defines a DataSource protocol (port) that abstracts data access. Vole implements it via VoleDataSource:
class DataSource(Protocol):
async def read_aligned(pvs, t0_ns, t1_ns, *, align, index, grid_dt_ns) -> AlignedWindow
async def read_latest(pv) -> Sample | None
async def read_binned(pvs, t0_ns, t1_ns, *, target_buckets) -> AlignedWindow
Auto-provisioning logic¶
VoleDataSource intercepts PVNotBuffered errors and transparently provisions:
read_aligned(pvs=[...])
│
├── Try BufferService.read_aligned()
│ └── Raises PVNotBuffered for unknown PV
│
├── For each missing PV:
│ ├── Acquire per-PV lock (prevent race on concurrent provisions)
│ ├── fetch_window(pv, t0_ns, t1_ns) --> list[Sample] from Mole
│ ├── buffer_service.seed(pv, samples)
│ └── subscribe_live([pv]) --> register with Hare
│
└── Retry BufferService.read_aligned()
Dependencies are injected at construction:
fetch_window— callback to Mole gateway for historical datafetch_binned— callback for pre-aggregated binned datasubscribe_live— callback to Hare for live subscriptionclock— injectable for testing (defaults totime.time_ns)
Concurrency model¶
Per-PV async locks¶
Every PV in PVStore has a dedicated asyncio.Lock. Operations that mutate a ring (append, seed, drop) acquire the lock for that PV. This allows concurrent operations on different PVs without contention.
Alphabetical lock acquisition¶
Multi-PV reads (read_aligned) must acquire locks for all requested PVs. To prevent deadlocks, locks are always acquired in alphabetical order by PV name:
sorted_pvs = sorted(pvs)
for pv in sorted_pvs:
await store.lock_for(pv).acquire()
This guarantees a consistent lock ordering regardless of the order PVs appear in the request.
HareIngestService¶
HareIngestService bridges Hare's ClientChannel protocol to Vole's buffer:
Hare PVBroker
│
└── send_json(frame) --> VoleChannel
│
├── "initial" frame: bulk seed of current values
└── "diff" frame: incremental updates
│
└── For each PV in frame:
├── Strip ca:// / pva:// prefix
├── Convert wire dict to Sample
└── buffer_service.append(pv, sample)
Key behaviors:
- Implements Hare's
ClientChannelprotocol via the innerVoleChannelclass - Normalizes PV names by stripping protocol prefixes (
ca://,pva://) - Converts Hare's
PVValuewire format (dict withvalue,timestamp,severityfields) to Canopy'sSampledomain object - Gracefully degrades if Hare is not available (import wrapped in try/except)
Module reference¶
Gateway¶
canopy.vole.gateway
¶
Public surface of the Vole module for in-process callers.
Other Canopy modules import only from this file; the rest of canopy.vole.*
is private implementation.
watermark_ns()
¶
Receive time of the newest Hare flush ingest has fully applied; 0 without ingest.
pin(pvs, holder)
¶
Keep these PVs' rings and ingest alive for holder (a live table eval).
unpin(holder)
async
¶
Drop every pin of holder; a deactivation expiry skipped while pinned is re-armed.
ensure_capacity(pv, max_points=None)
¶
Grow-only: a table input's ring holds at least settle_depth samples.
subscribe_live(pvs)
async
¶
Subscribe Vole to live updates from Hare for these PVs.
subscribe_latest(pvs)
async
¶
Subscribe to live updates with a size-1 ring per PV (latest value only).
Used by scalar formula subscriptions that only need read_latest —
avoids accumulating a full ring buffer per PV. Never lowers an existing
ring's capacity. The ring is keyed by the canonical name, the key ingest
appends under, so a ca://X binding seeds ring X and no orphan.
unsubscribe_live(pvs)
async
¶
Unsubscribe from live updates for these PVs.
on_change(pv, callback)
¶
Subscribe to notifications when a PV ring receives new data.
Returns an unsubscribe function. Used by the Formula Engine to trigger re-evaluation.
Services¶
BufferService¶
canopy.vole.services.buffer_service
¶
Coordinates store/alignment/eviction; the implementation behind the gateway.
BufferService(store, alignment, eviction, clock, config, notifier=None)
¶
Orchestrates store, alignment, and eviction for the Vole buffer.
append(pv, sample, *, recv_ns=0, after_connect=False)
async
¶
Append a live sample to the PV's ring.
Under unrelievable memory pressure an append to an unpinned ring is refused; a pinned ring (bounded by its own ceiling, shrunk by eviction) keeps ingesting, since its subscription is the reason it is pinned.
seed(pv, samples, *, max_points=None)
async
¶
Bulk insert historical samples; returns count actually stored.
drop(pv)
async
¶
Remove a PV's ring entirely. Idempotent.
ensure_capacity(pv, max_points=None)
¶
Grow pv's ring to at least max_points (default settle_depth); never shrinks.
defer_provision(pv, until_ns)
¶
Record that a failed provision of pv may be retried after until_ns.
Kept on the ring when there is one, else in a side table (a refused PV has no ring yet) so a PV the archiver refuses costs one Mole call per period.
ring_slice(pv, ts_from_ns)
¶
One synchronous copy of the samples with ts >= ts_from_ns plus the outage intervals.
in_open_outage(pv)
¶
True while pv's connection is down (an outage opened and not yet closed).
open_outage(pv, now_ns)
¶
Open an outage on pv and tell its subscribers, so live formulas re-evaluate now.
A disconnect stores no sample, so without this notification a formula would keep its last value until the PV came back.
close_outage(pv, now_ns)
¶
Close pv's open outage and tell its subscribers.
read_window(pv, t0_ns, t1_ns, *, align='last', max_points=None)
async
¶
Single-PV window read with optional decimation.
read_aligned(pvs, t0_ns, t1_ns, *, align='last', index='union', grid_dt_ns=None)
async
¶
Multi-PV aligned read.
read_latest(pv)
async
¶
Return the most recent sample for a PV, or None.
EvictionService¶
canopy.vole.services.eviction_service
¶
EvictionService(store, config, on_evict=None)
¶
Memory pressure detection and LRU eviction.
Unpinned rings are dropped whole, LRU first. When only pinned rings remain
over the ceiling, the largest ones are shrunk to settle_depth instead of
dropped, so the ingest subscription that is the reason for the pin survives
and Vole stays bounded. A shrink forgets the ring's provisioned history.
evict_lru(*, target_bytes=None)
async
¶
Drop unpinned rings by LRU, then shrink pinned ones, until under ceiling.
Returns the PV names dropped. Stops when nothing is left to drop or shrink.
ChangeNotifier¶
canopy.vole.services.notifier
¶
Change-notification pub/sub for Vole ring buffers.
When a ring receives new data via append(), the notifier fires registered callbacks so downstream consumers (Formula Engine) can react without polling.
Buffer internals¶
PerPVRing¶
canopy.vole.buffer.ring
¶
StoredSample
¶
Bases: NamedTuple
PerPVRing(*, max_points)
¶
Bounded, time-ordered, append-only ring for one PV.
Backed by a sorted list with bisect for O(log N) lookups. FIFO eviction enforced on every mutation when ceilings are exceeded.
Also carries the per-PV state that lives and dies with the ring: whether its archive history has been provisioned (and when a failed attempt may be retried), and the outage intervals ingest recorded on the receive clock.
outages
property
¶
Closed intervals (start_ns, end_ns) plus the open one as (start_ns, None).
outage_open
property
¶
True while an outage is open (the PV's connection is down now).
append(sample, now_ns)
¶
Append one sample. Returns False if out-of-order (dropped).
seed(samples, now_ns)
¶
Bulk insert sorted archive samples. Returns count actually stored.
Samples whose ts_ns overlaps existing live data are discarded (live wins).
slice(t0_ns, t1_ns)
¶
Return samples in [t0_ns, t1_ns] inclusive.
slice_from(ts_from_ns)
¶
One O(k) copy of the samples with ts_ns >= ts_from_ns.
sample_before(ts_ns)
¶
Return the last sample with ts_ns < given ts.
last_at_or_before(ts_ns)
¶
Return the last sample with ts_ns <= given ts.
samples_since(recv_after_ns)
¶
Every live sample received after recv_after_ns, oldest first.
Scans back from the newest sample and stops at the first one received at or before the argument -- archive-seeded samples carry 0, so the scan is O(new samples) and never walks the seeded history.
ensure_capacity(max_points)
¶
Grow-only: never lowers an existing ceiling.
shrink_to(max_points)
¶
Lower the ceiling, trim to the newest max_points and forget the provisioned history.
Returns the number of samples trimmed. Used only under memory pressure.
PVStore¶
canopy.vole.buffer.store
¶
PVStore(config)
¶
Registry of per-PV rings with lifecycle management, plus the pin registry.
A pin names a holder (a live table eval) that needs the PV's ring and ingest to stay alive: pinned rings are skipped by LRU eviction and by grace teardown. Pins are keyed by the stripped PV name, the one grace and ingest use.
ensure_capacity(pv, max_points)
¶
Grow pv's ring to at least max_points; a missing ring is created at config.max_points.
unpin(holder)
¶
Remove every pin of holder; returns the PVs no longer pinned by anyone.
open_outage(pv, now_ns)
¶
Open an outage on pv's ring, or hold it until the ring is created.
in_open_outage(pv)
¶
True while pv has an open outage, on its ring or still pending (no ring yet).
close_outage(pv, now_ns)
¶
Close pv's open outage.
An outage opened before the PV had a ring creates the ring here (with the interval) since the reconnect sample that closes it is about to land in that ring anyway. A ring dropped (grace, eviction) mid-outage loses the interval with the rest of its state.
lru_candidates()
¶
Unpinned rings sorted by last_access_ns ascending (LRU first).
pinned_candidates()
¶
Pinned rings, largest first.
DataSource adapter¶
canopy.vole.adapter
¶
DataSource adapter: bridges Vole's BufferService to the Formula Engine's DataSource protocol.
The Formula Engine imports this class; it is constructed in formula_engine_lifespan() and injected into FormulaService. The Formula Engine never imports canopy.vole.gateway directly.
When a PV is not yet buffered, the adapter auto-provisions it: fetches historical data from Mole and subscribes to live updates via Hare.
VoleDataSource(buffer_service, fetch_window=None, fetch_binned=None, subscribe_live=None, clock=None, is_live_fed=None)
¶
Implements the Formula Engine's DataSource protocol and the sample-record port over BufferService.
read_aligned(history) provisions every requested PV not yet provisioned; see_provision.read_latestof a live-fed name (is_live_fed) reads the ring as it is and never provisions: an archived value is never served as live.last_at_or_before,samples_sinceandring_sliceare the synchronous reads the Formula Engine's table store makes; tables never provision.
in_open_outage(name)
¶
True while name's Hare connection is down, whether or not it has a ring yet.