Skip to main content

epics_base_rs/server/record/
record_instance.rs

1use std::collections::HashMap;
2use std::sync::Arc;
3use std::sync::Mutex as StdMutex;
4use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
5
6use crate::error::{CaError, CaResult};
7use crate::server::event_queue::{EventReader, EventUser};
8use crate::server::pv::{MonitorEvent, Subscriber};
9use crate::server::recgbl::EventMask;
10use crate::server::snapshot::{
11    ControlInfo, DisplayInfo, EnumInfo, EnumStringForm, PropertySupport,
12};
13use crate::types::{DbFieldType, EpicsValue, PvString, c_parse};
14
15use super::alarm::{AlarmSeverity, AnalogAlarmConfig};
16use super::common_fields::CommonFields;
17use super::link::{
18    ParsedLink, out_link_discards_cp, parse_forward_link_v2, parse_link_v2, parse_output_link_v2,
19};
20use super::menu_choices::MenuBound;
21use super::record_trait::{
22    AuxPostMask, CommonFieldPutResult, FieldDeclaration, FieldDesc, ProcessSnapshot, Record,
23    RecordProcessResult, SubroutineFn,
24};
25use super::scan::{ScanType, SimModeScan};
26
27/// Every client-visible `special(SPC_NOMOD)` field of `dbCommon.dbd:13-190`.
28///
29/// These are common fields — no record's `field_list` declares them — so the
30/// declaration names them here. The remaining `SPC_NOMOD` entries in
31/// `dbCommon.dbd` (MLOK, MLIS, BKLNK, ASP, PPN, PPNR, SPVT, RSET, DSET, DPVT,
32/// RDES, LSET, BKPT) are `DBF_NOACCESS`: they have no field API in this port at
33/// all, and C refuses them one level earlier, at `dbNameToAddr`.
34///
35/// TIME is `DBF_NOACCESS` in C too (`dbpf REC.TIME` → "failed"), but this port
36/// resolves `.TIME`, so the declaration must cover it.
37///
38/// Read only through [`RecordInstance::is_no_mod`].
39const DBCOMMON_NOMOD: &[&str] = &[
40    "NAME", "STAT", "SEVR", "AMSG", "NSTA", "NSEV", "NAMSG", "ACKS", "ACKT", "LCNT", "PACT",
41    "PUTF", "RPRO", "TIME", "UTAG",
42];
43
44/// Put-notify completion wait-set — the C `dbNotify.c` `processNotify`
45/// waitList analogue (`dbNotifyAdd` / `dbNotifyCompletion`).
46///
47/// A `ca_put_callback` / WRITE_NOTIFY completion must fire only after the
48/// originating (put-target) record AND every record reached through its
49/// FLNK / OUT / process-action dispatch chain (synchronous *or* async)
50/// has finished processing. A single wait-set owns the completion
51/// oneshot; only it fires, and only when the last chain member leaves.
52///
53/// Counting convention: [`Self::new`] arms `pending = 1` for the
54/// originating record (which always joins). Every additional PP target
55/// that will process under the active notify [`Self::enter`]s on join
56/// (C `dbNotifyAdd`), and every record [`Self::leave`]s when its
57/// processing completes (C `dbNotifyCompletion`). The oneshot fires on
58/// the `leave` that drops `pending` to zero.
59pub struct NotifyWaitSet {
60    pending: AtomicUsize,
61    tx: StdMutex<Option<crate::runtime::sync::oneshot::Sender<()>>>,
62}
63
64impl NotifyWaitSet {
65    /// Arm a wait-set whose `tx` fires when the chain settles. `pending`
66    /// starts at 1 for the originating record — its completion `leave`s
67    /// that implicit slot, so a put with no chain targets fires
68    /// immediately on the originating record's own completion.
69    pub fn new(tx: crate::runtime::sync::oneshot::Sender<()>) -> Arc<Self> {
70        Arc::new(Self {
71            pending: AtomicUsize::new(1),
72            tx: StdMutex::new(Some(tx)),
73        })
74    }
75
76    /// A PP target joined the chain (C `dbNotifyAdd`). Balanced by exactly
77    /// one [`Self::leave`].
78    pub fn enter(&self) {
79        self.pending.fetch_add(1, Ordering::AcqRel);
80    }
81
82    /// A record finished its contribution (C `dbNotifyCompletion`). Fires
83    /// the completion oneshot on the `leave` that empties the set.
84    pub fn leave(&self) {
85        let prev = self.pending.fetch_sub(1, Ordering::AcqRel);
86        debug_assert!(prev >= 1, "NotifyWaitSet::leave underflow");
87        if prev == 1 {
88            if let Some(tx) = self.tx.lock().unwrap().take() {
89                let _ = tx.send(());
90            }
91        }
92    }
93
94    /// True once every chain member has left (the completion has fired).
95    /// Used by the put entry to decide synchronous (return `None`) vs
96    /// async-pending (return the receiver) completion.
97    pub fn completed(&self) -> bool {
98        self.pending.load(Ordering::Acquire) == 0
99    }
100}
101
102/// A put-notify (`dbPutNotify` — CA WRITE_NOTIFY, `caput -c`) that landed on a
103/// PACT record and was therefore deferred WHOLE.
104///
105/// C `processNotifyCommon` (dbNotify.c:225-231) tests `precord->pact` above
106/// `ppn->putCallback`, so nothing is written and nothing is marked: the record
107/// joins the notify's wait list in state `notifyRestartInProgress`, and when the
108/// async cycle completes the put is replayed against a record that is no longer
109/// active — value written, record processed, callback fired only after THAT
110/// process finishes. So a client's "callback returned" still means "the value I
111/// sent has been processed".
112///
113/// softIoc 7.0.10.1-DEV, `ASY` (calcout, `ODLY=4`, `A=5`), `caput -c ASY.A 7`
114/// issued 1 s into the async cycle:
115///
116/// ```text
117/// t=1s  A=5  PACT=1                      <- cycle in flight
118/// t=2s  A=5  PACT=1  RPRO=0              <- put-notify pending: nothing written
119/// t=4s  A=7  PACT=1                      <- cycle done; the put is replayed
120/// callback returns at t=6.9s: A=7 VAL=7  <- after the RESTARTED process
121/// ```
122pub struct DeferredNotifyPut {
123    /// The field the client wrote (already upper-cased).
124    pub field: String,
125    /// The value it wrote — held here, unwritten, until the restart.
126    pub value: crate::types::EpicsValue,
127    /// The client's completion channel. The replayed put builds its wait-set
128    /// around this sender, so the callback fires on the restarted process, not
129    /// on the in-flight cycle.
130    pub completion: crate::runtime::sync::oneshot::Sender<()>,
131}
132
133/// The PACT→idle transition, as a value.
134///
135/// # Invariant
136///
137/// `RecordInstance::deferred_notify_put.is_some()` ⟹ PACT is held. A
138/// put-notify is parked ONLY on the `is_processing()` arm of the put entry
139/// ([`RecordInstance::park_notify_put`]), and PACT can be released ONLY by
140/// [`RecordInstance::leave_pact`], which takes the park with it. So the
141/// deferral cannot outlive the PACT window it was parked in — the strand is
142/// unrepresentable rather than guarded against.
143///
144/// The token is `#[must_use]`: a release site cannot silently drop the parked
145/// put. Its single consumer is `PvDatabase::apply_pact_exit`, called from the
146/// released cycle's `recGblFwdLink` tail — C `recGbl.c:295` (`if (pdbc->ppn)
147/// dbNotifyCompletion(pdbc)`), which is where C queues the restart callback
148/// (`dbNotify.c:466-469`, state `notifyRestartInProgress`). Holding the token
149/// to the tail rather than replaying at the `pact = FALSE` store is what keeps
150/// the replay behind the rest of the cycle, exactly as C's queued callback is.
151#[must_use = "a put-notify parked on this record is stranded unless the PactExit \
152              reaches PvDatabase::apply_pact_exit"]
153pub struct PactExit(Option<DeferredNotifyPut>);
154
155impl Drop for PactExit {
156    /// Last-resort canary. Every release site hands its token to
157    /// `PvDatabase::apply_pact_exit`; a token reaching here still holding a
158    /// parked put means a PACT release path was added without a tail. The
159    /// client is not left hanging (dropping `completion` errors its receiver),
160    /// but the put's value IS lost, so say so.
161    fn drop(&mut self) {
162        if self.0.is_some() {
163            tracing::error!(
164                "PactExit dropped with a put-notify still parked: a PACT release \
165                 path is not routed through PvDatabase::apply_pact_exit"
166            );
167        }
168    }
169}
170
171impl PactExit {
172    /// The put-notify this release freed, if one was parked.
173    pub(crate) fn into_deferred(mut self) -> Option<DeferredNotifyPut> {
174        self.0.take()
175    }
176
177    /// Fold two releases of the same cycle into one token.
178    ///
179    /// A simulated SDLY continuation releases PACT inside `check_simulation_mode`
180    /// and again at the `is_continuation` arm; the second release finds PACT
181    /// already clear and carries nothing, because the first took the park.
182    pub(crate) fn merge(mut self, mut other: PactExit) -> PactExit {
183        debug_assert!(
184            self.0.is_none() || other.0.is_none(),
185            "a parked put-notify can be released only once per cycle"
186        );
187        PactExit(self.0.take().or_else(|| other.0.take()))
188    }
189
190    /// A cycle that released no PACT (and therefore freed no put-notify).
191    pub(crate) fn none() -> PactExit {
192        PactExit(None)
193    }
194}
195
196/// Cached metadata for a record.
197///
198/// Stores the result of `populate_display_info` / `populate_control_info` /
199/// `populate_enum_info` so subsequent `snapshot_for_field` /
200/// `make_monitor_snapshot` calls can skip rebuilding the metadata. The
201/// cache is invalidated whenever a metadata-class field is written
202/// (EGU, PREC, HOPR, LOPR, alarm limits, DRVH/DRVL, state strings).
203///
204/// In a CA-only IOC this is a CPU win; in a hybrid CA + PVA IOC where
205/// every snapshot needs full metadata for NTScalar serialization, the
206/// cache eliminates redundant per-event populate work.
207#[derive(Clone, Default)]
208pub(crate) struct MetadataSnapshot {
209    pub display: Option<DisplayInfo>,
210    pub control: Option<ControlInfo>,
211    pub enums: Option<EnumInfo>,
212}
213
214/// Returns true if this field is property-class — the C `prop(YES)`
215/// dbd attribute: writing a changed value posts `DBE_PROPERTY` to the
216/// record's subscribers AND invalidates the metadata cache. Field name
217/// is expected uppercase.
218///
219/// **Every field read by `populate_display_info`,
220/// `populate_control_info`, or `populate_enum_info` MUST be in this
221/// set** — otherwise the cache serves stale metadata until some other
222/// tracked field is written. The reverse does not hold: a field may be
223/// property-class without being a cache source (e.g. the motor fields
224/// below feed the live-computed `field_metadata_override`, never the
225/// cache — its invalidation on their write is harmless).
226///
227/// Currently uncovered (because it is not yet populated by any
228/// `populate_*` function): `DESC` (would map to `display.description`
229/// — populate hook missing). The `Q:form` info tag is now wired
230/// (`populate_display_info` -> `display.form`), but as an immutable
231/// load-time info tag — not a runtime field — it needs no cache
232/// invalidation and so is intentionally absent from this field set.
233fn is_metadata_field(name: &str) -> bool {
234    matches!(
235        name,
236        // Display info (analog + integer + motor) — `prop(YES)` in
237        // ai/ao/longin/longout DBDs.
238        "EGU" | "PREC" | "HOPR" | "LOPR" | "HLM" | "LLM"
239        // Alarm limits (used by both display and the analog_alarm config) —
240        // ai/ao/longin/longout `prop(YES)`.
241        | "HIHI" | "HIGH" | "LOW" | "LOLO"
242        // Alarm severities for the four limit thresholds —
243        // ai/ao/longin/longout `prop(YES)` per upstream DBDs
244        // (`aiRecord.dbd.pod` lines 357-388).
245        | "HHSV" | "HSV" | "LSV" | "LLSV"
246        // Output ctrl limits — ao/longout `prop(YES)`.
247        | "DRVH" | "DRVL"
248        // motor `prop(YES)` (`motorRecord.dbd` 154/161/289/361/368):
249        // VBAS/VMAX bound VELO's range, MRES the RVAL/RRBV raw range,
250        // DHLM/DLLM the DVAL/DRBV range — all served per field by
251        // `Record::field_metadata_override` (C get_graphic_double /
252        // get_control_double). HLM/LLM/EGU/PREC and the alarm limits
253        // are motor `prop(YES)` too, already listed above.
254        | "VBAS" | "VMAX" | "MRES" | "DHLM" | "DLLM"
255        // bi/bo/busy enum strings — `prop(YES)`.
256        | "ZNAM" | "ONAM"
257        // bi/bo state severities — `biRecord.dbd.pod` / `boRecord.dbd.pod`
258        // `prop(YES)` for ZSV/OSV/COSV (zero / one / change-of-state).
259        | "ZSV" | "OSV" | "COSV"
260        // mbbi/mbbo state strings (16 levels) — `prop(YES)`.
261        | "ZRST" | "ONST" | "TWST" | "THST" | "FRST" | "FVST" | "SXST" | "SVST"
262        | "EIST" | "NIST" | "TEST" | "ELST" | "TVST" | "TTST" | "FTST" | "FFST"
263    )
264}
265
266/// One alarm limit for a DBR_AL_DOUBLE response: the value when its
267/// severity threshold is enabled, `NaN` otherwise. Mirrors C
268/// `get_alarm_double`'s `prec->hhsv ? prec->hihi : epicsNAN` — a NONZERO
269/// test on the raw ordinal, so an out-of-range severity still enables the
270/// limit.
271fn gated(severity: i16, limit: f64) -> f64 {
272    if severity != 0 { limit } else { f64::NAN }
273}
274
275/// Extract the RAW stored ordinal a put lands in a `menu(menuAlarmSevr)`
276/// severity field (`HHSV`/`HSV`/`LSV`/`LLSV`/`UDFS`/`DISS`), WITHOUT clamping
277/// to the 0..=3 valid range.
278///
279/// C's numeric menu put stores whatever `(epicsEnum16)` the value truncates to
280/// (`dbConvert.c::putDoubleEnum` = `*pfield = (epicsEnum16)*psrc`), so
281/// `caput REC.HSV 4` keeps `4` and `caput REC.HSV -1` keeps `65535` — both
282/// wire-visible (served signed as `-1`) and both used verbatim to derive the
283/// alarm. The carrier is `i16` so the 16-bit pattern round-trips; the alarm
284/// meaning is read back with [`AlarmSeverity::from_u16`] and the C nonzero
285/// enable with `!= 0`.
286///
287/// A numeric value has already been wrapped to `epicsEnum16` upstream
288/// (`EpicsValue::convert_to(Enum)`, the one owner of C's double→enum cast); this
289/// only reinterprets its bit pattern. A `String` is a db-load / internal-link
290/// label (a client string put is rejected-or-resolved by `putStringMenu`
291/// upstream), resolved to its ordinal here.
292fn menu_ordinal_raw(value: &EpicsValue) -> i16 {
293    match value {
294        EpicsValue::String(s) => match s.as_str_lossy().as_ref() {
295            "NO_ALARM" => 0,
296            "MINOR" => 1,
297            "MAJOR" => 2,
298            "INVALID" => 3,
299            other => other
300                .parse::<i64>()
301                .ok()
302                .map(|n| n as u16 as i16)
303                .unwrap_or(0),
304        },
305        other => other.to_f64().unwrap_or(0.0) as i64 as u16 as i16,
306    }
307}
308
309/// Coerce a db-loaded `String` for a numeric/menu **common** field to that
310/// field's canonical DBF type before [`RecordInstance::put_common_field`]
311/// dispatches on it.
312///
313/// The db loader applies a record's own fields with the typed
314/// `EpicsValue::parse(desc.dbf_type, value_str)` (`db_loader::apply_fields`),
315/// but a field absent from `field_list` is pushed to the common-field path as
316/// a raw `EpicsValue::String` — it has no `FieldDesc` to parse against. The
317/// numeric common-field arms in `put_common_field` match only their typed
318/// variant, so without this step a `.db` `field(PHAS, "1")`,
319/// `field(PRIO, "HIGH")`, `field(DISS, "MAJOR")`, `field(DISA, "1")`, … is
320/// silently dropped at IOC load. Routing the String through the same
321/// `EpicsValue::parse` the record-field path uses handles the numeric *and*
322/// menu-label forms uniformly, so the arm receives the value it expects.
323///
324/// Only fields whose canonical type is numeric/menu are listed; the
325/// Port of libcom `epicsParseInt32(str, &to, 10, NULL)`
326/// (`libcom/src/misc/epicsStdlib.c:26-53,245-261`), which is how pvxs parses
327/// the `nsec:lsb:` digit count. Returns `None` for every status the C
328/// returns non-zero for:
329///
330/// - `S_stdlib_noConversion` — `strtol` consumed nothing (empty / no digits)
331/// - `S_stdlib_extraneous` — trailing non-space bytes with `units == NULL`
332/// - `S_stdlib_overflow` — outside `epicsInt32`
333///
334/// Leading and trailing ASCII whitespace and a leading `+`/`-` sign are
335/// accepted, matching `epicsParseLong`'s `isspace` skips and `strtol`.
336fn epics_parse_int32_base10(s: &str) -> Option<i32> {
337    // `while ((c = *str) && isspace(c)) ++str;` then `strtol(str, &endp, 10)`.
338    let body = s.trim_start_matches(|c: char| c.is_ascii_whitespace());
339    let (sign, digits) = match body.strip_prefix(['+', '-']) {
340        Some(rest) if body.starts_with('-') => (-1i64, rest),
341        Some(rest) => (1i64, rest),
342        None => (1i64, body),
343    };
344    let end = digits
345        .find(|c: char| !c.is_ascii_digit())
346        .unwrap_or(digits.len());
347    if end == 0 {
348        return None; // endp == str → S_stdlib_noConversion
349    }
350    // `if (c && !units) return S_stdlib_extraneous;` after skipping trailing
351    // whitespace.
352    if !digits[end..]
353        .trim_start_matches(|c: char| c.is_ascii_whitespace())
354        .is_empty()
355    {
356        return None;
357    }
358    // ERANGE from `strtol`, then the explicit `epicsInt32` range check.
359    let magnitude: i64 = digits[..end].parse().ok()?;
360    i32::try_from(sign * magnitude).ok()
361}
362
363/// The STORED type of a `dbCommon` field — the variant its
364/// [`RecordInstance::put_common_field_bounded`] arm binds, which is not always
365/// the type the `.dbd` DECLARES it as (a `menu()` field is declared `DBF_MENU`
366/// and served `DBR_ENUM`, but held here as its bare index).
367///
368/// String-typed common fields (DESC, ASG, OUT, TSEL, …) have no entry: their
369/// arms take the string verbatim.
370fn stored_common_field_type(name: &str) -> Option<DbFieldType> {
371    Some(match name {
372        "SCAN" | "SSCN" | "PINI" => DbFieldType::Enum,
373        "TSE" | "PHAS" | "PRIO" | "DISV" | "DISA" | "DISS" | "LCNT" | "UDFS" | "ACKT" | "ACKS"
374        | "SEVR" | "STAT" | "NSEV" | "NSTA" => DbFieldType::Short,
375        // The analog-alarm limits and the hysteresis margin — `DBF_DOUBLE` in
376        // every dbd that declares them (`aiRecord.dbd.pod:357-388`,
377        // `calcRecord.dbd.pod:716-744`, `sCalcoutRecord.dbd:479-531`). A field
378        // missing from this table reaches its arm as whatever variant the caller
379        // built, and an arm that binds a typed variant then drops it: that is
380        // how `field(HYST,"2")` silently became 0 on every record whose
381        // hysteresis lives in `common.hyst`
382        // (calc/calcout/scalcout/ai/ao/longin/int64in).
383        "HIHI" | "HIGH" | "LOW" | "LOLO" | "HYST" => DbFieldType::Double,
384        // The `DBF_UCHAR` flags. `bool` here, a NUMBER in C.
385        "DISP" | "UDF" | "TPRO" | "RPRO" | "BKPT" | "PROC" => DbFieldType::Char,
386        _ => return None,
387    })
388}
389
390/// **The single owner of "what type does a `dbCommon` field hold"**, run on
391/// EVERY put before the typed arms below see the value — so an arm may bind one
392/// variant and know the put cannot have arrived in another.
393///
394/// This is not a string-parsing convenience. A common field is reached by three
395/// writers with three different ideas of the value's shape: the db loader hands
396/// every field over as a raw `String`; a `dbPut` arrives coerced to the field's
397/// DECLARED type (`DBF_MENU` → `Enum` for PRIO, `DBF_UCHAR` → `Char` for DISP);
398/// an internal link delivers whatever its source stored. Before this ran on the
399/// non-`String` shapes too, each arm's single-variant `if let` was a silent
400/// drop for the other two writers — `caput REC.PRIO HIGH` resolved its label to
401/// `Enum(2)` and then vanished at the arm, leaving PRIO at 0.
402///
403/// An unparseable String is returned as-is so the arm drops it, and a menu
404/// field's bad label FAILS the put (`S_db_badChoice`) rather than landing as
405/// index 0.
406fn coerce_common_field(name: &str, value: EpicsValue, bound: MenuBound) -> CaResult<EpicsValue> {
407    let Some(dbf) = stored_common_field_type(name) else {
408        return Ok(value);
409    };
410    let EpicsValue::String(s) = &value else {
411        // Already typed: project onto the stored type through the one
412        // value-coercion owner. `convert_to` short-circuits a value that is
413        // already `dbf`, so the common case costs nothing.
414        return Ok(value.convert_to(dbf));
415    };
416    let text = s.as_str_lossy();
417    // A `DBF_MENU` common field resolves its label against THAT field's own
418    // menu through the one converter every menu-field string put uses
419    // (C `dbConvert.c::putStringMenu`: exact label, else an index below
420    // `nChoice`, else `S_db_badChoice`) — the same rule the record-specific
421    // menu fields follow in `coerce_write_value`. The failure PROPAGATES: the
422    // field-blind `EpicsValue::parse` fallback below must never see a menu
423    // field, or `caput REC.PRIO Bogus` lands as index 0 instead of failing.
424    //
425    // SCAN/SSCN/PINI are menu fields like any other and go through the same
426    // converter. They used to each carry a hand-written `from_str` that drifted
427    // from C: `ScanType::from_str` case-folded and invented `"0.5 second"`
428    // aliases for menuScan's `".5 second"` (and mapped any out-of-range index
429    // to Passive), `SimModeScan::from_str` took any u16, `PiniMode::from_str`
430    // trimmed. C has ONE converter and it does none of that.
431    if let Some(choices) = super::menu_choices::shared_menu_choices(name) {
432        return super::menu_choices::resolve_menu_field_string_bounded(
433            name, choices, dbf, &text, bound,
434        );
435    }
436    // Numeric (non-menu) common field: C's `dbPut` runs the string through the
437    // SAME `epicsParse*` (`dbConvert.c` `putString*`) the record data fields use,
438    // and a non-zero status REFUSES the whole put (`dbAccess.c:1362`, mapped to
439    // `ECA_PUTFAIL`). Route it through the single owner of that conversion —
440    // [`c_parse::put_string`] — instead of the field-blind `EpicsValue::parse`,
441    // which wrapped (`256 as u8 == 0`) and swallowed the error (`Err(_) =>
442    // Ok(value)`), so `caput REC.PROC 256` and `caput REC.PROC notanumber` were
443    // accepted where C rejects them.
444    //
445    // Key the parse on the field's C-DECLARED width, not its stored variant: the
446    // `DBF_UCHAR` flags (DISP/UDF/TPRO/RPRO/BKPT/PROC, `dbCommon.dbd`) are held in
447    // the signed `Char` variant here but C parses them with `epicsParseUInt8`, so
448    // `caput REC.PROC 255` and `caput REC.PROC -1` (→255) are accepted and only
449    // `256`+/non-numeric refused. `put_string` returns the value in the declared
450    // variant; project it back onto the stored variant through the one
451    // value-coercion owner (byte-identity for `UChar`→`Char`).
452    let declared = match dbf {
453        DbFieldType::Char => DbFieldType::UChar,
454        other => other,
455    };
456    let Some(target) = c_parse::NumericField::of(declared) else {
457        // Unreachable: every numeric `stored_common_field_type` (Char/Short/
458        // Double, all with a numeric row) reaches here; the `Enum` menu types
459        // returned above. Keep the pre-parse value rather than panic.
460        return Ok(value);
461    };
462    c_parse::put_string(name, target, text.trim()).map(|parsed| parsed.convert_to(dbf))
463}
464
465/// The alarm-acknowledge request types C's `dbPut` dispatches on
466/// (`dbAccess.c:1331-1335`): `DBR_PUT_ACKT` and `DBR_PUT_ACKS`.
467///
468/// Acknowledgement is a *request type*, not a field write — the two handlers
469/// run above the `SPC_NOMOD` gate that refuses every ordinary put to ACKT/ACKS.
470#[derive(Debug, Clone, Copy, PartialEq, Eq)]
471pub enum AlarmAck {
472    /// `DBR_PUT_ACKT` → `putAckt`: set transient-alarm acknowledgement.
473    Transient,
474    /// `DBR_PUT_ACKS` → `putAcks`: acknowledge an alarm of this severity.
475    Severity,
476}
477
478/// A type-erased record instance stored in the database.
479pub struct RecordInstance {
480    pub name: String,
481    pub record: Box<dyn Record>,
482    pub common: CommonFields,
483    pub subscribers: HashMap<String, Vec<Subscriber>>,
484    // Link parse cache
485    pub parsed_inp: ParsedLink,
486    pub parsed_out: ParsedLink,
487    pub parsed_flnk: ParsedLink,
488    pub parsed_sdis: ParsedLink,
489    pub parsed_tsel: ParsedLink,
490    // Device support
491    pub device: Option<Box<dyn super::super::device_support::DeviceSupport>>,
492    // Subroutine (for sub records)
493    pub subroutine: Option<Arc<SubroutineFn>>,
494    /// PACT (C `precord->pact`) — the re-entrancy guard, and the record's
495    /// "busy" state for every put that lands on it.
496    ///
497    /// PRIVATE by construction: entered through [`RecordInstance::enter_pact`]
498    /// and released ONLY through [`RecordInstance::leave_pact`], which hands
499    /// back the [`PactExit`] carrying any put-notify parked on this PACT window.
500    /// A `pact.store(false)` open-coded at a release site is what stranded the
501    /// deferral on the ODLY/SDLY paths; it is no longer expressible.
502    pact: AtomicBool,
503    // Put-notify wait-set this record currently belongs to (C
504    // `precord->ppn`). Set when the record joins an active put-notify
505    // (originating put target, or a FLNK/OUT PP target via `dbNotifyAdd`);
506    // taken + `leave`d when the record's processing completes. `None`
507    // outside any put-notify. See [`NotifyWaitSet`].
508    pub notify: Option<Arc<NotifyWaitSet>>,
509    /// A put-notify that arrived while this record was PACT, deferred WHOLE —
510    /// C `processNotifyCommon` (dbNotify.c:225-231) tests `precord->pact`
511    /// ABOVE `putCallback`, so a `dbPutNotify` onto a busy record writes
512    /// nothing: no value, no RPRO. The record is parked on the notify's wait
513    /// list and the entire put — value, process, callback — is restarted once
514    /// the async cycle completes. See [`DeferredNotifyPut`] and
515    /// `PvDatabase::restart_deferred_notify_put`, the single owner that applies
516    /// it. `None` outside that window.
517    ///
518    /// PRIVATE, and paired with [`Self::pact`] by the [`PactExit`] invariant:
519    /// parked only by [`Self::park_notify_put`] (reachable only from the
520    /// PACT arm of the put entry), taken only by [`Self::leave_pact`].
521    deferred_notify_put: Option<DeferredNotifyPut>,
522    /// The value of each subscribed field as ALREADY PUBLISHED to that
523    /// field's `DBE_VALUE`/`DBE_LOG` subscribers. The generic
524    /// change-detection loop in every snapshot builder posts a field only
525    /// when its current value differs from this — so this map is what
526    /// C's per-record `*_lst` / MARK state is to `monitor()`.
527    ///
528    /// # Invariant (CONTRACT)
529    ///
530    /// A field's value MUST NOT be published twice by the framework.
531    /// Concretely: every value-class post (a `db_post_events` carrying
532    /// `DBE_VALUE` and/or `DBE_LOG`) MUST advance this map for the field it
533    /// posts; an alarm-only / property-only post MUST NOT (those classes do
534    /// not deliver the value to a `DBE_VALUE`/`DBE_LOG` subscriber, so the
535    /// change is still owed to them).
536    ///
537    /// In C, `dbPut` (dbAccess.c:1407-1414) is the record's ONLY post for a
538    /// put: `db_post_events(precord, pfieldsave, DBE_VALUE|DBE_LOG)`. No
539    /// record's `monitor()` re-posts that field — it posts a closed set and
540    /// compares against its own `*_lst` fields. A framework that posts on the
541    /// put and then change-detects the same field on the next process cycle
542    /// sends an event C never sends.
543    ///
544    /// # Owner
545    ///
546    /// [`RecordInstance::record_value_post`] is the SINGLE writer. The field
547    /// is private so no path outside this module can advance (or fail to
548    /// advance) it: the snapshot builders read it through
549    /// [`RecordInstance::posted_value`] and every poster —
550    /// [`RecordInstance::notify_field_with_origin`] included — advances it
551    /// through the owner.
552    last_posted: HashMap<String, EpicsValue>,
553    /// The live store for a field the record's `.dbd` DECLARES but the record
554    /// struct has no `put_field` arm / no storage for — the WRITE analog of the
555    /// read-side [`Self::declared_default`] fallback.
556    ///
557    /// C makes every `.dbd` field not just readable but WRITABLE: `dbPutField`
558    /// resolves the field from its `dbFldDes` and `dbPut` writes the incoming
559    /// value into record memory, whether or not any record code ever reads it
560    /// back — a `caput dfanout.HOPR 10` sticks even though `dfanoutRecord.c`
561    /// never touches HOPR. A Rust record models only the fields it has
562    /// behaviour for, so a field it declares but never stores had nowhere for a
563    /// put to land: [`Self::put_common_field`]'s catch-all reported
564    /// `S_dbLib_fieldNotFound` and the client's put was refused, while a READ of
565    /// the same field succeeded through `declared_default`. This map is that
566    /// missing storage — one uniform mechanism for the whole family, not a
567    /// per-field struct member on each record type.
568    ///
569    /// Keyed by upper-case field name, holding the value already coerced to the
570    /// field's C-declared DBF type (the same projection `declared_default` and
571    /// the read path serve). [`Self::resolve_field`] reads it BEFORE
572    /// `declared_default`, so a read reflects a prior write and an untouched
573    /// field still reads its `.dbd` initial. Empty for a record whose declared
574    /// fields are all modeled.
575    declared_overrides: HashMap<String, EpicsValue>,
576    /// Set by `check_deadband_ext` for waveform/aai/aao when their
577    /// content hash changed this cycle (C `monitor()` On Change mode,
578    /// waveformRecord.c:310-319). The snapshot builders read it to post
579    /// `HASH` with a literal `DBE_VALUE` event, independent of the VAL
580    /// post mask. False for every record without the MPST/APST/HASH
581    /// mechanism.
582    pub(crate) array_hash_changed: bool,
583    /// One-shot "skip the registered subroutine this cycle" signal for aSub
584    /// `LFLG=READ`. The async processing path resolves the `SUBL` link before
585    /// taking this lock; when the resolved name is bad (C `fetch_values` ->
586    /// `S_db_BadSub`) or the link read failed, C `process` runs `do_sub` only
587    /// on `!status`, so the subroutine is skipped. Set by the resolution
588    /// apply, consumed (and cleared) by [`Self::run_registered_subroutine`];
589    /// `false` for every record without a pending bad re-resolution.
590    pub(crate) suppress_subroutine_run: bool,
591    /// Generation counter for ReprocessAfter timer cancellation.
592    /// Bumped each process cycle. Spawned timers check this to avoid
593    /// stale re-processes from accumulated timers.
594    pub reprocess_generation: Arc<std::sync::atomic::AtomicU64>,
595    /// Generation counter for the monitor watchdog
596    /// ([`Record::watchdog_interval`] / [`Record::watchdog_fire`]), bumped by
597    /// each `PvDatabase::arm_watchdog` so a re-arm supersedes the tick already
598    /// in flight — C `callbackRequestDelayed` replacing an outstanding delayed
599    /// callback. Deliberately NOT `reprocess_generation`: C's histogram wdog is
600    /// its own `epicsCallback`, independent of the record's SDLY/async
601    /// re-entry, so an SDLY defer must not cancel the watchdog nor vice versa.
602    pub watchdog_generation: Arc<std::sync::atomic::AtomicU64>,
603    /// Per-record info tags from `info("key", "value")` directives in
604    /// the .db file (epics-base info(...) grammar). Consumers include
605    /// asyn (`asyn:READBACK`), record-as-PV bridge tags
606    /// (`Q:group`, `Q:form`), and IOC-specific extensions. Empty for
607    /// records loaded without info(...) clauses.
608    pub info: HashMap<String, String>,
609    /// Cached metadata (display/control/enums) — `None` means stale or
610    /// not yet built. Populated lazily by `snapshot_for_field` /
611    /// `make_monitor_snapshot` and invalidated by `invalidate_metadata_cache`
612    /// whenever a metadata-class field (EGU/PREC/HOPR/LOPR/limit/state)
613    /// is written.
614    ///
615    /// Wrapped in `std::sync::Mutex` for interior mutability — the
616    /// containing `RecordInstance` is shared via `Arc<RwLock<...>>` from
617    /// `PvDatabase`, and snapshot construction holds a read lock; the
618    /// inner Mutex lets us still mutate the cache from a `&self` method.
619    ///
620    /// # Cache invariant (CONTRACT)
621    ///
622    /// The cache is **only correct under the following contract**: every
623    /// code path that mutates a metadata-class field (the set defined in
624    /// the file-private `is_metadata_field` predicate) MUST call
625    /// [`RecordInstance::notify_field_written`] (or
626    /// [`RecordInstance::invalidate_metadata_cache`] directly) afterward.
627    ///
628    /// All current write paths in `field_io.rs` already do this. If you
629    /// add a new code path that:
630    ///
631    /// - calls `instance.record.put_field(...)` directly, OR
632    /// - mutates record fields from inside `Record::process()`,
633    ///   `Record::on_put`, or `Record::special` and that mutation could
634    ///   touch a metadata-class field, OR
635    /// - lets a `Box<dyn Record>` implementation expose its own
636    ///   mutation methods that change metadata fields,
637    ///
638    /// then call `instance.notify_field_written(field_name)` to keep the
639    /// cache consistent. Forgetting will produce a stale snapshot —
640    /// monitors will continue to see the old EGU/PREC/limits until the
641    /// next legitimate metadata-field write triggers invalidation.
642    ///
643    /// # Symmetric note for `populate_*` extensions
644    ///
645    /// If a future change adds a new field to `populate_display_info`,
646    /// `populate_control_info`, or `populate_enum_info` (e.g. populating
647    /// `display.description` from DESC), the new source field name MUST
648    /// also be added to `is_metadata_field` so writes to it invalidate
649    /// the cache. (The `Q:form` -> `display.form` mapping is exempt: it
650    /// reads an immutable load-time info tag, not a runtime field.)
651    pub(crate) metadata_cache: StdMutex<Option<MetadataSnapshot>>,
652}
653
654/// The cycle status [`RecordInstance::run_registered_subroutine`] reports when
655/// `do_sub` was skipped — C's `fetch_values` failure / `S_db_BadSub` path, which
656/// leaves `process`'s `status` non-zero (aSubRecord.c:216-224).
657const SUBROUTINE_STATUS_SKIPPED: i64 = -1;
658/// No subroutine is bound: C `do_sub` returns `S_db_BadSub` (aSubRecord.c:255).
659const SUBROUTINE_STATUS_NO_SUB: i64 = -2;
660/// The bound subroutine returned `Err` — no C counterpart (a C subroutine
661/// returns a `long`), and a failed cycle either way.
662const SUBROUTINE_STATUS_ERROR: i64 = -3;
663
664/// C `monitor()`'s post of the deadband field, as assembled by the single owner
665/// [`RecordInstance::deadband_post`].
666pub(crate) struct DeadbandPost {
667    /// C's `monitor_mask` for this cycle. Also the mask the
668    /// [`Record::fields_posted_with_value_mask`] secondaries ride: C posts them
669    /// from INSIDE the `if (monitor_mask)` guard, with the same mask.
670    pub mask: EventMask,
671    /// The deadband field's own post — `(field, value)`. `None` when no class
672    /// fired (C's `if (monitor_mask)` skips the post) or the field does not
673    /// resolve.
674    pub field: Option<(String, EpicsValue)>,
675}
676
677/// A value's `DBR_STRING` form, for a source whose field metadata is NOT
678/// reachable (an external CA/PVA link, a constant, an lnkCalc result) — the
679/// fallback half of [`RecordInstance::field_as_dbr_string`], which is also the
680/// whole rule once the local choice table has had its say.
681///
682/// A pvalink NTEnum still resolves its label here: the carrier brings its own
683/// `choices` (pvxs `pvalink_lset.cpp:344-356` — a `DBR_STRING` target copies
684/// `choices[index]`). A bare `Enum` index from a link whose labels the port
685/// cannot reach falls back to its decimal form, like the CA `*_STRING` encoder.
686/// **The** declaration lookup: a field's `dbFldDes`, in C's terms.
687///
688/// The record type's declaration is [`FieldDeclaration::field_list`] — the
689/// generated `.dbd` table where one exists and the hand-written table where it
690/// does not, never both. `dbCommon` is asked last, so a record-specific field
691/// shadows the common one.
692///
693/// A free function, not just a [`RecordInstance`] method, because the sites that
694/// need the declaration do not all hold an instance — a constant-link seed, a
695/// link write, the db loader all have `&dyn Record`.
696///
697/// `None` for a field with no declaration at all: a virtual field (`RTYP`,
698/// `TIME`, ...), which C answers from dbStaticLib rather than from a `dbFldDes`.
699pub(crate) fn field_desc_of<R: Record + ?Sized>(
700    record: &R,
701    field: &str,
702) -> Option<&'static FieldDesc> {
703    let named = |t: &'static [FieldDesc]| t.iter().find(|f| f.name.eq_ignore_ascii_case(field));
704    named(record.field_list()).or_else(|| named(super::dbd_generated::DB_COMMON_FIELDS))
705}
706
707/// **The single owner of "which choice list does this field resolve against"**,
708/// asked by BOTH sides of a menu field:
709///
710/// * the READ side ([`RecordInstance::enum_string_form_for`]) — C `getMenuString`,
711///   which renders the stored index as its choice;
712/// * the WRITE side ([`crate::server::record::coerce_put_value`]) — C
713///   `putStringMenu`, which resolves an incoming label to that same index.
714///
715/// They MUST see the same list or the field is not round-trippable. The write
716/// side used to ask only [`Record::menu_field_choices`] (the record's hand
717/// table), so an `aSub`'s `caput FTA LONG` found no menu, fell through to the
718/// numeric parse and landed as index 0 — while the read side, on the `.dbd`
719/// menu, rendered index 0 as `STRING`.
720///
721/// Order is C's: the field's own `menu()` from the declaration, then the
722/// record's hand table where the `.dbd` does not reach (the downstream crates'
723/// record types), then the `dbCommon` menus.
724///
725/// The last step — [`shared_menu_choices`](super::menu_choices::shared_menu_choices)
726/// — is a heuristic keyed on the field NAME (`OSV`, `SIMS`, `HHSV`, …), so it is
727/// consulted ONLY when the field's declaration does not already pin a non-menu
728/// type: a menu is served as `DBR_ENUM`, so a field DECLARED `DBF_STRING` is
729/// never a menu. Without this gate scalcout's string `OSV` ("Output string
730/// value") matched the name-based `menuAlarmSevr` entry a same-named bi/bo
731/// severity field owns, and `caput SCALCOUT.OSV <string>` was rejected with
732/// `S_db_badChoice` where C accepts the string.
733pub(crate) fn menu_choices_of<R: Record + ?Sized>(
734    record: &R,
735    field: &str,
736) -> Option<&'static [&'static str]> {
737    // `DTYP` is `DBF_DEVICE`: its choices are the record type's DEVICE menu
738    // (C `dbDeviceMenu`, built from the `device()` declarations), which is
739    // per-record-type and so cannot live in the shared `dbCommon` FieldDesc.
740    if field.eq_ignore_ascii_case("DTYP") {
741        return super::dbd_generated::device_menu(record.record_type());
742    }
743    let desc = field_desc_of(record, field);
744    desc.and_then(|f| f.menu)
745        .or_else(|| record.menu_field_choices(field))
746        .or_else(|| {
747            // Name-based fallback — but the declared type wins: a `DBF_STRING`
748            // field is not a menu even when a same-named field elsewhere is.
749            if desc.is_some_and(|f| f.dbf_type == DbFieldType::String) {
750                None
751            } else {
752                super::menu_choices::shared_menu_choices(field)
753            }
754        })
755}
756
757/// The `DBF_*` type `field` is SERVED as, for a caller that holds only a
758/// `&dyn Record` — the free-function form of
759/// [`RecordInstance::declared_field_type`], and the ONLY way any site outside
760/// the instance may turn a [`FieldDesc`] into a type.
761///
762/// A [`FieldDesc::runtime_typed`] field (`waveform.VAL` typed by `FTVL`, an
763/// `aSub`'s `A`..`U` typed by `FTA`..`FTU`) has NO type in its declaration: C's
764/// `cvt_dbaddr` overwrites `paddr->field_type` from record state, so the `.dbd`
765/// entry is a placeholder and the value the record stores is the answer. Every
766/// caller falls back to that value, which is why this returns `None` rather than
767/// the placeholder — handing out `DBF_DOUBLE` for a `FTVL=CHAR` waveform is how
768/// a string written down an output link became `0.0`.
769pub(crate) fn declared_field_type_of<R: Record + ?Sized>(
770    record: &R,
771    field: &str,
772) -> Option<DbFieldType> {
773    let desc = field_desc_of(record, field)?;
774    (!desc.runtime_typed).then_some(desc.dbf_type)
775}
776
777pub(crate) fn value_as_dbr_string(value: &EpicsValue) -> Option<PvString> {
778    match value {
779        EpicsValue::String(s) => Some(s.clone()),
780        EpicsValue::Enum(v) => Some(PvString::from(v.to_string())),
781        EpicsValue::EnumWithChoices { index, choices } => Some(
782            choices
783                .get(*index as usize)
784                .cloned()
785                .unwrap_or_else(|| PvString::from(index.to_string())),
786        ),
787        other => match other.clone().convert_to(DbFieldType::String) {
788            EpicsValue::String(s) => Some(s),
789            _ => None,
790        },
791    }
792}
793
794impl RecordInstance {
795    pub fn new(name: String, record: impl Record) -> Self {
796        Self::new_boxed(name, Box::new(record))
797    }
798
799    pub fn new_boxed(name: String, record: Box<dyn Record>) -> Self {
800        let rtype = record.record_type();
801        let analog_alarm = match rtype {
802            // C parity: every record type whose dbd carries
803            // HIHI/HIGH/LOW/LOLO/HHSV/HSV/LSV/LLSV gets an analog-alarm
804            // config slot. Previously calc / calcout were missing —
805            // their put_field for those fields silently no-op'd
806            // because `self.common.analog_alarm` was None at the
807            // mutation site. Confirmed via
808            // calcRecord.dbd.pod:716-744 (HIHI..LLSV) and
809            // calcoutRecord.dbd.pod:1103+ (same). `sub` carries the same
810            // HIHI/HIGH/LOLO/LOW + HHSV/HSV/LSV/LLSV set
811            // (subRecord.dbd.pod:569-642) and runs the analog `checkAlarms`.
812            // `scalcout` declares the identical set (`sCalcoutRecord.dbd:479-531`
813            // HIHI/LOLO/HIGH/LOW/HHSV/LLSV/HSV/LSV/HYST + `:858` LALM) and its
814            // `checkAlarms` (`sCalcoutRecord.c:699-751`) is the same ladder, run
815            // BEFORE the OOPT switch (`:371`) precisely so a limit excursion can
816            // drive IVOA. Without the slot the record had no alarm surface at
817            // all: `caput scalc.HIHI 5` was a `FieldNotFound` and a scalcout
818            // could never go MINOR/MAJOR on its own result.
819            //
820            // **This match is the single owner of "which records have the analog
821            // ladder"** — `evaluate_alarms` runs it off the slot's presence, so a
822            // record added here gets the ladder and one absent cannot.
823            "ai" | "ao" | "longin" | "longout" | "int64in" | "int64out" | "calc" | "calcout"
824            | "sub" | "scalcout" => Some(AnalogAlarmConfig::default()),
825            _ => None,
826        };
827        let mut common = CommonFields::default();
828        common.analog_alarm = analog_alarm;
829
830        Self {
831            name,
832            record,
833            common,
834            subscribers: HashMap::new(),
835            parsed_inp: ParsedLink::None,
836            parsed_out: ParsedLink::None,
837            parsed_flnk: ParsedLink::None,
838            parsed_sdis: ParsedLink::None,
839            parsed_tsel: ParsedLink::None,
840            device: None,
841            subroutine: None,
842            pact: AtomicBool::new(false),
843            notify: None,
844            deferred_notify_put: None,
845            last_posted: HashMap::new(),
846            declared_overrides: HashMap::new(),
847            array_hash_changed: false,
848            suppress_subroutine_run: false,
849            reprocess_generation: Arc::new(std::sync::atomic::AtomicU64::new(0)),
850            watchdog_generation: Arc::new(std::sync::atomic::AtomicU64::new(0)),
851            info: HashMap::new(),
852            metadata_cache: StdMutex::new(None),
853        }
854    }
855
856    /// **The owner of a record's init passes** — C `iocInit.c::doInitRecord0`
857    /// (`:508-536`) and `doInitRecord1`. Nothing else may call
858    /// `Record::init_record`.
859    ///
860    /// C runs a prologue on EVERY record before pass 0, and it is the reason
861    /// this is one function instead of two `init_record` calls at each caller:
862    ///
863    /// ```c
864    /// /* Reset the process active field */
865    /// precord->pact = FALSE;
866    ///
867    /// /* Initial UDF severity */
868    /// if (precord->udf && precord->stat == UDF_ALARM)
869    ///     precord->sevr = precord->udfs;
870    /// ```
871    ///
872    /// A record is born `udf = 1`, `stat = UDF_ALARM` (dbCommon.dbd
873    /// `initial("UDF")`), `udfs = INVALID` — so after `iocInit` a record that
874    /// has NEVER processed advertises `STAT=UDF SEVR=INVALID`, not
875    /// `NO_ALARM`. That is what makes an `MS` consumer inherit
876    /// `LINK`/`INVALID` from a not-yet-processed source, the IOC-startup
877    /// ordering case MS exists for (softIoc-verified). A record whose
878    /// `init_record` or device support defines the value clears UDF and the
879    /// severity goes away on its first process.
880    ///
881    /// `name` is used only for the init-failure diagnostics C sends to errlog.
882    ///
883    /// Crate-private on purpose: the passes must run against the record's FINAL
884    /// loaded field set (the initial UDF severity is a function of UDF/STAT/
885    /// UDFS, and a `.db` `field(VAL,…)` clears UDF at load — C
886    /// `dbStaticLib.c:2653-2661`). The one caller is the creation sink,
887    /// [`crate::server::database::PvDatabase::add_loaded_record`], which takes
888    /// the load and the record together so no path can init a half-loaded
889    /// record.
890    pub(crate) fn run_init_passes(&mut self, name: &str) {
891        // C's `precord->pact = FALSE` — a record cannot be mid-process at init,
892        // so this release provably frees nothing: no client put has run, so the
893        // `PactExit` invariant (`deferred_notify_put.is_some()` ⟹ PACT) makes a
894        // parked put-notify here unreachable.
895        let deferred = self.leave_pact().into_deferred();
896        debug_assert!(
897            deferred.is_none(),
898            "a record cannot hold a parked put-notify at init"
899        );
900        drop(deferred);
901        if self.common.udf != 0
902            && self.common.stat == crate::server::recgbl::alarm_status::UDF_ALARM
903        {
904            self.common.sevr = AlarmSeverity::from_u16(self.common.udfs as u16);
905        }
906        if let Err(e) = self.record.init_record(0) {
907            eprintln!("init_record(0) failed for {name}: {e}");
908        }
909        if let Err(e) = self.record.init_record(1) {
910            eprintln!("init_record(1) failed for {name}: {e}");
911        }
912        // The UDF tail of pass 1. `init_record` cannot reach UDF (a common
913        // field), so the record types whose C `init_record` ends in
914        // `prec->udf = FALSE` — histogram's `clear_histogram`, aao's constant
915        // DOL, mbboDirect's B0..B1F fold (epics-base dabcf89) — deliver it
916        // through this hook instead. It lives HERE, inside the init owner,
917        // because it is part of the same C pass: a creation path that ran the
918        // passes but skipped the tail (iocsh `dbLoadRecords` did) left those
919        // records UDF=1 where C has UDF=0.
920        // The `post_init_finalize_undef` hook is a cross-crate record-trait API
921        // over a `bool` (histogram/aao/mbboDirect implement it); bridge the raw
922        // `u8` carrier through it here at the single init owner.
923        let mut udf = self.common.udf != 0;
924        if let Err(e) = self.record.post_init_finalize_undef(&mut udf) {
925            eprintln!("post_init_finalize_undef failed for {name}: {e}");
926        }
927        self.common.udf = udf as u8;
928        // C `init_record` that ends in `prec->udf = 0; recGblResetAlarms(prec)`
929        // — the asyn record, defined and no-alarm the moment it loads. The born
930        // `UDF`/`INVALID` (and the UDF-severity derivation above) are overwritten
931        // here: at init `nsta`/`nsev` are 0, so `rec_gbl_reset_alarms` transfers
932        // `STAT`/`SEVR` to `NO_ALARM`. Runs after `post_init_finalize_undef` so
933        // it is the final word on this record's initial alarm state.
934        if self.record.init_resets_alarms() {
935            self.common.udf = 0;
936            let _ = crate::server::recgbl::rec_gbl_reset_alarms(&mut self.common);
937        }
938        // C `init_record` can END with `prec->pact = TRUE` to disable a record
939        // it cannot process (`subRecord.c:119-123`, an empty SNAM). PACT has one
940        // owner, so the record declares the fact and the owner parks it — after
941        // the passes, so the `leave_pact()` above cannot undo it. There is
942        // nothing to release later: `dbProcess` takes the PACT-active branch on
943        // every scan from here on, which is exactly the point.
944        if self.record.init_record_parks_pact() {
945            self.enter_pact();
946        }
947    }
948
949    /// SINGLE OWNER of the DTYP -> soft-output-dset mapping. The dset table
950    /// decides what a soft OUT-link write carries; no caller may re-derive it.
951    ///
952    /// C ships two soft output dsets per output record type and DTYP picks one:
953    /// `devXxxSoft.c::write_xxx` puts VAL/OVAL on the OUT link, while
954    /// `devXxxSoftRaw.c::write_xxx` puts the RAW word — `dbPutLink(&prec->out,
955    /// DBR_LONG, &prec->rval, 1)` (`devAoSoftRaw.c:44`, `devBoSoftRaw.c:65`) or
956    /// `data = prec->rval & prec->mask` (`devMbboSoftRaw.c:71-75`,
957    /// `devMbboDirectSoftRaw.c:71-75`).
958    ///
959    /// `Record::raw_soft_output_value` IS the SoftRaw column of that table:
960    /// `Some` exactly for the record types C ships a SoftRaw dset for. A record
961    /// type C has no SoftRaw dset for keeps the plain soft-channel value —
962    /// `DTYP="Raw Soft Channel"` on a `longout` is a `.db` error C rejects at
963    /// init ("no device support"), and the port's lenient reading of it (the
964    /// same one [`crate::server::device_support::is_soft_dtyp`] already applies
965    /// on the input side) must not turn the write into a silent no-op.
966    ///
967    /// `None` means DTYP names device support that owns the write — real
968    /// hardware, or "Async Soft Channel", whose dset is a registered async
969    /// device.
970    pub fn soft_output_value(&self) -> Option<Option<EpicsValue>> {
971        if self.common.dtyp == "Raw Soft Channel" {
972            return Some(
973                self.record
974                    .raw_soft_output_value()
975                    .or_else(|| self.record.output_link_value()),
976            );
977        }
978        if self.common.dtyp.is_empty() || self.common.dtyp == "Soft Channel" {
979            return Some(self.record.output_link_value());
980        }
981        None
982    }
983
984    /// Set a single `info("key", "value")` tag on this record. Last
985    /// write wins. Used by the .db loader (`info(...)` directive) and
986    /// `dbpf`-style tools.
987    pub fn set_info(&mut self, key: impl Into<String>, value: impl Into<String>) {
988        self.info.insert(key.into(), value.into());
989    }
990
991    /// Look up a single info tag. Returns `None` when the record has
992    /// no tag with that key.
993    pub fn get_info(&self, key: &str) -> Option<&str> {
994        self.info.get(key).map(|s| s.as_str())
995    }
996
997    /// The value of `field` already published to its `DBE_VALUE`/`DBE_LOG`
998    /// subscribers, or `None` when the framework has never published one.
999    /// The read side of the `last_posted` contract — see the field's docs.
1000    pub(crate) fn posted_value(&self, field: &str) -> Option<&EpicsValue> {
1001        self.last_posted.get(field)
1002    }
1003
1004    /// SINGLE OWNER of `last_posted`: record that `value` has been published
1005    /// to `field`'s `DBE_VALUE`/`DBE_LOG` subscribers, so no later cycle
1006    /// change-detects and re-publishes it.
1007    ///
1008    /// Every value-class post — the snapshot builders' change-detected posts,
1009    /// the intermediate async-notify posts, and the put-time
1010    /// [`Self::notify_field_with_origin`] post that C makes from `dbPut`
1011    /// (dbAccess.c:1414) — routes through here. Alarm-only / property-only
1012    /// posts MUST NOT call it: they deliver nothing to a value-class
1013    /// subscriber, so the value is still owed.
1014    pub(crate) fn record_value_post(&mut self, field: &str, value: EpicsValue) {
1015        if let Some(slot) = self.last_posted.get_mut(field) {
1016            *slot = value;
1017        } else {
1018            self.last_posted.insert(field.to_string(), value);
1019        }
1020    }
1021
1022    /// Invalidate the metadata cache. Called after writing any
1023    /// metadata-class field (EGU, PREC, HOPR/LOPR, alarm limits,
1024    /// DRVH/DRVL, enum strings). The next snapshot will rebuild the
1025    /// cache from the new values.
1026    pub fn invalidate_metadata_cache(&self) {
1027        if let Ok(mut guard) = self.metadata_cache.lock() {
1028            *guard = None;
1029        }
1030    }
1031
1032    /// Hook called by the database after a field is written. If the
1033    /// field is in the metadata-class set, the cache is invalidated so
1034    /// the next snapshot picks up the new value.
1035    ///
1036    /// Field name is automatically uppercased.
1037    pub fn notify_field_written(&self, field: &str) {
1038        let upper = field.to_ascii_uppercase();
1039        if is_metadata_field(&upper) {
1040            self.invalidate_metadata_cache();
1041        }
1042    }
1043
1044    /// Like [`notify_field_written`] but skips the invalidation when
1045    /// the put did not actually change the field's value. Mirrors
1046    /// epics-base `faac1df1` — `DBE_PROPERTY` events fire only on
1047    /// real changes, not on idempotent writes (the C path compares
1048    /// `paddr->pfield` against the converted payload before setting
1049    /// the `propertyUpdate` flag).
1050    ///
1051    /// `prev` is the value captured BEFORE the put. Callers that
1052    /// don't need the change-detection (e.g. internal writers that
1053    /// know the field is non-metadata) can keep using
1054    /// [`notify_field_written`].
1055    // must post EventMask::PROPERTY to all field subscribers when metadata changes
1056    pub fn notify_field_written_if_changed(&mut self, field: &str, prev: Option<&EpicsValue>) {
1057        let upper = field.to_ascii_uppercase();
1058        if !is_metadata_field(&upper) {
1059            return;
1060        }
1061        let now = self.record.get_field(&upper);
1062        if prev != now.as_ref() {
1063            self.invalidate_metadata_cache();
1064            // mirror C dbAccess.c:1396-1397 db_post_events(precord, NULL, DBE_PROPERTY).
1065            // Collect keys first to avoid a re-entrant immutable borrow on subscribers.
1066            let fields: Vec<String> = self.subscribers.keys().cloned().collect();
1067            for f in fields {
1068                self.notify_field_with_origin(&f, crate::server::recgbl::EventMask::PROPERTY, 0);
1069            }
1070        }
1071    }
1072
1073    /// Returns the cached MetadataSnapshot, building and storing it on
1074    /// the first call (or after invalidation). Used by both
1075    /// `snapshot_for_field` and `make_monitor_snapshot` so the populate
1076    /// cost is paid at most once per metadata-stable interval.
1077    fn cached_metadata(&self) -> MetadataSnapshot {
1078        // Fast path: cache hit
1079        if let Ok(guard) = self.metadata_cache.lock()
1080            && let Some(cached) = guard.as_ref()
1081        {
1082            return cached.clone();
1083        }
1084
1085        // Cache miss: build a fresh metadata snapshot
1086        let mut tmp = super::super::snapshot::Snapshot::new(
1087            EpicsValue::Double(0.0),
1088            0,
1089            0,
1090            std::time::SystemTime::UNIX_EPOCH,
1091        );
1092        self.populate_display_info(&mut tmp);
1093        self.populate_control_info(&mut tmp);
1094        self.populate_enum_info(&mut tmp);
1095
1096        let meta = MetadataSnapshot {
1097            display: tmp.display,
1098            control: tmp.control,
1099            enums: tmp.enums,
1100        };
1101
1102        // Store back; ignore poisoning (cache is best-effort).
1103        if let Ok(mut guard) = self.metadata_cache.lock() {
1104            *guard = Some(meta.clone());
1105        }
1106        meta
1107    }
1108
1109    /// C `dbChannelSpecial(chan) == SPC_NOMOD` — **the single owner of the
1110    /// no-modify declaration**, for every consumer that needs to know whether a
1111    /// field can be written.
1112    ///
1113    /// C declares it once, in the `.dbd`, and reads it in two unrelated places:
1114    ///
1115    /// * `dbPut` (`dbAccess.c:123-126`, via `dbPutSpecial(paddr, 0)`) refuses
1116    ///   the write — the port's `check_no_mod` gate;
1117    /// * `rsrvCheckPut` (`rsrv/camessage.c:2540-2551`) — `if
1118    ///   (dbChannelSpecial(pciu->dbch) == SPC_NOMOD) return 0;` — which feeds
1119    ///   the CA `ACCESS_RIGHTS` write bit (`camessage.c:1123-1124`) as well as
1120    ///   both put paths, so a client sees `Access: read, no write` and never
1121    ///   sends the doomed write.
1122    ///
1123    /// Only the first consumer existed in the port, so every dbCommon NOMOD
1124    /// field advertised WRITE on the wire (`caput N1.SEVR 2` was refused
1125    /// server-side, after the client had already sent it, with an async
1126    /// exception instead of C's clean client-side "Write access denied").
1127    ///
1128    /// Three sources, one answer:
1129    ///
1130    /// 1. the dbCommon `SPC_NOMOD` set below — common fields, so no record's
1131    ///    `field_list` declares them;
1132    /// 2. the record type's **declaration**, resolved by [`Self::field_desc`] —
1133    ///    the vendored `.dbd` whenever one exists, and only for a record type
1134    ///    that has no `.dbd` at all (`motor`, `optics`, `scaler`, `std`) the
1135    ///    record's own hand-written table, which for those Tier 3 types
1136    ///    genuinely *is* their declaration;
1137    /// 3. [`Record::field_no_mod`] — an SPC_NOMOD a record's `cvt_dbaddr`
1138    ///    raises from its own state (compress VAL under BALG=LIFO,
1139    ///    `compressRecord.c:398-407`), which a static `FieldDesc` cannot
1140    ///    express.
1141    ///
1142    /// `field` may be any case.
1143    pub fn is_no_mod(&self, field: &str) -> bool {
1144        if DBCOMMON_NOMOD.iter().any(|f| f.eq_ignore_ascii_case(field)) {
1145            return true;
1146        }
1147        if self.field_desc(field).is_some_and(|f| f.read_only) {
1148            return true;
1149        }
1150        self.record.field_no_mod(field)
1151    }
1152
1153    /// Check if the record is currently processing (PACT equivalent).
1154    pub fn is_processing(&self) -> bool {
1155        self.pact.load(std::sync::atomic::Ordering::Acquire)
1156    }
1157
1158    /// C `prec->pact = TRUE` — the record goes busy for an async device
1159    /// round-trip, an SDLY simulation defer, or an ODLY reprocess window.
1160    pub fn enter_pact(&self) {
1161        self.pact.store(true, std::sync::atomic::Ordering::Release);
1162    }
1163
1164    /// C `prec->pact = FALSE` — the ONLY release of PACT.
1165    ///
1166    /// Every PACT→idle transition takes the put-notify parked on that window
1167    /// with it (C `dbNotifyCompletion`, reached from `recGblFwdLink` on every
1168    /// path that ends a cycle). The returned [`PactExit`] is `#[must_use]`, so
1169    /// a release site cannot strand the deferral the way the open-coded
1170    /// `processing.store(false)` at the ODLY continuation and the three SIM/SDLY
1171    /// releases did.
1172    pub fn leave_pact(&mut self) -> PactExit {
1173        self.pact.store(false, std::sync::atomic::Ordering::Release);
1174        PactExit(self.deferred_notify_put.take())
1175    }
1176
1177    /// True when a put-notify already owns this record — an in-flight wait-set
1178    /// (C `precord->ppn`) or a park from a previous PACT arm. C
1179    /// `processNotifyCommon` (dbNotify.c:213-217) queues a second notify on the
1180    /// record's restart list; the port refuses it (`S_db_Blocked` /
1181    /// `ECA_PUTCBINPROG`) — see [`Self::park_notify_put`].
1182    pub fn put_notify_busy(&self) -> bool {
1183        self.notify.is_some() || self.deferred_notify_put.is_some()
1184    }
1185
1186    /// Park a put-notify that landed on a PACT record (C `processNotifyCommon`,
1187    /// dbNotify.c:225-231). `Err(put)` hands the put back when another
1188    /// put-notify already owns the record.
1189    ///
1190    /// The [`PactExit`] invariant — `deferred_notify_put.is_some()` ⟹ PACT —
1191    /// is established here: this is the only park, and it is only reachable
1192    /// from the caller's `is_processing()` arm.
1193    pub fn park_notify_put(&mut self, put: DeferredNotifyPut) -> Result<(), DeferredNotifyPut> {
1194        debug_assert!(
1195            self.is_processing(),
1196            "a put-notify may be parked only on a PACT record"
1197        );
1198        if self.put_notify_busy() {
1199            return Err(put);
1200        }
1201        self.deferred_notify_put = Some(put);
1202        Ok(())
1203    }
1204
1205    /// Unified field resolution: record fields → common fields → virtual fields.
1206    pub fn resolve_field(&self, name: &str) -> Option<EpicsValue> {
1207        let name = name.to_ascii_uppercase();
1208        self.record
1209            .get_field(&name)
1210            .or_else(|| self.get_common_field(&name))
1211            .or_else(|| self.get_virtual_field(&name))
1212            .or_else(|| self.declared_overrides.get(&name).cloned())
1213            .or_else(|| self.declared_default(&name))
1214    }
1215
1216    /// The value a field that is DECLARED by the `.dbd` but has no live store
1217    /// on this record serves: its `initial(...)`, or a type-zero.
1218    ///
1219    /// C makes *every* `.dbd` field addressable — `dbNameToAddr` resolves the
1220    /// field from its `dbFldDes` and `dbGet` reads it out of record memory,
1221    /// which the dbd loader seeded with `initial()` (or left zero). A Rust
1222    /// record implements only the fields it has behaviour for, so a field it
1223    /// declares but never touches — `aSub.OVAL`, `sub.LA`, `sel.HOPR` — had no
1224    /// channel at all: [`Self::resolve_field`]'s three accessors all returned
1225    /// `None` and CA create-channel answered `S_dbLib_recNotFound`.
1226    ///
1227    /// The declared table is the contract for *which* fields exist; this is the
1228    /// last resort for the *value* of one with no runtime accessor, and it is
1229    /// exactly what an unprocessed C record on an empty `.db` returns —
1230    /// [`apply_dbd_initials`](crate::server::db_loader) seeds the same
1231    /// `initial()` into the fields the record *does* store, from the same
1232    /// generated table, so the two paths agree by construction.
1233    fn declared_default(&self, name: &str) -> Option<EpicsValue> {
1234        let desc = self.field_desc(name)?;
1235        // A `runtime_typed` field (`VAL`/`BG`, re-typed from `FTVL`/`SDEF`) is
1236        // record-owned by definition and its placeholder `dbf_type` is not what
1237        // it serves; never synthesise one here — the record itself answers it.
1238        if desc.runtime_typed {
1239            return None;
1240        }
1241        let initial = desc.initial.unwrap_or("");
1242        if let Some(choices) = desc
1243            .menu
1244            .or_else(|| self.record.menu_field_choices(name))
1245            .or_else(|| super::shared_menu_choices(name))
1246        {
1247            // A menu field with no `initial(...)` is index 0, exactly as an
1248            // empty numeric field is 0 below.
1249            if initial.is_empty() {
1250                return Some(EpicsValue::Enum(0));
1251            }
1252            return super::resolve_menu_field_string_db_load(name, choices, desc.dbf_type, initial)
1253                .ok();
1254        }
1255        // `parse` maps an empty string to the declared type's zero, so this one
1256        // call serves both `initial(...)` and no-initial fields.
1257        EpicsValue::parse_bytes(desc.dbf_type, initial.as_bytes()).ok()
1258    }
1259
1260    /// Resolve a field for EPICS `$` long-string (character-array) access.
1261    ///
1262    /// The `$` channel-name modifier (C `dbChannel.c:486-505`) re-views a
1263    /// field as a `DBR_CHAR` array: a `DBF_STRING` field becomes a char
1264    /// array of `field_size` elements, a link field a char array of
1265    /// `PVLINK_STRINGSZ`, and every other field type is rejected with
1266    /// `S_dbLib_fieldNotFound`. pvxs serves that char view as a
1267    /// `form = "String"` long-string `NTScalar` — it reads the `DBR_CHAR`
1268    /// bytes and NUL-terminates them back into a string
1269    /// (`ioc/iocsource.cpp:133-136`, `ioc/channel.cpp:62-74`).
1270    ///
1271    /// Both `DBF_STRING` fields and link fields resolve to an
1272    /// [`EpicsValue::String`] in this database (a link resolves to its
1273    /// textual form, see [`Self::get_common_field`]), so a field is
1274    /// `$`-eligible exactly when it resolves to a string value. Returns
1275    /// that string value for an eligible field, or `None` for a field the
1276    /// `$` modifier cannot view as a char array (the
1277    /// `S_dbLib_fieldNotFound` case) — the single owner of the
1278    /// dbChannel `$`-eligibility rule for the channel-resolution layer.
1279    pub fn resolve_string_view_field(&self, name: &str) -> Option<EpicsValue> {
1280        match self.resolve_field(name)? {
1281            v @ EpicsValue::String(_) => Some(v),
1282            _ => None,
1283        }
1284    }
1285
1286    /// Choice table for a field served as `DBR_ENUM` from a `DBF_MENU`:
1287    /// the record's own record-specific menu
1288    /// ([`Record::menu_field_choices`](super::record_trait::Record::menu_field_choices)),
1289    /// else a shared menu keyed by field name
1290    /// ([`shared_menu_choices`](super::menu_choices::shared_menu_choices)).
1291    /// The choices a `menu()` field serves as its `DBR_ENUM` labels.
1292    ///
1293    /// The `.dbd` declaration is the first and best answer: a generated
1294    /// [`FieldDesc`] carries the field's own `menu(...)` choices, which is what
1295    /// C's `dbGetFieldIndex` -> `pamapdbfType` -> menu lookup resolves. The two
1296    /// hand-maintained fallbacks below are for record types still on a
1297    /// hand-written table; they go away with the last of them.
1298    ///
1299    /// `shared_menu_choices` in particular keys on the field NAME alone, across
1300    /// every record type — which is only correct while no two record types give
1301    /// the same field name different menus. Asking the field's own descriptor
1302    /// first removes that assumption.
1303    fn menu_choices_for(&self, field: &str) -> Option<&'static [&'static str]> {
1304        menu_choices_of(self.record.as_ref(), field)
1305    }
1306
1307    /// The choices this record's `DTYP` selects among — C's `dbDeviceMenu` for
1308    /// the record type, in `.dbd` declaration order.
1309    ///
1310    /// C's DTYP field IS the index into this list, and an unset DTYP is index 0
1311    /// — which is why a bare `record(ai,"X"){}` serves `Soft Channel` and a
1312    /// `record(calc,"X"){}`, whose record type declares no device support at
1313    /// all, serves the empty string.
1314    ///
1315    /// The port stores the device NAME rather than the index, because the name
1316    /// is what the device-support registry dispatches on, and a name registered
1317    /// at runtime by a downstream crate (`asynInt32`) has no `device()` line in
1318    /// any vendored `.dbd`. Such a name is appended as its own slot, so the
1319    /// index and the string still name the SAME device support: there is no
1320    /// value of DTYP that renders as a device this record is not bound to.
1321    /// `None` when the record type declares NO device support at all — C's
1322    /// `dbDeviceMenu *pdevs = paddr->pfldDes->ftPvt; if (!pdevs) goto nostrs;`
1323    /// (`dbAccess.c:176-179`), which clears `DBR_ENUM_STRS` so the client is
1324    /// sent no choice list at all.
1325    ///
1326    /// C keeps that case DISTINCT from a device menu that exists but is empty,
1327    /// and says so at `dbAccess.c:205`: *"indicate option data not available.
1328    /// distinct from no_str==0"*. An empty-but-present menu is still marked,
1329    /// with `no_str = 0`; a missing menu is not marked. Returning `Vec` here
1330    /// and defaulting the missing menu to `[]` collapsed the two, so a
1331    /// `record(calc,"X"){}` — whose record type has no `device()` line — served
1332    /// `value.choices = {0}[]` where QSRV2 omits the leaf entirely.
1333    pub(crate) fn device_choices(&self) -> Option<Vec<PvString>> {
1334        let record_type = self.record.record_type();
1335        // Base's build-time menu (`epics-base-rs/dbd`), then the menus a
1336        // downstream crate whose device support has no vendored `device()` line
1337        // registered at runtime (asyn's `asynInt32`, `asynFloat64`, ...). C's
1338        // `dbDeviceMenu` is the concatenation of every `device()` the loaded
1339        // `.dbd` set declares, in load order — base first, then asyn — so the
1340        // merge appends the contributed choices AFTER the declared ones.
1341        let declared = super::dbd_generated::device_menu(record_type);
1342        let contributed = super::contributed_device_menu(record_type);
1343        // The C None-vs-empty distinction (`dbAccess.c:176-179` vs `:205`): the
1344        // menu is present iff the loaded `.dbd` set declares ANY `device()` for
1345        // this type. A type base declares none for but asyn does (structurally
1346        // possible, though none of asyn's are such) is therefore present, not
1347        // None; a type neither declares for (calc) stays None.
1348        if declared.is_none() && contributed.is_empty() {
1349            return None;
1350        }
1351        let mut names: Vec<&str> = Vec::new();
1352        if let Some(declared) = declared {
1353            names.extend_from_slice(declared);
1354        }
1355        names.extend(contributed.iter().copied());
1356        let dtyp = self.common.dtyp.as_str();
1357        if !dtyp.is_empty() && !names.contains(&dtyp) {
1358            names.push(dtyp);
1359        }
1360        Some(names.iter().map(|c| PvString::from(*c)).collect())
1361    }
1362
1363    /// C `dbPutFieldLink`'s link-type gate (`dbAccess.c:1125-1137`): a link
1364    /// written at RUNTIME is held to the same `dbCanSetLink` rule as one written
1365    /// by the `.db`, against the device support the record's CURRENT `DTYP`
1366    /// binds. Same rule, same owner — [`super::check_link_assignment`]; only the
1367    /// DTYP it is asked about differs (the record's, not the `.db` text's).
1368    ///
1369    /// [`MenuBound::DbLoad`] is exempt, and that is not a hole: on the db-load
1370    /// path C does not check a link as each field is parsed either. It checks
1371    /// once, at `iocInit`, over the record as loaded (`dbStaticLib.c:2178-2231`)
1372    /// — which is why `field(INP,…)` may precede `field(DTYP,…)` in a `.db` and
1373    /// still bind. `db_loader::check_link_types` is that pass, and it reads the
1374    /// record's DTYP out of the whole field set, so it does not depend on the
1375    /// order the `.db` happened to spell them in. Gating here as well would
1376    /// re-introduce exactly that order dependence.
1377    fn check_link_assignment(
1378        &self,
1379        upper_field: &str,
1380        text: &str,
1381        bound: MenuBound,
1382    ) -> CaResult<()> {
1383        if matches!(bound, MenuBound::DbLoad) {
1384            return Ok(());
1385        }
1386        super::check_link_assignment(
1387            self.record.record_type(),
1388            Some(self.common.dtyp.as_str()),
1389            upper_field,
1390            text,
1391        )
1392    }
1393
1394    /// The value of the `DTYP` field: the index of the bound device support in
1395    /// [`Self::device_choices`]. An unset DTYP is index 0, exactly as in C.
1396    pub(crate) fn dtyp_index(&self) -> u16 {
1397        let dtyp = self.common.dtyp.as_str();
1398        if dtyp.is_empty() {
1399            return 0;
1400        }
1401        // A record type with no device menu has no slot for any DTYP, so the
1402        // index stays 0 — the same answer the old `unwrap_or(&[])` gave.
1403        self.device_choices()
1404            .unwrap_or_default()
1405            .iter()
1406            .position(|c| c.as_str_lossy() == dtyp)
1407            .unwrap_or(0) as u16
1408    }
1409
1410    /// **The** owner of "what string does this enum-valued field render as" —
1411    /// C's `[DBF_*][DBR_STRING]` conversion row, chosen by the field's DBF
1412    /// class. Every path that renders an enum as a string goes through here:
1413    /// the CA/PVA encoders (via [`snapshot::EnumInfo::string_form`] on the
1414    /// snapshot this builds) and the db-link read
1415    /// ([`Self::field_as_dbr_string`]). There is exactly one such table per
1416    /// field, and no path may reconstruct a second one.
1417    ///
1418    /// C's dispatch, and this function's, in the same order:
1419    ///
1420    /// * `DBF_MENU` / `DBF_DEVICE` -> `getMenuString` / `getDeviceString`, the
1421    ///   field's own choice list. Asked FIRST, because a menu field on a record
1422    ///   whose `VAL` is an enum (`bo.OMSL`) must render its menu's choices, not
1423    ///   the record's `ZNAM`/`ONAM`.
1424    /// * `DBF_ENUM` `VAL` -> `getEnumString` -> the record's `get_enum_str`
1425    ///   rset ([`Record::enum_string_form`](super::record_trait::Record::enum_string_form)).
1426    ///
1427    /// `None` when the field has neither — C answers `S_db_noRSET`, an error;
1428    /// the port renders empty.
1429    ///
1430    /// Each class brings its own out-of-range rule with it (see
1431    /// [`EnumOverflow`](crate::server::snapshot::EnumOverflow)); the index is
1432    /// rendered as a number for a `DBF_MENU` and ONLY for a `DBF_MENU`.
1433    pub(crate) fn enum_string_form_for(&self, field: &str) -> Option<EnumStringForm> {
1434        if field.eq_ignore_ascii_case("DTYP") {
1435            // `None` propagates C's `goto nostrs` (`dbAccess.c:178`): a record
1436            // type with no `device()` declaration supplies no choice list, so
1437            // the leaf is omitted rather than marked empty.
1438            return self.device_choices().map(EnumStringForm::device);
1439        }
1440        if let Some(choices) = self.menu_choices_for(field) {
1441            return Some(EnumStringForm::menu(
1442                choices.iter().map(|c| PvString::from(*c)),
1443            ));
1444        }
1445        if field.eq_ignore_ascii_case("VAL") {
1446            return self.record.enum_string_form();
1447        }
1448        None
1449    }
1450
1451    /// Is `field` one of the DBF classes C's soft device support writes as
1452    /// `DBR_STRING`?
1453    ///
1454    /// `devsCalcoutSoft.c:128-130` (and its async twin, :83-85) switches the
1455    /// scalcout OUT put on the TARGET field's DBF type and sends `OSV` — the
1456    /// string result — for seven of them:
1457    ///
1458    /// ```c
1459    /// case DBF_STRING: case DBF_ENUM: case DBF_MENU: case DBF_DEVICE:
1460    /// case DBF_INLINK: case DBF_OUTLINK: case DBF_FWDLINK:
1461    ///     status = dbPutLink(&pscalcout->out, DBR_STRING, &pscalcout->osv, 1);
1462    /// ```
1463    ///
1464    /// [`DbFieldType`] is the port's DBR *wire* type and cannot express
1465    /// `DBF_MENU` / `DBF_DEVICE` — C's DBF class is not the DBR type. The
1466    /// classification therefore lives here, with the record's field metadata,
1467    /// where each class is already known:
1468    ///
1469    /// * `DBF_STRING` and the three link classes — the port stores links and
1470    ///   `DTYP` (C's only `DBF_DEVICE` field) as strings;
1471    /// * `DBF_ENUM` — an enum-typed field;
1472    /// * `DBF_MENU` — a menu-index field, i.e. one this record resolves choice
1473    ///   labels for ([`Self::menu_choices_for`]): `PRIO`, `STAT`, `SEVR`,
1474    ///   `DISS`, `ACKT`, `SCAN`, `IVOA`, `OMSL`, … The index is stored as a
1475    ///   short, so a same-named field that is NOT a menu index (scalcout's
1476    ///   string `OSV` shares a name with the alarm-severity menu) is
1477    ///   classified by its own type, not by the name collision.
1478    ///
1479    /// Everything else (`DBF_DOUBLE`, `DBF_LONG`, `DBF_CHAR`, …) falls to the
1480    /// device support's `default:` arm.
1481    ///
1482    /// The question is about the target field's DECLARED class, so it is asked
1483    /// of the declaration ([`Self::declared_field_type`]) and not of the
1484    /// variant the record stores: C's `switch` is on `dbAddr.field_type`, which
1485    /// `dbNameToAddr` took from the `dbFldDes`. `DBF_MENU` and `DBF_DEVICE` both
1486    /// map to `DbFieldType::Enum` in the generated tables (`mapDBFToDBR`), and
1487    /// the three link classes to `DbFieldType::String`, so the seven C arms are
1488    /// exactly these two.
1489    pub(crate) fn field_puts_as_string(&self, field: &str) -> bool {
1490        let Some(declared) = self.declared_field_type(field) else {
1491            return false;
1492        };
1493        matches!(declared, DbFieldType::String | DbFieldType::Enum)
1494    }
1495
1496    /// The field's value as C `dbGetLink(plink, DBR_STRING, ...)` delivers it —
1497    /// the SOURCE side of an input link read with
1498    /// [`LinkReadAs::String`](super::record_trait::LinkReadAs::String).
1499    ///
1500    /// C converts at the source, through `dbConvert.c`'s
1501    /// `[field_type][DBR_STRING]` table: a `DBF_ENUM` field goes through
1502    /// `getEnumString` → the record's `get_enum_str` (mbbi's `ZRST`.., bi's
1503    /// `ZNAM`/`ONAM`) and a `DBF_MENU` field through `getMenuString` → the
1504    /// menu's choice string, i.e. the state LABEL in both cases, never the
1505    /// index. Only the record holds those tables, so the render lives here with
1506    /// the field metadata — the link-read owner has an index and nothing to
1507    /// resolve it with.
1508    ///
1509    /// The render goes through [`Self::enum_string_form_for`], the same owner
1510    /// the CA/PVA encoders use, so a link read and a `caget -t` of one field can
1511    /// never disagree about its string.
1512    pub(crate) fn field_as_dbr_string(&self, field: &str) -> Option<PvString> {
1513        let value = self.resolve_field(field)?;
1514        // A `DBF_ENUM` index, and a `DBF_MENU` index (stored as a short),
1515        // render through the field's string source. A short field that is
1516        // neither has no source and stays the plain number C converts it to.
1517        let idx = match value {
1518            EpicsValue::Enum(v) => Some(v),
1519            EpicsValue::Short(v) => u16::try_from(v).ok(),
1520            _ => None,
1521        };
1522        if let Some(idx) = idx
1523            && let Some(form) = self.enum_string_form_for(field)
1524        {
1525            return Some(form.render(idx));
1526        }
1527        value_as_dbr_string(&value)
1528    }
1529
1530    /// The field's declaration — its `dbFldDes`, in C's terms.
1531    ///
1532    /// The `.dbd` is the declaration, so the table generated FROM the `.dbd`
1533    /// ([`dbd_generated::record_fields`](super::dbd_generated::record_fields))
1534    /// is asked first, for every record type that has one. A record's own
1535    /// [`Record::field_list`](super::record_trait::Record::field_list) is a
1536    /// hand-written stand-in for that table, and it is consulted only for a
1537    /// record type the `.dbd` does not cover (`subArray`, and the record types
1538    /// the downstream crates add). It cannot be the primary answer: several of
1539    /// those tables are *derived from the record's Rust storage types* — the
1540    /// `#[derive(EpicsRecord)]` records type `longin.ADEL` `DBF_DOUBLE`
1541    /// because the struct member is an `f64`, where the `.dbd` says
1542    /// `DBF_LONG` — and reading the type off the storage is the whole defect
1543    /// this owner exists to close.
1544    ///
1545    /// `dbCommon` last, matching the order [`Self::resolve_field`] reads the
1546    /// value in, so a record-specific field always shadows the common one in
1547    /// both halves.
1548    ///
1549    /// `None` for a field with no declaration at all: a virtual field
1550    /// (`RTYP`, `TIME`, ...), which C answers from dbStaticLib rather than
1551    /// from a `dbFldDes`.
1552    pub(crate) fn field_desc(&self, field: &str) -> Option<&'static FieldDesc> {
1553        field_desc_of(self.record.as_ref(), field)
1554    }
1555
1556    /// The `DBF_*` type `field` is SERVED as — the single source of truth for
1557    /// the type on the wire, on every delivery path.
1558    ///
1559    /// This is the field's DECLARED type ([`FieldDesc::dbf_type`], from the
1560    /// `.dbd`), not the type of whatever variant the record happens to store.
1561    /// C resolves a channel's `field_type` from the `dbFldDes` at
1562    /// name-resolution time (`dbChannelCreate` -> `dbNameToAddr`,
1563    /// `dbAccess.c:184-205`) and every later `dbGet`/`db_post_events` converts
1564    /// the stored bytes to it — the storage is private to the record, the
1565    /// declaration is the contract.
1566    ///
1567    /// Two answers are NOT the declaration:
1568    ///
1569    /// * a [`FieldDesc::runtime_typed`] field — C's `cvt_dbaddr` overwrites
1570    ///   `paddr->field_type` from record state (`FTVL`, `FTA`, `SDEF`), and
1571    ///   this port's `cvt_dbaddr` is the variant the record stores;
1572    /// * a field with no `FieldDesc` at all (a virtual field).
1573    ///
1574    /// In both cases the value's own type is the answer, so this returns
1575    /// `None` and [`Self::project_to_declared_type`] leaves the value alone.
1576    pub fn declared_field_type(&self, field: &str) -> Option<DbFieldType> {
1577        declared_field_type_of(self.record.as_ref(), field)
1578    }
1579
1580    /// Project a field's stored value onto its declared type
1581    /// ([`Self::declared_field_type`]) — the single owner of "what type this
1582    /// field goes on the wire as", run by the CA create-channel path
1583    /// ([`Self::client_field_value`]), the GET path
1584    /// ([`Self::snapshot_for_field`]) and the MONITOR path
1585    /// ([`Self::make_monitor_snapshot`]), so all three announce and serve the
1586    /// same type.
1587    ///
1588    /// The projection is [`EpicsValue::convert_to`], the one value-coercion
1589    /// owner — the same routine `dbGet` converts through. Never re-derive a
1590    /// conversion here: C picks its routine from BOTH the source and the
1591    /// destination type, and only `convert_to` knows that table.
1592    ///
1593    /// Idempotent: a value already of its declared type is short-circuited by
1594    /// `convert_to`, and re-projecting a projected value is a no-op. That is
1595    /// what lets the CA path derive the native type from the value it is about
1596    /// to serve.
1597    pub fn project_to_declared_type(&self, field: &str, value: EpicsValue) -> EpicsValue {
1598        match self.declared_field_type(field) {
1599            Some(declared) => value.convert_to(declared),
1600            None => value,
1601        }
1602    }
1603
1604    /// The client-facing value of `field`: the resolved value projected onto
1605    /// the field's declared type ([`Self::project_to_declared_type`]), so a
1606    /// native type derived from the value — which is what the CA
1607    /// create-channel path does — is the DECLARED type, and matches the
1608    /// GET/MONITOR data byte for byte.
1609    pub fn client_field_value(&self, field: &str) -> Option<EpicsValue> {
1610        let value = self.resolve_field(field)?;
1611        Some(self.project_to_declared_type(field, value))
1612    }
1613
1614    /// Attach a `DBF_MENU` field's `menu()` choice labels to a built snapshot,
1615    /// so the CA/PVA enum encoders present `"NO CONVERSION"` rather than `0`.
1616    ///
1617    /// The VALUE half of the `DBF_MENU` -> `DBR_ENUM` mapping is not here: the
1618    /// `.dbd` declares a menu field `DBF_MENU`, the generator types that
1619    /// `DbFieldType::Enum` (`mapDBFToDBR`), and
1620    /// [`Self::project_to_declared_type`] — which every delivery path runs —
1621    /// makes the served value an [`EpicsValue::Enum`] on that declaration
1622    /// alone. So the label table is all that is left to attach, and it is
1623    /// attached exactly when the served value came out an enum. A same-named
1624    /// field that is NOT a menu index (`scalcout.OSV`, declared `DBF_STRING`,
1625    /// shares a name with the alarm-severity menu) is served as its own
1626    /// declared string and gets no choice table.
1627    fn attach_menu_enum(&self, field: &str, snap: &mut super::super::snapshot::Snapshot) {
1628        if !matches!(snap.value, EpicsValue::Enum(_)) {
1629            return;
1630        }
1631        // `VAL` is the one field whose two rset slots differ: C's
1632        // `get_enum_strs` (the `DBR_GR_ENUM` labels) is TRIMMED to `no_str`
1633        // while `get_enum_str` (the DBR_STRING form) indexes the untrimmed
1634        // state array. `populate_enum_info` owns that pair; every OTHER
1635        // enum-valued field is a menu or a device, whose one choice list
1636        // answers both (C `getMenuString`/`getDeviceString` index the same
1637        // `papChoiceValue` the GR_ENUM reply carries).
1638        if field.eq_ignore_ascii_case("VAL") {
1639            return;
1640        }
1641        let Some(form) = self.enum_string_form_for(field) else {
1642            return;
1643        };
1644        snap.enums = Some(super::super::snapshot::EnumInfo::with_string_form(
1645            form.slots.clone(),
1646            form,
1647        ));
1648    }
1649
1650    /// Build a Snapshot with full metadata for the given field.
1651    pub fn snapshot_for_field(&self, field: &str) -> Option<super::super::snapshot::Snapshot> {
1652        // The GET path serves the field at its DECLARED type, the same type
1653        // the CA create-channel path announced from `client_field_value` and
1654        // the same one the monitor path posts.
1655        let value = self.client_field_value(field)?;
1656        let mut snap = super::super::snapshot::Snapshot::new(
1657            value,
1658            self.common.stat,
1659            self.common.sevr as u16,
1660            self.common.time,
1661        );
1662        // Default the served `timeStamp.userTag` to the record's `utag`,
1663        // mirroring pvxs `iocsource.cpp:245` (`auto utag = meta.utag;`).
1664        // The 64-bit `epicsUTag` narrows to the int32 NT wire field by
1665        // truncating to the low 32 bits — pvxs assigns the same uint64
1666        // straight into the `Int32` `timeStamp.userTag`. The `Q:time:tag`
1667        // nsec-LSB split below overrides this when configured, matching
1668        // pvxs `if(info.nsecMask) utag = meta.time.nsec & info.nsecMask;`
1669        // (:247).
1670        snap.user_tag = self.common.utag as i32;
1671        // Carry the record's committed alarm message (`common.amsg`) so a
1672        // PVA read serves `alarm.message` from the record's own amsg
1673        // (pvxs `iocsource.cpp:230-236` prefers `meta.amsg`) rather than a
1674        // string re-synthesized from the condition code. Empty for records
1675        // that raise no message (C's plain `recGblSetSevr` clears namsg).
1676        snap.alarm.amsg = self.common.amsg.clone();
1677
1678        // Pull display/control/enums from the metadata cache (build on
1679        // first call, hit thereafter until invalidated by a metadata-class
1680        // field write).
1681        let meta = self.cached_metadata();
1682        snap.display = meta.display;
1683        snap.control = meta.control;
1684        snap.enums = meta.enums;
1685
1686        // The cache above is the record's VAL metadata. C routes PER FIELD, so
1687        // a non-VAL-class field does NOT get VAL's limits — see
1688        // [`Self::route_field_metadata`], which owns that decision.
1689        self.route_field_metadata(field, &mut snap);
1690
1691        // Per-field RSET metadata (C get_units/get_precision/
1692        // get_graphic_double/get_control_double/get_alarm_double key on
1693        // dbGetFieldIndex) patches the record-level cache for this field.
1694        self.apply_field_metadata_override(field, &mut snap);
1695
1696        // DBF_MENU field (a shared menu such as `SCAN`/`OMSL`/`HHSV`/... or
1697        // a record-specific menu such as `sel.SELM`): carry the menu index
1698        // as DBR_ENUM and attach its `menu()` choice labels. See
1699        // `attach_menu_enum`. This overrides any record VAL enum table
1700        // copied from the metadata cache above, because a menu field
1701        // carries its own menu's choices, not the record's VAL state
1702        // strings.
1703        self.attach_menu_enum(field, &mut snap);
1704
1705        // The metadata VALUES and the mask that says which of them this
1706        // channel actually supplies are assigned by the same owner, from the
1707        // settled value, so they cannot disagree.
1708        self.assign_property_support(field, &mut snap);
1709
1710        // apply `info(Q:time:tag, "nsec:lsb:N")` — pvxs
1711        // `iocsource.cpp:239-248` publishes `nanoseconds & ~nsecMask` and
1712        // moves `nanoseconds & nsecMask` into `timeStamp.userTag`. The
1713        // split is applied to both `snap.timestamp` and `snap.user_tag` so
1714        // downstream encoders (NTScalar `timeStamp`, QSRV groups) all see
1715        // the same shape. A zero mask (tag absent or unparseable) is a
1716        // no-op inside the helper, exactly as pvxs's `if(info.nsecMask)`
1717        // gate is.
1718        crate::server::snapshot::apply_nsec_mask(&mut snap, self.qtime_nsec_mask());
1719
1720        Some(snap)
1721    }
1722
1723    /// Resolve `info(Q:time:tag)` to pvxs's `MappingInfo::nsecMask`.
1724    /// Returns 0 (the "no split" mask) when the tag is absent or does not
1725    /// parse — pvxs leaves `nsecMask` at its 0 initialiser in that case.
1726    ///
1727    /// pvxs `ioc/typeutils.cpp:79-88`:
1728    ///
1729    /// ```c
1730    /// if(auto val = ent.info("Q:time:tag")) {
1731    ///     epicsInt32 dig = 0;
1732    ///     if(strncmp(val, "nsec:lsb:", 9)==0 && !epicsParseInt32(&val[9], &dig, 10, nullptr)) {
1733    ///         nsecMask = (uint64_t(1u)<<dig)-1u;
1734    ///     }
1735    /// }
1736    /// ```
1737    ///
1738    /// The prefix test is a byte-exact `strncmp` — no case folding and no
1739    /// whitespace tolerance, so `NSEC:LSB:4` and `nsec: lsb: 4` do NOT
1740    /// match and leave the timestamp alone. There is no bounds clamp
1741    /// either: any `dig` `epicsParseInt32` accepts is shifted verbatim, so
1742    /// `nsec:lsb:31` yields the `0x7FFF_FFFF` mask pvxs actually serves.
1743    fn qtime_nsec_mask(&self) -> u64 {
1744        let Some(rest) = self
1745            .get_info("Q:time:tag")
1746            .and_then(|v| v.strip_prefix("nsec:lsb:"))
1747        else {
1748            return 0;
1749        };
1750        let Some(dig) = epics_parse_int32_base10(rest) else {
1751            return 0;
1752        };
1753        // C shifts `uint64_t(1u)` by an `epicsInt32`. A `dig` outside
1754        // `0..=63` is UB in C++; every ISA EPICS builds on (x86-64 `shlq`,
1755        // aarch64 `lsl`) takes the shift count modulo 64, which is what
1756        // `wrapping_shl` does — so `nsec:lsb:64` disables the split
1757        // (mask 0) and a negative `dig` shifts by `dig & 63`, the same
1758        // masks pvxs produces on those hosts.
1759        1u64.wrapping_shl(dig as u32) - 1
1760    }
1761
1762    /// Populate DisplayInfo from record fields if applicable.
1763    /// Resolve the `Q:form` info-tag value to a `display.form` menu index.
1764    ///
1765    /// pvxs publishes the fixed seven-entry form menu
1766    /// (Default/String/Binary/Decimal/Hex/Exponential/Engineering) for every
1767    /// numeric value and, for the VAL field only, sets `display.form.index`
1768    /// to the slot whose name equals the field's `Q:form` info tag
1769    /// (`iocsource.cpp:42-62`, case-sensitive). Unset or unrecognised ->
1770    /// `None` (form stays 0 = Default), exactly as pvxs leaves the index
1771    /// untouched on no match.
1772    fn q_form_index(&self) -> Option<i16> {
1773        const FORM_NAMES: [&str; 7] = [
1774            "Default",
1775            "String",
1776            "Binary",
1777            "Decimal",
1778            "Hex",
1779            "Exponential",
1780            "Engineering",
1781        ];
1782        let tag = self.info.get("Q:form")?;
1783        FORM_NAMES
1784            .iter()
1785            .position(|name| name == tag)
1786            .map(|i| i as i16)
1787    }
1788
1789    /// Stamp a built snapshot with the property mask THIS channel supplies —
1790    /// [`Self::property_support`] narrowed to the addressed field by C's
1791    /// second gate ([`PropertySupport::narrowed_to_field`]). Called by both
1792    /// snapshot builders once the value has settled (after
1793    /// [`Self::attach_menu_enum`] promoted a `DBF_MENU` field to its
1794    /// `DBR_ENUM` form), so the mask is read off the same value the client
1795    /// receives and no consumer has to re-derive either gate.
1796    fn assign_property_support(&self, field: &str, snap: &mut super::super::snapshot::Snapshot) {
1797        snap.properties = self.record.property_support().narrowed_to_field(
1798            snap.value.db_field_type(),
1799            self.menu_choices_for(field).is_some(),
1800        );
1801    }
1802
1803    /// The property mask a channel on `field` supplies, without building a
1804    /// snapshot — what a PVA server needs to decide which NT leaves it may
1805    /// MARK for a channel it has not read yet (QSRV resolves a group's member
1806    /// masks once, at monitor start, rather than per event).
1807    ///
1808    /// Same two gates, same owner as [`Self::assign_property_support`]: an
1809    /// unknown field supplies nothing.
1810    pub fn property_support_for_field(&self, field: &str) -> PropertySupport {
1811        let Some(value) = self.client_field_value(field) else {
1812            return PropertySupport::NONE;
1813        };
1814        self.record.property_support().narrowed_to_field(
1815            value.db_field_type(),
1816            self.menu_choices_for(field).is_some(),
1817        )
1818    }
1819
1820    fn populate_display_info(&self, snap: &mut super::super::snapshot::Snapshot) {
1821        let rtype = self.record.record_type();
1822        match rtype {
1823            "ai" | "ao" | "calc" | "calcout" => {
1824                let egu = self
1825                    .record
1826                    .get_field("EGU")
1827                    .and_then(|v| {
1828                        if let EpicsValue::String(s) = v {
1829                            Some(s)
1830                        } else {
1831                            None
1832                        }
1833                    })
1834                    .unwrap_or_default();
1835                let prec = self
1836                    .record
1837                    .get_field("PREC")
1838                    .and_then(|v| v.to_f64())
1839                    .unwrap_or(0.0) as i16;
1840                let hopr = self
1841                    .record
1842                    .get_field("HOPR")
1843                    .and_then(|v| v.to_f64())
1844                    .unwrap_or(0.0);
1845                let lopr = self
1846                    .record
1847                    .get_field("LOPR")
1848                    .and_then(|v| v.to_f64())
1849                    .unwrap_or(0.0);
1850                snap.display = Some(super::super::snapshot::DisplayInfo {
1851                    units: egu,
1852                    precision: prec,
1853                    upper_disp_limit: hopr,
1854                    lower_disp_limit: lopr,
1855                    ..Default::default()
1856                });
1857            }
1858            "longin" | "longout" | "int64in" | "int64out" => {
1859                let egu = self
1860                    .record
1861                    .get_field("EGU")
1862                    .and_then(|v| {
1863                        if let EpicsValue::String(s) = v {
1864                            Some(s)
1865                        } else {
1866                            None
1867                        }
1868                    })
1869                    .unwrap_or_default();
1870                let hopr = self
1871                    .record
1872                    .get_field("HOPR")
1873                    .and_then(|v| v.to_f64())
1874                    .unwrap_or(0.0);
1875                let lopr = self
1876                    .record
1877                    .get_field("LOPR")
1878                    .and_then(|v| v.to_f64())
1879                    .unwrap_or(0.0);
1880                snap.display = Some(super::super::snapshot::DisplayInfo {
1881                    units: egu,
1882                    precision: 0,
1883                    upper_disp_limit: hopr,
1884                    lower_disp_limit: lopr,
1885                    ..Default::default()
1886                });
1887            }
1888            // waveform/aai/aao — HOPR/LOPR/PREC/EGU for VAL display limits.
1889            // (waveformRecord.c:251-252,239; aaiRecord.c:280-281,268; aaoRecord.c:283-284)
1890            "waveform" | "aai" | "aao" => {
1891                let egu = self
1892                    .record
1893                    .get_field("EGU")
1894                    .and_then(|v| {
1895                        if let EpicsValue::String(s) = v {
1896                            Some(s)
1897                        } else {
1898                            None
1899                        }
1900                    })
1901                    .unwrap_or_default();
1902                let prec = self
1903                    .record
1904                    .get_field("PREC")
1905                    .and_then(|v| v.to_f64())
1906                    .unwrap_or(0.0) as i16;
1907                let hopr = self
1908                    .record
1909                    .get_field("HOPR")
1910                    .and_then(|v| v.to_f64())
1911                    .unwrap_or(0.0);
1912                let lopr = self
1913                    .record
1914                    .get_field("LOPR")
1915                    .and_then(|v| v.to_f64())
1916                    .unwrap_or(0.0);
1917                snap.display = Some(super::super::snapshot::DisplayInfo {
1918                    units: egu,
1919                    precision: prec,
1920                    upper_disp_limit: hopr,
1921                    lower_disp_limit: lopr,
1922                    ..Default::default()
1923                });
1924            }
1925            // compress — HOPR/LOPR/PREC/EGU for VAL display limits.
1926            // (compressRecord.c:478-479,464,455)
1927            "compress" => {
1928                let egu = self
1929                    .record
1930                    .get_field("EGU")
1931                    .and_then(|v| {
1932                        if let EpicsValue::String(s) = v {
1933                            Some(s)
1934                        } else {
1935                            None
1936                        }
1937                    })
1938                    .unwrap_or_default();
1939                let prec = self
1940                    .record
1941                    .get_field("PREC")
1942                    .and_then(|v| v.to_f64())
1943                    .unwrap_or(0.0) as i16;
1944                let hopr = self
1945                    .record
1946                    .get_field("HOPR")
1947                    .and_then(|v| v.to_f64())
1948                    .unwrap_or(0.0);
1949                let lopr = self
1950                    .record
1951                    .get_field("LOPR")
1952                    .and_then(|v| v.to_f64())
1953                    .unwrap_or(0.0);
1954                snap.display = Some(super::super::snapshot::DisplayInfo {
1955                    units: egu,
1956                    precision: prec,
1957                    upper_disp_limit: hopr,
1958                    lower_disp_limit: lopr,
1959                    ..Default::default()
1960                });
1961            }
1962            "motor" => {
1963                let egu = self
1964                    .record
1965                    .get_field("EGU")
1966                    .and_then(|v| {
1967                        if let EpicsValue::String(s) = v {
1968                            Some(s)
1969                        } else {
1970                            None
1971                        }
1972                    })
1973                    .unwrap_or_default();
1974                let prec = self
1975                    .record
1976                    .get_field("PREC")
1977                    .and_then(|v| v.to_f64())
1978                    .unwrap_or(0.0) as i16;
1979                let hlm = self
1980                    .record
1981                    .get_field("HLM")
1982                    .and_then(|v| v.to_f64())
1983                    .unwrap_or(0.0);
1984                let llm = self
1985                    .record
1986                    .get_field("LLM")
1987                    .and_then(|v| v.to_f64())
1988                    .unwrap_or(0.0);
1989                snap.display = Some(super::super::snapshot::DisplayInfo {
1990                    units: egu,
1991                    precision: prec,
1992                    upper_disp_limit: hlm,
1993                    lower_disp_limit: llm,
1994                    ..Default::default()
1995                });
1996            }
1997            _ => {}
1998        }
1999        // Apply the `Q:form` display-format hint. The match above builds
2000        // `snap.display` only for numeric record types — the same set for
2001        // which pvxs emits `display.form.choices`. This cache is
2002        // record-level (it is the VAL field's metadata); the VAL-only rule
2003        // pvxs applies to `display.form.index` (`iocsource.cpp:53`) is
2004        // enforced per served field in `apply_field_metadata_override`.
2005        if let Some(display) = snap.display.as_mut() {
2006            if let Some(form) = self.q_form_index() {
2007                display.form = form;
2008            }
2009        }
2010    }
2011
2012    /// Populate ControlInfo from record fields if applicable.
2013    fn populate_control_info(&self, snap: &mut super::super::snapshot::Snapshot) {
2014        let rtype = self.record.record_type();
2015        match rtype {
2016            // ao unconditionally uses DRVH/DRVL (aoRecord.c:356-357).
2017            "ao" => {
2018                let upper = self
2019                    .record
2020                    .get_field("DRVH")
2021                    .and_then(|v| v.to_f64())
2022                    .unwrap_or(0.0);
2023                let lower = self
2024                    .record
2025                    .get_field("DRVL")
2026                    .and_then(|v| v.to_f64())
2027                    .unwrap_or(0.0);
2028                snap.control = Some(super::super::snapshot::ControlInfo {
2029                    upper_ctrl_limit: upper,
2030                    lower_ctrl_limit: lower,
2031                });
2032            }
2033            // longout/int64out use DRVH/DRVL only when drvh > drvl, else HOPR/LOPR
2034            // (longoutRecord.c:282-287, int64outRecord.c:265-270).
2035            "longout" | "int64out" => {
2036                let drvh = self
2037                    .record
2038                    .get_field("DRVH")
2039                    .and_then(|v| v.to_f64())
2040                    .unwrap_or(0.0);
2041                let drvl = self
2042                    .record
2043                    .get_field("DRVL")
2044                    .and_then(|v| v.to_f64())
2045                    .unwrap_or(0.0);
2046                let (upper, lower) = if drvh > drvl {
2047                    (drvh, drvl)
2048                } else {
2049                    let hopr = self
2050                        .record
2051                        .get_field("HOPR")
2052                        .and_then(|v| v.to_f64())
2053                        .unwrap_or(0.0);
2054                    let lopr = self
2055                        .record
2056                        .get_field("LOPR")
2057                        .and_then(|v| v.to_f64())
2058                        .unwrap_or(0.0);
2059                    (hopr, lopr)
2060                };
2061                snap.control = Some(super::super::snapshot::ControlInfo {
2062                    upper_ctrl_limit: upper,
2063                    lower_ctrl_limit: lower,
2064                });
2065            }
2066            "motor" => {
2067                // Motor records use HLM/LLM as control limits
2068                let hlm = self
2069                    .record
2070                    .get_field("HLM")
2071                    .and_then(|v| v.to_f64())
2072                    .unwrap_or(0.0);
2073                let llm = self
2074                    .record
2075                    .get_field("LLM")
2076                    .and_then(|v| v.to_f64())
2077                    .unwrap_or(0.0);
2078                snap.control = Some(super::super::snapshot::ControlInfo {
2079                    upper_ctrl_limit: hlm,
2080                    lower_ctrl_limit: llm,
2081                });
2082            }
2083            // int64in uses HOPR/LOPR as control limits (int64inRecord.c:226-227)
2084            "ai" | "int64in" | "longin" | "calc" | "calcout" => {
2085                // Input records use HOPR/LOPR as control limits
2086                let hopr = self
2087                    .record
2088                    .get_field("HOPR")
2089                    .and_then(|v| v.to_f64())
2090                    .unwrap_or(0.0);
2091                let lopr = self
2092                    .record
2093                    .get_field("LOPR")
2094                    .and_then(|v| v.to_f64())
2095                    .unwrap_or(0.0);
2096                snap.control = Some(super::super::snapshot::ControlInfo {
2097                    upper_ctrl_limit: hopr,
2098                    lower_ctrl_limit: lopr,
2099                });
2100            }
2101            // Array records map their VAL control limits to HOPR/LOPR, exactly
2102            // like the display limits above (waveformRecord.c get_control_double
2103            // VAL case; aaiRecord.c:293-303; aaoRecord.c; compressRecord.c:487-501).
2104            // Without this arm an array DBR_CTRL collapses the control range to
2105            // 0/0 while the scalar records expose it.
2106            "waveform" | "aai" | "aao" | "compress" => {
2107                let hopr = self
2108                    .record
2109                    .get_field("HOPR")
2110                    .and_then(|v| v.to_f64())
2111                    .unwrap_or(0.0);
2112                let lopr = self
2113                    .record
2114                    .get_field("LOPR")
2115                    .and_then(|v| v.to_f64())
2116                    .unwrap_or(0.0);
2117                snap.control = Some(super::super::snapshot::ControlInfo {
2118                    upper_ctrl_limit: hopr,
2119                    lower_ctrl_limit: lopr,
2120                });
2121            }
2122            _ => {}
2123        }
2124    }
2125
2126    /// Populate EnumInfo — C rset `get_enum_strs`.
2127    ///
2128    /// The table comes from [`Record::enum_state_strings`], the SAME slot the
2129    /// string-put converter (`dbConvert.c::putStringEnum`) resolves against, so
2130    /// the choice list a client reads and the names it may write are one table
2131    /// by construction. It arrives already trimmed to C's `no_str` (bi/bo/busy
2132    /// drop an empty ONAM behind a set ZNAM — `boRecord.c:342-352`; mbbi/mbbo
2133    /// cut at the last non-empty state — `mbbiRecord.c:262-269`).
2134    ///
2135    /// The `DBR_STRING` half of the same channel is the record's OTHER rset slot
2136    /// (`get_enum_str`), which is not this trimmed list — see
2137    /// [`EnumStringForm`]. A record that has no such slot (every record but
2138    /// bi/bo/busy/mbbi/mbbo, including the downstream crates' own enum records)
2139    /// renders from its label list, which is what C's absent slot amounts to.
2140    fn populate_enum_info(&self, snap: &mut super::super::snapshot::Snapshot) {
2141        if let Some(strings) = self.record.enum_state_strings() {
2142            snap.enums = Some(match self.record.enum_string_form() {
2143                Some(form) => super::super::snapshot::EnumInfo::with_string_form(strings, form),
2144                None => super::super::snapshot::EnumInfo::new(strings),
2145            });
2146        }
2147    }
2148
2149    /// Get a common field value.
2150    pub fn get_common_field(&self, name: &str) -> Option<EpicsValue> {
2151        match name {
2152            "SEVR" => Some(EpicsValue::Short(self.common.sevr as i16)),
2153            "STAT" => Some(EpicsValue::Short(self.common.stat as i16)),
2154            "NSEV" => Some(EpicsValue::Short(self.common.nsev as i16)),
2155            "NSTA" => Some(EpicsValue::Short(self.common.nsta as i16)),
2156            // epics-base PR #568 / #566 — alarm message string.
2157            "AMSG" => Some(EpicsValue::String(self.common.amsg.clone().into())),
2158            "NAMSG" => Some(EpicsValue::String(self.common.namsg.clone().into())),
2159            "ACKS" => Some(EpicsValue::Short(self.common.acks as i16)),
2160            // `ACKT` and `PINI` are `DBF_MENU` (`menuYesNo` /`menuPini`,
2161            // `dbCommon.dbd.pod:335,169`), not `DBF_UCHAR`: they carry a menu
2162            // index, which `promote_menu_value` lifts to `DBR_ENUM` with the
2163            // menu's choice strings. Storing them as `Short` is what makes
2164            // them eligible for that promotion — see `promote_menu_value`.
2165            "ACKT" => Some(EpicsValue::Short(if self.common.ackt { 1 } else { 0 })),
2166            // DBF_UCHAR: served as UChar (declared type) so the raw put byte
2167            // round-trips to the wire — see the DISP/TPRO comment above.
2168            "UDF" => Some(EpicsValue::UChar(self.common.udf)),
2169            "UDFS" => Some(EpicsValue::Short(self.common.udfs)),
2170            "SCAN" => Some(EpicsValue::Enum(self.common.scan.to_u16())),
2171            "SSCN" => Some(EpicsValue::Enum(self.common.sscn.to_u16())),
2172            // `OLDSIMM` is `DBF_MENU`/`menu(menuSimm)`, stored as the menu index
2173            // and promoted to `DBR_ENUM` with the NO/YES/RAW labels by
2174            // `promote_menu_value` (shared registry — the saved copy is ALWAYS
2175            // menuSimm, unlike the live SIMM). Written only by the simulation
2176            // owner (`rec_gbl_save_simm`); `special(SPC_NOMOD)` for clients.
2177            "OLDSIMM" => Some(EpicsValue::Short(self.common.oldsimm)),
2178            "PINI" => Some(EpicsValue::Short(self.common.pini)),
2179            // DISP/TPRO/RPRO/UDF are `DBF_UCHAR` in `dbCommon.dbd`. Serve them
2180            // as `UChar` — their DECLARED type — so `project_to_declared_type`
2181            // is identity and the raw put byte reaches the wire untouched (C
2182            // stores the byte and `caget` renders `DBR_CHAR` signed: 255 → -1).
2183            // Serving `Char` here instead routed the value through the lossy
2184            // `Char → UChar` projection (signed −1 clamped to 0), so a
2185            // `caput DISP 255` read back as 0 rather than C's -1. `BKPT` is
2186            // `DBF_NOACCESS`: no `FieldDesc`, no projection, served `Char`.
2187            "TPRO" => Some(EpicsValue::UChar(self.common.tpro)),
2188            "BKPT" => Some(EpicsValue::Char(self.common.bkpt)),
2189            "FLNK" => Some(EpicsValue::String(self.common.flnk.clone().into())),
2190            // A record type whose C `.dbd` has no INP has no `.INP` channel
2191            // either — C's dbChannel resolution is the dbd, so `dbgf HI.INP` on
2192            // a histogram answers "PV 'HI.INP' not found". The port keeps INP on
2193            // `CommonFields` for every record, so `declares_inp_link()` is what
2194            // stands in for the dbd, and it must gate the read side as well as
2195            // the write side (`put_common_field`) — otherwise the field is
2196            // unloadable and unwritable yet still resolves as a channel.
2197            "INP" if self.record.declares_inp_link() => {
2198                Some(EpicsValue::String(self.common.inp.clone().into()))
2199            }
2200            "OUT" => Some(EpicsValue::String(self.common.out.clone().into())),
2201            // C's DTYP is `DBF_DEVICE`: an epicsEnum16 index into the record
2202            // type's device menu, NOT the name. The name is what this port
2203            // stores and dispatches on; the index is what the wire carries.
2204            "DTYP" => Some(EpicsValue::Enum(self.dtyp_index())),
2205            "TSE" => Some(EpicsValue::Short(self.common.tse)),
2206            "TSEL" => Some(EpicsValue::String(self.common.tsel.clone().into())),
2207            // C `UTAG` is DBF_UINT64 — exposed natively as the unsigned
2208            // 64-bit value variant so values above i64::MAX round-trip.
2209            "UTAG" => Some(EpicsValue::UInt64(self.common.utag)),
2210            "ASG" => Some(EpicsValue::String(self.common.asg.clone().into())),
2211            "ASL" => Some(EpicsValue::Char(self.common.asl)),
2212            "DESC" => Some(EpicsValue::String(self.common.desc.clone())),
2213            "PHAS" => Some(EpicsValue::Short(self.common.phas)),
2214            "EVNT" => Some(EpicsValue::String(self.common.evnt.clone().into())),
2215            "PRIO" => Some(EpicsValue::Short(self.common.prio)),
2216            "DISV" => Some(EpicsValue::Short(self.common.disv)),
2217            "DISA" => Some(EpicsValue::Short(self.common.disa)),
2218            "SDIS" => Some(EpicsValue::String(self.common.sdis.clone().into())),
2219            "DISS" => Some(EpicsValue::Short(self.common.diss)),
2220            "HYST" => Some(EpicsValue::Double(self.common.hyst)),
2221            "LCNT" => Some(EpicsValue::Short(self.common.lcnt)),
2222            "DISP" => Some(EpicsValue::UChar(self.common.disp)),
2223            "PUTF" => Some(EpicsValue::Char(if self.common.putf { 1 } else { 0 })),
2224            "RPRO" => Some(EpicsValue::UChar(self.common.rpro)),
2225            "PACT" => Some(EpicsValue::Char(if self.is_processing() { 1 } else { 0 })),
2226            // C `dbCommon.dbd`: `field(PROC,DBF_UCHAR)` — the raw put byte is
2227            // retained in `prec->proc` and served back SIGNED as `DBR_CHAR`
2228            // (`caput PROC 255` → `caget` = -1), exactly like DISP/RPRO. The
2229            // `pp(TRUE)` force-process is orthogonal: writing PROC still
2230            // reprocesses the record (put-path intercept), but the byte sticks.
2231            "PROC" => Some(EpicsValue::UChar(self.common.proc_field)),
2232            // Analog alarm fields
2233            "HIHI" => self
2234                .common
2235                .analog_alarm
2236                .as_ref()
2237                .map(|a| EpicsValue::Double(a.hihi)),
2238            "HIGH" => self
2239                .common
2240                .analog_alarm
2241                .as_ref()
2242                .map(|a| EpicsValue::Double(a.high)),
2243            "LOW" => self
2244                .common
2245                .analog_alarm
2246                .as_ref()
2247                .map(|a| EpicsValue::Double(a.low)),
2248            "LOLO" => self
2249                .common
2250                .analog_alarm
2251                .as_ref()
2252                .map(|a| EpicsValue::Double(a.lolo)),
2253            "HHSV" => self
2254                .common
2255                .analog_alarm
2256                .as_ref()
2257                .map(|a| EpicsValue::Short(a.hhsv)),
2258            "HSV" => self
2259                .common
2260                .analog_alarm
2261                .as_ref()
2262                .map(|a| EpicsValue::Short(a.hsv)),
2263            "LSV" => self
2264                .common
2265                .analog_alarm
2266                .as_ref()
2267                .map(|a| EpicsValue::Short(a.lsv)),
2268            "LLSV" => self
2269                .common
2270                .analog_alarm
2271                .as_ref()
2272                .map(|a| EpicsValue::Short(a.llsv)),
2273            // swait OUTN is aliased to common.out
2274            "OUTN" => {
2275                if self.record.record_type() == "swait" {
2276                    Some(EpicsValue::String(self.common.out.clone().into()))
2277                } else {
2278                    None
2279                }
2280            }
2281            _ => None,
2282        }
2283    }
2284
2285    /// `true` when the record type declares `name` in its own `field_list`,
2286    /// i.e. the record stores the field itself and owns whatever behaviour
2287    /// hangs off it.
2288    ///
2289    /// This separates the two meanings a link field carries. `common.inp` /
2290    /// `common.out` is the link *text* — always the value the `.db` file
2291    /// wrote, for every record type, because C device support reads
2292    /// `prec->inp` / `prec->out` at `init_record` no matter which layer owns
2293    /// the field ([`crate::server::db_loader::apply_fields`] keeps it
2294    /// populated). `parsed_inp` / `parsed_out` is the *framework's* dispatch
2295    /// of that link, and is armed only for a record type that does NOT
2296    /// declare the field: a record that declares it drives the link itself
2297    /// (`multi_output_links` for `acalcout`/`scalcout`, device support for
2298    /// `motorRecord`/`scalerRecord`, or its own `process`). Arming the
2299    /// framework path for those too would write the link twice per cycle.
2300    fn record_declares_field(&self, name: &str) -> bool {
2301        self.record.implements_field(name)
2302    }
2303
2304    /// Set a common field value from a runtime `dbPut` (CA/PVA/`dbpf`/link).
2305    /// Returns what scan index changes are needed.
2306    ///
2307    /// A `DBF_MENU` common field's string is converted by C's runtime
2308    /// converter, `dbConvert.c::putStringMenu` — see [`MenuBound::DbPut`].
2309    pub fn put_common_field(
2310        &mut self,
2311        name: &str,
2312        value: EpicsValue,
2313    ) -> CaResult<CommonFieldPutResult> {
2314        self.put_common_field_bounded(name, value, MenuBound::DbPut)
2315    }
2316
2317    /// **The single owner of a record's SCAN transition** — C `dbPutField` on
2318    /// SCAN, which is `scanDelete(precord)` … `scanAdd(precord)`
2319    /// (`dbAccess.c::dbPutSpecial` SPC_SCAN, dbScan.c:236-248).
2320    ///
2321    /// Two callers reach it, and they are the two C sites that move a record
2322    /// between scan lists: a `SCAN` put ([`Self::put_common_field`]) and the
2323    /// simulation-mode scan swap (`recGblCheckSimm`, recGbl.c:427-437, which
2324    /// calls exactly the same `scanDelete`/`scanAdd` pair). Returns the delta
2325    /// for the scan-index owner (`PvDatabase::update_scan_index`) to apply once
2326    /// the record lock is down; [`CommonFieldPutResult::NoChange`] when the scan
2327    /// did not move.
2328    pub fn set_scan(&mut self, new_scan: ScanType) -> CommonFieldPutResult {
2329        let old_scan = self.common.scan;
2330        self.common.scan = new_scan;
2331        if old_scan == new_scan {
2332            return CommonFieldPutResult::NoChange;
2333        }
2334        // C `scanDelete`/`scanAdd` call the record's device support
2335        // `get_ioint_info(1)` / `get_ioint_info(0)`. Only a change of I/O Intr
2336        // *membership* reaches those; a Passive→"1 second" move calls neither.
2337        let was_io_intr = old_scan == ScanType::IoIntr;
2338        let is_io_intr = new_scan == ScanType::IoIntr;
2339        if was_io_intr != is_io_intr {
2340            self.record.set_io_intr_scan(is_io_intr);
2341        }
2342        CommonFieldPutResult::ScanChanged {
2343            old_scan,
2344            new_scan,
2345            phas: self.common.phas,
2346        }
2347    }
2348
2349    /// C `recGblSaveSimm` (`recGbl.c:421-425`) — latch the CURRENT simulation
2350    /// mode into OLDSIMM:
2351    ///
2352    /// ```c
2353    /// void recGblSaveSimm(const epicsEnum16 sscn,
2354    ///     epicsEnum16 *poldsimm, const epicsEnum16 simm) {
2355    ///     if (sscn == USHRT_MAX) return;
2356    ///     *poldsimm = simm;
2357    /// }
2358    /// ```
2359    ///
2360    /// **The only writer of `CommonFields::oldsimm`.** Must run BEFORE the SIMM
2361    /// value moves — C calls it from `special(SPC_MOD)` pass 0 (before the put)
2362    /// and from `recGblGetSimm`/`recGblInitSimm` before the SIML read. The
2363    /// `sscn == 65535` guard is C's: with SSCN unset there is no scan to swap
2364    /// to, so the latch is not even taken (and [`Self::rec_gbl_check_simm`]
2365    /// bails on the same test, so the stale OLDSIMM is never read).
2366    ///
2367    /// A record type with no SSCN/OLDSIMM in its C dbd (`busy`, `swait`) passes
2368    /// neither pointer to any recGbl helper: no-op here.
2369    pub fn rec_gbl_save_simm(&mut self) {
2370        if !self.record.uses_recgbl_simm_helpers() {
2371            return;
2372        }
2373        // C `recGblSaveSimm`: `if (*psscn == USHRT_MAX) return;` — the literal
2374        // sentinel, not "any index outside the menu".
2375        if self.common.sscn.is_unset() {
2376            return;
2377        }
2378        if let Some(EpicsValue::Short(simm)) = self.record.get_field("SIMM") {
2379            self.common.oldsimm = simm;
2380        }
2381    }
2382
2383    /// C `recGblCheckSimm` (`recGbl.c:427-437`) — on a SIMM transition, swap the
2384    /// record's SCAN with SSCN:
2385    ///
2386    /// ```c
2387    /// void recGblCheckSimm(struct dbCommon *pcommon, epicsEnum16 *psscn,
2388    ///     const epicsEnum16 oldsimm, const epicsEnum16 simm) {
2389    ///     if (*psscn == USHRT_MAX) return;
2390    ///     if (simm != oldsimm) {
2391    ///         epicsUInt16 scan = pcommon->scan;
2392    ///         scanDelete(pcommon);
2393    ///         pcommon->scan = *psscn;
2394    ///         scanAdd(pcommon);
2395    ///         *psscn = scan;
2396    ///     }
2397    /// }
2398    /// ```
2399    ///
2400    /// This is what makes SSCN mean anything at all: a record configured
2401    /// `field(SCAN,"1 second") field(SSCN,"Passive")` stops periodic scanning
2402    /// the moment SIMM leaves NO, and resumes it when SIMM goes back — with the
2403    /// two fields having traded places each time. Both are a genuine swap, not
2404    /// an assignment: SSCN ends up holding the scan the record just left.
2405    ///
2406    /// **The only writer of the SIMM-driven SCAN/SSCN swap.** The scan-list
2407    /// move itself goes through the single SCAN owner [`Self::set_scan`], whose
2408    /// [`CommonFieldPutResult`] the caller hands to
2409    /// `PvDatabase::update_scan_index` once the record lock is down. Runs AFTER
2410    /// the SIMM value moved — C `special(SPC_MOD)` pass 1, and the tail of
2411    /// `recGblGetSimm`/`recGblInitSimm`.
2412    pub fn rec_gbl_check_simm(&mut self) -> CommonFieldPutResult {
2413        if !self.record.uses_recgbl_simm_helpers() {
2414            return CommonFieldPutResult::NoChange;
2415        }
2416        let Some(sim_scan) = self.common.sscn.scan() else {
2417            // `*psscn == USHRT_MAX` — SSCN unset, no swap. An SSCN that is
2418            // merely ILLEGAL still swaps: C assigns it into SCAN and `scanAdd`
2419            // then declines to scan the record.
2420            return CommonFieldPutResult::NoChange;
2421        };
2422        let Some(EpicsValue::Short(simm)) = self.record.get_field("SIMM") else {
2423            return CommonFieldPutResult::NoChange;
2424        };
2425        if simm == self.common.oldsimm {
2426            return CommonFieldPutResult::NoChange;
2427        }
2428        let previous_scan = self.common.scan;
2429        let result = self.set_scan(sim_scan);
2430        self.common.sscn = SimModeScan::from_scan(previous_scan);
2431        result
2432    }
2433
2434    /// C `dbAccess.c::putAckt` (`:1285-1300`) — the **only** writer of ACKT.
2435    ///
2436    /// Reached from `dbPut` for a `DBR_PUT_ACKT` request *type*
2437    /// (`dbAccess.c:1331-1332`), ABOVE the `SPC_NOMOD` gate that refuses every
2438    /// ordinary put to the field. Posts exactly what C posts: the ACKT change,
2439    /// the ACKS it may lower, and the record-wide `DBE_ALARM` — and only when
2440    /// `ackt` actually changed (C returns 0 early otherwise).
2441    pub fn put_ackt(&mut self, value: u16) {
2442        let new_ackt = value != 0;
2443        if new_ackt == self.common.ackt {
2444            return;
2445        }
2446        use crate::server::recgbl::EventMask;
2447        let ack_mask = EventMask::VALUE | EventMask::ALARM;
2448        self.common.ackt = new_ackt;
2449        self.cleanup_subscribers();
2450        self.notify_field("ACKT", ack_mask);
2451        // C `:1294-1297`: turning transient acknowledgement off lowers a
2452        // sticky ACKS down to the current SEVR — an alarm that has already
2453        // cleared must not keep a higher unacknowledged severity.
2454        if !new_ackt && self.common.acks > self.common.sevr {
2455            self.common.acks = self.common.sevr;
2456            self.notify_field("ACKS", ack_mask);
2457        }
2458        self.notify_record_alarm();
2459    }
2460
2461    /// C `dbAccess.c::putAcks` (`:1302-1315`) — the **only** runtime writer of
2462    /// ACKS. Reached from `dbPut` for a `DBR_PUT_ACKS` request type, ABOVE the
2463    /// `SPC_NOMOD` gate.
2464    ///
2465    /// The acknowledged severity is compared against the STORED unacknowledged
2466    /// severity `acks`, not the current `sevr`: an operator acknowledging at
2467    /// the severity that was latched into ACKS clears it even after `sevr` has
2468    /// since dropped. A too-low acknowledgement changes nothing and posts
2469    /// nothing; an acknowledgement of an already-clear ACKS still posts, which
2470    /// is C's literal `if (*psev >= precord->acks)` (0 >= 0 holds).
2471    pub fn put_acks(&mut self, value: u16) {
2472        let sev = AlarmSeverity::from_u16(value);
2473        if sev < self.common.acks {
2474            return;
2475        }
2476        use crate::server::recgbl::EventMask;
2477        self.common.acks = AlarmSeverity::NoAlarm;
2478        self.cleanup_subscribers();
2479        self.notify_field("ACKS", EventMask::VALUE | EventMask::ALARM);
2480        self.notify_record_alarm();
2481    }
2482
2483    /// Set a common field value from the `.db` loader, which in C is a
2484    /// different converter with a different out-of-menu bound
2485    /// (`dbStaticRun.c::dbPutStringNum`; see [`MenuBound::DbLoad`]). It is what
2486    /// lets `field(SSCN,"65535")` — the menuScan "use SCAN" sentinel, out of
2487    /// the menu's 0-9 range — load, while `caput REC.SSCN 65535` is refused at
2488    /// runtime exactly as C refuses it.
2489    pub fn put_common_field_db_load(
2490        &mut self,
2491        name: &str,
2492        value: EpicsValue,
2493    ) -> CaResult<CommonFieldPutResult> {
2494        self.put_common_field_bounded(name, value, MenuBound::DbLoad)
2495    }
2496
2497    fn put_common_field_bounded(
2498        &mut self,
2499        name: &str,
2500        value: EpicsValue,
2501        bound: MenuBound,
2502    ) -> CaResult<CommonFieldPutResult> {
2503        let name = name.to_ascii_uppercase();
2504        self.record.validate_put(&name, &value)?;
2505        self.record.special(&name, false)?;
2506        // The db loader hands every common field to this path as a raw
2507        // `EpicsValue::String` (no per-field `FieldDesc` to parse against).
2508        // Coerce it to the field's canonical numeric/menu type up front so the
2509        // typed arms below apply a `field(PHAS, "1")` / `field(PRIO, "HIGH")`
2510        // directive instead of silently dropping it at IOC load. String-typed
2511        // and already-typed values pass through unchanged.
2512        let value = coerce_common_field(&name, value, bound)?;
2513        match name.as_str() {
2514            // `special(SPC_NOMOD)` — C `dbPutSpecial` refuses the put with
2515            // `S_db_noMod` (dbAccess.c:123-127). OLDSIMM is written only by the
2516            // simulation-mode owner (`rec_gbl_save_simm`).
2517            "OLDSIMM" => return Err(CaError::ReadOnlyField(name)),
2518            "SEVR" => {
2519                if let EpicsValue::Short(v) = value {
2520                    self.common.sevr = AlarmSeverity::from_u16(v as u16);
2521                }
2522            }
2523            "STAT" => {
2524                if let EpicsValue::Short(v) = value {
2525                    self.common.stat = v as u16;
2526                }
2527            }
2528            "NSEV" => {
2529                if let EpicsValue::Short(v) = value {
2530                    self.common.nsev = AlarmSeverity::from_u16(v as u16);
2531                }
2532            }
2533            "NSTA" => {
2534                if let EpicsValue::Short(v) = value {
2535                    self.common.nsta = v as u16;
2536                }
2537            }
2538            "AMSG" => {
2539                if let EpicsValue::String(s) = value {
2540                    self.common.amsg = s.as_str_lossy().into_owned();
2541                }
2542            }
2543            "NAMSG" => {
2544                if let EpicsValue::String(s) = value {
2545                    self.common.namsg = s.as_str_lossy().into_owned();
2546                }
2547            }
2548            // ACKS/ACKT carry NO acknowledgement semantics here. They are
2549            // `special(SPC_NOMOD)` in `dbCommon.dbd:150-159`, so no runtime put
2550            // reaches this arm — the gate refuses it. C's acknowledgement is
2551            // driven by the DBR *request type* (`DBR_PUT_ACKS`/`ACKT`), which
2552            // `dbPut` intercepts ABOVE the SPC_NOMOD gate and hands to
2553            // [`Self::put_acks`] / [`Self::put_ackt`]. What is left here is the
2554            // `dbLoadRecords` / `dbStaticLib` load path (`field(ACKT,"YES")`),
2555            // which stores the value verbatim — C `dbPutString` never crosses
2556            // `dbPut`.
2557            "ACKS" => {
2558                if let EpicsValue::Short(v) = value {
2559                    self.common.acks = AlarmSeverity::from_u16(v as u16);
2560                }
2561            }
2562            "ACKT" => match value {
2563                EpicsValue::Char(v) => self.common.ackt = v != 0,
2564                EpicsValue::Short(v) => self.common.ackt = v != 0,
2565                _ => return Ok(CommonFieldPutResult::NoChange),
2566            },
2567            "UDF" => {
2568                // Store the raw put byte (C keeps the epicsUInt8 verbatim); a
2569                // record that re-derives UDF on process overwrites it, one that
2570                // sources nothing this cycle keeps it (put-defect cluster #3).
2571                // The calc family reads UDF straight from `common` too
2572                // (`clears_udf() == false`), so the stored byte stands.
2573                if let EpicsValue::Char(v) = value {
2574                    self.common.udf = v;
2575                }
2576            }
2577            "UDFS" => {
2578                self.common.udfs = menu_ordinal_raw(&value);
2579            }
2580            // The `String` form never reaches these three menu arms:
2581            // `coerce_common_field` has already run it through the one
2582            // menu converter, which either produced an `Enum` index or failed
2583            // the put with `S_db_badChoice`.
2584            "SCAN" => {
2585                let new_scan = match &value {
2586                    EpicsValue::Short(v) => ScanType::from_u16(*v as u16),
2587                    EpicsValue::Enum(v) => ScanType::from_u16(*v),
2588                    _ => return Ok(CommonFieldPutResult::NoChange),
2589                };
2590                let result = self.set_scan(new_scan);
2591                if !matches!(result, CommonFieldPutResult::NoChange) {
2592                    self.record.on_put(&name);
2593                    self.record.special(&name, true)?;
2594                    return Ok(result);
2595                }
2596            }
2597            "SSCN" => {
2598                let new_sscn = match &value {
2599                    EpicsValue::Short(v) => SimModeScan::from_u16(*v as u16),
2600                    EpicsValue::Enum(v) => SimModeScan::from_u16(*v),
2601                    _ => return Ok(CommonFieldPutResult::NoChange),
2602                };
2603                self.common.sscn = new_sscn;
2604            }
2605            // `PINI` is `menu(menuPini)` — the six choices NO/YES/RUN/RUNNING/
2606            // PAUSE/PAUSED (`menuPini.dbd.pod:59-65`). Resolved exactly like
2607            // `SCAN`: a menu label or a bare index, never a truthiness test.
2608            // The pre-fix `bool` arm collapsed `RUN` (index 2) to `false`, so
2609            // `caput REC.PINI RUN` *disabled* PINI instead of selecting the
2610            // iocRun pass.
2611            "PINI" => {
2612                // Store the RAW ordinal (see [`CommonFields::pini`]): C's numeric
2613                // menu put keeps `(epicsEnum16)`, so an out-of-range `caput
2614                // REC.PINI 6` / `-1` round-trips and simply matches no lifecycle
2615                // pass in `doRecordPini`. A `String` label is already resolved to
2616                // `Enum` by `coerce_common_field` (menuPini via `putStringMenu`).
2617                self.common.pini = match &value {
2618                    EpicsValue::Short(v) => *v,
2619                    EpicsValue::Char(v) => *v as i16,
2620                    EpicsValue::Enum(v) => *v as i16,
2621                    _ => return Ok(CommonFieldPutResult::NoChange),
2622                };
2623            }
2624            "TPRO" => {
2625                if let EpicsValue::Char(v) = value {
2626                    self.common.tpro = v;
2627                }
2628            }
2629            "BKPT" => {
2630                if let EpicsValue::Char(v) = value {
2631                    self.common.bkpt = v;
2632                }
2633            }
2634            "FLNK" => {
2635                if let EpicsValue::String(s) = value {
2636                    self.common.flnk = s.as_str_lossy().into_owned();
2637                    self.parsed_flnk = parse_forward_link_v2(&self.common.flnk);
2638                }
2639            }
2640            "INP" => {
2641                // A record type whose C `.dbd` has no INP must refuse it, the
2642                // way C's dbd does ("field not found" at load, record inert) —
2643                // `histogram`'s input link is SVL, not INP
2644                // (histogramRecord.dbd.pod:212). Without this the port accepts a
2645                // `field(INP,...)` no C IOC can load.
2646                if !self.record.declares_inp_link() {
2647                    return Err(CaError::FieldNotFound("INP".to_string()));
2648                }
2649                if let EpicsValue::String(s) = value {
2650                    self.check_link_assignment("INP", &s.as_str_lossy(), bound)?;
2651                    self.common.inp = s.as_str_lossy().into_owned();
2652                    if !self.record_declares_field("INP") {
2653                        self.parsed_inp = parse_link_v2(&self.common.inp);
2654                    }
2655                }
2656            }
2657            "OUT" => {
2658                if let EpicsValue::String(s) = value {
2659                    let s = s.as_str_lossy();
2660                    self.check_link_assignment("OUT", &s, bound)?;
2661                    // C `dbParseLink` (dbStaticLib.c:2382-2386) discards a
2662                    // CP/CPP modifier on a DBF_OUTLINK and warns once, naming
2663                    // the holder record, its field and the target. The discard
2664                    // itself is owned by `parse_output_link_v2` below; only the
2665                    // diagnostic lives here, where the record name exists and
2666                    // the link text is being (re)loaded rather than re-parsed
2667                    // per process cycle.
2668                    if out_link_discards_cp(&s) {
2669                        tracing::warn!(
2670                            target: "epics_base_rs::record",
2671                            record = %self.name,
2672                            field = "OUT",
2673                            link = %s,
2674                            "Discarding CP/CPP modifier in CA output link"
2675                        );
2676                    }
2677                    self.common.out = s.into_owned();
2678                    // C `dbDbPutValue` (dbDbLink.c:386-389): an OUT
2679                    // link processes its target only on an explicit
2680                    // ` PP` token (or a `.PROC` destination). A bare
2681                    // OUT link is NPP — `parse_output_link_v2`
2682                    // downgrades the modifier-less `ProcessPassive`
2683                    // default that `parse_link_v2` would otherwise
2684                    // apply.
2685                    if !self.record_declares_field("OUT") {
2686                        self.parsed_out = parse_output_link_v2(&self.common.out);
2687                    }
2688                    // C `longoutRecord.c::special` (PR #6c573b4 part 2)
2689                    // and similar OOCH-style hooks need `after=true`
2690                    // to fire after the link has actually moved. The
2691                    // earlier `validate_put` + `special(name, false)`
2692                    // pair only covered the before-side.
2693                    self.record.special(&name, true)?;
2694                }
2695            }
2696            // Two shapes reach DTYP and both name a device support:
2697            //
2698            // * the `.db` loader hands over the NAME verbatim, and it may be a
2699            //   name registered at runtime by a downstream crate ("asynInt32")
2700            //   that no vendored `.dbd` declares — C would reject that at load,
2701            //   the port's registry accepts it (Tier 3);
2702            // * a `dbPut` arrives as the menu INDEX, because `DBF_DEVICE` is
2703            //   served as `DBR_ENUM` and `coerce_put_value` already resolved an
2704            //   incoming label through the device menu (C `putStringMenu`,
2705            //   which fails `S_db_badChoice` on a name the menu does not have).
2706            //
2707            // The index is only meaningful against the DECLARED menu, which is
2708            // what the converter bounded it by.
2709            "DTYP" => match value {
2710                EpicsValue::String(s) => self.common.dtyp = s.as_str_lossy().into_owned(),
2711                EpicsValue::Enum(i) => {
2712                    let declared =
2713                        super::dbd_generated::device_menu(self.record.record_type()).unwrap_or(&[]);
2714                    match declared.get(i as usize) {
2715                        Some(name) => self.common.dtyp = (*name).to_string(),
2716                        None => return Ok(CommonFieldPutResult::NoChange),
2717                    }
2718                }
2719                _ => return Ok(CommonFieldPutResult::NoChange),
2720            },
2721            "TSE" => {
2722                if let EpicsValue::Short(v) = value {
2723                    self.common.tse = v;
2724                }
2725            }
2726            "TSEL" => {
2727                if let EpicsValue::String(s) = value {
2728                    self.common.tsel = s.as_str_lossy().into_owned();
2729                    self.parsed_tsel = parse_link_v2(&self.common.tsel);
2730                }
2731            }
2732            "UTAG" => {
2733                // C UTAG is DBF_UINT64 — accept any integer-shaped value and
2734                // store the unsigned 64-bit tag. The db loader feeds every
2735                // common field as EpicsValue::String, so parse field(UTAG, "N")
2736                // rather than dropping it silently at IOC load; a CA write to
2737                // this u64 field crosses as DBR_DOUBLE (CA has no uint64 wire
2738                // type), so accept Double too.
2739                match value {
2740                    EpicsValue::UInt64(v) => self.common.utag = v,
2741                    EpicsValue::Int64(v) => self.common.utag = v as u64,
2742                    EpicsValue::Long(v) => self.common.utag = v as u64,
2743                    EpicsValue::Short(v) => self.common.utag = v as u64,
2744                    EpicsValue::Enum(v) => self.common.utag = v as u64,
2745                    EpicsValue::Char(v) => self.common.utag = v as u64,
2746                    EpicsValue::Double(v) => self.common.utag = v as u64,
2747                    EpicsValue::String(s) => {
2748                        if let Ok(EpicsValue::UInt64(v)) =
2749                            EpicsValue::parse(DbFieldType::UInt64, s.as_str_lossy().trim())
2750                        {
2751                            self.common.utag = v;
2752                        }
2753                    }
2754                    _ => {}
2755                }
2756            }
2757            "ASG" => {
2758                if let EpicsValue::String(s) = value {
2759                    self.common.asg = s.as_str_lossy().into_owned();
2760                }
2761            }
2762            "ASL" => {
2763                // C dbCommon.ASL is `epicsUInt32` in the .dbd but
2764                // only ever 0 or 1; accept Char / Short / Long for
2765                // the common put paths and clamp to {0, 1}.
2766                // db_loader feeds every common field as
2767                // `EpicsValue::String`; also accept that so a
2768                // `.db` `field(ASL, "1")` directive isn't silently
2769                // ignored at IOC load.
2770                let n: i64 = match value {
2771                    EpicsValue::Char(v) => v as i64,
2772                    EpicsValue::Short(v) => v as i64,
2773                    EpicsValue::Long(v) => v as i64,
2774                    EpicsValue::Int64(v) => v,
2775                    EpicsValue::String(s) => s.as_str_lossy().trim().parse().unwrap_or(0),
2776                    _ => return Ok(CommonFieldPutResult::NoChange),
2777                };
2778                self.common.asl = if n != 0 { 1 } else { 0 };
2779            }
2780            "DESC" => {
2781                if let EpicsValue::String(s) = value {
2782                    // DBF_STRING data field — store the bytes verbatim so a
2783                    // non-UTF-8 DESC round-trips unchanged.
2784                    self.common.desc = s;
2785                }
2786            }
2787            "PHAS" => {
2788                if let EpicsValue::Short(v) = value {
2789                    let old_phas = self.common.phas;
2790                    self.common.phas = v;
2791                    // Only a record that IS in a scan list can be re-sorted
2792                    // within one; the same gate the index owner applies.
2793                    if old_phas != v && self.common.scan.scan_list().is_some() {
2794                        let scan = self.common.scan;
2795                        self.record.on_put(&name);
2796                        self.record.special(&name, true)?;
2797                        return Ok(CommonFieldPutResult::PhasChanged {
2798                            scan,
2799                            old_phas,
2800                            new_phas: v,
2801                        });
2802                    }
2803                }
2804            }
2805            "EVNT" => {
2806                // C `EVNT` is DBF_STRING (event name). Accept a
2807                // string directly; accept a numeric value too for
2808                // backward compatibility (numeric events / a calc
2809                // record driving EVNT) by formatting it as a string.
2810                match value {
2811                    EpicsValue::String(s) => self.common.evnt = s.as_str_lossy().into_owned(),
2812                    EpicsValue::Short(v) => self.common.evnt = v.to_string(),
2813                    EpicsValue::Long(v) => self.common.evnt = v.to_string(),
2814                    EpicsValue::Enum(v) => self.common.evnt = v.to_string(),
2815                    EpicsValue::Double(v) => {
2816                        // Match C `eventNameToHandle`: a double with
2817                        // an integer part is treated as that integer.
2818                        self.common.evnt = (v as i64).to_string();
2819                    }
2820                    _ => {}
2821                }
2822            }
2823            "PRIO" => {
2824                if let EpicsValue::Short(v) = value {
2825                    self.common.prio = v;
2826                }
2827            }
2828            "DISV" => {
2829                if let EpicsValue::Short(v) = value {
2830                    self.common.disv = v;
2831                }
2832            }
2833            "DISA" => {
2834                if let EpicsValue::Short(v) = value {
2835                    self.common.disa = v;
2836                }
2837            }
2838            "SDIS" => {
2839                if let EpicsValue::String(s) = value {
2840                    self.common.sdis = s.as_str_lossy().into_owned();
2841                    self.parsed_sdis = parse_link_v2(&self.common.sdis);
2842                }
2843            }
2844            "DISS" => {
2845                self.common.diss = menu_ordinal_raw(&value);
2846            }
2847            "HYST" => {
2848                if let Some(v) = value.to_f64() {
2849                    self.common.hyst = v;
2850                }
2851            }
2852            "LCNT" => {
2853                if let EpicsValue::Short(v) = value {
2854                    self.common.lcnt = v;
2855                }
2856            }
2857            "DISP" => {
2858                if let EpicsValue::Char(v) = value {
2859                    self.common.disp = v;
2860                }
2861            }
2862            "PUTF" => return Err(CaError::ReadOnlyField("PUTF".into())),
2863            "RPRO" => {
2864                if let EpicsValue::Char(v) = value {
2865                    self.common.rpro = v;
2866                }
2867            }
2868            "PACT" => return Err(CaError::ReadOnlyField("PACT".into())),
2869            // C `dbPut` stores the raw byte in `prec->proc` (retained across
2870            // processing — C never resets it); `coerce_common_field` has
2871            // already projected the put onto `DBF_UCHAR` (→ `Char`). The
2872            // `pp(TRUE)` reprocess is driven separately by the put-path
2873            // force-process intercept, so this arm ONLY records the byte.
2874            "PROC" => {
2875                if let EpicsValue::Char(v) = value {
2876                    self.common.proc_field = v;
2877                }
2878            }
2879            // Analog alarm limits. The DB-load String was already coerced to
2880            // `Double` by `coerce_common_field` — the one owner of
2881            // "what type does this common field hold" — so every writer
2882            // (`.db` load, `caput`, a link) lands here with a numeric value.
2883            "HIHI" => {
2884                if let (Some(v), Some(a)) = (value.to_f64(), self.common.analog_alarm.as_mut()) {
2885                    a.hihi = v;
2886                }
2887            }
2888            "HIGH" => {
2889                if let (Some(v), Some(a)) = (value.to_f64(), self.common.analog_alarm.as_mut()) {
2890                    a.high = v;
2891                }
2892            }
2893            "LOW" => {
2894                if let (Some(v), Some(a)) = (value.to_f64(), self.common.analog_alarm.as_mut()) {
2895                    a.low = v;
2896                }
2897            }
2898            "LOLO" => {
2899                if let (Some(v), Some(a)) = (value.to_f64(), self.common.analog_alarm.as_mut()) {
2900                    a.lolo = v;
2901                }
2902            }
2903            "HHSV" => {
2904                if let Some(a) = &mut self.common.analog_alarm {
2905                    a.hhsv = menu_ordinal_raw(&value);
2906                }
2907            }
2908            "HSV" => {
2909                if let Some(a) = &mut self.common.analog_alarm {
2910                    a.hsv = menu_ordinal_raw(&value);
2911                }
2912            }
2913            "LSV" => {
2914                if let Some(a) = &mut self.common.analog_alarm {
2915                    a.lsv = menu_ordinal_raw(&value);
2916                }
2917            }
2918            "LLSV" => {
2919                if let Some(a) = &mut self.common.analog_alarm {
2920                    a.llsv = menu_ordinal_raw(&value);
2921                }
2922            }
2923            // swait-specific: OUTN is the output link name for swait records.
2924            // Mirrors to common.out so the processing framework dispatches it.
2925            "OUTN" => {
2926                if self.record.record_type() != "swait" {
2927                    // No OUTN field on any other record type — the same
2928                    // `S_dbLib_fieldNotFound` the catch-all below reports.
2929                    return Err(self.unknown_field_error(name));
2930                }
2931                if let EpicsValue::String(s) = value {
2932                    self.common.out = s.as_str_lossy().into_owned();
2933                    // Bare OUT link is NPP — see the "OUT" arm.
2934                    self.parsed_out = parse_output_link_v2(&self.common.out);
2935                }
2936            }
2937            // C `dbNameToAddr` (dbAccess.c:660-676) resolves the field part
2938            // with `dbFindFieldPart`, then falls back to `dbGetAttributePart`.
2939            // A name that is neither a record field, nor a dbCommon field, nor
2940            // an attribute resolves to nothing (`S_dbLib_fieldNotFound`), so
2941            // `dbPutField` is never reached and the caller reports the error —
2942            // `dbpf` prints "PV '%s' not found" and returns -1 (dbTest.c:787-795).
2943            // Returning success here made a put to a misspelled field a silent
2944            // no-op.
2945            //
2946            // But a field the record's `.dbd` DECLARES and no arm above stored
2947            // is NOT unknown: C `dbPut` writes it into record memory even when
2948            // no record code reads it back (`caput dfanout.HOPR 10`). Land it in
2949            // the per-instance declared-override store — the write analog of
2950            // `declared_default` — so the put is accepted and a later read
2951            // reflects it. `put_declared_override` still returns
2952            // `unknown_field_error` for a name with no `dbFldDes`, so a
2953            // misspelled field is refused exactly as before.
2954            _ => return self.put_declared_override(&name, value),
2955        }
2956        self.record.on_put(&name);
2957        // C `dbPut` (dbAccess.c:1399-1405) returns the after-put
2958        // `dbPutSpecial(paddr, 1)` status to the caller — the stored value
2959        // stays, but the monitor post and the process are skipped and the
2960        // client sees the failure. Never drop it.
2961        self.record.special(&name, true)?;
2962        Ok(CommonFieldPutResult::NoChange)
2963    }
2964
2965    /// The error C reports for a write to a field name that
2966    /// [`Self::put_common_field`] does not own.
2967    ///
2968    /// Two C outcomes, split by whether the name resolves at all:
2969    ///
2970    /// - A record *attribute* (`NAME`, `RTYP`) resolves — `dbGetAttributePart`
2971    ///   succeeds — but the write is refused: `NAME` is `special(SPC_NOMOD)`
2972    ///   (dbCommon.dbd:13-17) so `dbPutSpecial` pass 0 returns `S_db_noMod`
2973    ///   (dbAccess.c:123-124), and an attribute address carries
2974    ///   `special == SPC_ATTRIBUTE`, which `dbPutField` rejects with the same
2975    ///   `S_db_noMod` (dbAccess.c:1252-1253).
2976    /// - Anything else does not resolve: `S_dbLib_fieldNotFound`.
2977    fn unknown_field_error(&self, name: String) -> CaError {
2978        if self.get_virtual_field(&name).is_some() {
2979            CaError::ReadOnlyField(name)
2980        } else {
2981            CaError::FieldNotFound(name)
2982        }
2983    }
2984
2985    /// Store a put to a field the record's `.dbd` DECLARES but the record
2986    /// models no storage for — the WRITE owner of [`Self::declared_overrides`]
2987    /// and the write analog of [`Self::declared_default`].
2988    ///
2989    /// Reached only from [`Self::put_common_field_bounded`]'s catch-all, i.e.
2990    /// after both `Record::put_field` (returned `FieldNotFound`) and every
2991    /// `dbCommon` arm above have declined the field. Three gates, mirroring
2992    /// C `dbNameToAddr`/`dbPut`:
2993    ///
2994    /// * NO `dbFldDes` (`field_desc` is `None`) — the name is not a field of
2995    ///   this record type at all. C resolves nothing and `dbPutField` reports
2996    ///   `S_dbLib_fieldNotFound`; return [`Self::unknown_field_error`] (which
2997    ///   also renders `NAME`/`RTYP` as the read-only attributes they are).
2998    /// * `special(SPC_NOMOD)` — a declared field that is immutable
2999    ///   ([`Self::is_no_mod`]: the `.dbd` `read_only`/attribute bit or the
3000    ///   record's runtime `field_no_mod`). C refuses the put with `S_db_noMod`;
3001    ///   the runtime dispatch already gates this via `field_io::check_no_mod`,
3002    ///   but the db-load path does not, so enforce it here too — never store an
3003    ///   SPC_NOMOD field in the override map.
3004    /// * [`FieldDesc::runtime_typed`] — a field whose served type C's
3005    ///   `cvt_dbaddr` re-derives from record state (`waveform.VAL` from `FTVL`,
3006    ///   `aSub.A` from `FTA`). Such a field is record-owned by definition, so
3007    ///   its `put_field` should have taken the put; if it somehow reached here
3008    ///   the override store must not shadow it (`declared_default` skips it for
3009    ///   the same reason). Treat as not-found rather than store a value under
3010    ///   the wrong type.
3011    /// * PARTIALLY modeled — `Record::get_field` serves the field but no
3012    ///   `put_field` arm accepts it (`calcout.PVAL` → `self.pval`). The record
3013    ///   owns the read path, so the write belongs in its own `put_field`, not a
3014    ///   shadow cell; refuse here rather than store a value `resolve_field`
3015    ///   would never reach. See the inline note on the `get_field` guard.
3016    ///
3017    /// Otherwise coerce the incoming value to the field's C-declared DBF type
3018    /// through the one write-side value-coercion owner
3019    /// ([`coerce_put_value`](crate::server::record::coerce_put_value)) — so a
3020    /// `.db`/`caput` string parses with C's range rules (`caput REC.PREC 99999`
3021    /// into a `DBF_SHORT` is refused, not wrapped) and a menu label resolves
3022    /// against the field's own choices — and store it. Returns
3023    /// [`CommonFieldPutResult::NoChange`]: there is no scan/phas/alarm side
3024    /// effect for a metadata field with no record behaviour, and the caller's
3025    /// value-field monitor post reads the stored value back through
3026    /// [`Self::resolve_field`].
3027    fn put_declared_override(
3028        &mut self,
3029        name: &str,
3030        value: EpicsValue,
3031    ) -> CaResult<CommonFieldPutResult> {
3032        let Some(desc) = self.field_desc(name) else {
3033            return Err(self.unknown_field_error(name.to_string()));
3034        };
3035        if desc.runtime_typed {
3036            return Err(self.unknown_field_error(name.to_string()));
3037        }
3038        if self.is_no_mod(name) {
3039            // C `dbPutSpecial` pass 0 refuses SPC_NOMOD with `S_db_noMod`.
3040            return Err(CaError::ReadOnlyField(name.to_string()));
3041        }
3042        // The override is the WRITABLE TWIN of `declared_default`, and
3043        // `declared_default` is `resolve_field`'s fallback ONLY when the record
3044        // itself serves nothing (`Record::get_field` is `None`). If the record
3045        // DOES serve this field (`get_field` is `Some`), it is not unmodeled —
3046        // it is PARTIALLY modeled: a getter into record memory (e.g.
3047        // `calcout.PVAL` → `self.pval`, which `process()` also writes) but no
3048        // matching `put_field` arm. Storing here would place the value in a
3049        // second cell that `resolve_field` never reaches (`get_field` shadows
3050        // the override) and that no `process()` keeps in step — a silent write
3051        // loss. Such a field's put belongs in the record's OWN `put_field`
3052        // (a per-record setter, a distinct change); refuse it here rather than
3053        // half-accept it, so `resolve_field` stays single-valued. A field the
3054        // record does not serve at all falls through to be stored.
3055        if self.record.get_field(name).is_some() {
3056            return Err(self.unknown_field_error(name.to_string()));
3057        }
3058        let target = desc.dbf_type;
3059        let coerced =
3060            crate::server::record::coerce_put_value(self.record.as_ref(), name, target, value)?;
3061        self.declared_overrides
3062            .insert(name.to_ascii_uppercase(), coerced);
3063        Ok(CommonFieldPutResult::NoChange)
3064    }
3065
3066    /// Get virtual fields (NAME, RTYP).
3067    pub fn get_virtual_field(&self, name: &str) -> Option<EpicsValue> {
3068        match name {
3069            "NAME" => Some(EpicsValue::String(self.name.clone().into())),
3070            "RTYP" => Some(EpicsValue::String(
3071                self.record.record_type().to_string().into(),
3072            )),
3073            _ => None,
3074        }
3075    }
3076
3077    /// Evaluate alarms based on record type and current value.
3078    /// Uses rec_gbl_set_sevr to accumulate into nsta/nsev.
3079    ///
3080    /// CALC_ALARM is NOT raised here. C raises it inside the record's own
3081    /// `process()` (`calcRecord.c:121-123`, `calcoutRecord.c:238-241`,
3082    /// `sCalcoutRecord.c:357-363`, `aCalcoutRecord.c:304-305`,
3083    /// `swaitRecord.c:409-410`), and in the port [`Record::check_alarms`] — which
3084    /// runs immediately before this — is that owner. It used to be raised here
3085    /// instead, keyed on a hardcoded `rtype` list plus a `CALC_ALARM` pseudo-field
3086    /// no DBD declares; swait is what that construction cost: it carried the flag
3087    /// but was not on the list, so a failed `calcPerform` alarmed nowhere.
3088    pub fn evaluate_alarms(&mut self) {
3089        use crate::server::recgbl;
3090
3091        // Check UDF first — but only for record types whose C support carries
3092        // the `if (prec->udf) recGblSetSevr(..., UDF_ALARM, ...)` guard. C has
3093        // no central UDF alarm; see `Record::raises_udf_alarm`.
3094        if self.record.raises_udf_alarm() {
3095            recgbl::rec_gbl_check_udf(
3096                &mut self.common,
3097                self.record.udf_alarm_on_exact_one(),
3098                self.record.udf_alarm_message(),
3099            );
3100        }
3101
3102        // The analog-alarm SLOT is the enumeration — a record has the ladder iff
3103        // `new_boxed` gave it a config, which is the one place the C `.dbd`
3104        // survey lives. A second `match rtype` here was the same list written
3105        // twice, and the two could disagree: scalcout was in neither, so its ten
3106        // C alarm fields could not even be put.
3107        //
3108        // bi / bo / busy / mbbi / mbbo STATE+COS (and mbbo SOFT) alarm evaluation
3109        // lives in each record's `Record::check_alarms` hook (C `checkAlarms`);
3110        // those records carry no analog config, so they never reach here and
3111        // cannot double-raise.
3112        if let Some(ref alarm_cfg) = self.common.analog_alarm.clone() {
3113            let val = match self.record.val() {
3114                Some(EpicsValue::Double(v)) => v,
3115                Some(EpicsValue::Long(v)) => v as f64,
3116                Some(EpicsValue::Int64(v)) => v as f64,
3117                _ => return,
3118            };
3119            self.evaluate_analog_alarm(val, alarm_cfg);
3120        }
3121    }
3122
3123    fn evaluate_analog_alarm(&mut self, val: f64, cfg: &AnalogAlarmConfig) {
3124        use crate::server::recgbl::{self, alarm_status};
3125
3126        // C `checkAlarms` returns immediately on a UDF cycle: it raises
3127        // `UDF_ALARM`/`UDFS` (already done by `rec_gbl_check_udf` in
3128        // `evaluate_alarms`), zeroes `AFVL` on the AFTC-capable records, and
3129        // returns BEFORE the range check — so `LALM` is left untouched and
3130        // `AFVL` is not filtered this cycle. The identical guard appears in
3131        // every record that shares this arm (`aiRecord.c:319-323`,
3132        // `aoRecord.c:383-386`, `longinRecord.c:274-278`,
3133        // `longoutRecord.c:317-320`, `int64inRecord.c:267-271`,
3134        // `int64outRecord.c:298-301`, `calcRecord.c:300-304`,
3135        // `calcoutRecord.c:563-566`). AFTC-capable records (ai/longin/
3136        // int64in/calc) carry `AFVL` and zero it (`prec->afvl = 0`); the
3137        // out records (ao/longout/int64out/calcout) have no `AFVL` and just
3138        // return. Running the range check here would drift `LALM` to `val`
3139        // (NaN on an undefined cycle) and filter `AFVL` — both observable.
3140        if self.common.udf != 0 {
3141            if matches!(
3142                self.record.record_type(),
3143                "calc" | "ai" | "longin" | "int64in"
3144            ) && self.record.get_field("AFVL").and_then(|v| v.to_f64()) != Some(0.0)
3145            {
3146                let _ = self.record.put_field("AFVL", EpicsValue::Double(0.0));
3147            }
3148            return;
3149        }
3150
3151        let hyst = self.common.hyst;
3152        let lalm = self
3153            .record
3154            .get_field("LALM")
3155            .and_then(|v| v.to_f64())
3156            .unwrap_or(val);
3157
3158        // C-style per-level hysteresis: alarm fires if val passes the level,
3159        // OR if we were already at that alarm level (lalm == alev) and val
3160        // hasn't retreated past the hysteresis margin.
3161        //
3162        // `alarm_range` is the C-style integer level: 1=Lolo, 2=Low,
3163        // 3=Normal, 4=High, 5=Hihi. Required for the calc-record AFTC
3164        // filter (`calcRecord.c::checkAlarms:339-381`) which filters
3165        // on the range level (not on severity) and re-maps back.
3166        // C's `checkAlarms` enables each level with a NONZERO test on the raw
3167        // severity ordinal (`if (prec->hhsv && …)`) and passes that raw ordinal
3168        // to `recGblSetSevr`; `recGblResetAlarms` then clamps the resulting
3169        // *severity* to `INVALID_ALARM` while the *status* keeps the level. So an
3170        // out-of-range selector (`HHSV = 4`) still fires HIHI and lands
3171        // SEVR=INVALID/STAT=HIHI — reproduced by testing `!= 0` and mapping the
3172        // ordinal through [`AlarmSeverity::from_u16`] (which clamps `>= 3` to
3173        // `Invalid`).
3174        let (mut new_sevr, mut new_stat, mut alev, mut alarm_range) = if cfg.hhsv != 0
3175            && (val >= cfg.hihi || (lalm == cfg.hihi && val >= cfg.hihi - hyst))
3176        {
3177            (
3178                AlarmSeverity::from_u16(cfg.hhsv as u16),
3179                alarm_status::HIHI_ALARM,
3180                cfg.hihi,
3181                5u16,
3182            )
3183        } else if cfg.llsv != 0 && (val <= cfg.lolo || (lalm == cfg.lolo && val <= cfg.lolo + hyst))
3184        {
3185            (
3186                AlarmSeverity::from_u16(cfg.llsv as u16),
3187                alarm_status::LOLO_ALARM,
3188                cfg.lolo,
3189                1u16,
3190            )
3191        } else if cfg.hsv != 0 && (val >= cfg.high || (lalm == cfg.high && val >= cfg.high - hyst))
3192        {
3193            (
3194                AlarmSeverity::from_u16(cfg.hsv as u16),
3195                alarm_status::HIGH_ALARM,
3196                cfg.high,
3197                4u16,
3198            )
3199        } else if cfg.lsv != 0 && (val <= cfg.low || (lalm == cfg.low && val <= cfg.low + hyst)) {
3200            (
3201                AlarmSeverity::from_u16(cfg.lsv as u16),
3202                alarm_status::LOW_ALARM,
3203                cfg.low,
3204                2u16,
3205            )
3206        } else {
3207            (AlarmSeverity::NoAlarm, alarm_status::NO_ALARM, val, 3u16)
3208        };
3209
3210        // C parity: the alarm-range AFTC low-pass filter
3211        // (`{ai,longin,int64in,calc}Record.c::checkAlarms`) smooths the
3212        // integer `alarmRange` and re-maps. Only records that carry the
3213        // AFTC/AFVL fields run it — `ao`/`longout`/`int64out`/`calcout`
3214        // have no AFTC field (confirmed via the respective `.dbd.pod`),
3215        // so they are excluded.
3216        let aftc_capable = matches!(
3217            self.record.record_type(),
3218            "calc" | "ai" | "longin" | "int64in"
3219        );
3220        if aftc_capable {
3221            let aftc = self
3222                .record
3223                .get_field("AFTC")
3224                .and_then(|v| v.to_f64())
3225                .unwrap_or(0.0);
3226            let afvl = self
3227                .record
3228                .get_field("AFVL")
3229                .and_then(|v| v.to_f64())
3230                .unwrap_or(0.0);
3231            if aftc > 0.0 {
3232                let now = crate::runtime::general_time::get_current();
3233                let (filtered_range, new_afvl) = crate::server::records::alarm_filter::aftc_filter(
3234                    alarm_range,
3235                    aftc,
3236                    afvl,
3237                    self.common.time,
3238                    now,
3239                );
3240                let _ = self.record.put_field("AFVL", EpicsValue::Double(new_afvl));
3241                if filtered_range != alarm_range {
3242                    // Re-map filtered range back to (sevr, stat, alev).
3243                    let (mapped_sevr, mapped_stat, mapped_alev) = match filtered_range {
3244                        5 => (
3245                            AlarmSeverity::from_u16(cfg.hhsv as u16),
3246                            alarm_status::HIHI_ALARM,
3247                            cfg.hihi,
3248                        ),
3249                        4 => (
3250                            AlarmSeverity::from_u16(cfg.hsv as u16),
3251                            alarm_status::HIGH_ALARM,
3252                            cfg.high,
3253                        ),
3254                        2 => (
3255                            AlarmSeverity::from_u16(cfg.lsv as u16),
3256                            alarm_status::LOW_ALARM,
3257                            cfg.low,
3258                        ),
3259                        1 => (
3260                            AlarmSeverity::from_u16(cfg.llsv as u16),
3261                            alarm_status::LOLO_ALARM,
3262                            cfg.lolo,
3263                        ),
3264                        _ => (AlarmSeverity::NoAlarm, alarm_status::NO_ALARM, val),
3265                    };
3266                    new_sevr = mapped_sevr;
3267                    new_stat = mapped_stat;
3268                    alev = mapped_alev;
3269                    alarm_range = filtered_range;
3270                }
3271            } else {
3272                // aftc <= 0 disables the filter. C `checkAlarms`
3273                // (e.g. aiRecord.c:356,402) initialises the local
3274                // `afvl = 0` and unconditionally stores `prec->afvl =
3275                // afvl` at the end, so a disabled filter drives AFVL to
3276                // 0. Mirror that here so a stale accumulator from a prior
3277                // `aftc > 0` run cannot mis-seed the filter if AFTC is
3278                // re-enabled later.
3279                if afvl != 0.0 {
3280                    let _ = self.record.put_field("AFVL", EpicsValue::Double(0.0));
3281                }
3282            }
3283        }
3284        let _ = alarm_range; // suppress unused-var on non-calc paths
3285
3286        if new_sevr != AlarmSeverity::NoAlarm {
3287            recgbl::rec_gbl_set_sevr(&mut self.common, new_stat, new_sevr);
3288            // C sets LALM to the alarm threshold level, not the current value
3289            let _ = self.record.put_field("LALM", EpicsValue::Double(alev));
3290        } else {
3291            // No alarm condition: reset LALM to current value (like C)
3292            let _ = self.record.put_field("LALM", EpicsValue::Double(val));
3293        }
3294    }
3295
3296    /// Invoke the registered subroutine (`sub`/`aSub` `SNAM`) if one is
3297    /// bound, before the record's `process()` body runs.
3298    ///
3299    /// C `subRecord.c::do_sub` / `aSubRecord.c::do_sub` call the named
3300    /// subroutine on EVERY `process()`. The function registry lives on the
3301    /// framework (`RecordInstance::subroutine`), not on the record, so the
3302    /// record's own `process()` is a no-op for these two types and the
3303    /// framework must drive the call. This is the SINGLE owner of that call
3304    /// for every dispatch path: the main engine
3305    /// (`process_record_with_links_inner`, the SCAN / event / CA-put-to-PP /
3306    /// FLNK path) and the by-name `process_local` (`db.process_record`,
3307    /// QSRV group / foreign-call path) both route through here, so a
3308    /// `sub`/`aSub` runs identically regardless of how it is processed.
3309    /// Previously only `process_local` invoked the subroutine, so on the
3310    /// main engine path `VAL`/`VALA..VALU`/`OUTA..OUTU` never updated.
3311    /// The cycle's status is delivered to the record on EVERY exit path — see
3312    /// [`Record::set_subroutine_status`], which aSub's OUT-link gate reads. The
3313    /// delivery is factored out of the body below so a future early return
3314    /// cannot skip it: the body returns the status, this wrapper publishes it.
3315    pub(crate) fn run_registered_subroutine(&mut self) -> CaResult<()> {
3316        let outcome = self.run_subroutine_body();
3317        // A subroutine that errored out has no C counterpart (a C subroutine
3318        // returns a `long`); it is a failed cycle, so it takes the non-zero
3319        // arm — no outputs.
3320        let status = *outcome.as_ref().unwrap_or(&SUBROUTINE_STATUS_ERROR);
3321        self.record.set_subroutine_status(status);
3322        outcome.map(|_| ())
3323    }
3324
3325    /// Returns C `process`'s `status` for this cycle: 0 only when `do_sub` ran
3326    /// and returned 0.
3327    fn run_subroutine_body(&mut self) -> CaResult<i64> {
3328        use crate::server::recgbl::{self, alarm_status};
3329
3330        // aSub `LFLG=READ`: a `SUBL` re-resolution that found a bad/unregistered
3331        // name (C `fetch_values` -> `S_db_BadSub`) or failed to read the link
3332        // signals "skip do_sub this cycle" — C `process` runs `do_sub` only on
3333        // `!status`. The framework's failed input-link fetch arms the same flag.
3334        // One-shot: taken (cleared) whether or not a subroutine is set, so it
3335        // never leaks into the next cycle. The single consumer of the flag,
3336        // shared by every process path.
3337        if std::mem::take(&mut self.suppress_subroutine_run) {
3338            return Ok(SUBROUTINE_STATUS_SKIPPED);
3339        }
3340
3341        // Clone the Arc so the borrow on `self.subroutine` is released
3342        // before we mutate `self.record` / `self.common` below.
3343        let Some(sub_fn) = self.subroutine.clone() else {
3344            // C `do_sub` (aSubRecord.c:459-465, subRecord.c:118-123)
3345            // short-circuits an EMPTY SNAM to `return 0` BEFORE the
3346            // `pfunc == NULL` -> `S_db_BadSub` check: a subroutine record with
3347            // no SNAM is not a bad-sub, it is a no-op that completes with
3348            // status 0. Only a NON-empty, unregistered SNAM yields
3349            // `S_db_BadSub`.
3350            //
3351            // aSub depends on this: C `process` (aSubRecord.c:224) runs
3352            // `prec->val = status` (= 0) every cycle, forcing VAL back to 0.
3353            // C `monitor()` (aSubRecord.c:414) posts VAL only on
3354            // `val != oval`, so with val==oval==0 a periodic (SCAN) cycle
3355            // posts nothing — the driven `dbPut`s are the only VAL events.
3356            // Without the reset the port leaves VAL holding the last client
3357            // put, and the deadband gate re-posts it on every scan (the aSub
3358            // scanned monitor over-posts: 7 updates where C posts 4). `sub`
3359            // never reaches here with an empty SNAM — it parks PACT at init
3360            // (`Record::init_record_parks_pact`, subRecord.c:119-123) and does
3361            // not process — so the VAL write is scoped to aSub, whose VAL is
3362            // the do_sub status.
3363            let snam_empty = matches!(
3364                self.record.get_field("SNAM"),
3365                Some(EpicsValue::String(s)) if s.is_empty()
3366            );
3367            if snam_empty {
3368                if self.record.record_type() == "aSub" {
3369                    // C `prec->val = do_sub() = 0`.
3370                    let _ = self.record.put_field("VAL", EpicsValue::Long(0));
3371                }
3372                return Ok(0);
3373            }
3374            // A non-empty but unregistered SNAM: C `do_sub` returns
3375            // `S_db_BadSub`, so the cycle's status is non-zero.
3376            return Ok(SUBROUTINE_STATUS_NO_SUB);
3377        };
3378        // C `do_sub` returns the subroutine's `long` status.
3379        let status = sub_fn(&mut *self.record)?;
3380
3381        // aSub publishes the status as VAL (C `aSubRecord.c:223`
3382        // `prec->val = status`). The subroutine's computed outputs live in
3383        // VALA..VALU, so VAL is the return code and overwrites whatever the
3384        // closure may have written to VAL. `sub` does NOT do this — its VAL
3385        // is the value the subroutine computed.
3386        if self.record.record_type() == "aSub" {
3387            // aSub VAL is DBF_LONG (epicsInt32); the do_sub status is a C `long`
3388            // truncated into it (`prec->val = status`).
3389            let _ = self
3390                .record
3391                .put_field("VAL", EpicsValue::Long(status as i32));
3392        }
3393
3394        // A negative status raises SOFT_ALARM at the record's BRSV severity
3395        // (C `do_sub`: `if (status < 0) recGblSetSevr(SOFT_ALARM,
3396        // prec->brsv)`). It accumulates into nsta/nsev for this cycle's
3397        // recGblResetAlarms commit and runs before checkAlarms, so a higher
3398        // analog severity (e.g. the shared analog-alarm owner) still wins via
3399        // the raise-only rule. BRSV defaults to NO_ALARM, under which
3400        // recGblSetSevr is a no-op.
3401        if status < 0 {
3402            let brsv = self
3403                .record
3404                .get_field("BRSV")
3405                .and_then(|v| v.to_f64())
3406                .map(|f| AlarmSeverity::from_u16(f as u16))
3407                .unwrap_or(AlarmSeverity::NoAlarm);
3408            recgbl::rec_gbl_set_sevr(&mut self.common, alarm_status::SOFT_ALARM, brsv);
3409        } else if self.record.record_type() == "aSub" {
3410            // C `aSubRecord.c::do_sub` (469-470): a subroutine that ran and
3411            // returned `>= 0` DEFINES the record — `else prec->udf = FALSE`.
3412            // aSub opts out of the framework's per-cycle blanket UDF re-derive
3413            // (`Record::clears_udf` == false), so THIS is aSub's UDF clear,
3414            // reached only on the path where the subroutine actually executed
3415            // (past the suppress / no-sub early returns above). `sub` keeps the
3416            // blanket re-derive (`clears_udf` true, C `do_sub` `udf =
3417            // isnan(val)`), so it is deliberately not cleared here.
3418            self.common.udf = 0;
3419        }
3420        Ok(status)
3421    }
3422
3423    /// The single owner of a process cycle's SUBSCRIBER posts — C `monitor()`'s
3424    /// "post every subscribed field this cycle touched" loop.
3425    ///
3426    /// Every processing path (`process_record_with_links_inner`, the deferred
3427    /// async-completion path, the simulation path, and [`Self::process_local`])
3428    /// calls this; none of them may reimplement the rules, because a rule that
3429    /// holds on one path and not another is a monitor that fires on a scan cycle
3430    /// but not on an async completion. The per-field mask resolvers
3431    /// ([`AuxPostMask`], [`crate::server::record::value_gate`]) were already
3432    /// single-owned for the same reason — this is the loop around them.
3433    ///
3434    /// It also UPDATES `last_posted` for everything it emits, and it TAKES the
3435    /// record's per-cycle post mask ([`Record::take_cycle_posted_fields`]), so
3436    /// it must run exactly once per cycle.
3437    ///
3438    /// The rules, in order:
3439    ///
3440    /// * The deadband field (default VAL), the
3441    ///   [`recgbl::RECGBL_POSTED_ALARM_FIELDS`](crate::server::recgbl::RECGBL_POSTED_ALARM_FIELDS)
3442    ///   (SEVR/STAT/AMSG/ACKS) and UDF are emitted by the caller with their own
3443    ///   C masks and are skipped here.
3444    /// * [`Record::event_posted_fields`] post from their own event path
3445    ///   (waveform HASH) — never from change detection.
3446    /// * [`Record::process_posted_fields`], when declared, is the closed set of
3447    ///   fields a process cycle may post at all.
3448    /// * A secondary value field ([`Record::fields_posted_with_value_mask`])
3449    ///   carries VAL's monitor mask, gated per its [`ValuePostGate`].
3450    /// * A CHANGED field carries [`AuxPostMask::mask_for`] — unless it is a
3451    ///   [`Record::fields_posted_only_when_marked`] field, which C never
3452    ///   change-detects (aCalcout AA..LL) and which therefore posts from its
3453    ///   mark alone.
3454    /// * An UNCHANGED field posts only if the record marked it this cycle:
3455    ///   statically ([`Record::force_posted_fields`]), per-cycle
3456    ///   ([`Record::take_cycle_posted_fields`]), on the alarm transition
3457    ///   ([`Record::alarm_cycle_monitored_fields`]), or in the DBE_LOG sweep
3458    ///   ([`Record::log_swept_fields`]).
3459    pub(crate) fn collect_subscriber_posts(
3460        &mut self,
3461        deadband_field: &str,
3462        deadband_mask: EventMask,
3463        alarm_bits: EventMask,
3464        aux_post: AuxPostMask,
3465        include_val: bool,
3466    ) -> Vec<(String, EpicsValue, EventMask)> {
3467        use crate::server::record::{CyclePostMask, ValuePostGate, value_gate};
3468
3469        // C's default for a change-detected auxiliary post:
3470        // `monitor_mask | DBE_VALUE | DBE_LOG` (calcRecord.c:420, subRecord.c:400;
3471        // motor `DBE_VAL_LOG` for marked fields, motorRecord.cc:3522-3645).
3472        let aux_mask = alarm_bits | EventMask::VALUE | EventMask::LOG;
3473        let alarm_fanout: &[&str] = if alarm_bits.is_empty() {
3474            &[]
3475        } else {
3476            self.record.alarm_cycle_monitored_fields()
3477        };
3478        let force_fields = self.record.force_posted_fields();
3479        // TAKE — this also clears the state it answers from (C's
3480        // `pcalc->newm = 0`), which is why this loop may run only once per cycle.
3481        let cycle_posted = self.record.take_cycle_posted_fields();
3482        let log_swept = self.record.log_swept_fields();
3483        // C change-detects nothing about these fields; only the record's own
3484        // per-cycle mark may post them (aCalcout AA..LL — no PAA..PLL previous
3485        // copy exists to compare against).
3486        let marked_only = self.record.fields_posted_only_when_marked();
3487        let value_masked = self.record.fields_posted_with_value_mask();
3488        let event_posted = self.record.event_posted_fields();
3489        let process_posted = self.record.process_posted_fields();
3490
3491        let mut sub_updates: Vec<(String, EpicsValue, EventMask)> = Vec::new();
3492        for (field, subs) in &self.subscribers {
3493            if subs.is_empty()
3494                || field == deadband_field
3495                // SEVR/STAT/AMSG/ACKS are posted by `recGblResetAlarms` itself,
3496                // each with its own C mask (recGbl.c:201-217) — the caller emits
3497                // them from `alarm_field_posts`. A second, change-detected copy
3498                // here would double-post with a mask C never uses for them
3499                // (`alarm_bits | DBE_VALUE | DBE_LOG` instead of C's DBE_VALUE
3500                // on ACKS). UDF is excluded for the opposite reason: NO C
3501                // `monitor()` posts it at all, so a processing cycle that
3502                // redefines VAL must emit no `.UDF` event (a caput to `.UDF`
3503                // still posts, through the generic put path).
3504                || crate::server::recgbl::RECGBL_POSTED_ALARM_FIELDS.contains(&field.as_str())
3505                || field == "UDF"
3506                || event_posted.contains(&field.as_str())
3507                || !process_posted.is_none_or(|allowed| allowed.contains(&field.as_str()))
3508            {
3509                continue;
3510            }
3511            let Some(val) = self.resolve_field(field) else {
3512                continue;
3513            };
3514            let changed = match self.posted_value(field) {
3515                Some(prev) => prev != &val,
3516                None => true,
3517            };
3518            if let Some(gate) = value_gate(value_masked, field) {
3519                // C posts this secondary value field with VAL's own monitor_mask,
3520                // from inside the guard that decides whether VAL posts at all —
3521                // never a forced DBE_VALUE|DBE_LOG. `ValuePostGate` says whether C
3522                // also re-tests the field's own value inside that guard (ai RVAL,
3523                // aiRecord.c:462) or posts it whenever the guard fires (timestamp
3524                // RVAL, timestampRecord.c:160).
3525                let post = match gate {
3526                    ValuePostGate::OnChange => changed && !deadband_mask.is_empty(),
3527                    ValuePostGate::WithValue => include_val,
3528                };
3529                if post {
3530                    sub_updates.push((field.clone(), val.clone(), deadband_mask));
3531                }
3532            } else if changed && !marked_only.contains(&field.as_str()) {
3533                sub_updates.push((
3534                    field.clone(),
3535                    val.clone(),
3536                    aux_post.mask_for(field, alarm_bits, deadband_mask),
3537                ));
3538            } else if force_fields.contains(&field.as_str()) {
3539                // C `monitor()` posts a statically re-marked field with
3540                // `monitor_mask | DBE_VAL_LOG` even when unchanged.
3541                sub_updates.push((field.clone(), val.clone(), aux_mask));
3542            } else if cycle_posted.iter().any(|(name, _)| *name == field) {
3543                // One event per MARK, each with the mask of the C call site that
3544                // made it (`CyclePostMask`) — a field marked twice (aCalcout's
3545                // AMASK `afterCalc` post AND its NEWM `monitor()` post) is posted
3546                // twice, exactly as C posts it from both loops.
3547                for (_, cycle_mask) in cycle_posted.iter().filter(|(name, _)| *name == field) {
3548                    let mask = match cycle_mask {
3549                        CyclePostMask::Value => EventMask::VALUE,
3550                        CyclePostMask::ValueLog => EventMask::VALUE | EventMask::LOG,
3551                        CyclePostMask::MonitorValueLog => aux_mask,
3552                    };
3553                    sub_updates.push((field.clone(), val.clone(), mask));
3554                }
3555            } else if alarm_fanout.contains(&field.as_str()) {
3556                // C motor `monitor()` (motorRecord.cc:3513-3645) posts every listed
3557                // field once `monitor_mask != 0`, so a DBE_ALARM-only subscriber
3558                // observes the alarm moment on any of them.
3559                sub_updates.push((field.clone(), val.clone(), alarm_bits));
3560            }
3561            // C `scalerRecord.c::monitor():757-773` posts EVERY S1..Snch with a
3562            // literal DBE_LOG on every cycle it runs (it runs when `ss == IDLE`,
3563            // scalerRecord.c:510). That sweep is INDEPENDENT of the change post,
3564            // not an alternative to it: on the count-completion cycle `ss` is
3565            // IDLE and `updateCounts()` has ALREADY posted each changed Sn with
3566            // DBE_VALUE (:582), so C emits two events for that field in that one
3567            // cycle — DBE_VALUE, then DBE_LOG. Making this an `else if` on
3568            // `changed` dropped the DBE_LOG half exactly when it matters: a
3569            // DBE_LOG-only archiver would never receive the final counts.
3570            //
3571            // The sweep carries the ALARM-transition bits too. DEVIATION from C,
3572            // deliberate — CBUG-B19. C's `monitor()` opens with
3573            // `monitor_mask = recGblResetAlarms(pscal); monitor_mask |=
3574            // (DBE_VALUE|DBE_LOG);` and then posts with a LITERAL `DBE_LOG`
3575            // (scalerRecord.c:764-771) — `monitor_mask` is assigned, OR-ed, and
3576            // never read. Those two lines are dead, and their only plausible use
3577            // was as the third `db_post_events` argument.
3578            // `recGblResetAlarms` returns the alarm-transition mask that every
3579            // other record ORs into its value posts, so discarding it drops the
3580            // alarm bit: a client subscribed to `Sn` with DBE_ALARM receives
3581            // NOTHING on an alarm-severity transition of the record.
3582            //
3583            // The DBE_VALUE half of C's dead `|=` is deliberately NOT
3584            // resurrected: this sweep is unconditional, so adding VALUE would
3585            // fire a value event at every VALUE subscriber on every idle scan,
3586            // changed or not — that would be a new defect, not a fix. The value
3587            // path is separately served by the change post (C's `updateCounts()`
3588            // DBE_VALUE at `:582`).
3589            if log_swept.contains(&field.as_str()) {
3590                sub_updates.push((field.clone(), val, EventMask::LOG | alarm_bits));
3591            }
3592        }
3593        for (field, val, _) in &sub_updates {
3594            self.record_value_post(field, val.clone());
3595        }
3596        sub_updates
3597    }
3598
3599    /// Basic process: process record, evaluate alarms, timestamp, build snapshot.
3600    /// This does NOT handle links — see process_with_context in database.rs.
3601    ///
3602    /// Returns the value/log snapshot plus a list of alarm-field posts
3603    /// (`SEVR`/`STAT`/`AMSG`/`ACKS`) with their individual C event masks.
3604    /// `SEVR` is posted `DBE_VALUE` only; `STAT`/`AMSG` carry `DBE_ALARM`
3605    /// (sevr/amsg change) and/or `DBE_VALUE` (stat change). The caller
3606    /// must fire these via `notify_field` so a `DBE_VALUE`-only `.SEVR`
3607    /// subscriber is not missed on an alarm-only change and a
3608    /// `DBE_ALARM`-only subscriber is not wrongly notified — C parity
3609    /// with `recGblResetAlarms` (recGbl.c:201-220), matching the
3610    /// `processing.rs` link path.
3611    pub fn process_local(
3612        &mut self,
3613    ) -> CaResult<(
3614        ProcessSnapshot,
3615        Vec<(&'static str, crate::server::recgbl::EventMask)>,
3616    )> {
3617        use crate::server::recgbl::{self, EventMask};
3618        const LCNT_ALARM_THRESHOLD: i16 = 10;
3619
3620        if self.pact.swap(true, std::sync::atomic::Ordering::AcqRel) {
3621            // C `dbProcess` PACT-active guard (dbAccess.c:544-557):
3622            //
3623            //   if ((precord->stat == SCAN_ALARM) ||
3624            //       (precord->lcnt++ < MAX_LOCK) ||
3625            //       (precord->sevr >= INVALID_ALARM)) goto all_done;
3626            //   recGblSetSevrMsg(precord, SCAN_ALARM, INVALID_ALARM,
3627            //                    "Async in progress");
3628            //
3629            // The alarm fires EXACTLY ONCE — on the attempt whose
3630            // pre-increment lcnt equals MAX_LOCK — and is then blocked
3631            // by the stat == SCAN_ALARM / sevr >= INVALID bails, the
3632            // same shape as the link path
3633            // (`process_record_with_links_inner`). The pre-fix guard
3634            // here used post-increment `lcnt >= threshold` with no
3635            // already-raised bail, so every reentrant attempt past the
3636            // threshold re-posted the unchanged SEVR/STAT/VAL (and the
3637            // first fire came one attempt early); it also wrote
3638            // sevr/stat directly, skipping `recGblSetSevrMsg` +
3639            // `recGblResetAlarms` — losing the "Async in progress"
3640            // AMSG and the acks bookkeeping the reset performs.
3641            let already_scan_alarm = self.common.stat == recgbl::alarm_status::SCAN_ALARM;
3642            let already_invalid = self.common.sevr >= AlarmSeverity::Invalid;
3643            let lcnt_before = self.common.lcnt;
3644            self.common.lcnt = lcnt_before.saturating_add(1);
3645            if already_scan_alarm || lcnt_before < LCNT_ALARM_THRESHOLD || already_invalid {
3646                return Ok((
3647                    ProcessSnapshot {
3648                        changed_fields: Vec::new(),
3649                    },
3650                    Vec::new(),
3651                ));
3652            }
3653            recgbl::rec_gbl_set_sevr_msg(
3654                &mut self.common,
3655                recgbl::alarm_status::SCAN_ALARM,
3656                AlarmSeverity::Invalid,
3657                "Async in progress",
3658            );
3659            let _ = recgbl::rec_gbl_reset_alarms(&mut self.common);
3660            // Per-field C masks (recGbl.c:201-220): this guard only
3661            // runs on a fresh SCAN_ALARM/INVALID raise, so sevr AND
3662            // stat both moved — SEVR posts DBE_VALUE, STAT/AMSG post
3663            // the shared `stat_mask` = DBE_ALARM|DBE_VALUE, VAL posts
3664            // DBE_VALUE|DBE_LOG plus `val_mask` = DBE_ALARM.
3665            let stat_mask = EventMask::ALARM | EventMask::VALUE;
3666            let mut changed_fields = Vec::new();
3667            if let Some(val) = self.record.val() {
3668                changed_fields.push((
3669                    "VAL".to_string(),
3670                    val,
3671                    EventMask::VALUE | EventMask::LOG | EventMask::ALARM,
3672                ));
3673            }
3674            changed_fields.push((
3675                "SEVR".to_string(),
3676                EpicsValue::Short(self.common.sevr as i16),
3677                EventMask::VALUE,
3678            ));
3679            changed_fields.push((
3680                "STAT".to_string(),
3681                EpicsValue::Short(self.common.stat as i16),
3682                stat_mask,
3683            ));
3684            // AMSG carries "Async in progress" alongside the STAT
3685            // transition (C recGbl.c posts STAT and AMSG together
3686            // when any alarm field moved).
3687            changed_fields.push((
3688                "AMSG".to_string(),
3689                EpicsValue::String(self.common.amsg.clone().into()),
3690                stat_mask,
3691            ));
3692            return Ok((ProcessSnapshot { changed_fields }, Vec::new()));
3693        }
3694        self.common.lcnt = 0;
3695        // RAII guard that resets `self.pact` to false on drop — both for the
3696        // normal exit path and for any `?` early return. The guard holds a raw
3697        // pointer rather than a reference because we still need `self` mutably
3698        // while the guard is alive (the record body below mutates other `self`
3699        // fields).
3700        //
3701        // This is the one PACT release that does not go through `leave_pact`,
3702        // and it provably frees nothing: `process_local` holds `&mut self` for
3703        // the whole PACT window, and a put-notify is parked only through
3704        // `park_notify_put`, which needs that same `&mut`. So no deferral can
3705        // be created inside the window, and the `swap(true)` above proved none
3706        // existed on entry (`deferred_notify_put.is_some()` ⟹ PACT).
3707        debug_assert!(
3708            self.deferred_notify_put.is_none(),
3709            "PactExit invariant: a parked put-notify implies PACT, which the \
3710             swap above proved was clear"
3711        );
3712        struct ProcessGuard(*const AtomicBool);
3713        // SAFETY: AtomicBool is Sync; raw pointers don't auto-derive
3714        // Send. We hand-roll Send because the ptr targets a field of
3715        // `self`, which the caller already proves can be borrowed
3716        // through this code path. The pointer is only ever read for an
3717        // atomic store, never written, dereferenced for raw access, or
3718        // escaped from this scope.
3719        unsafe impl Send for ProcessGuard {}
3720        impl Drop for ProcessGuard {
3721            fn drop(&mut self) {
3722                // SAFETY: `self.0` was constructed from
3723                // `&self.pact as *const AtomicBool` below, where
3724                // `self` is the live RecordInstance whose lifetime
3725                // strictly outlives `_guard`. RecordInstance is
3726                // !Unpin-equivalent in practice (we never move it
3727                // while held in the database's `Arc<RwLock<_>>`), so
3728                // the pointer remains valid until Drop runs.
3729                unsafe { &*self.0 }.store(false, std::sync::atomic::Ordering::Release);
3730            }
3731        }
3732        let _guard = ProcessGuard(&self.pact as *const AtomicBool);
3733
3734        // Call subroutine if registered (for sub/aSub records). Single owner
3735        // shared with the main engine path — see `run_registered_subroutine`.
3736        self.run_registered_subroutine()?;
3737        // Soft-Channel input records must skip the RVAL->VAL convert
3738        // (C `devAiSoft.c` `read_ai` returns 2 = "don't convert" for
3739        // every Soft-Channel input record, incl. one with a constant /
3740        // unset INP). Without this, `process_local` on a soft input
3741        // with a preset VAL — e.g. NaN — would run `convert()` and
3742        // clobber it, after which the UDF check below would see a
3743        // defined value and wrongly clear UDF. The
3744        // `processing.rs` link path already does this; `process_local`
3745        // is the separate foreign-call path (`db.process_record`) and
3746        // needs the same skip. "Raw Soft Channel" has a distinct DTYP
3747        // so it is excluded by `is_soft` and still runs convert.
3748        //
3749        // Gated on `soft_channel_skips_convert()` — identical to the
3750        // `processing.rs` link path — so this only suppresses the
3751        // `RVAL → VAL` convert step. `set_device_did_compute` is an
3752        // overloaded hook: `ai/bi/mbbi/mbbi_direct` read it as
3753        // "skip convert" (override true), but `epid` reads it as
3754        // "skip the whole built-in PID compute" (keeps default false).
3755        // Without this gate, a Soft-Channel `epid` driven through
3756        // `process_local` (`db.process_record`, e.g. QSRV group proc
3757        // members) would skip `do_pid()` entirely — the regression
3758        // d1032fe5 fixed on the `processing.rs` path only.
3759        {
3760            let is_soft = self.common.dtyp.is_empty() || self.common.dtyp == "Soft Channel";
3761            let is_output = self.record.can_device_write();
3762            if is_soft && !is_output && self.record.soft_channel_skips_convert() {
3763                self.record.set_device_did_compute(true);
3764            }
3765        }
3766        // Push framework-owned common state (UDF/PHAS/TSE/TSEL) so the
3767        // record's process() can see it — same as the processing.rs link
3768        // path. `process_local` is the foreign-call path
3769        // (`db.process_record`); without this a record driven through it
3770        // (e.g. QSRV group-process members) would not see UDF/TSE.
3771        {
3772            let ctx = self.common.process_context();
3773            self.record.set_process_context(&ctx);
3774        }
3775        let outcome = self.record.process()?;
3776        let process_result = outcome.result;
3777        // Note: process_local() does not execute ProcessActions — those are
3778        // handled by the full process_record_with_links() path in processing.rs.
3779
3780        // If the record reports it modified a metadata-class field during
3781        // process(), invalidate the metadata cache so the next snapshot
3782        // rebuilds from the new values. Default impl returns false, so
3783        // most records pay zero cost here.
3784        if self.record.took_metadata_change() {
3785            self.invalidate_metadata_cache();
3786            // mirror C db_post_events(precord, NULL, DBE_PROPERTY) after record processing.
3787            let fields: Vec<String> = self.subscribers.keys().cloned().collect();
3788            for f in fields {
3789                self.notify_field_with_origin(&f, crate::server::recgbl::EventMask::PROPERTY, 0);
3790            }
3791        }
3792
3793        if process_result == RecordProcessResult::AsyncPending {
3794            // Async: PACT stays set, no further processing this cycle
3795            // Don't clear processing flag (guard won't run — we leak it intentionally)
3796            std::mem::forget(_guard);
3797            return Ok((
3798                ProcessSnapshot {
3799                    changed_fields: Vec::new(),
3800                },
3801                Vec::new(),
3802            ));
3803        }
3804        if let RecordProcessResult::AsyncPendingNotify(fields) = process_result {
3805            // Intermediate notification (e.g. DMOV=0 at move start).
3806            // Unlike AsyncPending, we DO release the processing flag so
3807            // subsequent I/O Intr cycles can continue processing normally.
3808            self.common.time = crate::runtime::general_time::get_current();
3809            // Filter out fields that haven't actually changed, and update
3810            // MLST/last_posted for those that have. Each intermediate
3811            // post carries DBE_VALUE|DBE_LOG — C motor's mid-move
3812            // `db_post_events` calls use `DBE_VAL_LOG`
3813            // (motorRecord.cc:2606 DMOV, and every other do_work post);
3814            // no alarm transition ran on this pending pass.
3815            let mut changed_fields = Vec::new();
3816            for (name, val) in fields {
3817                let changed = match self.posted_value(&name) {
3818                    Some(prev) => prev != &val,
3819                    None => true,
3820                };
3821                if changed {
3822                    if name == "VAL" {
3823                        if let Some(f) = val.to_f64() {
3824                            self.put_coerced("MLST", f);
3825                            self.common.mlst = Some(f);
3826                        }
3827                    }
3828                    self.record_value_post(&name, val.clone());
3829                    changed_fields.push((name, val, EventMask::VALUE | EventMask::LOG));
3830                }
3831            }
3832            // _guard drops here, clearing the processing flag
3833            return Ok((ProcessSnapshot { changed_fields }, Vec::new()));
3834        }
3835        if process_result == RecordProcessResult::CompleteNoEmit {
3836            // The record accumulated this cycle without emitting (compress
3837            // `status == 1`). C `compressRecord.c:365` runs the completion
3838            // epilogue (udf clear, timestamp, monitor, FLNK) only on an emit
3839            // cycle (`if (status != 1)`), so a non-emitting cycle must publish
3840            // nothing — skip the epilogue and return an empty snapshot, exactly
3841            // as the production engine path does in `processing.rs`. This keeps
3842            // the emit-gate uniform across both process-dispatch paths so the
3843            // invariant holds by construction, not by "process_local never
3844            // produces it". CompleteNoEmit is synchronous (PACT already
3845            // cleared); the `_guard` drops here, clearing the processing flag.
3846            return Ok((
3847                ProcessSnapshot {
3848                    changed_fields: Vec::new(),
3849                },
3850                Vec::new(),
3851            ));
3852        }
3853
3854        // `CompleteDeferOutput` (swait ODLY delay-start) is NOT special-cased
3855        // here: it deliberately shares the Complete value-side snapshot builder
3856        // below. C `swaitRecord.c::process` posts the value side (`monitor()`,
3857        // line 475) on the delaying cycle, so building the snapshot now is the
3858        // correct, parity-matching behavior — unlike `CompleteNoEmit` above,
3859        // whose fall-through would wrongly emit. The variant's *other* halves —
3860        // holding PACT across the delay and deferring OUT/OEVT/FLNK to the
3861        // `ReprocessAfter` continuation — are the engine path's responsibility
3862        // (`processing.rs::process_record_with_links_inner`); `process_local` is
3863        // a body-only test helper that dispatches no FLNK/output and no
3864        // `ProcessAction`, and no test drives a swait ODLY record through it. So
3865        // the invariant still holds by construction across both dispatch paths:
3866        // both publish the value side here, both leave the output side to the
3867        // engine.
3868
3869        // UDF update before alarm evaluation — C parity (see
3870        // `processing.rs`). A NaN / undefined value keeps UDF true so
3871        // `recGblCheckUDF` raises UDF_ALARM this cycle instead of the
3872        // record reporting a stale/garbage value with no alarm.
3873        if self.record.clears_udf() {
3874            self.common.udf = self.record.value_is_undefined() as u8;
3875        }
3876        // Per-record alarm hook (C `checkAlarms()`).
3877        self.record.check_alarms(&mut self.common);
3878
3879        // Evaluate alarms (accumulates into nsta/nsev)
3880        self.evaluate_alarms();
3881
3882        // Transfer nsta/nsev → sevr/stat, detect alarm change
3883        let alarm_result = recgbl::rec_gbl_reset_alarms(&mut self.common);
3884
3885        self.common.time = crate::runtime::general_time::get_current();
3886        // UDF already updated above — do not clear unconditionally.
3887
3888        // Deadband check for VAL monitor filtering
3889        let (include_val, include_archive) = self.check_deadband_ext();
3890        // C `recGblResetAlarms` `val_mask = DBE_ALARM`
3891        // (recGbl.c:194/203/212): every monitored-value post this cycle
3892        // carries DBE_ALARM when the severity/status OR the alarm
3893        // message moved — same parity rule as the `processing.rs`
3894        // paths.
3895        let alarm_bits = if alarm_result.alarm_changed || alarm_result.amsg_changed {
3896            EventMask::ALARM
3897        } else {
3898            EventMask::NONE
3899        };
3900
3901        // Build snapshot
3902        let mut changed_fields = Vec::new();
3903        // Same deadband-field routing and per-field mask as the
3904        // `processing.rs` paths: the tracked field posts the classes
3905        // that actually fired (MDEL → DBE_VALUE, ADEL → DBE_LOG, alarm
3906        // movement → DBE_ALARM); a non-primary deadband field (motor
3907        // RBV — C motor `monitor()`, motorRecord.cc:3468-3507) leaves
3908        // VAL to the generic change-detection loop below.
3909        let deadband_field = self.record.monitor_deadband_field();
3910        // The mask every change-detected aux field posts with — owned by
3911        // `AuxPostMask`, the same resolver the `processing.rs` paths use, so
3912        // this builder cannot drift from them on what mask a field carries.
3913        let aux_post = AuxPostMask::of(self.record.as_ref());
3914        // The deadband field's post — mask owned by `deadband_post`, the single
3915        // assembler C's `db_post_events(&prec->val, monitor_mask)` maps to.
3916        let deadband = self.deadband_post(alarm_bits, include_val, include_archive);
3917        let deadband_mask = deadband.mask;
3918        if let Some((field, value)) = deadband.field {
3919            changed_fields.push((field, value, deadband_mask));
3920        }
3921        // C `recGblResetAlarms` (recGbl.c:201-220) posts each alarm
3922        // field with its OWN per-field mask, not one record-wide mask:
3923        //   * SEVR — DBE_VALUE, ONLY on a sevr change.
3924        //   * STAT — DBE_ALARM (sevr change) | DBE_VALUE (stat change).
3925        //   * ACKS — DBE_VALUE, only when an alarm field moved.
3926        // Pushing SEVR/STAT into `changed_fields` collapses them onto
3927        // the single record-wide `event_mask` (which carries ALARM on
3928        // `alarm_changed`): a DBE_VALUE-only `.SEVR` subscriber would
3929        // miss a stat-only-driven sevr change, and a DBE_ALARM-only
3930        // `.SEVR` subscriber would be wrongly notified. Post them via
3931        // `notify_field` with their individual masks instead — exactly
3932        // as the `processing.rs` link path does.
3933        let sevr_changed = self.common.sevr != alarm_result.prev_sevr;
3934        let stat_changed = self.common.stat != alarm_result.prev_stat;
3935        let stat_mask = {
3936            let mut m = EventMask::NONE;
3937            // C `recGblResetAlarms` carries DBE_ALARM on the STAT/AMSG
3938            // posts whenever the severity OR the alarm message moved —
3939            // not on a severity change alone. Aligning with the
3940            // `processing.rs` link path (and `complete_async_record`).
3941            if sevr_changed || alarm_result.amsg_changed {
3942                m |= EventMask::ALARM;
3943            }
3944            if stat_changed {
3945                m |= EventMask::VALUE;
3946            }
3947            m
3948        };
3949        let mut alarm_posts: Vec<(&'static str, EventMask)> = Vec::new();
3950        if sevr_changed {
3951            alarm_posts.push(("SEVR", EventMask::VALUE));
3952        }
3953        if !stat_mask.is_empty() {
3954            alarm_posts.push(("STAT", stat_mask));
3955            // AMSG shares STAT's mask — C posts it alongside STAT when
3956            // any alarm field moved.
3957            alarm_posts.push(("AMSG", stat_mask));
3958        }
3959        // C parity (recGbl.c:214-217): ACKS is posted (DBE_VALUE) whenever the
3960        // alarm-acknowledge rule fires — `acks_posted` already folds in C's
3961        // `if (stat_mask)` guard, and the post carries no value-change test.
3962        if alarm_result.acks_posted {
3963            alarm_posts.push(("ACKS", EventMask::VALUE));
3964        }
3965
3966        // The cycle's subscriber posts — assembled by the single owner
3967        // `collect_subscriber_posts`, shared with every `processing.rs` path.
3968        changed_fields.extend(self.collect_subscriber_posts(
3969            deadband_field,
3970            deadband_mask,
3971            alarm_bits,
3972            aux_post,
3973            include_val,
3974        ));
3975        // C waveform/aai/aao `monitor()` posts HASH with a literal
3976        // `DBE_VALUE` only on a content-hash change (waveformRecord.c:
3977        // 317-319), independent of the VAL post mask. `array_hash_changed`
3978        // was set by `check_deadband_ext` this cycle.
3979        if self.array_hash_changed {
3980            if let Some(h) = self.resolve_field("HASH") {
3981                changed_fields.push(("HASH".to_string(), h, EventMask::VALUE));
3982            }
3983        }
3984
3985        // No `.UDF` post — C `monitor()` posts UDF nowhere, and
3986        // `recGblResetAlarms` (recGbl.c:204-216) posts only SEVR/STAT/AMSG/
3987        // ACKS. A `.UDF` event exists only where C's generic `dbPut` posts
3988        // the field it wrote (dbAccess.c:1420-1430) — i.e. a client caput to
3989        // `.UDF` itself.
3990
3991        Ok((ProcessSnapshot { changed_fields }, alarm_posts))
3992    }
3993
3994    /// Put a f64 value into a record field, coercing to the field's native type.
3995    pub(crate) fn put_coerced(&mut self, field: &str, val: f64) {
3996        use crate::types::EpicsValue;
3997        let target_type = self
3998            .record
3999            .get_field(field)
4000            .map(|v| v.db_field_type())
4001            .unwrap_or(crate::types::DbFieldType::Double);
4002        let coerced = EpicsValue::Double(val).convert_to(target_type);
4003        let _ = self.record.put_field(field, coerced);
4004    }
4005
4006    /// Check MDEL/ADEL deadbands for VAL monitor/archive filtering.
4007    /// Returns `(monitor_trigger, archive_trigger)`.
4008    ///
4009    /// Updates `MLST`/`ALST` (record-owned) and the `CommonFields`
4010    /// `mlst/alst` shadow when a trigger fires. Records without
4011    /// MDEL/ADEL (e.g. motor) default to deadband=0 (any actual
4012    /// change triggers).
4013    ///
4014    /// Delegates per-axis deadband comparison to the free function
4015    /// [`check_deadband`] below — see that function's docstring for
4016    /// the four-quadrant NaN/infinity rule mirroring C
4017    /// `recGblCheckDeadband` (recGbl.c:345-370).
4018    ///
4019    /// **C-parity design note**: the Rust port uses `NaN` as the
4020    /// "never posted" sentinel for `MLST`/`ALST`. C achieves the
4021    /// same first-publish guarantee by allocating MLST/ALST in
4022    /// BSS-zeroed storage with a value of 0.0 that the C code is
4023    /// allowed to match against — but the first observed value is
4024    /// not necessarily 0.0, and the C rule "MLST==0 means never
4025    /// posted" relies on the deadband comparison `abs(val - 0.0)`
4026    /// firing on any non-zero first value. NaN is strictly more
4027    /// correct for the Rust port because a legitimate first
4028    /// `val=0.0` still fires on `NaN.is_nan() → true`. This
4029    /// sentinel-as-design is intentional, documented inside
4030    /// [`check_deadband`] (the `oldval.is_nan() → return true` short
4031    /// circuit). It is NOT a deviation inherited from an earlier
4032    /// silent compromise — `record_tests.rs::deadband_*` pins both
4033    /// the NaN-sentinel behaviour and the C four-quadrant transitions.
4034    /// The single owner of the deadband field's monitor post — C `monitor()`'s
4035    /// `db_post_events(&prec->val, monitor_mask)`, the one post every record
4036    /// makes for the value it deadbands.
4037    ///
4038    /// [`Self::check_deadband_ext`] decides WHETHER the MDEL/ADEL classes fired;
4039    /// this decides what the resulting post looks like, and it is the only place
4040    /// that assembles that mask. The three `processing.rs` snapshot builders and
4041    /// the `notify_monitors` path all route through here, so a record's mask rule
4042    /// cannot hold on one processing path and not another.
4043    ///
4044    /// Two record hooks strip C's `DBE_LOG` from the post:
4045    ///
4046    /// * [`Record::value_only_change_fields`] — C posts a literal `DBE_VALUE`
4047    ///   (scaler VAL, scalerRecord.c:478).
4048    /// * [`Record::fields_posted_with_monitor_mask`] — C posts
4049    ///   `monitor_mask | DBE_VALUE` (event VAL, eventRecord.c:163). `monitor_mask`
4050    ///   there is `recGblResetAlarms`'s return, i.e. the alarm bits alone, so the
4051    ///   post carries `DBE_VALUE` (+ `DBE_ALARM` when the alarm moved) and never
4052    ///   the archive `DBE_LOG` — an event's VAL reaches a `DBE_LOG` archiver on
4053    ///   no cycle at all.
4054    ///
4055    /// [`DeadbandPost::field`] is `None` when no class fired, i.e. when C's
4056    /// `if (monitor_mask)` guard would skip the post.
4057    /// C `monitor()`'s VALUE / LOG gate for the primary-value post —
4058    /// `(include_val, include_archive)`, the single owner every processing path
4059    /// feeds into [`Self::deadband_post`] and [`Self::collect_subscriber_posts`].
4060    /// Keeping it in one place is what stops the rule from holding on the
4061    /// synchronous path but not the async-continuation / put-notify paths.
4062    pub(crate) fn value_include_classes(&mut self) -> (bool, bool) {
4063        // fanout/seq "trigger" records post VAL only with the alarm events
4064        // `recGblResetAlarms` returns, never DBE_VALUE/DBE_LOG — see
4065        // `Record::process_posts_value_monitor`. The alarm bits still reach VAL
4066        // via `deadband_post`'s `alarm_bits`, so an alarm transition still posts
4067        // it; only the value/archive classes are suppressed.
4068        if !self.record.process_posts_value_monitor() {
4069            return (false, false);
4070        }
4071        match self.record.monitor_value_changed() {
4072            // lsi/lso post VALUE|LOG only when the string actually changed (C
4073            // `lsiRecord.c`/`lsoRecord.c` monitor: `len != olen || memcmp(oval,
4074            // val, len)`); they have no MDEL/ADEL deadband to express that, so
4075            // the gate is explicit. The MPST/APST `menuPost` "Always" override
4076            // OR-adds DBE_VALUE / DBE_LOG even on an unchanged cycle (C monitor:
4077            // `if (mpst == menuPost_Always) events |= DBE_VALUE; if (apst ==
4078            // menuPost_Always) events |= DBE_LOG;`).
4079            Some(changed) => {
4080                let (val_always, archive_always) = self.record.monitor_always_post();
4081                (changed || val_always, changed || archive_always)
4082            }
4083            None => {
4084                if self.record.uses_monitor_deadband() {
4085                    self.check_deadband_ext()
4086                } else {
4087                    // Binary records (bi/bo/busy/mbbi/mbbo): always post monitors
4088                    (true, true)
4089                }
4090            }
4091        }
4092    }
4093
4094    pub(crate) fn deadband_post(
4095        &self,
4096        alarm_bits: EventMask,
4097        include_val: bool,
4098        include_archive: bool,
4099    ) -> DeadbandPost {
4100        let field = self.record.monitor_deadband_field();
4101        let log_suppressed = self.record.value_only_change_fields().contains(&field)
4102            || self
4103                .record
4104                .fields_posted_with_monitor_mask()
4105                .contains(&field);
4106
4107        let mut mask = alarm_bits;
4108        if include_val {
4109            mask |= EventMask::VALUE;
4110        }
4111        if include_archive && !log_suppressed {
4112            mask |= EventMask::LOG;
4113        }
4114
4115        // The closed set applies to THIS post too. `process_posted_fields` is
4116        // "the CLOSED set of fields a process cycle of this record may post" —
4117        // and the deadband post is a post. A record whose C `monitor()` never
4118        // names the deadband field must not have one invented for it: transform
4119        // `monitor()` (transformRecord.c:786-808) walks A..P and posts no VAL
4120        // at all — VAL is an inert dummy (`:422`) — so an alarm cycle, whose
4121        // `alarm_bits` alone make `mask` non-empty, was firing a `.VAL` monitor
4122        // C never sends. Gating here rather than at each builder keeps the
4123        // single owner of the deadband post the single enforcer of the set.
4124        let in_closed_set = self
4125            .record
4126            .process_posted_fields()
4127            .is_none_or(|allowed| allowed.contains(&field));
4128
4129        let value = if mask.is_empty() || !in_closed_set {
4130            None
4131        } else if field == "VAL" {
4132            self.record.val()
4133        } else {
4134            self.resolve_field(field)
4135        };
4136        DeadbandPost {
4137            mask,
4138            field: value.map(|v| (field.to_string(), v)),
4139        }
4140    }
4141
4142    pub fn check_deadband_ext(&mut self) -> (bool, bool) {
4143        // C waveform/aai/aao `monitor()` (waveformRecord.c:291-326) replaces
4144        // the analog MDEL/ADEL deadband with the MPST/APST "Always vs On
4145        // Change" mechanism: the record hashes its array content and posts
4146        // `DBE_VALUE`/`DBE_LOG` either always or only when the hash changed,
4147        // and posts `HASH` (`DBE_VALUE`) on a hash change. The record owns
4148        // the hash compute + `HASH` update; `array_hash_changed` carries the
4149        // event to the snapshot builders, which post `HASH` (the field is
4150        // excluded from the generic change-detection loop via
4151        // `event_posted_fields`).
4152        if let Some(post) = self.record.array_monitor_post() {
4153            self.array_hash_changed = post.hash_changed;
4154            return (post.post_value, post.post_archive);
4155        }
4156        self.array_hash_changed = false;
4157
4158        // The deadband is evaluated against `monitor_deadband_value()`,
4159        // not `val()` directly: a record whose monitored quantity is
4160        // not its primary value (e.g. the motor record, VAL=setpoint /
4161        // RBV=readback — C `monitor()` deadbands RBV) overrides that
4162        // hook. Default is `val()`, so other records are unaffected.
4163        let val = match self
4164            .record
4165            .monitor_deadband_value()
4166            .and_then(|v| v.to_f64())
4167        {
4168            Some(v) => v,
4169            None => return (true, true),
4170        };
4171
4172        let mdel = self
4173            .record
4174            .get_field("MDEL")
4175            .and_then(|v| v.to_f64())
4176            .unwrap_or(0.0);
4177        let adel = self
4178            .record
4179            .get_field("ADEL")
4180            .and_then(|v| v.to_f64())
4181            .unwrap_or(0.0);
4182
4183        // Use record's MLST/ALST fields if available, otherwise fall back to CommonFields
4184        let mlst = self
4185            .record
4186            .get_field("MLST")
4187            .and_then(|v| v.to_f64())
4188            .or(self.common.mlst)
4189            .unwrap_or(f64::NAN);
4190        let alst = self
4191            .record
4192            .get_field("ALST")
4193            .and_then(|v| v.to_f64())
4194            .or(self.common.alst)
4195            .unwrap_or(f64::NAN);
4196
4197        let monitor_trigger = check_deadband(val, mlst, mdel);
4198        let archive_trigger = check_deadband(val, alst, adel);
4199
4200        if archive_trigger {
4201            self.put_coerced("ALST", val);
4202            self.common.alst = Some(val);
4203        }
4204        if monitor_trigger {
4205            self.put_coerced("MLST", val);
4206            self.common.mlst = Some(val);
4207        }
4208
4209        (monitor_trigger, archive_trigger)
4210    }
4211
4212    /// Build a Snapshot for a given value, populated with the record's display metadata.
4213    /// Uses the metadata cache so the populate cost is paid at most once
4214    /// per metadata-stable interval (cf. `cached_metadata`).
4215    pub fn make_monitor_snapshot(
4216        &self,
4217        field: &str,
4218        value: EpicsValue,
4219    ) -> super::super::snapshot::Snapshot {
4220        // A monitor update is posted from the record's own change-detection
4221        // loop, which hands over the STORED variant. Project it onto the
4222        // field's declared type here, at the same owner the GET path and the
4223        // CA create-channel path use, or a client that was told `DBR_ENUM` at
4224        // create time would be posted a `DBR_SHORT` update.
4225        let value = self.project_to_declared_type(field, value);
4226        let mut snap = super::super::snapshot::Snapshot::new(
4227            value,
4228            self.common.stat,
4229            self.common.sevr as u16,
4230            self.common.time,
4231        );
4232        // Carry the record's `utag` into the monitor update's
4233        // `timeStamp.userTag`, same as the GET path
4234        // (`snapshot_for_field`) and pvxs `iocsource.cpp:245`. Narrows
4235        // the 64-bit `epicsUTag` to the int32 wire field by low-32-bit
4236        // truncation.
4237        snap.user_tag = self.common.utag as i32;
4238        // Same amsg carry as the GET path (`snapshot_for_field`): a monitor
4239        // update serves the record's own `common.amsg`, so PVA
4240        // `alarm.message` matches a read of the same channel.
4241        snap.alarm.amsg = self.common.amsg.clone();
4242        let meta = self.cached_metadata();
4243        snap.display = meta.display;
4244        snap.control = meta.control;
4245        snap.enums = meta.enums;
4246        // Same per-field routing owner as the GET path — a monitor update must
4247        // carry the same metadata a read of that field would.
4248        self.route_field_metadata(field, &mut snap);
4249        // Per-field RSET metadata, same as the GET path
4250        // (`snapshot_for_field`) — a monitor update for VELO must carry
4251        // VELO's limits, not the record-level VAL limits.
4252        self.apply_field_metadata_override(field, &mut snap);
4253        // A monitored DBF_MENU field carries the same DBR_ENUM value and
4254        // choice labels as the GET path, so a `camonitor`/`pvmonitor`
4255        // update shows the menu label, not a bare index.
4256        self.attach_menu_enum(field, &mut snap);
4257        // Same owner, same settled value, same mask as the GET path.
4258        self.assign_property_support(field, &mut snap);
4259        snap
4260    }
4261
4262    /// Apply a record's per-field metadata override (C RSET
4263    /// `get_units`/`get_precision`/`get_graphic_double`/
4264    /// `get_control_double`/`get_alarm_double`, all keyed by field)
4265    /// over the cached record-level metadata. Shared by the GET and
4266    /// monitor snapshot builders. Computed live on every call — never
4267    /// cached — so overrides derived from fields outside the
4268    /// `is_metadata_field` set cannot go stale.
4269    ///
4270    /// This is also where the record-level `Q:form` info tag is narrowed to
4271    /// the served field: QSRV assigns `display.form.index` only when the
4272    /// channel addresses the VAL field (`IOCSource::initialize` gates it on
4273    /// `dbIsValueField(dbChannelFldDes(chan))`, `iocsource.cpp:53`; the form
4274    /// *menu*, `form.choices`, is published for every field). The metadata
4275    /// cache is per-record, so a channel on `REC.RVAL` of a record carrying
4276    /// `info(Q:form, "Hex")` used to report Hex where pvxs reports Default.
4277    /// Both `Snapshot` producers (`snapshot_for_field` for GET,
4278    /// `make_monitor_snapshot` for updates) run this one owner, so
4279    /// `DisplayInfo::form` means exactly one thing on every path: the form
4280    /// index that applies to THIS field.
4281    fn apply_field_metadata_override(
4282        &self,
4283        field: &str,
4284        snap: &mut super::super::snapshot::Snapshot,
4285    ) {
4286        if let Some(display) = snap.display.as_mut()
4287            && !crate::server::database::is_value_field(field)
4288        {
4289            display.form = 0;
4290        }
4291        let Some(ov) = self.record.field_metadata_override(field) else {
4292            return;
4293        };
4294        if ov.units.is_some()
4295            || ov.precision.is_some()
4296            || ov.disp_limits.is_some()
4297            || ov.alarm_limits.is_some()
4298        {
4299            let d = snap.display.get_or_insert_with(Default::default);
4300            if let Some(units) = ov.units {
4301                d.units = units;
4302            }
4303            if let Some(precision) = ov.precision {
4304                d.precision = precision;
4305            }
4306            if let Some((upper, lower)) = ov.disp_limits {
4307                d.upper_disp_limit = upper;
4308                d.lower_disp_limit = lower;
4309            }
4310            if let Some((hihi, high, low, lolo)) = ov.alarm_limits {
4311                d.upper_alarm_limit = hihi;
4312                d.upper_warning_limit = high;
4313                d.lower_warning_limit = low;
4314                d.lower_alarm_limit = lolo;
4315            }
4316        }
4317        if let Some((upper, lower)) = ov.ctrl_limits {
4318            let c = snap.control.get_or_insert_with(Default::default);
4319            c.upper_ctrl_limit = upper;
4320            c.lower_ctrl_limit = lower;
4321        }
4322    }
4323
4324    /// C's rset metadata slots route **per field**, on `dbGetFieldIndex`. The
4325    /// port's metadata cache is the record's VAL metadata, and serving it to
4326    /// every field is what made a non-VAL field report VAL's limits.
4327    ///
4328    /// Every base record's `get_control_double` / `get_alarm_double` has the
4329    /// same two-arm shape: a listed set of field indices that take the
4330    /// record's own limits, and a `default:` arm that hands the field to
4331    /// `recGblGetControlDouble` / `recGblGetAlarmDouble` — the field TYPE's
4332    /// numeric range, and four NaN. This routes the `default:` arm; a listed
4333    /// field keeps the cache, which already holds exactly the record's own
4334    /// limits (and already distinguishes `ao`'s DRVH/DRVL from `ai`'s
4335    /// HOPR/LOPR).
4336    ///
4337    /// The three slots' listed sets are **different**, and each has its own
4338    /// owner here: [`Self::control_explicit_field`],
4339    /// [`Self::graphic_explicit_field`] and [`Self::alarm_explicit_field`].
4340    /// They are separate switches over separate field lists in C, so the
4341    /// membership question is asked once per slot, never once for both — and
4342    /// each list varies by record TYPE, so it is asked once per type too.
4343    ///
4344    /// Measured on a real `softIocPVX` against `record(calc,"X"){}`:
4345    /// `.PHAS` (DBF_SHORT, unlisted) serves control ±32767 — the SHRT range —
4346    /// while `.VAL` and `.HIHI` (both listed) serve 0/0 from HOPR/LOPR.
4347    ///
4348    /// Deliberately NOT routed here, and why:
4349    ///
4350    /// * **display (graphic) limits.** Unlike control, the `default:` arm of
4351    ///   `get_graphic_double` tries a LINK first
4352    ///   (`calcRecord.c` `get_linkNumber` → `dbGetGraphicLimits`) and only
4353    ///   falls to `recGbl` for a field that backs no link. A constant (unset)
4354    ///   link has no metadata getters, so the `dbAccess.c:216` 0/0 seed stands
4355    ///   — measured: `CALC.A` serves display 0/0 but control ±1e300. Which
4356    ///   fields back links is per-record C knowledge the port models nowhere
4357    ///   (no `FieldDesc` relation, no trait hook), so defaulting display to the
4358    ///   type range would CREATE defects on every link-backed field.
4359    /// * **units / precision.** Same link-first shape
4360    ///   (`calcRecord.c` `get_units`, `get_precision`).
4361    ///
4362    /// Both remain a measured residue rather than a guess.
4363    ///
4364    /// The last arm is not the same for every record type — a slot can also
4365    /// fall through WITHOUT delegating, keeping the seed. That fact is one bit
4366    /// per record type, read from its C source: [`control_default_arm`].
4367    fn route_field_metadata(&self, field: &str, snap: &mut super::super::snapshot::Snapshot) {
4368        // The rset slots this record type actually supplies. A NULL slot makes
4369        // `dbAccess.c` clear the option bit, so the leaf is never served and
4370        // there is nothing to route — minting a value here would put a
4371        // fabricated number on the CA wire, which has no marking layer to
4372        // suppress it (`codec.rs` `get_limits` reads these structs ungated).
4373        let slots = self.record.property_support();
4374        let rtype = self.record.record_type();
4375
4376        // C `get_control_double`'s last arm. No base record routes control
4377        // through a link: `dbGetControlLimits` has zero callers in all of
4378        // base, so unlike display this arm needs no link branch.
4379        if slots.control_double && !Self::control_explicit_field(rtype, field) {
4380            let (upper, lower) =
4381                match super::record_trait::control_default_arm(self.record.record_type()) {
4382                    // `recGblGetControlDouble` → `getMaxRangeValues(field_type)`.
4383                    // A type with no case in C's switch (STRING/MENU/DEVICE/links)
4384                    // is written by nothing, leaving the `dbAccess.c:256` seed —
4385                    // which is 0/0, exactly what `unwrap_or` supplies.
4386                    super::record_trait::RsetDefaultArm::RecGblRange => {
4387                        self.rec_gbl_range_for(field).unwrap_or((0.0, 0.0))
4388                    }
4389                    // The slot exists but writes nothing here, so the same
4390                    // `dbAccess.c:256` seed stands. Modelled as a value rather
4391                    // than as `None`: C's option bit is ON (the slot is supplied
4392                    // and returned 0), so the leaf IS served — carrying the seed.
4393                    super::record_trait::RsetDefaultArm::Seed => (0.0, 0.0),
4394                };
4395            snap.control = Some(super::super::snapshot::ControlInfo {
4396                upper_ctrl_limit: upper,
4397                lower_ctrl_limit: lower,
4398            });
4399        }
4400
4401        // C `get_graphic_double`'s last arm. Unlike control this one has a LINK
4402        // branch ahead of the recGbl call, so the three answers are: keep the
4403        // cache (listed on HOPR/LOPR), the link's limits, or the default arm.
4404        if slots.graphic_double && !Self::graphic_explicit_field(rtype, field) {
4405            let (upper, lower) = if Self::graphic_link_backed_field(rtype, field) {
4406                // `dbGetGraphicLimits` on a CONSTANT link writes nothing — a
4407                // constant has no metadata getters — so the `dbAccess.c:216`
4408                // seed stands. The port has no link metadata to consult, and a
4409                // link that IS connected would be answered by the upstream
4410                // record, which this routing does not model either; both land
4411                // here as the seed.
4412                (0.0, 0.0)
4413            } else {
4414                match super::record_trait::graphic_default_arm(rtype) {
4415                    super::record_trait::RsetDefaultArm::RecGblRange => {
4416                        self.rec_gbl_range_for(field).unwrap_or((0.0, 0.0))
4417                    }
4418                    super::record_trait::RsetDefaultArm::Seed => (0.0, 0.0),
4419                }
4420            };
4421            let d = snap.display.get_or_insert_with(Default::default);
4422            d.upper_disp_limit = upper;
4423            d.lower_disp_limit = lower;
4424        }
4425
4426        // C `get_alarm_double`, BOTH arms. This branch owns the four limits
4427        // outright: `slots.alarm_double` is exactly the condition under which
4428        // `getProperties` assigns the four `valueAlarm.*Limit` leaves, so
4429        // whenever the leaves are served this assigns them.
4430        //
4431        // The explicit arm used to be left to the record-level metadata cache
4432        // (`populate_display_info`), whose `match rtype` covered only some of
4433        // the types that supply the slot. A type it missed reached the wire
4434        // with `snap.display == None` and the four leaves kept the NT's
4435        // structural 0 — measured: DFANOUT.VAL, SEL.VAL and SUB.VAL served 0
4436        // where C serves NaN. That made "which limits does VAL carry" depend on
4437        // a match arm existing somewhere else, which is the dual meaning this
4438        // single owner removes.
4439        if slots.alarm_double {
4440            let (hihi, high, low, lolo) = if Self::alarm_explicit_field(rtype, field) {
4441                self.explicit_alarm_limits(rtype)
4442            } else {
4443                // The link-backed sibling arm lands on the same answer:
4444                // `dbAccess.c:294` seeds four NaN, and a constant link supplies
4445                // no alarm limits to overwrite them.
4446                crate::server::recgbl::rec_gbl_get_alarm_double()
4447            };
4448            // The four alarm limits live on DisplayInfo because that mirrors
4449            // C's `dbr_gr_double` packing, which the CA encoder depends on.
4450            // Minting it here is safe: every other DisplayInfo field defaults
4451            // to the same value the `None` path already served.
4452            let d = snap.display.get_or_insert_with(Default::default);
4453            d.upper_alarm_limit = hihi;
4454            d.upper_warning_limit = high;
4455            d.lower_warning_limit = low;
4456            d.lower_alarm_limit = lolo;
4457        }
4458    }
4459
4460    /// The four limits C's `get_alarm_double` serves for the fields its rset
4461    /// lists — [`alarm_explicit_fields`](super::record_trait::alarm_explicit_fields).
4462    ///
4463    /// Read through [`Self::resolve_field`], the same unified accessor C's
4464    /// `prec->hihi` is. The port stores the eight alarm fields in one of two
4465    /// disjoint homes — `common.analog_alarm` for the types with the analog
4466    /// ladder (`ai`/`ao`/`calc`/…), the record's own struct for the types
4467    /// without it (`dfanout`/`sel`) — and `resolve_field` spans both. Reading
4468    /// the ladder slot directly instead would answer NaN for every `dfanout`
4469    /// and `sel` no matter how its HIHI/HHSV were set, because those two types
4470    /// have no slot at all.
4471    fn explicit_alarm_limits(&self, rtype: &str) -> (f64, f64, f64, f64) {
4472        let limit = |name: &str| {
4473            self.resolve_field(name)
4474                .and_then(|v| v.to_f64())
4475                .unwrap_or(0.0)
4476        };
4477        // The raw stored ordinal, NOT clamped to 0..=3: C tests `prec->hhsv`
4478        // for NONZERO, so an out-of-range severity still enables its limit.
4479        let severity = |name: &str| {
4480            self.resolve_field(name)
4481                .and_then(|v| v.to_f64())
4482                .unwrap_or(0.0) as i16
4483        };
4484        match super::record_trait::alarm_val_arm(rtype) {
4485            super::record_trait::AlarmValArm::Unconditional => {
4486                (limit("HIHI"), limit("HIGH"), limit("LOW"), limit("LOLO"))
4487            }
4488            super::record_trait::AlarmValArm::Gated => (
4489                gated(severity("HHSV"), limit("HIHI")),
4490                gated(severity("HSV"), limit("HIGH")),
4491                gated(severity("LSV"), limit("LOW")),
4492                gated(severity("LLSV"), limit("LOLO")),
4493            ),
4494        }
4495    }
4496
4497    /// The fields C's **`get_control_double`** answers with the record's own
4498    /// cached limits, rather than letting them fall to the `default:` arm.
4499    ///
4500    /// "VAL plus the seven alarm bands" is one type's list, not the shared
4501    /// one: it holds for `ai` (`aiRecord.c:267-288`), `ao`, `calc`, `calcout`,
4502    /// `longin`, `longout`, `int64in`, `int64out` and `sub`
4503    /// (`subRecord.c:272-292`) — the `_` arm — and for no other type. Every
4504    /// list below is transcribed from that type's own rset:
4505    ///
4506    /// * `aSub` (`aSubRecord.c:372-376`) is a bare `recGblGetControlDouble`:
4507    ///   it lists NOTHING, VAL included.
4508    /// * `seq` (`seqRecord.c:342-353`) lists only DLYn and `bo`
4509    ///   (`boRecord.c:310-318`) only HIGH — and both answer a LITERAL rather
4510    ///   than the cache, so they come from
4511    ///   [`Record::field_metadata_override`] (which runs after this routing
4512    ///   and wins over the `default:` arm). Nothing of these two types keeps
4513    ///   the cache, VAL included.
4514    /// * `dfanout` (`dfanoutRecord.c:197-213`) lists VAL and the three
4515    ///   latches but NOT the four bands.
4516    /// * `sel` (`selRecord.c:203-235`) lists the eight plus `A`..`L` /
4517    ///   `LA`..`LL`; `acalcout`/`scalcout` (`aCalcoutRecord.c:793-822`,
4518    ///   `sCalcoutRecord.c:653-680`) list VAL and the four bands but NOT the
4519    ///   latches, plus `A`..`L` / `PA`..`PL`.
4520    /// * `epid` (`epidRecord.c:157-180`) lists VAL, the four bands and CVAL on
4521    ///   HOPR/LOPR; `motor` (`motorRecord.cc:3269-3305`) lists VAL and RBV on
4522    ///   HLM/LLM.
4523    /// * the array types (`waveformRecord.c:268-289`, `aaiRecord.c:293-310`,
4524    ///   `aaoRecord.c:296-313`, `compressRecord.c:487-502`,
4525    ///   `histogramRecord.c:458-475`, `subArrayRecord.c:262-291`) list VAL
4526    ///   alone on the cache — their other listed fields answer computed spans,
4527    ///   so those too come from [`Record::field_metadata_override`].
4528    ///
4529    /// Fields whose listed case answers something OTHER than the record's
4530    /// cached limits are deliberately absent — `motor`'s DVAL/DRBV (DHLM/DLLM)
4531    /// and `epid`'s OVAL/P/I/D (DRVH/DRVL) have no override yet and so still
4532    /// take the `default:` arm.
4533    ///
4534    /// **Not** the other two slots' lists — see [`Self::alarm_explicit_field`]
4535    /// (smaller) and [`Self::graphic_explicit_field`] (larger, and cut short
4536    /// for different types). C's three rset arms are separate switches over
4537    /// separate field lists, so one shared predicate could only ever be right
4538    /// for one of them.
4539    fn control_explicit_field(rtype: &str, field: &str) -> bool {
4540        // The two types that list nothing the cache can answer, VAL included.
4541        if matches!(rtype, "aSub" | "seq" | "bo") {
4542            return false;
4543        }
4544        if crate::server::database::is_value_field(field) {
4545            return true;
4546        }
4547        let f = field.to_ascii_uppercase();
4548        let bands: &[&str] = match rtype {
4549            "dfanout" => &["LALM", "ALST", "MLST"],
4550            "acalcout" | "scalcout" | "epid" => &["HIHI", "HIGH", "LOW", "LOLO"],
4551            "waveform" | "aai" | "aao" | "compress" | "histogram" | "subArray" | "motor" => &[],
4552            _ => &["HIHI", "HIGH", "LOW", "LOLO", "LALM", "ALST", "MLST"],
4553        };
4554        if bands.contains(&f.as_str()) {
4555            return true;
4556        }
4557        match rtype {
4558            // sel's args are 12 (`SEL_MAX`), not the calc family's 21.
4559            "sel" => Self::calc_arg_field(&f, 12),
4560            "acalcout" | "scalcout" => {
4561                Self::calc_arg_field(&f, 12)
4562                    || matches!(f.as_bytes(), [b'P', c] if c.is_ascii_uppercase() && *c <= b'L')
4563            }
4564            "epid" => f == "CVAL",
4565            "motor" => f == "RBV",
4566            _ => false,
4567        }
4568    }
4569
4570    /// The fields C's **`get_alarm_double`** lists explicitly — **VAL alone**,
4571    /// not the eight [`Self::control_explicit_field`] lists.
4572    ///
4573    /// Transcribed from every rset in base that supplies the slot; each is a
4574    /// bare `if (dbGetFieldIndex(paddr) == indexof(VAL))` with every other
4575    /// field falling to `recGblGetAlarmDouble` (`recGbl.c:155-162`, four NaN):
4576    /// `aiRecord.c:293`, `aoRecord.c:365`, `calcRecord.c:258`,
4577    /// `calcoutRecord.c`, `dfanoutRecord.c:216`, `int64inRecord.c:235`,
4578    /// `int64outRecord.c`, `longinRecord.c`, `longoutRecord.c`,
4579    /// `selRecord.c:222`, `subRecord.c:236`.
4580    ///
4581    /// So `.HIHI` serves VAL's *control* limits but NOT VAL's *alarm* limits —
4582    /// the band fields' four alarm limits are the recGbl NaN. Routing both
4583    /// slots off one VAL-class predicate is what put the record's own
4584    /// valueAlarm limits on all eight.
4585    ///
4586    /// Which fields each type lists — and the fact that some list none, and
4587    /// that `motor` lists two — is one per-type table,
4588    /// [`alarm_explicit_fields`](super::record_trait::alarm_explicit_fields);
4589    /// what that listed arm ANSWERS is its twin,
4590    /// [`alarm_val_arm`](super::record_trait::alarm_val_arm). Keeping the two
4591    /// questions in one place is what lets this predicate stay a pure
4592    /// membership test.
4593    fn alarm_explicit_field(rtype: &str, field: &str) -> bool {
4594        super::record_trait::alarm_explicit_fields(rtype)
4595            .iter()
4596            .any(|f| field.eq_ignore_ascii_case(f))
4597    }
4598
4599    /// `A`..`A+n-1` (a single letter) or `LA`..`LA+n-1` — C's calc-family
4600    /// argument fields, addressed by index range rather than by name.
4601    ///
4602    /// `calcRecord.c:161-167` / `calcoutRecord.c:417-423` test
4603    /// `idx >= indexof(A) && idx < indexof(A) + CALCPERFORM_NARGS`, and the dbd
4604    /// declares those `CALCPERFORM_NARGS` fields contiguously as the single
4605    /// letters `A`..`U` (`postfix.h:29` = 21, `calcRecord.dbd.pod:801-985`), so
4606    /// the index range and the letter range are the same set.
4607    fn calc_arg_field(field: &str, nargs: u8) -> bool {
4608        let last = b'A' + nargs - 1;
4609        match field.as_bytes() {
4610            [c] => c.is_ascii_uppercase() && *c <= last,
4611            [b'L', c] => c.is_ascii_uppercase() && *c <= last,
4612            _ => false,
4613        }
4614    }
4615
4616    /// The fields C's **`get_graphic_double`** answers with the record's own
4617    /// `HOPR`/`LOPR` — which is exactly what the VAL metadata cache already
4618    /// holds, so routing must leave them on it.
4619    ///
4620    /// The third membership question, and a third distinct set: the alarm arm
4621    /// lists VAL alone and the control arm lists the eight, but graphic lists
4622    /// the eight PLUS a per-type tail, and two types cut it short.
4623    ///
4624    /// * base analog (`aiRecord.c:244-266`, `aoRecord.c:316-339`,
4625    ///   `calcRecord.c:187-212`, `calcoutRecord.c:452-484`,
4626    ///   `subRecord.c:222-247`, `selRecord.c:181-201`,
4627    ///   `dfanoutRecord.c:181-195`, `longinRecord.c:190-204`,
4628    ///   `longoutRecord.c`, `int64inRecord.c:196-210`, `int64outRecord.c`):
4629    ///   the eight.
4630    /// * `acalcout`/`scalcout` (`aCalcoutRecord.c:1046`, `sCalcoutRecord.c:906`)
4631    ///   list only VAL/HIHI/HIGH/LOW/LOLO — NOT LALM/ALST/MLST — plus the
4632    ///   `A`..`L` and `PA`..`PL` ranges.
4633    /// * `sel` (`selRecord.c:193-196`) also lists `A`..`L` / `LA`..`LL`, via a
4634    ///   GCC case range. It has no link arm at all, so its args are HOPR/LOPR
4635    ///   where calc's identically-named ones are link-backed.
4636    /// * the SVAL family (`aiRecord.c:253`, `longinRecord.c`,
4637    ///   `int64inRecord.c:205`), `ao`'s `OVAL`/`PVAL`/`IVOV`
4638    ///   (`aoRecord.c:322-338`), and `compress`'s `IHIL`/`ILIL`
4639    ///   (`compressRecord.c:474-476`).
4640    ///
4641    /// Fields whose graphic case answers something OTHER than HOPR/LOPR are
4642    /// NOT here — they cannot keep the cache and are supplied by
4643    /// [`Record::field_metadata_override`] instead (`histogram` WDTH,
4644    /// `subArray`/`waveform`/`aai`/`aao` index fields, `seq` DLYn,
4645    /// `calcout` ODLY).
4646    fn graphic_explicit_field(rtype: &str, field: &str) -> bool {
4647        // The two types that do not list VAL. Neither switch is keyed on
4648        // VAL at all: `seqRecord.c:282-297` keys on `index - indexof(DLY0)`,
4649        // so every field BELOW DLY0 — VAL included — reaches
4650        // `recGblGetGraphicDouble`; `aSubRecord.c:350-368` keys on the link
4651        // number, and VAL is neither an inlink nor an outlink, so it falls out
4652        // having written nothing (the `graphic_default_arm` Seed).
4653        //
4654        // Measured: `SEQ.VAL` served display 0/0 — the empty VAL cache — where
4655        // C serves the DBF_LONG range.
4656        if matches!(rtype, "seq" | "aSub") {
4657            return false;
4658        }
4659        if crate::server::database::is_value_field(field) {
4660            return true;
4661        }
4662        let f = field.to_ascii_uppercase();
4663        let bands: &[&str] = match rtype {
4664            "acalcout" | "scalcout" => &["HIHI", "HIGH", "LOW", "LOLO"],
4665            _ => &["HIHI", "HIGH", "LOW", "LOLO", "LALM", "ALST", "MLST"],
4666        };
4667        if bands.contains(&f.as_str()) {
4668            return true;
4669        }
4670        match rtype {
4671            "ai" | "longin" | "int64in" => f == "SVAL",
4672            "ao" => matches!(f.as_str(), "OVAL" | "PVAL" | "IVOV"),
4673            "compress" => matches!(f.as_str(), "IHIL" | "ILIL"),
4674            // sel's args are 12 (`SEL_MAX`), not the calc family's 21.
4675            "sel" => Self::calc_arg_field(&f, 12),
4676            // A..L and PA..PL, both to HOPR/LOPR.
4677            "acalcout" | "scalcout" => {
4678                Self::calc_arg_field(&f, 12)
4679                    || matches!(f.as_bytes(), [b'P', c] if c.is_ascii_uppercase() && *c <= b'L')
4680            }
4681            _ => false,
4682        }
4683    }
4684
4685    /// The fields whose C `get_graphic_double` routes through a LINK —
4686    /// `dbGetGraphicLimits` on the link that backs the field, not the field's
4687    /// own type range.
4688    ///
4689    /// This is the one thing display needs that control never did:
4690    /// `dbGetControlLimits` has zero callers in all of base, so the control
4691    /// arm had no link branch to model. Graphic does, and it is what makes the
4692    /// display default arm NOT a straight flip to the type range.
4693    ///
4694    /// A link left unset is a CONSTANT link, which supplies no metadata
4695    /// getters, so `dbGetGraphicLimits` writes nothing and the
4696    /// `dbAccess.c:216` `(0.0, 0.0)` seed stands — measured: `CALC.A` serves
4697    /// display 0/0 where its DBF_DOUBLE type range would be ±1e300, while
4698    /// `CALC.PHAS` (no link) serves the DBF_SHORT range ±32767.
4699    ///
4700    /// Four types, both by mechanical index test:
4701    /// * `calc`/`calcout`/`sub` — `get_linkNumber` (`calcRecord.c:161-167`,
4702    ///   `calcoutRecord.c:417-423`, `subRecord.c:198-204`): `A`..`A+NARGS` and
4703    ///   `LA`..`LA+NARGS`, both onto `&prec->inpa + n`. calc/calcout use
4704    ///   `CALCPERFORM_NARGS` (21); `sub` uses `INP_ARG_MAX`
4705    ///   (`subRecord.c:89`), also 21.
4706    /// * `seq` — `seqRecord.c:322-338`: field offset from `DLY0` with
4707    ///   `offset & 3 == 2` is `DOn`, routed through `get_dol(prec, offset)`.
4708    ///
4709    /// `sel` names its args the same way and is deliberately NOT here: its
4710    /// rset lists them explicitly on HOPR/LOPR and calls `dbGetGraphicLimits`
4711    /// nowhere.
4712    fn graphic_link_backed_field(rtype: &str, field: &str) -> bool {
4713        let f = field.to_ascii_uppercase();
4714        match rtype {
4715            "calc" | "calcout" | "sub" => Self::calc_arg_field(&f, 21),
4716            // DLY0/DOL0/DO0/LNK0, DLY1/... — DOn is offset 2 of each group of
4717            // four, i.e. the `DO` prefix over the same 0-F suffix set.
4718            "seq" => {
4719                matches!(f.as_bytes(), [b'D', b'O', c] if c.is_ascii_digit() || (b'A'..=b'F').contains(c))
4720            }
4721            _ => false,
4722        }
4723    }
4724
4725    /// The field's type as the **dbd declares it**, which is the only type
4726    /// `recGblGetPrec` / `getMaxRangeValues` ever see.
4727    ///
4728    /// C reads `pdbFldDes->field_type` (`recGbl.c:127`, `:151`, `:169`) — the
4729    /// STATIC descriptor — so a `cvt_dbaddr` retype (the port's
4730    /// `runtime_typed`, DBF_NOACCESS in the dbd) never reaches the switch and
4731    /// the switch has no case for it. `None` reproduces that: no case, no
4732    /// write.
4733    fn static_field_type(&self, field: &str) -> Option<crate::types::DbFieldType> {
4734        let desc = self.field_desc(field)?;
4735        (!desc.runtime_typed).then_some(desc.dbf_type)
4736    }
4737
4738    /// `recGblGetGraphicDouble` / `recGblGetControlDouble` for `field` — the
4739    /// same `getMaxRangeValues` table both C entry points share
4740    /// (`recGbl.c:146-171`). `None` where C's switch has no case (STRING,
4741    /// MENU, DEVICE, NOACCESS, links), which writes nothing.
4742    fn rec_gbl_range_for(&self, field: &str) -> Option<(f64, f64)> {
4743        let desc = self.field_desc(field)?;
4744        crate::server::recgbl::rec_gbl_get_graphic_double(
4745            self.static_field_type(field),
4746            desc.menu.is_some(),
4747        )
4748    }
4749
4750    /// Notify subscribers from a snapshot (call outside lock).
4751    /// Each entry carries its own posting mask: only subscribers whose
4752    /// mask intersects that field's mask are notified, and the
4753    /// delivered [`MonitorEvent`] reports exactly that field's classes
4754    /// (C `db_post_events(prec, &field, mask)` per-field granularity).
4755    pub fn notify_from_snapshot(&self, snapshot: &ProcessSnapshot) {
4756        use crate::server::database::filters::FilteredMonitorEvent;
4757        use crate::server::recgbl::EventMask;
4758
4759        for (field, value, posting_mask) in &snapshot.changed_fields {
4760            let posting_mask = *posting_mask;
4761            if let Some(subs) = self.subscribers.get(field) {
4762                // Build a full snapshot once per field (with display metadata)
4763                let mon_snap = self.make_monitor_snapshot(field, value.clone());
4764                for sub in subs {
4765                    // Paused subscriber (`db_event_disable`): suppress at
4766                    // the source — no delivery, no coalesce.
4767                    if !sub.active {
4768                        continue;
4769                    }
4770                    let sub_mask = EventMask::from_bits(sub.mask);
4771                    // Only send when posting mask intersects subscriber mask.
4772                    // Empty posting mask means nothing changed — skip.
4773                    if !posting_mask.is_empty() && sub_mask.intersects(posting_mask) {
4774                        let event = MonitorEvent {
4775                            snapshot: mon_snap.clone(),
4776                            origin: 0,
4777                            mask: posting_mask,
4778                        };
4779                        // Server-side filter chain (3.15.7). Empty chain
4780                        // is identity, so no behaviour change for the
4781                        // common no-filter case.
4782                        let filtered = if sub.filters.is_empty() {
4783                            Some(event)
4784                        } else {
4785                            sub.filters
4786                                .apply(FilteredMonitorEvent::new(event))
4787                                .map(|fe| fe.event)
4788                        };
4789                        let Some(event) = filtered else {
4790                            continue;
4791                        };
4792                        // C `db_queue_event_log`: append, or replace this
4793                        // monitor's last queued entry in place when the queue
4794                        // is in flow control or nearly full. The queue owns
4795                        // that decision and counts the displaced value.
4796                        sub.post(event);
4797                    }
4798                }
4799            }
4800        }
4801    }
4802
4803    /// Notify subscribers of a specific field, filtering by event mask.
4804    pub fn notify_field(&mut self, field: &str, mask: crate::server::recgbl::EventMask) {
4805        self.notify_field_with_origin(field, mask, 0);
4806    }
4807
4808    /// C `db_post_events(precord, NULL, DBE_ALARM)`: post a record-wide
4809    /// alarm event. Delivers to every subscriber on any field whose mask
4810    /// includes DBE_ALARM, each carrying its own monitored field's current
4811    /// value (the per-field `notify_field` already filters by mask
4812    /// intersection). Used by the alarm-acknowledge (ACKT/ACKS) put path so
4813    /// an alarm-mask monitor on any field observes the acknowledgement.
4814    pub fn notify_record_alarm(&mut self) {
4815        let fields: Vec<String> = self.subscribers.keys().cloned().collect();
4816        for field in fields {
4817            self.notify_field(&field, crate::server::recgbl::EventMask::ALARM);
4818        }
4819    }
4820
4821    /// Notify subscribers with an origin tag for self-write filtering.
4822    ///
4823    /// This is C `db_post_events(precord, pfield, mask)` for one field, and —
4824    /// per the `last_posted` contract — the poster that advances the
4825    /// already-published value when `mask` carries a value class. Taking
4826    /// `&mut self` is what makes that unbypassable: there is no way to publish
4827    /// a field's value through the framework without the change detector
4828    /// learning that it was published.
4829    pub fn notify_field_with_origin(
4830        &mut self,
4831        field: &str,
4832        mask: crate::server::recgbl::EventMask,
4833        origin: u64,
4834    ) {
4835        use crate::server::database::filters::FilteredMonitorEvent;
4836        // A value-class post publishes the field to its DBE_VALUE/DBE_LOG
4837        // subscribers, exactly as C's `dbPut` does for the put field
4838        // (dbAccess.c:1414) — record it so the next process cycle's
4839        // change-detection loop does not publish the same value a second
4840        // time. An alarm-only / property-only post publishes no value, so it
4841        // leaves the map alone.
4842        let publishes_value = mask.intersects(
4843            crate::server::recgbl::EventMask::VALUE | crate::server::recgbl::EventMask::LOG,
4844        );
4845        let mut posted: Option<EpicsValue> = None;
4846        if let Some(subs) = self.subscribers.get(field) {
4847            if let Some(value) = self.resolve_field(field) {
4848                if publishes_value {
4849                    posted = Some(value.clone());
4850                }
4851                let mon_snap = self.make_monitor_snapshot(field, value);
4852                for sub in subs {
4853                    // Paused subscriber (`db_event_disable`): suppress at
4854                    // the source — no delivery, no coalesce.
4855                    if !sub.active {
4856                        continue;
4857                    }
4858                    let sub_mask = crate::server::recgbl::EventMask::from_bits(sub.mask);
4859                    if mask.is_empty() || sub_mask.intersects(mask) {
4860                        let event = MonitorEvent {
4861                            snapshot: mon_snap.clone(),
4862                            origin,
4863                            mask,
4864                        };
4865                        // Server-side filter chain (3.15.7). Empty
4866                        // chain (the default for every subscriber
4867                        // until a `.{filter:opts}` PV-name suffix
4868                        // parser wires one in) is the identity, so
4869                        // existing subscribers see no behaviour
4870                        // change. A filter returning `None` silences
4871                        // this event for this subscriber only.
4872                        let filtered = if sub.filters.is_empty() {
4873                            Some(event)
4874                        } else {
4875                            sub.filters
4876                                .apply(FilteredMonitorEvent::new(event))
4877                                .map(|fe| fe.event)
4878                        };
4879                        let Some(event) = filtered else {
4880                            continue;
4881                        };
4882                        // Same single post owner as the snapshot path.
4883                        sub.post(event);
4884                    }
4885                }
4886            }
4887        }
4888        // The value is now published to this field's value-class subscribers:
4889        // hand it to the `last_posted` owner so the change detector does not
4890        // publish it again. Delivery to any individual subscriber may have
4891        // been filtered out, exactly as C's `db_post_events` may find an empty
4892        // `mlis` — C still leaves `monitor()`'s `*_lst` state advanced by the
4893        // cycle that ran, so the post, not the delivery, is what counts.
4894        if let Some(value) = posted {
4895            self.record_value_post(field, value);
4896        }
4897    }
4898
4899    /// Add a subscriber for a specific field. Returns `None` when the
4900    /// per-field subscriber cap (`EPICS_CAS_MAX_SUBSCRIBERS_PER_PV`)
4901    /// is reached. the parallel cap on `ProcessVariable`
4902    /// defends against a misbehaving client opening many
4903    /// MONITOR ops against one shared PV; the same defence is needed
4904    /// for record fields, which the CA server's
4905    /// `ChannelTarget::RecordField` path lands on.
4906    pub fn add_subscriber(
4907        &mut self,
4908        field: &str,
4909        sid: u32,
4910        data_type: DbFieldType,
4911        mask: u16,
4912    ) -> Option<EventReader> {
4913        self.add_subscriber_on(&EventUser::new(), field, sid, data_type, mask)
4914    }
4915
4916    /// Add a field subscriber whose events queue on `user`'s event queue —
4917    /// C `db_add_event` with the circuit's `event_user` as context. Every
4918    /// subscription on one CA circuit shares that queue and therefore its
4919    /// `nDuplicates`, so a duplicate queued for one of them releases the
4920    /// EVENTS_OFF drain for all of them (`dbEvent.c:947`). In-process consumers
4921    /// use [`Self::add_subscriber`], which gives each its own `event_user`.
4922    pub fn add_subscriber_on(
4923        &mut self,
4924        user: &EventUser,
4925        field: &str,
4926        sid: u32,
4927        data_type: DbFieldType,
4928        mask: u16,
4929    ) -> Option<EventReader> {
4930        let cap = crate::server::pv::max_subscribers_per_pv();
4931        let field_str = field.to_string();
4932        let bucket = self.subscribers.entry(field_str.clone()).or_default();
4933        // Reap rows whose consumer is gone before
4934        // counting against the cap. A record field whose value
4935        // never changes (e.g. a quasi-static catalog field) never
4936        // triggers `notify_field_with_origin`'s retain-filter, so
4937        // a long-lived subscribe-disconnect storm could pin the
4938        // bucket at `cap` worth of dead rows and lock out
4939        // genuine new subscribers.
4940        bucket.retain(|s| !s.is_closed());
4941        if bucket.len() >= cap {
4942            tracing::warn!(
4943                record = %self.name,
4944                field = %field_str,
4945                live = bucket.len(),
4946                cap,
4947                "record field subscriber cap reached, refusing add_subscriber"
4948            );
4949            return None;
4950        }
4951        let (sink, reader) = crate::server::event_queue::attach(user, sid);
4952        bucket.push(Subscriber {
4953            sid,
4954            data_type,
4955            mask,
4956            sink,
4957            filters: crate::server::database::filters::FilterChain::new(),
4958            active: true,
4959        });
4960        // Initialize last_posted with current value so the first process cycle
4961        // doesn't treat it as "changed" (the initial value is already sent
4962        // to the client as part of EVENT_ADD response).
4963        if !self.last_posted.contains_key(&field_str) {
4964            if let Some(val) = self.resolve_field(&field_str) {
4965                self.last_posted.insert(field_str, val);
4966            }
4967        }
4968        Some(reader)
4969    }
4970
4971    /// Attach a filter to the most recently added subscriber for
4972    /// `field`. Returns `false` when no subscriber exists yet on that
4973    /// field (call `add_subscriber` first). The CA / PVA channel-name
4974    /// parsers will use this once `.{filter:opts}` syntax is wired.
4975    /// Tests can also use it directly to compose filter chains.
4976    pub fn attach_filter_to_last_subscriber(
4977        &mut self,
4978        field: &str,
4979        filter: std::sync::Arc<dyn crate::server::database::filters::SubscriptionFilter>,
4980    ) -> bool {
4981        if let Some(bucket) = self.subscribers.get_mut(field) {
4982            if let Some(sub) = bucket.last_mut() {
4983                sub.filters.push(filter);
4984                return true;
4985            }
4986        }
4987        false
4988    }
4989
4990    /// Remove a subscriber by subscription ID from all fields.
4991    pub fn remove_subscriber(&mut self, sid: u32) {
4992        for subs in self.subscribers.values_mut() {
4993            subs.retain(|s| s.sid != sid);
4994        }
4995    }
4996
4997    /// Pause / resume one subscriber's event flow at the source
4998    /// (`db_event_disable` / `db_event_enable`). `active == false`
4999    /// suppresses every subsequent post to this subscriber, so the record stops
5000    /// doing per-event work for it. Entries already queued stay queued and are
5001    /// still delivered, exactly as in C: `db_event_disable` only unlinks the
5002    /// subscription from the record's monitor list (`dbEvent.c:521-533`) and
5003    /// never reaches into the event queue. No-op if no subscriber has this
5004    /// `sid`. The caller holds the record write lock, so this is exclusive with
5005    /// the read-locked post paths that consult `Subscriber::active`.
5006    pub fn set_subscriber_active(&mut self, sid: u32, active: bool) {
5007        for subs in self.subscribers.values_mut() {
5008            for sub in subs.iter_mut() {
5009                if sub.sid == sid {
5010                    sub.active = active;
5011                }
5012            }
5013        }
5014    }
5015
5016    /// Clean up subscriber rows whose consumer is gone.
5017    pub fn cleanup_subscribers(&mut self) {
5018        for subs in self.subscribers.values_mut() {
5019            subs.retain(|s| !s.is_closed());
5020        }
5021    }
5022}
5023
5024/// C `recGblCheckDeadband` parity (recGbl.c:345-370). The four branches
5025/// the C path enumerates:
5026///
5027/// 1. Both `newval` and `oldval` finite: `delta = |old - new|`, fire when
5028///    `delta > deadband`.
5029/// 2. Exactly one of {newval, oldval} is NaN, the other not — OR exactly
5030///    one is +/-inf, the other not: `delta = +inf`, always fires.
5031/// 3. Both infinite with opposite signs: `delta = +inf`, always fires.
5032/// 4. Otherwise (e.g. both NaN, both same-signed infinity): no fire.
5033///
5034/// `oldval = NaN` is treated as "never posted" and fires (matches the
5035/// `mlst.is_nan() → trigger` short-circuit the Rust port already had).
5036/// `deadband < 0` fires unconditionally (matches `delta > deadband`
5037/// with a negative deadband — same effect on every numeric value).
5038pub(crate) fn check_deadband(newval: f64, oldval: f64, deadband: f64) -> bool {
5039    // Fire unconditionally when no prior posting has happened. C achieves
5040    // the same effect through the field being default-initialised to a
5041    // sentinel; Rust uses NaN-as-sentinel.
5042    if oldval.is_nan() {
5043        return true;
5044    }
5045    // Negative deadband short-circuits — any value passes.
5046    if deadband < 0.0 {
5047        return true;
5048    }
5049    let new_finite = newval.is_finite();
5050    let old_finite = oldval.is_finite();
5051    if new_finite && old_finite {
5052        return (newval - oldval).abs() > deadband;
5053    }
5054    // From here on, at least one of the two is not finite. We've already
5055    // ruled out oldval=NaN above, so any newval=NaN here is the "newval
5056    // went NaN while oldval was finite/inf" case — must fire (C case 2).
5057    if newval.is_nan() {
5058        return true;
5059    }
5060    // Exactly one infinite, the other finite: C case 2 → fire.
5061    if new_finite != old_finite {
5062        return true;
5063    }
5064    // Both infinite. Opposite signs → fire (C case 3); same sign → no
5065    // fire (C path leaves delta=0 and the `delta > deadband` check fails
5066    // for any non-negative deadband).
5067    newval != oldval
5068}
5069
5070#[cfg(test)]
5071mod device_menu_marking_tests {
5072    use super::*;
5073    use crate::server::records::ai::AiRecord;
5074    use crate::server::records::calc::CalcRecord;
5075    use crate::server::records::mbbo::MbboRecord;
5076
5077    /// C `dbAccess.c:176-179`: a `DBF_DEVICE` field whose record type declares
5078    /// no device support has `pfldDes->ftPvt == NULL` and takes `goto nostrs`,
5079    /// which clears `DBR_ENUM_STRS` — the client is sent NO choice list.
5080    ///
5081    /// `calc` declares no `device()` line, so QSRV2 omits `value.choices` on
5082    /// `CALC.DTYP`. The port used to default the missing menu to `[]` and mark
5083    /// an empty list instead.
5084    #[test]
5085    fn dtyp_of_a_record_type_with_no_device_support_supplies_no_choices() {
5086        let inst = RecordInstance::new("X".into(), CalcRecord::default());
5087        assert!(
5088            super::super::dbd_generated::device_menu("calc").is_none(),
5089            "precondition: calc declares no device() line (C ftPvt == NULL)"
5090        );
5091        assert!(
5092            inst.device_choices().is_none(),
5093            "a record type with no device menu must report None, not an empty list"
5094        );
5095        assert!(
5096            inst.enum_string_form_for("DTYP").is_none(),
5097            "DTYP must supply no enum-string form, so no `value.choices` is marked"
5098        );
5099    }
5100
5101    /// The other side of C's `dbAccess.c:205` comment — *"indicate option data
5102    /// not available. distinct from no_str==0"*. `ai` DOES declare device
5103    /// support, so its menu exists and its choices are served.
5104    #[test]
5105    fn dtyp_of_a_record_type_with_device_support_supplies_its_choices() {
5106        let inst = RecordInstance::new("X".into(), AiRecord::default());
5107        let choices = inst
5108            .device_choices()
5109            .expect("ai declares device() lines, so its menu exists");
5110        assert!(
5111            choices.iter().any(|c| c.as_str_lossy() == "Soft Channel"),
5112            "ai's device menu must carry its declared choices, got {choices:?}"
5113        );
5114        assert!(inst.enum_string_form_for("DTYP").is_some());
5115    }
5116
5117    /// An unset `DTYP` is index 0 on both sides of the distinction — a record
5118    /// type with no device menu has no slot for any DTYP, so the index stays 0
5119    /// rather than panicking or shifting.
5120    #[test]
5121    fn dtyp_index_is_zero_when_the_record_type_has_no_device_menu() {
5122        let inst = RecordInstance::new("X".into(), CalcRecord::default());
5123        assert_eq!(inst.dtyp_index(), 0);
5124    }
5125
5126    /// A downstream crate's registered device menu (asyn's) is merged AFTER the
5127    /// base-declared choices, matching a C fat softIoc that loaded `asyn.dbd`:
5128    /// `mbbo.DTYP` = the three base soft entries then `asynInt32`,
5129    /// `asynUInt32Digital`, in that order. `dtyp_index` reads the merged list,
5130    /// so an `mbbo` bound to `asynInt32` reports index 3 — the wire value C
5131    /// serves — instead of the appended-as-own-slot index the port gave before
5132    /// the menu was known.
5133    #[test]
5134    fn a_registered_device_menu_merges_after_the_base_declared_choices() {
5135        // The list asyn's generated `dbd_generated::DEVICE_MENU_MBBO` carries.
5136        static ASYN_MBBO: &[&str] = &["asynInt32", "asynUInt32Digital"];
5137        super::super::register_device_menu("mbbo", ASYN_MBBO);
5138
5139        let mut inst = RecordInstance::new("X".into(), MbboRecord::default());
5140        let merged: Vec<String> = inst
5141            .device_choices()
5142            .expect("mbbo declares device() lines")
5143            .iter()
5144            .map(|c| c.as_str_lossy().into_owned())
5145            .collect();
5146        assert_eq!(
5147            merged,
5148            vec![
5149                "Soft Channel",
5150                "Raw Soft Channel",
5151                "Async Soft Channel",
5152                "asynInt32",
5153                "asynUInt32Digital",
5154            ],
5155            "base-declared choices first, asyn-contributed appended in asyn.dbd order"
5156        );
5157
5158        inst.common.dtyp = "asynInt32".into();
5159        assert_eq!(
5160            inst.dtyp_index(),
5161            3,
5162            "an asyn DTYP indexes into the merged menu, not an appended own slot"
5163        );
5164    }
5165
5166    /// The None-vs-empty contract survives the merge: a record type neither
5167    /// base nor any downstream crate contributes a `device()` for (calc) stays
5168    /// `None`, never `Some([])`, even after asyn menus are registered in this
5169    /// process.
5170    #[test]
5171    fn calc_stays_none_after_asyn_menus_are_registered() {
5172        static ASYN_MBBO: &[&str] = &["asynInt32", "asynUInt32Digital"];
5173        super::super::register_device_menu("mbbo", ASYN_MBBO);
5174
5175        let inst = RecordInstance::new("X".into(), CalcRecord::default());
5176        assert!(
5177            inst.device_choices().is_none(),
5178            "calc declares no device() and gets no contribution — still None"
5179        );
5180    }
5181}
5182
5183#[cfg(test)]
5184mod property_support_owner_tests {
5185    use crate::server::record::record_trait::default_property_support;
5186    use crate::server::snapshot::PropertySupport as P;
5187
5188    /// `sseqRecord.c:124-144` — the rset table NULLs every property slot
5189    /// except `get_precision`:
5190    ///
5191    /// ```c
5192    /// NULL,           /* get_units */
5193    /// get_precision,  /* get_precision */
5194    /// NULL,           /* get_enum_str */
5195    /// NULL,           /* get_enum_strs */
5196    /// NULL,           /* put_enum_str */
5197    /// NULL,           /* get_graphic_double */
5198    /// NULL,           /* get_control_double */
5199    /// NULL            /* get_alarm_double */
5200    /// ```
5201    ///
5202    /// `sseq` was previously grouped with the full-numeric synApps types, so
5203    /// the port marked six leaves per field that QSRV2 omits entirely.
5204    #[test]
5205    fn sseq_supplies_only_precision() {
5206        assert_eq!(
5207            default_property_support("sseq"),
5208            P {
5209                precision: true,
5210                ..P::NONE
5211            }
5212        );
5213    }
5214
5215    /// A record type the table does not name keeps the permissive
5216    /// `NUMERIC` default rather than silently losing metadata. This is the
5217    /// arm `asyn` used to land on — and why marking had to become a trait
5218    /// method: asyn-rs cannot add a row here.
5219    #[test]
5220    fn an_untranscribed_record_type_keeps_the_permissive_default() {
5221        assert_eq!(default_property_support("no-such-record-type"), P::NUMERIC);
5222    }
5223}
5224
5225#[cfg(test)]
5226mod metadata_cache_tests {
5227    use super::*;
5228    use crate::server::records::ai::AiRecord;
5229
5230    /// Helper: build an AiRecord wrapped in a RecordInstance with EGU/PREC/HOPR/LOPR set.
5231    fn ai_instance() -> RecordInstance {
5232        let mut rec = AiRecord::default();
5233        let _ = rec.put_field("EGU", EpicsValue::String("degC".into()));
5234        let _ = rec.put_field("PREC", EpicsValue::Short(2));
5235        let _ = rec.put_field("HOPR", EpicsValue::Double(100.0));
5236        let _ = rec.put_field("LOPR", EpicsValue::Double(0.0));
5237        let _ = rec.put_field("VAL", EpicsValue::Double(25.0));
5238        RecordInstance::new("TEMP".to_string(), rec)
5239    }
5240
5241    /// a record-field monitor whose event queue has run short of room
5242    /// replaces its last queued entry in place (C `db_queue_event_log`,
5243    /// `dbEvent.c:812-820`), and the displaced value — which the consumer never
5244    /// observed — must be counted in the shared `dropped_monitor_events()`
5245    /// counter (C `nreplace`), the same accounting a `ProcessVariable` post
5246    /// uses. Before the fix the record-field path overwrote its coalesce slot
5247    /// without counting, hiding slow-consumer loss on the path most CA/PVA
5248    /// database monitors use. The counter is process-global, so the assertion is
5249    /// a strict monotonic increase (robust under parallel tests); the
5250    /// revert-verify runs this test in isolation.
5251    #[test]
5252    fn bfr10_record_field_overflow_counts_dropped_event() {
5253        use crate::server::event_queue::{event_que_size, events_per_que};
5254        use crate::server::pv::dropped_monitor_events;
5255        use crate::server::recgbl::EventMask;
5256        let mut inst = ai_instance();
5257        // Keep the reader alive and do NOT drain, so the ring fills to the
5258        // replace threshold and later posts displace the tail entry.
5259        let _reader = inst
5260            .add_subscriber(
5261                "VAL",
5262                1,
5263                crate::types::DbFieldType::Double,
5264                EventMask::VALUE.bits(),
5265            )
5266            .expect("subscriber added");
5267        let before = dropped_monitor_events();
5268        let posts = event_que_size() - events_per_que() + 10;
5269        for _ in 0..posts {
5270            inst.notify_field_with_origin("VAL", EventMask::VALUE, 0);
5271        }
5272        let after = dropped_monitor_events();
5273        assert!(
5274            after > before,
5275            "a post that replaces an unobserved queued entry must record a \
5276             dropped monitor event (before={before}, after={after})"
5277        );
5278    }
5279
5280    #[test]
5281    fn metadata_field_set_check() {
5282        // Sanity check that the metadata field set is recognized.
5283        assert!(is_metadata_field("EGU"));
5284        assert!(is_metadata_field("PREC"));
5285        assert!(is_metadata_field("HOPR"));
5286        assert!(is_metadata_field("LOPR"));
5287        assert!(is_metadata_field("HIHI"));
5288        assert!(is_metadata_field("DRVH"));
5289        assert!(is_metadata_field("ZNAM"));
5290        assert!(is_metadata_field("ZRST"));
5291        assert!(is_metadata_field("FFST"));
5292
5293        // Non-metadata fields should NOT invalidate the cache
5294        assert!(!is_metadata_field("VAL"));
5295        assert!(!is_metadata_field("DESC"));
5296        assert!(!is_metadata_field("SCAN"));
5297        assert!(!is_metadata_field("PHAS"));
5298    }
5299
5300    #[test]
5301    fn cache_starts_empty_then_populates_on_first_snapshot() {
5302        let inst = ai_instance();
5303
5304        // Cache starts empty
5305        assert!(inst.metadata_cache.lock().unwrap().is_none());
5306
5307        // First snapshot triggers populate + cache store
5308        let snap = inst.snapshot_for_field("VAL").unwrap();
5309        let display = snap.display.expect("ai snapshot must have display");
5310        assert_eq!(display.units, "degC");
5311        assert_eq!(display.precision, 2);
5312        assert_eq!(display.upper_disp_limit, 100.0);
5313        assert_eq!(display.lower_disp_limit, 0.0);
5314
5315        // Cache is now populated
5316        assert!(inst.metadata_cache.lock().unwrap().is_some());
5317    }
5318
5319    #[test]
5320    fn q_form_info_tag_sets_display_form_index() {
5321        // pvxs maps the `Q:form` info tag to `display.form.index` for the
5322        // VAL field (iocsource.cpp:42-62). "Hex" is slot 4 of the
5323        // seven-entry menu (Default/String/Binary/Decimal/Hex/...).
5324        let mut inst = ai_instance();
5325        inst.set_info("Q:form", "Hex");
5326        let snap = inst.snapshot_for_field("VAL").unwrap();
5327        let display = snap.display.expect("ai snapshot must have display");
5328        assert_eq!(display.form, 4, "Q:form=Hex -> display.form index 4");
5329    }
5330
5331    /// R16-31: `Q:form` is a record-level info tag, but QSRV assigns
5332    /// `display.form.index` only when the channel addresses the VAL field
5333    /// (`if(dbIsValueField(dbChannelFldDes(chan)))`, `iocsource.cpp:53`). A
5334    /// snapshot of any other field of the same record reports the default
5335    /// form, on both the GET and the monitor producer.
5336    #[test]
5337    fn q_form_applies_to_the_val_field_only() {
5338        let mut inst = ai_instance();
5339        inst.set_info("Q:form", "Hex");
5340
5341        let val = inst.snapshot_for_field("VAL").unwrap();
5342        assert_eq!(val.display.expect("ai display").form, 4);
5343
5344        for non_val in ["RVAL", "SEVR", "HOPR"] {
5345            let Some(snap) = inst.snapshot_for_field(non_val) else {
5346                panic!("ai.{non_val} must resolve");
5347            };
5348            assert_eq!(
5349                snap.display.expect("ai display").form,
5350                0,
5351                "Q:form must not reach ai.{non_val} — pvxs applies it to VAL only"
5352            );
5353        }
5354
5355        // The monitor producer shares the same per-field owner.
5356        let update = inst.make_monitor_snapshot("RVAL", EpicsValue::Long(7));
5357        assert_eq!(
5358            update.display.expect("ai display").form,
5359            0,
5360            "a monitor update on a non-VAL field carries the default form too"
5361        );
5362        let update = inst.make_monitor_snapshot("VAL", EpicsValue::Double(1.0));
5363        assert_eq!(update.display.expect("ai display").form, 4);
5364    }
5365
5366    #[test]
5367    fn q_form_absent_or_unknown_leaves_form_default() {
5368        // No `Q:form` tag -> form stays 0 (Default).
5369        let inst = ai_instance();
5370        let snap = inst.snapshot_for_field("VAL").unwrap();
5371        assert_eq!(snap.display.expect("ai display").form, 0);
5372
5373        // Unrecognised tag -> pvxs leaves the index untouched (0).
5374        let mut inst2 = ai_instance();
5375        inst2.set_info("Q:form", "Nonsense");
5376        let snap2 = inst2.snapshot_for_field("VAL").unwrap();
5377        assert_eq!(snap2.display.expect("ai display").form, 0);
5378    }
5379
5380    /// `info(Q:time:tag)` resolves to pvxs's `nsecMask`
5381    /// (`ioc/typeutils.cpp:79-88`). The prefix test there is a byte-exact
5382    /// `strncmp("nsec:lsb:", 9)` and the digit count is fed straight to
5383    /// `(uint64_t(1u)<<dig)-1u` — no case folding, no whitespace tolerance
5384    /// around the prefix, and no bounds clamp. Each boundary gets a case.
5385    #[test]
5386    fn qtime_nsec_mask_matches_pvxs_updatensecmask() {
5387        let cases: &[(&str, u64)] = &[
5388            // parses: `epicsParseInt32` skips whitespace around the digits
5389            // and accepts a sign.
5390            ("nsec:lsb:20", (1 << 20) - 1),
5391            ("nsec:lsb:1", 1),
5392            ("nsec:lsb: 4 ", 0xF),
5393            ("nsec:lsb:+4", 0xF),
5394            // no clamp: 31 is the mask pvxs actually serves (the old Rust
5395            // `(1..=30)` guard dropped it), and 0 is pvxs's "off" mask.
5396            ("nsec:lsb:31", 0x7FFF_FFFF),
5397            ("nsec:lsb:0", 0),
5398            // `strncmp` is byte-exact: case-folded or whitespace-split
5399            // prefixes do not match, so pvxs leaves `nsecMask` at 0.
5400            ("NSEC:LSB:4", 0),
5401            ("Nsec:Lsb:4", 0),
5402            ("nsec: lsb: 4", 0),
5403            (" nsec:lsb:4", 0),
5404            // `epicsParseInt32` failures: no conversion, extraneous trailing
5405            // bytes, overflow past epicsInt32.
5406            ("nsec:lsb:", 0),
5407            ("nsec:lsb:abc", 0),
5408            ("nsec:lsb:4x", 0),
5409            ("nsec:lsb:4 5", 0),
5410            ("nsec:lsb:99999999999999999999", 0),
5411            ("nsec:lsb:2147483648", 0),
5412        ];
5413        for (tag, want) in cases {
5414            let mut inst = ai_instance();
5415            inst.set_info("Q:time:tag", *tag);
5416            assert_eq!(
5417                inst.qtime_nsec_mask(),
5418                *want,
5419                "info(Q:time:tag, {tag:?}) must resolve to nsecMask {want:#x}"
5420            );
5421        }
5422        // Tag absent entirely → pvxs never enters the `if(auto val = ...)`
5423        // body and `nsecMask` stays 0.
5424        assert_eq!(ai_instance().qtime_nsec_mask(), 0);
5425    }
5426
5427    /// End-to-end on the snapshot: `nsec:lsb:31` publishes
5428    /// `nanoseconds & ~mask` (0, since nanoseconds < 1e9 < 2^31) and
5429    /// `userTag = nanoseconds & mask` (pvxs `iocsource.cpp:239-248`). The
5430    /// old `(1..=30)` clamp served the raw nanoseconds and the record's
5431    /// utag instead.
5432    #[test]
5433    fn qtime_nsec_lsb_31_is_served_not_ignored() {
5434        use std::time::{Duration, SystemTime};
5435        let mut inst = ai_instance();
5436        // 123_456_700, not …789: Windows `SystemTime` is a FILETIME with 100 ns
5437        // resolution, so a sub-100 ns literal is truncated on readback and the
5438        // assertion below would see …700. Any value < 2^31 exercises the
5439        // nsec:lsb:31 mask identically, so pin one that survives the round trip.
5440        inst.common.time = SystemTime::UNIX_EPOCH + Duration::new(42, 123_456_700);
5441        inst.common.utag = 5;
5442        inst.set_info("Q:time:tag", "nsec:lsb:31");
5443
5444        let snap = inst.snapshot_for_field("VAL").unwrap();
5445        assert_eq!(snap.user_tag, 123_456_700);
5446        assert_eq!(snap.timestamp.subsec_nanos(), 0);
5447        assert_eq!(snap.timestamp.unix_secs(), 42);
5448    }
5449
5450    /// The mirror boundary: a tag pvxs's `strncmp` rejects must leave the
5451    /// timestamp and the record's own utag alone. The old case-insensitive
5452    /// split matched `NSEC:LSB:4` and masked the wire timestamp pvxs serves
5453    /// unmasked.
5454    #[test]
5455    fn qtime_uppercase_tag_leaves_timestamp_untouched() {
5456        use std::time::{Duration, SystemTime};
5457        let mut inst = ai_instance();
5458        // 100 ns-multiple so the subsec_nanos assertion holds on Windows too;
5459        // see qtime_nsec_lsb_31_is_served_not_ignored for the FILETIME reason.
5460        inst.common.time = SystemTime::UNIX_EPOCH + Duration::new(42, 123_456_700);
5461        inst.common.utag = 5;
5462        inst.set_info("Q:time:tag", "NSEC:LSB:4");
5463
5464        let snap = inst.snapshot_for_field("VAL").unwrap();
5465        assert_eq!(
5466            snap.user_tag, 5,
5467            "record utag must survive a non-matching tag"
5468        );
5469        assert_eq!(snap.timestamp.subsec_nanos(), 123_456_700);
5470    }
5471
5472    /// the served `timeStamp.userTag` defaults to the record's `utag`
5473    /// (pvxs `iocsource.cpp:245`), on both the GET (`snapshot_for_field`)
5474    /// and MONITOR (`make_monitor_snapshot`) paths. Pre-fix both hard-set
5475    /// it to 0, dropping the record's tag. A bit-31 utag also pins the
5476    /// `u64 -> i32` narrowing: the low 32 bits' pattern is preserved
5477    /// (no clamp), matching pvxs assigning `epicsUTag` into the `Int32`
5478    /// wire field.
5479    #[test]
5480    fn snapshot_serves_record_utag_as_timestamp_usertag() {
5481        let mut inst = ai_instance();
5482        // no `info(Q:time:tag, ...)` on this record, so the nsec-LSB
5483        // override never fires and the utag default is what is served.
5484        inst.common.utag = 0x9000_0000;
5485        let want = 0x9000_0000u32 as i32;
5486
5487        let get = inst.snapshot_for_field("VAL").unwrap();
5488        assert_eq!(
5489            get.user_tag, want,
5490            "GET path must serve the record's utag as timeStamp.userTag"
5491        );
5492
5493        let mon = inst.make_monitor_snapshot("VAL", EpicsValue::Double(1.0));
5494        assert_eq!(
5495            mon.user_tag, want,
5496            "MONITOR path must carry the record's utag too"
5497        );
5498    }
5499
5500    #[test]
5501    fn cache_hit_returns_same_metadata() {
5502        let inst = ai_instance();
5503
5504        // Prime the cache
5505        let snap1 = inst.snapshot_for_field("VAL").unwrap();
5506        let display1 = snap1.display.unwrap();
5507
5508        // Subsequent snapshots return the same cached metadata
5509        let snap2 = inst.snapshot_for_field("VAL").unwrap();
5510        let display2 = snap2.display.unwrap();
5511
5512        assert_eq!(display1.units, display2.units);
5513        assert_eq!(display1.precision, display2.precision);
5514        assert_eq!(display1.upper_disp_limit, display2.upper_disp_limit);
5515        assert_eq!(display1.lower_disp_limit, display2.lower_disp_limit);
5516    }
5517
5518    #[test]
5519    fn invalidate_clears_cache() {
5520        let inst = ai_instance();
5521        let _ = inst.snapshot_for_field("VAL");
5522        assert!(inst.metadata_cache.lock().unwrap().is_some());
5523
5524        inst.invalidate_metadata_cache();
5525        assert!(inst.metadata_cache.lock().unwrap().is_none());
5526    }
5527
5528    #[test]
5529    fn notify_field_written_invalidates_for_metadata_field() {
5530        let inst = ai_instance();
5531        let _ = inst.snapshot_for_field("VAL");
5532        assert!(inst.metadata_cache.lock().unwrap().is_some());
5533
5534        // Writing a metadata field should invalidate
5535        inst.notify_field_written("EGU");
5536        assert!(inst.metadata_cache.lock().unwrap().is_none());
5537    }
5538
5539    #[test]
5540    fn notify_field_written_skips_non_metadata_field() {
5541        let inst = ai_instance();
5542        let _ = inst.snapshot_for_field("VAL");
5543        assert!(inst.metadata_cache.lock().unwrap().is_some());
5544
5545        // Writing a value field should NOT invalidate the cache
5546        inst.notify_field_written("VAL");
5547        assert!(inst.metadata_cache.lock().unwrap().is_some());
5548
5549        // Same for DESC
5550        inst.notify_field_written("DESC");
5551        assert!(inst.metadata_cache.lock().unwrap().is_some());
5552    }
5553
5554    #[test]
5555    fn notify_field_written_is_case_insensitive() {
5556        let inst = ai_instance();
5557        let _ = inst.snapshot_for_field("VAL");
5558        assert!(inst.metadata_cache.lock().unwrap().is_some());
5559
5560        // Lowercase metadata field name should still trigger invalidation
5561        inst.notify_field_written("egu");
5562        assert!(inst.metadata_cache.lock().unwrap().is_none());
5563    }
5564
5565    /// epics-base faac1df1 — `notify_field_written_if_changed` must
5566    /// SKIP the cache invalidation when the metadata field's value
5567    /// didn't actually change. Otherwise a stream of idempotent puts
5568    /// from a CSS panel binds DBE_PROPERTY subscribers to bogus
5569    /// "property changed" events on every cycle.
5570    #[test]
5571    fn notify_field_written_if_changed_skips_when_unchanged() {
5572        let mut inst = ai_instance();
5573        let _ = inst.snapshot_for_field("VAL");
5574        assert!(inst.metadata_cache.lock().unwrap().is_some());
5575
5576        // Capture prev, do a no-op put, then notify — cache must remain.
5577        let prev = inst.record.get_field("EGU");
5578        let _ = inst.record.put_field("EGU", prev.clone().unwrap());
5579        inst.notify_field_written_if_changed("EGU", prev.as_ref());
5580        assert!(
5581            inst.metadata_cache.lock().unwrap().is_some(),
5582            "no-op put must not invalidate the metadata cache"
5583        );
5584    }
5585
5586    /// And when the value DID change, the cache must invalidate.
5587    #[test]
5588    fn notify_field_written_if_changed_invalidates_on_real_change() {
5589        let mut inst = ai_instance();
5590        let _ = inst.snapshot_for_field("VAL");
5591        assert!(inst.metadata_cache.lock().unwrap().is_some());
5592
5593        let prev = inst.record.get_field("EGU");
5594        let _ = inst
5595            .record
5596            .put_field("EGU", EpicsValue::String("kPa".into()));
5597        inst.notify_field_written_if_changed("EGU", prev.as_ref());
5598        assert!(
5599            inst.metadata_cache.lock().unwrap().is_none(),
5600            "real metadata change must invalidate cache"
5601        );
5602    }
5603
5604    /// Non-metadata fields don't carry property semantics — the
5605    /// `if_changed` variant must never invalidate for them, matching
5606    /// the existing `notify_field_written` short-circuit.
5607    #[test]
5608    fn notify_field_written_if_changed_skips_non_metadata_field() {
5609        let mut inst = ai_instance();
5610        let _ = inst.snapshot_for_field("VAL");
5611        assert!(inst.metadata_cache.lock().unwrap().is_some());
5612        // VAL is not in is_metadata_field set — must be skipped even
5613        // with a changed value.
5614        inst.notify_field_written_if_changed("VAL", None);
5615        assert!(inst.metadata_cache.lock().unwrap().is_some());
5616    }
5617
5618    #[test]
5619    fn cache_picks_up_new_value_after_invalidation() {
5620        let mut inst = ai_instance();
5621
5622        // First snapshot: degC
5623        let snap1 = inst.snapshot_for_field("VAL").unwrap();
5624        assert_eq!(snap1.display.unwrap().units, "degC");
5625
5626        // Mutate EGU and invalidate
5627        let _ = inst
5628            .record
5629            .put_field("EGU", EpicsValue::String("mV".into()));
5630        inst.notify_field_written("EGU");
5631
5632        // Second snapshot: mV (rebuilt)
5633        let snap2 = inst.snapshot_for_field("VAL").unwrap();
5634        assert_eq!(snap2.display.unwrap().units, "mV");
5635    }
5636
5637    /// R19-41: every snapshot carries the mask of which properties the
5638    /// channel SUPPLIES — C's `rset` slots (`dbAccess.c:336-430` clears the
5639    /// option bit of each NULL slot) narrowed to the addressed field. One
5640    /// case per gate boundary; the three record types are the ones measured
5641    /// against pvxs, which marks none of these leaves.
5642    #[test]
5643    fn property_support_masks_what_the_record_type_does_not_supply() {
5644        use crate::server::records::longout::LongoutRecord;
5645        use crate::server::records::stringout::StringoutRecord;
5646        use crate::server::records::waveform::WaveformRecord;
5647
5648        // ai VAL (DBF_DOUBLE): every numeric slot, no enum strings.
5649        let ai = ai_instance();
5650        let p = ai.snapshot_for_field("VAL").unwrap().properties;
5651        assert_eq!(p, PropertySupport::NUMERIC);
5652        assert_eq!(
5653            ai.snapshot_for_field("VAL").unwrap().precision(),
5654            Some(2),
5655            "an ai supplies get_precision and VAL is DBF_DOUBLE"
5656        );
5657
5658        // ai RVAL (DBF_LONG): the SAME rset, but C keeps DBR_PRECISION only
5659        // for DBF_FLOAT/DBF_DOUBLE (`dbAccess.c:386-395`).
5660        let rval = ai.snapshot_for_field("RVAL").unwrap();
5661        assert!(
5662            !rval.properties.precision && rval.precision().is_none(),
5663            "a non-float field supplies no precision even when the rset does"
5664        );
5665        assert!(
5666            rval.properties.units,
5667            "the other slots are unaffected by the field's type"
5668        );
5669
5670        // longout: `#define get_precision NULL`.
5671        let lo = RecordInstance::new("LO".to_string(), LongoutRecord::default());
5672        let lo = lo.snapshot_for_field("VAL").unwrap();
5673        assert!(!lo.properties.precision && lo.precision().is_none());
5674        assert!(lo.properties.units && lo.properties.graphic_double);
5675
5676        // stringout: no property slot at all.
5677        let so = RecordInstance::new("SO".to_string(), StringoutRecord::default());
5678        let so = so.snapshot_for_field("VAL").unwrap();
5679        assert_eq!(so.properties, PropertySupport::NONE);
5680        assert!(so.units().is_none(), "a stringout supplies no EGU");
5681
5682        // waveform: `#define get_alarm_double NULL`.
5683        let wf = RecordInstance::new("WF".to_string(), WaveformRecord::default());
5684        let wf = wf.snapshot_for_field("VAL").unwrap();
5685        assert!(
5686            !wf.properties.alarm_double && wf.alarm_limits().is_none(),
5687            "a waveform supplies no alarm limits — a GUI must not draw bands at zero"
5688        );
5689        assert!(wf.properties.units && wf.properties.graphic_double);
5690    }
5691
5692    #[test]
5693    fn make_monitor_snapshot_uses_cache() {
5694        let inst = ai_instance();
5695        assert!(inst.metadata_cache.lock().unwrap().is_none());
5696
5697        // make_monitor_snapshot should also populate the cache
5698        let snap = inst.make_monitor_snapshot("VAL", EpicsValue::Double(42.0));
5699        assert!(snap.display.is_some());
5700        assert!(inst.metadata_cache.lock().unwrap().is_some());
5701
5702        // Subsequent call hits cache
5703        let snap2 = inst.make_monitor_snapshot("VAL", EpicsValue::Double(43.0));
5704        let d1 = snap.display.unwrap();
5705        let d2 = snap2.display.unwrap();
5706        assert_eq!(d1.units, d2.units);
5707        assert_eq!(d1.precision, d2.precision);
5708    }
5709
5710    /// Stub record with a per-field metadata override on SPD only —
5711    /// models a C RSET whose get_units/get_graphic_double key on
5712    /// dbGetFieldIndex (e.g. motorRecord.cc:3156-3361).
5713    struct PerFieldMetaRecord;
5714
5715    impl Record for PerFieldMetaRecord {
5716        fn record_type(&self) -> &'static str {
5717            "ai" // record-level metadata populates from EGU/PREC/HOPR/LOPR
5718        }
5719        fn get_field(&self, name: &str) -> Option<EpicsValue> {
5720            match name {
5721                "VAL" | "SPD" => Some(EpicsValue::Double(1.0)),
5722                "EGU" => Some(EpicsValue::String("mm".into())),
5723                "PREC" => Some(EpicsValue::Short(3)),
5724                "HOPR" => Some(EpicsValue::Double(100.0)),
5725                "LOPR" => Some(EpicsValue::Double(-100.0)),
5726                _ => None,
5727            }
5728        }
5729        fn put_field(&mut self, name: &str, _value: EpicsValue) -> CaResult<()> {
5730            Err(CaError::FieldNotFound(name.to_string()))
5731        }
5732        fn declared_fields(&self) -> &'static [crate::server::record::FieldDesc] {
5733            &[]
5734        }
5735        fn field_metadata_override(
5736            &self,
5737            field: &str,
5738        ) -> Option<crate::server::record::FieldMetadataOverride> {
5739            if field != "SPD" {
5740                return None;
5741            }
5742            Some(crate::server::record::FieldMetadataOverride {
5743                units: Some("mm/sec".into()),
5744                precision: Some(1),
5745                disp_limits: Some((5.0, 0.5)),
5746                ctrl_limits: Some((4.0, 1.0)),
5747                alarm_limits: Some((9.0, 8.0, -8.0, -9.0)),
5748            })
5749        }
5750    }
5751
5752    #[test]
5753    fn field_metadata_override_applies_on_get_and_monitor_paths() {
5754        let inst = RecordInstance::new("PFM".to_string(), PerFieldMetaRecord);
5755
5756        // VAL: no override — record-level metadata serves it.
5757        let snap = inst.snapshot_for_field("VAL").unwrap();
5758        let d = snap.display.unwrap();
5759        assert_eq!(d.units, "mm");
5760        assert_eq!(d.precision, 3);
5761        assert_eq!(d.upper_disp_limit, 100.0);
5762
5763        // SPD via the GET path: every member patched over the cache.
5764        let snap = inst.snapshot_for_field("SPD").unwrap();
5765        let d = snap.display.unwrap();
5766        assert_eq!(d.units, "mm/sec");
5767        assert_eq!(d.precision, 1);
5768        assert_eq!((d.upper_disp_limit, d.lower_disp_limit), (5.0, 0.5));
5769        assert_eq!(
5770            (
5771                d.upper_alarm_limit,
5772                d.upper_warning_limit,
5773                d.lower_warning_limit,
5774                d.lower_alarm_limit
5775            ),
5776            (9.0, 8.0, -8.0, -9.0)
5777        );
5778        let c = snap.control.unwrap();
5779        assert_eq!((c.upper_ctrl_limit, c.lower_ctrl_limit), (4.0, 1.0));
5780
5781        // SPD via the monitor path: identical override.
5782        let snap = inst.make_monitor_snapshot("SPD", EpicsValue::Double(2.0));
5783        let d = snap.display.unwrap();
5784        assert_eq!(d.units, "mm/sec");
5785        assert_eq!((d.upper_disp_limit, d.lower_disp_limit), (5.0, 0.5));
5786        let c = snap.control.unwrap();
5787        assert_eq!((c.upper_ctrl_limit, c.lower_ctrl_limit), (4.0, 1.0));
5788    }
5789
5790    /// Stub modelling the motor monitor() shape (C motorRecord.cc:
5791    /// 3468-3507): VAL is a setpoint, the MDEL/ADEL deadband tracks
5792    /// the RBV readback, which advances on every process.
5793    struct ReadbackDeadbandRecord {
5794        val: f64,
5795        rbv: f64,
5796        deadband: f64,
5797    }
5798
5799    impl Record for ReadbackDeadbandRecord {
5800        fn record_type(&self) -> &'static str {
5801            "ai"
5802        }
5803        fn process(&mut self) -> CaResult<crate::server::record::ProcessOutcome> {
5804            self.rbv += 30.0;
5805            Ok(crate::server::record::ProcessOutcome::complete())
5806        }
5807        fn get_field(&self, name: &str) -> Option<EpicsValue> {
5808            match name {
5809                "VAL" => Some(EpicsValue::Double(self.val)),
5810                "RBV" => Some(EpicsValue::Double(self.rbv)),
5811                "MDEL" | "ADEL" => Some(EpicsValue::Double(self.deadband)),
5812                _ => None,
5813            }
5814        }
5815        fn put_field(&mut self, name: &str, value: EpicsValue) -> CaResult<()> {
5816            match (name, value) {
5817                ("VAL", EpicsValue::Double(v)) => {
5818                    self.val = v;
5819                    Ok(())
5820                }
5821                ("MDEL", EpicsValue::Double(v)) => {
5822                    self.deadband = v;
5823                    Ok(())
5824                }
5825                _ => Err(CaError::FieldNotFound(name.to_string())),
5826            }
5827        }
5828        fn declared_fields(&self) -> &'static [crate::server::record::FieldDesc] {
5829            &[]
5830        }
5831        fn monitor_deadband_value(&self) -> Option<EpicsValue> {
5832            Some(EpicsValue::Double(self.rbv))
5833        }
5834        fn monitor_deadband_field(&self) -> &'static str {
5835            "RBV"
5836        }
5837    }
5838
5839    /// C motor monitor() parity: MDEL/ADEL throttle the deadband
5840    /// field's (RBV) delivery; VAL posts only when the setpoint
5841    /// actually changed — not on every readback poll.
5842    #[test]
5843    fn deadband_field_routes_readback_and_val_posts_only_on_change() {
5844        use crate::server::recgbl::EventMask;
5845        let mut inst = RecordInstance::new(
5846            "RDB".to_string(),
5847            ReadbackDeadbandRecord {
5848                val: 5.0,
5849                rbv: 0.0,
5850                deadband: 10.0,
5851            },
5852        );
5853        let _val_rx = inst
5854            .add_subscriber(
5855                "VAL",
5856                1,
5857                crate::types::DbFieldType::Double,
5858                EventMask::VALUE.bits(),
5859            )
5860            .expect("VAL subscriber");
5861        let _rbv_rx = inst
5862            .add_subscriber(
5863                "RBV",
5864                2,
5865                crate::types::DbFieldType::Double,
5866                EventMask::VALUE.bits(),
5867            )
5868            .expect("RBV subscriber");
5869        let names = |snap: &ProcessSnapshot| {
5870            snap.changed_fields
5871                .iter()
5872                .map(|(n, _, _)| n.clone())
5873                .collect::<Vec<_>>()
5874        };
5875
5876        // Cycle 1 (first publish): RBV fires via the deadband trigger
5877        // (MLST starts at the NaN never-posted sentinel). VAL must NOT
5878        // post: `add_subscriber` seeded `last_posted` with the current
5879        // value (the initial value already went out with EVENT_ADD), and
5880        // C monitor() posts VAL only when MARKED(M_VAL) — nothing marked
5881        // it.
5882        let (snap, _) = inst.process_local().unwrap();
5883        let n = names(&snap);
5884        assert!(n.contains(&"RBV".to_string()), "{n:?}");
5885        assert!(
5886            !n.contains(&"VAL".to_string()),
5887            "VAL unchanged since subscribe must not post: {n:?}"
5888        );
5889
5890        // Cycle 2: RBV moved past MDEL, VAL unchanged → RBV posted,
5891        // VAL not re-posted.
5892        let (snap, _) = inst.process_local().unwrap();
5893        let n = names(&snap);
5894        assert!(n.contains(&"RBV".to_string()), "RBV crossed MDEL: {n:?}");
5895        assert!(
5896            !n.contains(&"VAL".to_string()),
5897            "unchanged VAL must not post: {n:?}"
5898        );
5899
5900        // Cycle 3: widen the deadband — RBV moves within it → throttled.
5901        let _ = inst.record.put_field("MDEL", EpicsValue::Double(1000.0));
5902        let (snap, _) = inst.process_local().unwrap();
5903        let n = names(&snap);
5904        assert!(
5905            !n.contains(&"RBV".to_string()),
5906            "MDEL must throttle RBV: {n:?}"
5907        );
5908
5909        // Cycle 4: setpoint moves while RBV stays inside the deadband →
5910        // VAL posts via change detection, RBV stays throttled.
5911        let _ = inst.record.put_field("VAL", EpicsValue::Double(42.0));
5912        let (snap, _) = inst.process_local().unwrap();
5913        let n = names(&snap);
5914        assert!(
5915            n.contains(&"VAL".to_string()),
5916            "changed VAL must post: {n:?}"
5917        );
5918        assert!(
5919            !n.contains(&"RBV".to_string()),
5920            "MDEL must throttle RBV: {n:?}"
5921        );
5922    }
5923
5924    /// A subroutine-less aSub (empty SNAM — the record the PVA monitor
5925    /// oracle drives as `ORACLE:MONSCAN:ASUB`) mirrors C `do_sub`
5926    /// (aSubRecord.c:459-465): an empty SNAM returns 0 BEFORE the bad-sub
5927    /// check, and C `process` (`:224`) runs `prec->val = status = 0` every
5928    /// cycle. So a periodic scan forces VAL back to 0, and C `monitor()`
5929    /// (`:414`, `val != oval`) posts nothing — the driven `dbPut`s are the
5930    /// only VAL events.
5931    ///
5932    /// Before the fix the port's "no bound subroutine" branch returned
5933    /// `S_db_BadSub` and never wrote VAL, so a scanned aSub kept VAL at the
5934    /// last client put and the deadband gate re-posted it on every scan (the
5935    /// oracle's 7 updates where C posts 4). This pins both halves: `process`
5936    /// resets VAL to 0, and a scan of the reset value posts nothing.
5937    #[test]
5938    fn subroutineless_asub_process_resets_val_and_stops_scan_overposting() {
5939        use crate::server::recgbl::EventMask;
5940        use crate::server::records::asub_record::ASubRecord;
5941
5942        let mut inst = RecordInstance::new("ASUB".to_string(), ASubRecord::default());
5943        // The default record: no subroutine bound, SNAM empty.
5944        assert!(inst.subroutine.is_none());
5945        let _val_rx = inst
5946            .add_subscriber(
5947                "VAL",
5948                1,
5949                crate::types::DbFieldType::Long,
5950                EventMask::VALUE.bits(),
5951            )
5952            .expect("VAL subscriber");
5953        let posts_val =
5954            |snap: &ProcessSnapshot| snap.changed_fields.iter().any(|(n, _, _)| n == "VAL");
5955
5956        // A settling scan of the unchanged record: C `do_sub` returns 0 and
5957        // `process` leaves VAL at 0 (already 0), settling the monitor gate.
5958        let _ = inst.process_local().unwrap();
5959        assert_eq!(inst.record.get_field("VAL"), Some(EpicsValue::Long(0)));
5960        // status 0 -> C `if (!status)` drives every OUT link (aSub's
5961        // `multi_output_links` gate reads the cycle status); a bad-sub status
5962        // would suppress all 21.
5963        assert_eq!(
5964            inst.record.multi_output_links().len(),
5965            21,
5966            "empty-SNAM do_sub status must be 0, not S_db_BadSub"
5967        );
5968
5969        // A client caput lands on VAL (DBF_LONG, not process-passive: it posts
5970        // but does not itself process, leaving VAL non-zero — exactly how the
5971        // oracle drives the scanned reproducer between scans).
5972        inst.record.put_field("VAL", EpicsValue::Long(7)).unwrap();
5973
5974        // The periodic scan processes. C forces VAL back to 0 and posts
5975        // nothing (val == oval == 0). Before the fix VAL stayed 7 and the scan
5976        // re-posted it.
5977        let (snap, _) = inst.process_local().unwrap();
5978        assert_eq!(
5979            inst.record.get_field("VAL"),
5980            Some(EpicsValue::Long(0)),
5981            "a scan must reset VAL to the do_sub status (0)"
5982        );
5983        assert!(
5984            !posts_val(&snap),
5985            "a scan that resets VAL to 0 must not re-post it"
5986        );
5987
5988        // A second driven put + scan: the monitor marker stays at 0, so no
5989        // scan ever re-posts the reset value.
5990        inst.record.put_field("VAL", EpicsValue::Long(7)).unwrap();
5991        let (snap, _) = inst.process_local().unwrap();
5992        assert_eq!(inst.record.get_field("VAL"), Some(EpicsValue::Long(0)));
5993        assert!(
5994            !posts_val(&snap),
5995            "repeated scans must not re-post the reset VAL"
5996        );
5997    }
5998
5999    /// Record that names DIFF in `force_posted_fields` (the motor's C
6000    /// `process_motor_info` unconditional `MARK(M_DIFF)`) while keeping
6001    /// every value constant — a settled axis parked at a fixed non-zero
6002    /// following error. VAL is a control: not force-listed, so it must
6003    /// fall back to change-detection.
6004    struct ForcePostRecord {
6005        diff: f64,
6006        val: f64,
6007    }
6008
6009    impl Record for ForcePostRecord {
6010        fn record_type(&self) -> &'static str {
6011            "ai"
6012        }
6013        fn process(&mut self) -> CaResult<crate::server::record::ProcessOutcome> {
6014            // Values never change — the readback already matches; only the
6015            // unconditional MARK should keep DIFF flowing.
6016            Ok(crate::server::record::ProcessOutcome::complete())
6017        }
6018        fn get_field(&self, name: &str) -> Option<EpicsValue> {
6019            match name {
6020                "DIFF" => Some(EpicsValue::Double(self.diff)),
6021                "VAL" => Some(EpicsValue::Double(self.val)),
6022                _ => None,
6023            }
6024        }
6025        fn put_field(&mut self, name: &str, _value: EpicsValue) -> CaResult<()> {
6026            Err(CaError::FieldNotFound(name.to_string()))
6027        }
6028        fn declared_fields(&self) -> &'static [crate::server::record::FieldDesc] {
6029            &[]
6030        }
6031        fn force_posted_fields(&self) -> &'static [&'static str] {
6032            &["DIFF"]
6033        }
6034    }
6035
6036    /// C motorRecord parity: `process_motor_info` MARKs M_DIFF/M_RDIF every
6037    /// CALLBACK_DATA pass and `monitor()` posts them with `DBE_VAL_LOG`
6038    /// regardless of change, so a force-posted field re-posts on an
6039    /// otherwise-idle cycle while an unchanged non-force field does not.
6040    #[test]
6041    fn force_posted_field_reposts_unchanged_value_each_cycle() {
6042        use crate::server::recgbl::EventMask;
6043        let mut inst = RecordInstance::new(
6044            "FP".to_string(),
6045            ForcePostRecord {
6046                diff: 2.5,
6047                val: 1.0,
6048            },
6049        );
6050        let _diff_rx = inst
6051            .add_subscriber(
6052                "DIFF",
6053                1,
6054                crate::types::DbFieldType::Double,
6055                EventMask::VALUE.bits(),
6056            )
6057            .expect("DIFF subscriber");
6058        let _val_rx = inst
6059            .add_subscriber(
6060                "VAL",
6061                2,
6062                crate::types::DbFieldType::Double,
6063                EventMask::VALUE.bits(),
6064            )
6065            .expect("VAL subscriber");
6066        let names = |snap: &ProcessSnapshot| {
6067            snap.changed_fields
6068                .iter()
6069                .map(|(n, _, _)| n.clone())
6070                .collect::<Vec<_>>()
6071        };
6072
6073        // Cycle 1 (first publish): both DIFF and VAL post — last_posted is
6074        // empty so change-detection treats every subscribed field as new.
6075        let (snap1, _) = inst.process_local().unwrap();
6076        assert!(
6077            names(&snap1).contains(&"DIFF".to_string()),
6078            "DIFF posts on first publish: {:?}",
6079            names(&snap1)
6080        );
6081
6082        // Cycle 2: nothing changed. VAL (not force-listed) must NOT re-post;
6083        // DIFF (force-listed) MUST re-post — the C unconditional MARK +
6084        // DBE_VAL_LOG. This is the divergence MOT-1 closes.
6085        let (snap2, _) = inst.process_local().unwrap();
6086        assert!(
6087            names(&snap2).contains(&"DIFF".to_string()),
6088            "force-posted DIFF must re-post when unchanged: {:?}",
6089            names(&snap2)
6090        );
6091        assert!(
6092            !names(&snap2).contains(&"VAL".to_string()),
6093            "an unchanged non-force field must not re-post: {:?}",
6094            names(&snap2)
6095        );
6096        // The forced re-post carries DBE_VALUE|DBE_LOG (no alarm bits this
6097        // cycle), matching C `monitor_mask | DBE_VAL_LOG` with monitor_mask=0.
6098        let diff_mask = snap2
6099            .changed_fields
6100            .iter()
6101            .find(|(n, _, _)| n == "DIFF")
6102            .map(|(_, _, m)| *m)
6103            .expect("DIFF post present");
6104        assert_eq!(
6105            diff_mask.bits(),
6106            (EventMask::VALUE | EventMask::LOG).bits(),
6107            "forced re-post mask is DBE_VAL_LOG"
6108        );
6109    }
6110
6111    /// Record that names S1 in `log_swept_fields` (the scaler's idle
6112    /// `monitor()` DBE_LOG sweep) while keeping every value constant. S2
6113    /// is a control: subscribed but NOT swept, so an unchanged S2 must
6114    /// not re-post. Neither field is the primary `VAL`, so the default
6115    /// deadband field resolves to nothing and does not confound the test.
6116    struct LogSweepRecord {
6117        s1: i32,
6118        s2: i32,
6119    }
6120
6121    impl Record for LogSweepRecord {
6122        fn record_type(&self) -> &'static str {
6123            "scaler"
6124        }
6125        fn process(&mut self) -> CaResult<crate::server::record::ProcessOutcome> {
6126            // Counts never change — only the unconditional idle LOG sweep
6127            // should keep S1 flowing to a DBE_LOG (archiver) subscriber.
6128            Ok(crate::server::record::ProcessOutcome::complete())
6129        }
6130        fn get_field(&self, name: &str) -> Option<EpicsValue> {
6131            match name {
6132                "S1" => Some(EpicsValue::Long(self.s1)),
6133                "S2" => Some(EpicsValue::Long(self.s2)),
6134                _ => None,
6135            }
6136        }
6137        fn put_field(&mut self, name: &str, value: EpicsValue) -> CaResult<()> {
6138            match (name, value) {
6139                ("S1", EpicsValue::Long(v)) => {
6140                    self.s1 = v;
6141                    Ok(())
6142                }
6143                ("S2", EpicsValue::Long(v)) => {
6144                    self.s2 = v;
6145                    Ok(())
6146                }
6147                _ => Err(CaError::FieldNotFound(name.to_string())),
6148            }
6149        }
6150        fn declared_fields(&self) -> &'static [crate::server::record::FieldDesc] {
6151            &[]
6152        }
6153        fn log_swept_fields(&self) -> &'static [&'static str] {
6154            &["S1"]
6155        }
6156    }
6157
6158    /// C `scalerRecord.c::monitor():757-773` sweeps each active channel with a
6159    /// literal `DBE_LOG` on every cycle it runs, unconditionally — the sweep is
6160    /// INDEPENDENT of the change post, not an alternative to it (R12-62). So an
6161    /// UNCHANGED swept field posts `DBE_LOG` only, and a CHANGED swept field
6162    /// posts TWICE on that one cycle: once by change-detection, and once by the
6163    /// sweep with `DBE_LOG`. (In C's scaler those two are `updateCounts()`'s
6164    /// `DBE_VALUE` at `:582` and `monitor()`'s `DBE_LOG` at `:771`.) A
6165    /// non-swept field never re-posts when unchanged. `add_subscriber` seeds
6166    /// `last_posted` with the current value (the initial value goes out via
6167    /// EVENT_ADD), so a freshly subscribed unchanged field already takes the
6168    /// sweep path on cycle 1.
6169    #[test]
6170    fn log_swept_field_reposts_unchanged_with_log_mask_only() {
6171        use crate::server::recgbl::EventMask;
6172        let mut inst = RecordInstance::new("SW".to_string(), LogSweepRecord { s1: 7, s2: 9 });
6173        let _s1_rx = inst
6174            .add_subscriber(
6175                "S1",
6176                1,
6177                crate::types::DbFieldType::Long,
6178                EventMask::LOG.bits(),
6179            )
6180            .expect("S1 subscriber");
6181        let _s2_rx = inst
6182            .add_subscriber(
6183                "S2",
6184                2,
6185                crate::types::DbFieldType::Long,
6186                EventMask::VALUE.bits(),
6187            )
6188            .expect("S2 subscriber");
6189        let names = |snap: &ProcessSnapshot| {
6190            snap.changed_fields
6191                .iter()
6192                .map(|(n, _, _)| n.clone())
6193                .collect::<Vec<_>>()
6194        };
6195        let count_of = |snap: &ProcessSnapshot, f: &str| {
6196            snap.changed_fields
6197                .iter()
6198                .filter(|(n, _, _)| n == f)
6199                .count()
6200        };
6201        let mask_of = |snap: &ProcessSnapshot, f: &str| {
6202            snap.changed_fields
6203                .iter()
6204                .find(|(n, _, _)| n == f)
6205                .map(|(_, _, m)| *m)
6206        };
6207
6208        // Cycle 1: nothing changed since subscribe. S1 (swept) re-posts
6209        // with DBE_LOG ONLY; S2 (not swept) must NOT re-post.
6210        let (snap1, _) = inst.process_local().unwrap();
6211        assert!(
6212            names(&snap1).contains(&"S1".to_string()),
6213            "log-swept S1 must re-post when unchanged: {:?}",
6214            names(&snap1)
6215        );
6216        assert!(
6217            !names(&snap1).contains(&"S2".to_string()),
6218            "unchanged non-swept S2 must not re-post: {:?}",
6219            names(&snap1)
6220        );
6221        // DBE_LOG, plus the DBE_ALARM of this cycle's transition: a record
6222        // starts UDF/INVALID and its first process clears that, so cycle 1 IS an
6223        // alarm transition (CBUG-B19 — C's sweep drops the alarm bit; this
6224        // assertion used to require a bare DBE_LOG). No DBE_VALUE either way:
6225        // the counts have not moved.
6226        assert_eq!(
6227            mask_of(&snap1, "S1").unwrap().bits(),
6228            (EventMask::LOG | EventMask::ALARM).bits(),
6229            "idle sweep posts DBE_LOG + the alarm transition, never DBE_VALUE"
6230        );
6231
6232        // Cycle 2: S1's count changed. Change-detection delivers it, and the
6233        // sweep delivers it AGAIN with DBE_LOG — the two C `db_post_events`
6234        // calls of the count-completion cycle.
6235        inst.record.put_field("S1", EpicsValue::Long(8)).unwrap();
6236        let (snap2, _) = inst.process_local().unwrap();
6237        assert_eq!(
6238            count_of(&snap2, "S1"),
6239            2,
6240            "a changed swept field posts twice — change post + independent \
6241             DBE_LOG sweep: {:?}",
6242            snap2.changed_fields
6243        );
6244        let s1_masks: Vec<u16> = snap2
6245            .changed_fields
6246            .iter()
6247            .filter(|(n, _, _)| n == "S1")
6248            .map(|(_, _, m)| m.bits())
6249            .collect();
6250        assert_eq!(
6251            s1_masks,
6252            vec![
6253                (EventMask::VALUE | EventMask::LOG).bits(),
6254                EventMask::LOG.bits()
6255            ],
6256            "change post first (VALUE|LOG here — this stub is not a \
6257             value_only_change_fields record), then the sweep's literal DBE_LOG"
6258        );
6259
6260        // Cycle 3: unchanged again — back to the DBE_LOG-only sweep.
6261        let (snap3, _) = inst.process_local().unwrap();
6262        assert_eq!(
6263            mask_of(&snap3, "S1").unwrap().bits(),
6264            EventMask::LOG.bits(),
6265            "unchanged-again S1 returns to the DBE_LOG-only sweep"
6266        );
6267    }
6268
6269    /// A log-swept record that can raise an alarm on demand — the scaler's
6270    /// `do_alarm()` (scalerRecord.c:745-755) in miniature.
6271    struct AlarmingLogSweepRecord {
6272        s1: i32,
6273        alarm: bool,
6274    }
6275
6276    impl Record for AlarmingLogSweepRecord {
6277        fn record_type(&self) -> &'static str {
6278            "scaler"
6279        }
6280        fn process(&mut self) -> CaResult<crate::server::record::ProcessOutcome> {
6281            Ok(crate::server::record::ProcessOutcome::complete())
6282        }
6283        /// This fixture drives its alarm purely through `check_alarms`
6284        /// (`self.alarm`), so it must NOT also raise the central UDF alarm —
6285        /// otherwise the born `udf = 1` pins severity at INVALID every cycle
6286        /// and there is never a real NO_ALARM → INVALID transition to test.
6287        /// (Before `rec_gbl_check_udf` stopped fabricating a UDF message, the
6288        /// ALARM bit this test asserts came from that fabricated amsg
6289        /// flipping to "" — an artifact, not the severity transition the
6290        /// test name and comments describe.) With no UDF alarm, cycle 1
6291        /// genuinely clears the born UDF/INVALID to NO_ALARM, and the
6292        /// `self.alarm` cycle is a true severity transition.
6293        fn raises_udf_alarm(&self) -> bool {
6294            false
6295        }
6296        fn check_alarms(&mut self, common: &mut crate::server::record::CommonFields) {
6297            if self.alarm {
6298                crate::server::recgbl::rec_gbl_set_sevr(
6299                    common,
6300                    crate::server::recgbl::alarm_status::UDF_ALARM,
6301                    crate::server::record::AlarmSeverity::Invalid,
6302                );
6303            }
6304        }
6305        fn get_field(&self, name: &str) -> Option<EpicsValue> {
6306            match name {
6307                "S1" => Some(EpicsValue::Long(self.s1)),
6308                _ => None,
6309            }
6310        }
6311        fn put_field(&mut self, name: &str, value: EpicsValue) -> CaResult<()> {
6312            match (name, value) {
6313                ("S1", EpicsValue::Long(v)) => {
6314                    self.s1 = v;
6315                    Ok(())
6316                }
6317                _ => Err(CaError::FieldNotFound(name.to_string())),
6318            }
6319        }
6320        fn declared_fields(&self) -> &'static [crate::server::record::FieldDesc] {
6321            &[]
6322        }
6323        fn log_swept_fields(&self) -> &'static [&'static str] {
6324            &["S1"]
6325        }
6326        fn as_any_mut(&mut self) -> Option<&mut dyn std::any::Any> {
6327            Some(self)
6328        }
6329    }
6330
6331    /// CBUG-B19 — the sweep post carries the alarm-transition bits.
6332    ///
6333    /// DEVIATION from C, deliberate. C's scaler `monitor()` computes
6334    /// `monitor_mask = recGblResetAlarms(pscal)` (scalerRecord.c:764), ORs
6335    /// `DBE_VALUE|DBE_LOG` into it (`:766`), and then posts every `Sn` with a
6336    /// LITERAL `DBE_LOG` (`:771`) — `monitor_mask` is assigned, OR-ed, and never
6337    /// read. The alarm bit that `recGblResetAlarms` returns is exactly what every
6338    /// other record ORs into its value posts, so C drops it: a client subscribed
6339    /// to `Sn` with DBE_ALARM receives NOTHING on a severity transition.
6340    ///
6341    /// The DBE_VALUE half of C's dead `|=` is deliberately not resurrected — the
6342    /// sweep is unconditional, so a VALUE bit here would fire a value event on
6343    /// every idle scan whether or not the counts moved. The first assertion pins
6344    /// that.
6345    #[test]
6346    fn b19_log_swept_field_carries_the_alarm_transition_bits() {
6347        use crate::server::recgbl::EventMask;
6348        let mut inst = RecordInstance::new(
6349            "SW".to_string(),
6350            AlarmingLogSweepRecord {
6351                s1: 7,
6352                alarm: false,
6353            },
6354        );
6355        let _s1_rx = inst
6356            .add_subscriber(
6357                "S1",
6358                1,
6359                crate::types::DbFieldType::Long,
6360                (EventMask::LOG | EventMask::ALARM).bits(),
6361            )
6362            .expect("S1 subscriber");
6363        let mask_of = |snap: &ProcessSnapshot, f: &str| {
6364            snap.changed_fields
6365                .iter()
6366                .find(|(n, _, _)| n == f)
6367                .map(|(_, _, m)| *m)
6368        };
6369
6370        // Cycle 1 clears the record's initial UDF/INVALID alarm, which is itself
6371        // a transition; cycle 2 is the quiet baseline. The sweep is then DBE_LOG
6372        // alone — in particular NOT DBE_VALUE, since the counts have not moved.
6373        let _ = inst.process_local().unwrap();
6374        let (snap1, _) = inst.process_local().unwrap();
6375        assert_eq!(
6376            mask_of(&snap1, "S1").unwrap().bits(),
6377            EventMask::LOG.bits(),
6378            "no alarm transition → the sweep is DBE_LOG only"
6379        );
6380
6381        // The alarm fires: severity moves NO_ALARM → INVALID, so this cycle's
6382        // posts carry DBE_ALARM. C posts DBE_LOG here and the alarm subscriber
6383        // learns nothing.
6384        if let Some(r) = inst
6385            .record
6386            .as_any_mut()
6387            .and_then(|a| a.downcast_mut::<AlarmingLogSweepRecord>())
6388        {
6389            r.alarm = true;
6390        }
6391        let (snap2, _) = inst.process_local().unwrap();
6392        assert_eq!(
6393            mask_of(&snap2, "S1").unwrap().bits(),
6394            (EventMask::LOG | EventMask::ALARM).bits(),
6395            "the severity transition must reach the swept field (C drops it)"
6396        );
6397
6398        // Severity stays INVALID: no transition, so no alarm bit — the sweep is
6399        // DBE_LOG again.
6400        let (snap3, _) = inst.process_local().unwrap();
6401        assert_eq!(
6402            mask_of(&snap3, "S1").unwrap().bits(),
6403            EventMask::LOG.bits(),
6404            "a steady severity is not a transition"
6405        );
6406    }
6407
6408    /// Stub record that simulates a record whose process() mutates an
6409    /// internal metadata field. Used to verify that the
6410    /// `Record::took_metadata_change()` hook actually triggers cache
6411    /// invalidation in `process_local()`.
6412    struct MutatingMetaRecord {
6413        val: f64,
6414        egu: String,
6415        took_change: bool,
6416    }
6417
6418    impl Record for MutatingMetaRecord {
6419        fn record_type(&self) -> &'static str {
6420            "ai" // pretend to be ai so populate_display_info populates EGU
6421        }
6422        fn process(&mut self) -> CaResult<crate::server::record::ProcessOutcome> {
6423            // Simulate dynamic metadata change inside processing
6424            self.egu = "kV".into();
6425            self.took_change = true;
6426            Ok(crate::server::record::ProcessOutcome::complete())
6427        }
6428        fn get_field(&self, name: &str) -> Option<EpicsValue> {
6429            match name {
6430                "VAL" => Some(EpicsValue::Double(self.val)),
6431                "EGU" => Some(EpicsValue::String(self.egu.clone().into())),
6432                "PREC" => Some(EpicsValue::Short(0)),
6433                "HOPR" => Some(EpicsValue::Double(0.0)),
6434                "LOPR" => Some(EpicsValue::Double(0.0)),
6435                _ => None,
6436            }
6437        }
6438        fn put_field(&mut self, name: &str, value: EpicsValue) -> CaResult<()> {
6439            match (name, value) {
6440                ("VAL", EpicsValue::Double(v)) => {
6441                    self.val = v;
6442                    Ok(())
6443                }
6444                ("EGU", EpicsValue::String(s)) => {
6445                    self.egu = s.as_str_lossy().into_owned();
6446                    Ok(())
6447                }
6448                _ => Err(CaError::FieldNotFound(name.to_string())),
6449            }
6450        }
6451        fn declared_fields(&self) -> &'static [crate::server::record::FieldDesc] {
6452            &[]
6453        }
6454        fn took_metadata_change(&mut self) -> bool {
6455            let was = self.took_change;
6456            self.took_change = false; // reset after reporting
6457            was
6458        }
6459    }
6460
6461    #[test]
6462    fn process_local_invalidates_cache_on_took_metadata_change() {
6463        let mut inst = RecordInstance::new(
6464            "MUT".to_string(),
6465            MutatingMetaRecord {
6466                val: 1.0,
6467                egu: "V".to_string(),
6468                took_change: false,
6469            },
6470        );
6471
6472        // Build the cache once with the original EGU
6473        let snap1 = inst.snapshot_for_field("VAL").unwrap();
6474        assert_eq!(snap1.display.unwrap().units, "V");
6475        assert!(inst.metadata_cache.lock().unwrap().is_some());
6476
6477        // Run process_local — the stub record sets took_change inside process()
6478        let _ = inst.process_local();
6479
6480        // Cache should now be invalidated (took_metadata_change returned true)
6481        assert!(
6482            inst.metadata_cache.lock().unwrap().is_none(),
6483            "process_local should invalidate cache when took_metadata_change is true"
6484        );
6485
6486        // Next snapshot picks up the new EGU
6487        let snap2 = inst.snapshot_for_field("VAL").unwrap();
6488        assert_eq!(snap2.display.unwrap().units, "kV");
6489    }
6490
6491    /// Stub record that does NOT mutate metadata fields. Verifies the
6492    /// default `took_metadata_change` returns false and the cache stays.
6493    struct StableMetaRecord {
6494        val: f64,
6495    }
6496    impl Record for StableMetaRecord {
6497        fn record_type(&self) -> &'static str {
6498            "ai"
6499        }
6500        fn process(&mut self) -> CaResult<crate::server::record::ProcessOutcome> {
6501            self.val += 1.0;
6502            Ok(crate::server::record::ProcessOutcome::complete())
6503        }
6504        fn get_field(&self, name: &str) -> Option<EpicsValue> {
6505            match name {
6506                "VAL" => Some(EpicsValue::Double(self.val)),
6507                "EGU" => Some(EpicsValue::String("V".into())),
6508                "PREC" => Some(EpicsValue::Short(0)),
6509                "HOPR" => Some(EpicsValue::Double(0.0)),
6510                "LOPR" => Some(EpicsValue::Double(0.0)),
6511                _ => None,
6512            }
6513        }
6514        fn put_field(&mut self, _: &str, _: EpicsValue) -> CaResult<()> {
6515            Ok(())
6516        }
6517        fn declared_fields(&self) -> &'static [crate::server::record::FieldDesc] {
6518            &[]
6519        }
6520        // took_metadata_change uses default impl (returns false)
6521    }
6522
6523    #[test]
6524    fn process_local_keeps_cache_when_no_metadata_change() {
6525        let mut inst = RecordInstance::new("STABLE".to_string(), StableMetaRecord { val: 0.0 });
6526
6527        let _ = inst.snapshot_for_field("VAL");
6528        assert!(inst.metadata_cache.lock().unwrap().is_some());
6529
6530        // Run process_local several times — cache should remain intact
6531        let _ = inst.process_local();
6532        assert!(inst.metadata_cache.lock().unwrap().is_some());
6533        let _ = inst.process_local();
6534        assert!(inst.metadata_cache.lock().unwrap().is_some());
6535        let _ = inst.process_local();
6536        assert!(inst.metadata_cache.lock().unwrap().is_some());
6537    }
6538
6539    // ── Regression: DBE_PROPERTY event delivery boundaries ──────────────
6540
6541    /// motor `prop(YES)` fields (motorRecord.dbd 154/161/289/361/368)
6542    /// are property-class: a changed write must post DBE_PROPERTY
6543    /// (C dbAccess.c dbPut, `pfldDes->prop`). They feed the
6544    /// live-computed `field_metadata_override`, not the cache, but the
6545    /// posting gate is this same set.
6546    #[test]
6547    fn motor_prop_yes_fields_are_property_class() {
6548        for f in ["VBAS", "VMAX", "MRES", "DHLM", "DLLM"] {
6549            assert!(is_metadata_field(f), "{f} must be property-class");
6550        }
6551    }
6552
6553    /// Boundary 1: metadata field written with a CHANGED value, subscriber
6554    /// mask includes PROPERTY → subscriber receives an event.
6555    /// Mirrors C dbAccess.c:1396-1397 `db_post_events(precord,NULL,DBE_PROPERTY)`.
6556    #[test]
6557    fn r47_property_event_delivered_on_changed_metadata() {
6558        use crate::server::recgbl::EventMask;
6559        let mut inst = ai_instance();
6560        let mut rx = inst
6561            .add_subscriber(
6562                "VAL",
6563                1,
6564                crate::types::DbFieldType::Double,
6565                EventMask::PROPERTY.bits(),
6566            )
6567            .expect("subscriber added");
6568
6569        let prev = inst.record.get_field("EGU"); // "degC"
6570        let _ = inst
6571            .record
6572            .put_field("EGU", EpicsValue::String("kPa".into()));
6573        inst.notify_field_written_if_changed("EGU", prev.as_ref());
6574
6575        assert!(
6576            rx.try_recv().is_ok(),
6577            "PROPERTY subscriber must receive event when metadata field changes"
6578        );
6579    }
6580
6581    /// Boundary 2: same metadata field written with the SAME value → NO event.
6582    /// Matches C suppression at dbAccess.c:1379-1383 and the `prev != now` gate.
6583    #[test]
6584    fn r47_no_event_on_unchanged_metadata() {
6585        use crate::server::recgbl::EventMask;
6586        let mut inst = ai_instance();
6587        let mut rx = inst
6588            .add_subscriber(
6589                "VAL",
6590                1,
6591                crate::types::DbFieldType::Double,
6592                EventMask::PROPERTY.bits(),
6593            )
6594            .expect("subscriber added");
6595
6596        let prev = inst.record.get_field("EGU"); // "degC"
6597        // Write the same value — no change
6598        let _ = inst.record.put_field("EGU", prev.clone().unwrap());
6599        inst.notify_field_written_if_changed("EGU", prev.as_ref());
6600
6601        assert!(
6602            rx.try_recv().is_err(),
6603            "PROPERTY subscriber must NOT receive event when metadata value is unchanged"
6604        );
6605    }
6606
6607    /// Boundary 3: VALUE-only subscriber (no PROPERTY bit) receives NO event
6608    /// from a metadata write, even when the field value changed.
6609    #[test]
6610    fn r47_value_only_subscriber_no_event_on_metadata_write() {
6611        use crate::server::recgbl::EventMask;
6612        let mut inst = ai_instance();
6613        let mut rx = inst
6614            .add_subscriber(
6615                "VAL",
6616                1,
6617                crate::types::DbFieldType::Double,
6618                EventMask::VALUE.bits(),
6619            )
6620            .expect("subscriber added");
6621
6622        let prev = inst.record.get_field("EGU"); // "degC"
6623        let _ = inst
6624            .record
6625            .put_field("EGU", EpicsValue::String("kPa".into()));
6626        inst.notify_field_written_if_changed("EGU", prev.as_ref());
6627
6628        assert!(
6629            rx.try_recv().is_err(),
6630            "VALUE-only subscriber must NOT receive event from a metadata write"
6631        );
6632    }
6633
6634    /// Boundary 4 (took_metadata_change path): PROPERTY subscriber receives
6635    /// event after process_local() when the record reports a metadata change.
6636    #[test]
6637    fn r47_process_local_property_event_on_took_metadata_change() {
6638        use crate::server::recgbl::EventMask;
6639        let mut inst = RecordInstance::new(
6640            "MUT2".to_string(),
6641            MutatingMetaRecord {
6642                val: 1.0,
6643                egu: "V".to_string(),
6644                took_change: false,
6645            },
6646        );
6647        let mut rx = inst
6648            .add_subscriber(
6649                "VAL",
6650                1,
6651                crate::types::DbFieldType::Double,
6652                EventMask::PROPERTY.bits(),
6653            )
6654            .expect("subscriber added");
6655
6656        // process() sets took_change = true and updates egu to "kV"
6657        let _ = inst.process_local();
6658
6659        assert!(
6660            rx.try_recv().is_ok(),
6661            "PROPERTY subscriber must receive event after process_local reports took_metadata_change"
6662        );
6663    }
6664}
6665
6666#[cfg(test)]
6667mod aftc_filter_tests {
6668    //! Tests for the shared AFTC alarm-range filter
6669    //! (`records::alarm_filter::aftc_filter`) as driven by
6670    //! `evaluate_analog_alarm`. Pure-function tests: no record instance
6671    //! needed — the filter is a stateless transform of (raw_alarm, aftc,
6672    //! afvl_in, t_last, t_now). Algorithm provenance: 2009 EPICS
6673    //! Codeathon (epics-base `824d37811`), C `aiRecord.c:355-401`.
6674
6675    use crate::server::records::alarm_filter::aftc_filter;
6676    use std::time::{Duration, SystemTime};
6677
6678    fn at(secs: f64) -> SystemTime {
6679        SystemTime::UNIX_EPOCH + Duration::from_secs_f64(secs)
6680    }
6681
6682    #[test]
6683    fn disabled_when_aftc_le_zero() {
6684        // aftc=0 means filter disabled — pass-through.
6685        let (out, afvl) = aftc_filter(2, 0.0, 0.0, at(0.0), at(1.0));
6686        assert_eq!(out, 2);
6687        assert_eq!(afvl, 0.0);
6688    }
6689
6690    #[test]
6691    fn initial_sample_seeds_state_unchanged_alarm() {
6692        // afvl=0 means first sample after enable — alarm passes through
6693        // and accumulator seeds with the raw severity.
6694        let (out, afvl) = aftc_filter(2, 3.0, 0.0, at(0.0), at(0.5));
6695        assert_eq!(out, 2);
6696        assert_eq!(afvl, 2.0);
6697    }
6698
6699    #[test]
6700    fn raises_alarm_only_after_full_time_constant() {
6701        // Single-step heuristic: with `aftc = 3s` and `dt = 0.1s`, alpha
6702        // ≈ 0.967, so a one-shot raw_alarm=2 against afvl=0.0 should not
6703        // produce alarm=2 yet — the filter must hold off until the
6704        // accumulator crosses the threshold.
6705        // Seed with afvl=0.01 (tiny prior, simulating "almost no alarm
6706        // yet"); the filter must keep alarm at 0 after one short tick.
6707        let (out, afvl) = aftc_filter(2, 3.0, 0.01, at(0.0), at(0.1));
6708        assert_eq!(out, 0, "filter should suppress alarm rise on a 0.1s tick");
6709        assert!(afvl > 0.0 && afvl < 2.0);
6710    }
6711
6712    #[test]
6713    fn dt_zero_is_no_op() {
6714        // Two evaluations at the same instant produce no filter advance.
6715        let (out, afvl) = aftc_filter(2, 3.0, 1.5, at(0.0), at(0.0));
6716        assert_eq!(out, 1); // floor(|1.5|) = 1
6717        assert_eq!(afvl, 1.5);
6718    }
6719
6720    #[test]
6721    fn long_steady_state_converges_to_alarm() {
6722        // After many steps with raw_alarm=2 and dt much smaller than aftc,
6723        // the accumulator must converge towards 2.
6724        let aftc = 1.0;
6725        let mut afvl = 0.0;
6726        let mut last = at(0.0);
6727        let mut alarm = 0;
6728        for i in 1..=100 {
6729            let now = at(i as f64 * 0.05);
6730            let (out, new_afvl) = aftc_filter(2, aftc, afvl, last, now);
6731            alarm = out;
6732            afvl = new_afvl;
6733            last = now;
6734        }
6735        assert_eq!(
6736            alarm, 2,
6737            "after 5 s of steady raw=2 with aftc=1 s, output must reach 2"
6738        );
6739        assert!(afvl.abs() >= 1.99 && afvl.abs() <= 2.0);
6740    }
6741}
6742
6743#[cfg(test)]
6744mod check_deadband_tests {
6745    use super::check_deadband;
6746
6747    /// Sentinel: `oldval=NaN` means "no prior posting", always fire.
6748    #[test]
6749    fn nan_old_value_fires() {
6750        assert!(check_deadband(0.0, f64::NAN, 1.0));
6751        assert!(check_deadband(f64::NAN, f64::NAN, 1.0));
6752    }
6753
6754    /// C path: `delta > deadband` with both finite. delta within deadband
6755    /// must NOT fire.
6756    #[test]
6757    fn within_finite_deadband_does_not_fire() {
6758        assert!(!check_deadband(10.0, 10.5, 1.0));
6759        assert!(!check_deadband(10.0, 9.5, 1.0));
6760        // Boundary: `delta == deadband` is NOT strictly greater.
6761        assert!(!check_deadband(10.0, 11.0, 1.0));
6762    }
6763
6764    /// `delta > deadband` with both finite, beyond → fire.
6765    #[test]
6766    fn beyond_finite_deadband_fires() {
6767        assert!(check_deadband(10.0, 12.0, 1.0));
6768    }
6769
6770    /// Negative deadband acts as "always fire" (C `delta > deadband` is
6771    /// trivially true for any non-negative delta).
6772    #[test]
6773    fn negative_deadband_fires() {
6774        assert!(check_deadband(10.0, 10.0, -1.0));
6775    }
6776
6777    /// C parity bug fix (recGbl.c:355-358): exactly one of {newval,
6778    /// oldval} is NaN — fire. Rust port previously short-circuited only
6779    /// on `oldval=NaN`; `newval=NaN` with `oldval=finite` produced
6780    /// `(NaN - finite).abs() = NaN`, `NaN > deadband = false` →
6781    /// silently dropped the NaN transition. End effect: a record that
6782    /// went UDF (e.g. divide-by-zero in calc) never posted the change
6783    /// to monitors, leaving every camonitor seeing the last valid value.
6784    #[test]
6785    fn newval_nan_with_finite_oldval_fires() {
6786        assert!(check_deadband(f64::NAN, 10.0, 1.0));
6787    }
6788
6789    /// C path case 2 (recGbl.c:355): exactly one infinite, the other
6790    /// finite — fire.
6791    #[test]
6792    fn one_finite_one_infinite_fires() {
6793        assert!(check_deadband(f64::INFINITY, 10.0, 1.0));
6794        assert!(check_deadband(10.0, f64::INFINITY, 1.0));
6795        assert!(check_deadband(f64::NEG_INFINITY, 10.0, 1.0));
6796    }
6797
6798    /// C path case 3 (recGbl.c:360-362): both infinite with opposite
6799    /// signs — fire.
6800    #[test]
6801    fn opposite_signed_infinities_fire() {
6802        assert!(check_deadband(f64::INFINITY, f64::NEG_INFINITY, 1.0));
6803        assert!(check_deadband(f64::NEG_INFINITY, f64::INFINITY, 1.0));
6804    }
6805
6806    /// Same-signed infinity → no fire (C path leaves `delta = 0`,
6807    /// `0 > deadband` is false for any non-negative deadband).
6808    #[test]
6809    fn same_signed_infinity_does_not_fire() {
6810        assert!(!check_deadband(f64::INFINITY, f64::INFINITY, 1.0));
6811        assert!(!check_deadband(f64::NEG_INFINITY, f64::NEG_INFINITY, 1.0));
6812    }
6813}
6814
6815#[cfg(test)]
6816mod common_field_dbload_tests {
6817    use super::*;
6818    use crate::server::records::ai::AiRecord;
6819
6820    /// The db loader feeds every common field to `put_common_field` as an
6821    /// `EpicsValue::String`. Each numeric/menu common field directive must
6822    /// take effect at load — both the integer form (`field(PHAS, "1")`) and
6823    /// the menu-label form (`field(PRIO, "HIGH")`, `field(DISS, "MAJOR")`) —
6824    /// rather than being silently dropped because the arm matched only its
6825    /// typed variant. One assertion per affected common-field arm.
6826    #[test]
6827    fn db_loaded_string_common_fields_take_effect() {
6828        let mut inst = RecordInstance::new("REC".to_string(), AiRecord::default());
6829        let put = |inst: &mut RecordInstance, f: &str, v: &str| {
6830            inst.put_common_field_db_load(f, EpicsValue::String(v.into()))
6831                .unwrap_or_else(|e| panic!("put_common_field_db_load({f}, {v:?}) failed: {e}"));
6832        };
6833
6834        // Integer-valued directives.
6835        put(&mut inst, "PHAS", "1");
6836        assert_eq!(inst.common.phas, 1, "field(PHAS, \"1\")");
6837        put(&mut inst, "TSE", "-2");
6838        assert_eq!(inst.common.tse, -2, "field(TSE, \"-2\")");
6839        put(&mut inst, "DISV", "1");
6840        assert_eq!(inst.common.disv, 1, "field(DISV, \"1\")");
6841        put(&mut inst, "DISA", "1");
6842        assert_eq!(inst.common.disa, 1, "field(DISA, \"1\")");
6843        put(&mut inst, "LCNT", "3");
6844        assert_eq!(inst.common.lcnt, 3, "field(LCNT, \"3\")");
6845        put(&mut inst, "DISP", "1");
6846        assert!(inst.common.disp != 0, "field(DISP, \"1\")");
6847        put(&mut inst, "UDF", "0");
6848        assert!(inst.common.udf == 0, "field(UDF, \"0\")");
6849
6850        // Menu-label directives (resolved via the one menu converter).
6851        put(&mut inst, "PRIO", "HIGH");
6852        assert_eq!(inst.common.prio, 2, "field(PRIO, \"HIGH\")");
6853        put(&mut inst, "DISS", "MAJOR");
6854        assert_eq!(
6855            inst.common.diss,
6856            AlarmSeverity::Major as i16,
6857            "field(DISS, \"MAJOR\")"
6858        );
6859        put(&mut inst, "UDFS", "NO_ALARM");
6860        assert_eq!(
6861            inst.common.udfs,
6862            AlarmSeverity::NoAlarm as i16,
6863            "field(UDFS, \"NO_ALARM\")"
6864        );
6865        put(&mut inst, "ACKT", "NO");
6866        assert!(!inst.common.ackt, "field(ACKT, \"NO\")");
6867
6868        // Numeric form of a menu field still works (field(PRIO, "0")).
6869        put(&mut inst, "PRIO", "0");
6870        assert_eq!(inst.common.prio, 0, "field(PRIO, \"0\")");
6871
6872        // A String-typed common field is untouched by the coercion.
6873        put(&mut inst, "DESC", "a description");
6874        assert_eq!(inst.common.desc.as_str_lossy().as_ref(), "a description");
6875    }
6876}
6877
6878#[cfg(test)]
6879mod declared_override_tests {
6880    use super::*;
6881    use crate::server::records::dfanout::DfanoutRecord;
6882
6883    /// A field `dfanout`'s `.dbd` DECLARES (HOPR/LOPR/PREC/EGU) but the
6884    /// `DfanoutRecord` struct models no storage for: a put must be ACCEPTED and
6885    /// stored (C `dbPut` writes it into record memory), and a later
6886    /// `resolve_field` must serve the written value — not the `.dbd` initial.
6887    #[test]
6888    fn declared_but_unmodeled_field_put_is_stored_and_served() {
6889        let mut inst = RecordInstance::new("DF".to_string(), DfanoutRecord::default());
6890
6891        // Untouched: reads its declared default (initial / type-zero), NOT an
6892        // error, and the override store is empty.
6893        assert_eq!(inst.resolve_field("HOPR"), Some(EpicsValue::Double(0.0)));
6894        assert!(inst.declared_overrides.is_empty());
6895
6896        // DBF_DOUBLE, DBF_SHORT and DBF_STRING declared metadata fields all
6897        // land, coerced to the declared type.
6898        inst.put_common_field("HOPR", EpicsValue::String("10".into()))
6899            .expect("caput dfanout.HOPR 10 must be accepted");
6900        inst.put_common_field("PREC", EpicsValue::String("3".into()))
6901            .expect("caput dfanout.PREC 3 must be accepted");
6902        inst.put_common_field("EGU", EpicsValue::String("volts".into()))
6903            .expect("caput dfanout.EGU volts must be accepted");
6904
6905        assert_eq!(inst.resolve_field("HOPR"), Some(EpicsValue::Double(10.0)));
6906        assert_eq!(inst.resolve_field("PREC"), Some(EpicsValue::Short(3)));
6907        assert_eq!(
6908            inst.resolve_field("EGU"),
6909            Some(EpicsValue::String("volts".into()))
6910        );
6911        // Case-insensitive key: the lower-case read reaches the same slot.
6912        assert_eq!(inst.resolve_field("hopr"), Some(EpicsValue::Double(10.0)));
6913    }
6914
6915    /// The declared type's C range rules apply through the write-side coercion
6916    /// owner: `caput dfanout.PREC 99999` into a `DBF_SHORT` is REFUSED (C
6917    /// `epicsParseInt16` overflow → `S_db_badField`), and the field keeps its
6918    /// prior value — never wraps to a garbage `Short`.
6919    #[test]
6920    fn declared_override_honors_declared_type_range() {
6921        let mut inst = RecordInstance::new("DF".to_string(), DfanoutRecord::default());
6922        inst.put_common_field("PREC", EpicsValue::String("3".into()))
6923            .expect("in-range PREC accepted");
6924        assert!(
6925            inst.put_common_field("PREC", EpicsValue::String("99999".into()))
6926                .is_err(),
6927            "PREC 99999 overflows DBF_SHORT and must be refused"
6928        );
6929        assert!(
6930            inst.put_common_field("PREC", EpicsValue::String("abc".into()))
6931                .is_err(),
6932            "non-numeric PREC must be refused"
6933        );
6934        // The refused puts left the accepted value intact.
6935        assert_eq!(inst.resolve_field("PREC"), Some(EpicsValue::Short(3)));
6936    }
6937
6938    /// An UNDECLARED field name is still `FieldNotFound` — the override store
6939    /// captures only fields with a real `dbFldDes`, so a misspelled field is
6940    /// refused exactly as C's `dbNameToAddr` refuses it.
6941    #[test]
6942    fn undeclared_field_is_still_not_found() {
6943        let mut inst = RecordInstance::new("DF".to_string(), DfanoutRecord::default());
6944        assert!(matches!(
6945            inst.put_common_field("XYZZY", EpicsValue::String("1".into())),
6946            Err(CaError::FieldNotFound(_))
6947        ));
6948        assert!(inst.declared_overrides.is_empty());
6949    }
6950
6951    /// A PARTIALLY modeled field — one the record SERVES via `get_field` but
6952    /// has no `put_field` arm for (`calcout.PVAL` → `self.pval`) — must NOT
6953    /// land in the override map: doing so would place the value where
6954    /// `resolve_field` (which reads `get_field` first) never sees it, a silent
6955    /// write loss. The override is only for fields the record serves nothing
6956    /// for; a partially modeled field's put is the record's own concern.
6957    #[test]
6958    fn partially_modeled_field_is_not_captured_by_override() {
6959        use crate::server::records::calcout::CalcoutRecord;
6960        let mut inst = RecordInstance::new("CO".to_string(), CalcoutRecord::default());
6961        // PVAL is served by the record (its own storage), so it is not stored
6962        // in the override map; the map stays empty and no ghost cell shadows
6963        // the record's read.
6964        let _ = inst.put_common_field("PVAL", EpicsValue::String("1".into()));
6965        assert!(
6966            inst.declared_overrides.is_empty(),
6967            "a field the record serves via get_field must not enter the override map"
6968        );
6969    }
6970}