Skip to main content

epics_base_rs/server/database/
links.rs

1use std::collections::HashSet;
2use std::sync::Arc;
3
4use crate::runtime::sync::RwLock;
5use crate::server::record::{AlarmSeverity, NotifyWaitSet, RecordInstance, ScanType};
6use crate::types::EpicsValue;
7
8use super::processing::join_put_notify;
9use super::{LinkPutOp, PvDatabase, SelmKind, SelmResult, dbr_ushort_cast, select_link_indices_ex};
10
11/// Record-specific input link fields that may carry a CP/CPP modifier:
12/// DOL (ao/bo/longout/mbbo), DOL0-DOLF (seq — 16 groups), DOL1-DOLA
13/// (sseq — legacy 10 groups), NVL (sel), SELL (sseq), SGNL (histogram).
14///
15/// Shared by [`PvDatabase::record_link_fields`] (the single owner of
16/// "which fields on a record are links") and consumed transitively by
17/// both [`PvDatabase::setup_cp_links`] (CA CP/CPP) and the pvalink
18/// install scan (PVA CP/CPP), so the two enumerations cannot diverge.
19pub(crate) const CP_INPUT_LINK_FIELDS: &[&str] = &[
20    "DOL", "DOL0", "DOL1", "DOL2", "DOL3", "DOL4", "DOL5", "DOL6", "DOL7", "DOL8", "DOL9", "DOLA",
21    "DOLB", "DOLC", "DOLD", "DOLE", "DOLF", "NVL", "SELL", "SGNL",
22];
23
24/// Alarm state from a link source, used for MS/NMS propagation.
25///
26/// `amsg` is the alarm-message string — propagated from the source
27/// record's `common.amsg` so a downstream MS link sees the same
28/// human-readable explanation. Empty when the source has no message
29/// or when the link source is not a DB record.
30#[derive(Clone, Debug)]
31pub(crate) struct LinkAlarm {
32    pub stat: u16,
33    pub sevr: AlarmSeverity,
34    pub amsg: String,
35}
36
37/// Apply C `recGblInheritSevrMsg` (recGbl.c:263-281) for one MS-class
38/// link: fold the link source's alarm (`src`) into the destination
39/// record's PENDING alarm (`dest`) per the maximize-severity mode `ms`.
40///
41/// * **NMS** — no propagation.
42/// * **MS**  — raise dest severity to `src.sevr` under `LINK_ALARM`
43///   (NOT the source's stat); no message.
44/// * **MSI** — same as MS, but only when the source is at `INVALID`.
45/// * **MSS** — copy the source's stat + severity + amsg (the only mode
46///   that propagates the message).
47///
48/// Shared by the INPUT-link read path (`processing.rs`, where `dest` is
49/// the record reading its inputs) and the DB OUT-link write path
50/// ([`Database::write_db_link_value`], C `dbDbPutValue` →
51/// `recGblInheritSevrMsg`, dbDbLink.c:382-383, where `dest` is the
52/// OUT-link target). One implementation keeps the two sides from
53/// diverging — an earlier INPUT-side variant wrongly treated MS like
54/// MSS (propagating source stat + amsg through plain MS).
55pub(crate) fn inherit_sevr_msg(
56    dest: &mut crate::server::record::CommonFields,
57    ms: crate::server::record::MonitorSwitch,
58    src: &LinkAlarm,
59) {
60    use crate::server::recgbl::{alarm_status, rec_gbl_set_sevr, rec_gbl_set_sevr_msg};
61    use crate::server::record::{AlarmSeverity, MonitorSwitch};
62    match ms {
63        MonitorSwitch::Maximize => {
64            rec_gbl_set_sevr(dest, alarm_status::LINK_ALARM, src.sevr);
65        }
66        MonitorSwitch::MaximizeIfInvalid => {
67            if src.sevr == AlarmSeverity::Invalid {
68                rec_gbl_set_sevr(dest, alarm_status::LINK_ALARM, src.sevr);
69            }
70        }
71        MonitorSwitch::MaximizeStatus => {
72            rec_gbl_set_sevr_msg(dest, src.stat, src.sevr, src.amsg.clone());
73        }
74        MonitorSwitch::NoMaximize => {} // NMS: do not propagate
75    }
76}
77
78/// The source record's per-cycle state propagated to a DB OUT-link
79/// target, captured once from the source and threaded to every OUT-link
80/// write so all targets in one cycle see the same snapshot:
81///
82/// * `putf` / `notify` — the PUTF bit and put-notify wait-set that C
83///   `processTarget` carries to each target (dbDbLink.c:460-474).
84/// * `alarm` — the committed alarm that C `recGblInheritSevrMsg` folds
85///   into the dest per the link's MS-class switch (dbDbLink.c:382-383).
86///
87/// Bundled so the OUT-link write path threads one snapshot instead of
88/// three positional arguments. The FLNK process-trigger path keeps the
89/// lighter `PutNotifyCtx` (a forward link propagates no value and thus
90/// no alarm).
91#[derive(Clone, Copy)]
92pub(crate) struct OutLinkSrc<'a> {
93    pub putf: bool,
94    pub notify: Option<&'a Arc<NotifyWaitSet>>,
95    pub alarm: &'a LinkAlarm,
96}
97
98/// One `seq` link group — C `linkGrp { dly, dol, dov, lnk }`.
99#[derive(Clone, Debug)]
100pub(crate) struct SeqGroup {
101    /// DOLn input link string (empty when unset).
102    pub dol: String,
103    /// LNKn output link string (empty when unset).
104    pub lnk: String,
105    /// DLYn per-group delay in seconds.
106    pub dly: f64,
107    /// DOn value-storage field (`linkGrp.dov`) — used when DOLn is
108    /// an empty/constant link.
109    pub dov: f64,
110}
111
112/// Typed multi-output payload — replaces the legacy `\0`-packed
113/// `Vec<String>` so a link string containing an embedded NUL can
114/// never mis-split (parity review 04-L3).
115///
116/// `sseq` is NOT a variant here: a `sseq` record drives its per-step
117/// `LNKn` writes itself, in `SseqRecord::process()`, through the async
118/// PACT machine (C `sseqRecord.c::processCallback`) — not via this
119/// all-at-once dispatch.
120pub(crate) enum MultiOut {
121    /// fanout — 16 forward-link strings (LNK0..LNKF).
122    Fanout(Vec<String>),
123    /// dfanout — 16 output-link strings (OUTA..OUTP).
124    Dfanout(Vec<String>),
125    /// seq — 16 link groups (0..F).
126    Seq(Vec<SeqGroup>),
127}
128
129impl MultiOut {
130    /// Number of link slots — the `count` passed to the SELM selector.
131    fn len(&self) -> usize {
132        match self {
133            MultiOut::Fanout(v) => v.len(),
134            MultiOut::Dfanout(v) => v.len(),
135            MultiOut::Seq(v) => v.len(),
136        }
137    }
138}
139
140/// Record types whose multi-output link groups are dispatched by
141/// [`PvDatabase::dispatch_multi_output`].
142///
143/// SINGLE-OWNER INVARIANT — each of these record types' output links
144/// (fanout `LNKn`, dfanout `OUTn`, seq `LNKn`) is dispatched (value
145/// written + target forward-link processed) **exactly once per process
146/// cycle, by `dispatch_multi_output` and by nothing else**.
147///
148/// `dispatch_multi_output` is the sole owner because it is the only
149/// path that performs the full C-record model: SELL→SELN resolution,
150/// SELM/OFFS/SHFT selection, per-group DOLn input fetch, and per-group
151/// DLYn delay.
152///
153/// `sseq` is deliberately NOT listed: its `LNKn` writes are owned by
154/// `SseqRecord::process()` (the async PACT machine, C
155/// `sseqRecord.c::processCallback`), not by this dispatch. `sseq` also
156/// does not implement `Record::multi_output_links`, so the generic
157/// block skips it for that reason — there is no second dispatcher to
158/// gate against.
159///
160/// MUST NOT: the generic `multi_output_links` block in `processing.rs`
161/// (run unconditionally for every record after `dispatch_multi_output`)
162/// must skip any record type listed here. `multi_output_dispatch_owned`
163/// is consulted by that block (see `run_forward_link_tail_with_putf`
164/// §4.6) so a double-dispatch is structurally impossible, not merely
165/// removed at one call site.
166pub(crate) fn multi_output_dispatch_owned(record_type: &str) -> bool {
167    matches!(record_type, "fanout" | "dfanout" | "seq")
168}
169
170impl PvDatabase {
171    /// Read a `Db`-variant link's value honoring C `dbInitLink`'s
172    /// locality rule (`dbLink.c:118-130`): a PV link whose target record
173    /// exists in this IOC reads from the local database; a non-local
174    /// target is a CA link — `dbDbInitLink` fails to resolve it locally
175    /// and falls through to `dbCaAddLinkCallbackOpt`, so its value comes
176    /// from the external resolver. Pre-fix every `Db` arm read only the
177    /// local DB (`get_pv`) and returned `None` for a non-local target, so
178    /// a plain `INP="other:pv"` (no modifier) and a re-parsed multi-input
179    /// (`INPA`..`INPL`) / `DOL` link never read the remote value.
180    ///
181    /// This is the single owner of that rule for the value-read path, so
182    /// it holds uniformly — for every link field and regardless of an
183    /// explicit `CP`/`CPP`/`CA` modifier — not only the
184    /// `INP`/`OUT`/`TSEL`/`SDIS` parse caches the iocInit CP scan
185    /// rewrites (the per-cycle re-parsed links have no cache to rewrite,
186    /// so an init-time conversion can never reach them). The external
187    /// read routes through the lset's lazy-open path: the first read
188    /// opens the CA link and returns `None` until the monitor connects,
189    /// then serves the cached value — exactly C `dbCaGetLink`.
190    async fn read_db_link_value(&self, db: &crate::server::record::DbLink) -> Option<EpicsValue> {
191        self.read_target_value(&db.record, &db.field).await
192    }
193
194    /// Read a `(record, field)` link target's value, dispatching by C
195    /// `dbInitLink` locality (`dbLink.c:118-130`): a target present in
196    /// this IOC reads from the local database (`get_pv`); a non-local
197    /// target is a CA link, resolved through the external path
198    /// (`dbCaGetLink`). The single owner of that locality decision for
199    /// the value-read path — shared by [`Self::read_db_link_value`] (the
200    /// record's own `Db` link) and the lnkCalc input loop
201    /// ([`Self::evaluate_calc_link`]), whose `A..L` inputs are each their
202    /// own `dbInitLink` link and so become CA links when non-local.
203    async fn read_target_value(&self, record: &str, field: &str) -> Option<EpicsValue> {
204        let pv_name = if field == "VAL" {
205            record.to_string()
206        } else {
207            format!("{record}.{field}")
208        };
209        if self.has_name_no_resolve(record).await {
210            self.get_pv(&pv_name).await.ok()
211        } else {
212            self.resolve_external_pv(&pv_name).await
213        }
214    }
215
216    /// Read a value from a parsed link (DB, Constant, or external Ca/Pva).
217    ///
218    /// `visited` / `depth` are the caller's processing-chain state so a
219    /// PP source is processed within the same chain — see
220    /// [`Self::process_passive_db_source`] for why a fresh set / depth 0
221    /// would defeat the cycle guard.
222    pub(crate) async fn read_link_value(
223        &self,
224        link: &crate::server::record::ParsedLink,
225        visited: &mut HashSet<String>,
226        depth: usize,
227    ) -> Option<EpicsValue> {
228        match link {
229            crate::server::record::ParsedLink::None => None,
230            crate::server::record::ParsedLink::Ca(ca) => self.resolve_external_pv(&ca.pv).await,
231            crate::server::record::ParsedLink::Pva(name) => self.resolve_external_pv(name).await,
232            // Resolve through the per-link identity key (not bare `j.pv`)
233            // so two same-PV structured links keep distinct configs —
234            // matches the boundary key the write/scan/alarm paths use via
235            // `external_pv_name` (pvxs per-link `pvaLinkConfig`,
236            // ioc/pvalink.h:65).
237            crate::server::record::ParsedLink::PvaJson(j) => {
238                self.resolve_external_pv(&j.link_identity_key()).await
239            }
240            crate::server::record::ParsedLink::Constant(_) => link.constant_value(),
241            crate::server::record::ParsedLink::Db(db) => {
242                // PP: process source record if Passive before reading.
243                // Threads the caller's `visited`/`depth` so an A↔B PP
244                // cycle terminates at the existing cycle guard instead
245                // of recursing with a fresh set.
246                self.process_passive_db_source(db, visited, depth).await;
247                self.read_db_link_value(db).await
248            }
249            // Hardware links are dispatched by device support directly
250            // — there's no canonical "value" available from a generic
251            // read; return None so the framework treats the link as
252            // unresolvable for value-read purposes.
253            crate::server::record::ParsedLink::Hw(_) => None,
254            // lnkCalc: fetch each input PV, evaluate the expr,
255            // return the result. Timestamp passthrough is handled by
256            // `read_calc_link_with_time` for callers that need it.
257            crate::server::record::ParsedLink::Calc(calc) => self.evaluate_calc_link(calc).await,
258        }
259    }
260
261    /// Read a link's current value WITHOUT processing a Passive source —
262    /// the parity of C `dbGetLink` (`dbLink.c:325` → `dbTryGetLink` →
263    /// `lset->getValue`), which fetches the value for *any* link type
264    /// (DB / CA / PVA / constant / lnkCalc) and never processes the
265    /// target record.
266    ///
267    /// Distinct from [`Self::read_link_value`], which threads
268    /// `visited`/`depth` to PP-process a Passive DB source before reading
269    /// (the INPUT-link path). `dbGetLink` does no such processing, so the
270    /// DB arm here reads with a plain `get_pv` exactly as the pre-fix
271    /// control-link sites did.
272    ///
273    /// Used by the control links that C reads via `dbGetLink` every
274    /// process cycle — `SDIS`→`disa`, `SIML`→`simm`, `SELL`→`seln`, and
275    /// `TSEL`'s `TSE` load. The pre-fix sites open-coded an
276    /// `if let ParsedLink::Db` read, so a control link sourced over
277    /// CA/PVA or given as a constant was silently ignored.
278    pub(crate) async fn read_link_value_no_process(
279        &self,
280        link: &crate::server::record::ParsedLink,
281    ) -> Option<EpicsValue> {
282        match link {
283            crate::server::record::ParsedLink::None => None,
284            crate::server::record::ParsedLink::Ca(ca) => self.resolve_external_pv(&ca.pv).await,
285            crate::server::record::ParsedLink::Pva(name) => self.resolve_external_pv(name).await,
286            // Per-link identity key, as in `read_link_value` above.
287            crate::server::record::ParsedLink::PvaJson(j) => {
288                self.resolve_external_pv(&j.link_identity_key()).await
289            }
290            crate::server::record::ParsedLink::Constant(_) => link.constant_value(),
291            crate::server::record::ParsedLink::Db(db) => self.read_db_link_value(db).await,
292            // Hardware links carry no generic readable value.
293            crate::server::record::ParsedLink::Hw(_) => None,
294            crate::server::record::ParsedLink::Calc(calc) => self.evaluate_calc_link(calc).await,
295        }
296    }
297
298    /// lnkCalc evaluation: fetch each input PV, bind to calc engine
299    /// vars A..L, run `expr`, return the result as `EpicsValue::Double`.
300    /// Returns `None` if any input fetch fails, expr compile fails, or
301    /// eval fails — the caller treats the link as unresolvable.
302    pub async fn evaluate_calc_link(
303        &self,
304        calc: &crate::server::record::CalcLink,
305    ) -> Option<EpicsValue> {
306        use crate::calc::engine::{CALC_NARGS, NumericInputs};
307        // lnkCalc binds inputs to calc engine vars A..L (12). A link
308        // string carrying more than `CALC_NARGS` inputs is malformed —
309        // reject it rather than silently dropping the overflow args
310        // (the pre-fix `.take(12)` masked the misconfiguration).
311        if calc.args.len() > CALC_NARGS {
312            return None;
313        }
314        let mut vars = [0.0f64; CALC_NARGS];
315        for (i, arg) in calc.args.iter().enumerate() {
316            // Each lnkCalc input is its own `dbInitLink` link, so a
317            // non-local input record is a CA link — read it through the
318            // locality owner, not a local-only `get_pv`. `arg` is a bare
319            // record name or `record.FIELD`; split on the last `.`.
320            let (record, field) = match arg.rsplit_once('.') {
321                Some((r, f)) => (r, f),
322                None => (arg.as_str(), "VAL"),
323            };
324            let v = self.read_target_value(record, field).await?;
325            vars[i] = v.to_f64()?;
326        }
327        let compiled = crate::calc::compile(&calc.expr).ok()?;
328        let mut inputs = NumericInputs::with_vars(vars);
329        let result = crate::calc::eval(&compiled, &mut inputs).ok()?;
330        Some(EpicsValue::Double(result))
331    }
332
333    /// lnkCalc evaluation that also returns the timestamp pulled from
334    /// the input named by `time_source` (e.g. `'A'` → first input).
335    /// Returns `(value, Some(time))` when `time_source` is set and
336    /// the referenced input record has a timestamp, `(value, None)`
337    /// otherwise. The caller (link read path) uses `None` to mean
338    /// "consumer keeps its own apply_timestamp time".
339    pub async fn evaluate_calc_link_with_time(
340        &self,
341        calc: &crate::server::record::CalcLink,
342    ) -> Option<(EpicsValue, Option<std::time::SystemTime>)> {
343        let value = self.evaluate_calc_link(calc).await?;
344        let time = match calc.time_source {
345            Some(letter) => {
346                let idx = (letter as u8).saturating_sub(b'A') as usize;
347                let src = calc.args.get(idx)?;
348                // Strip `.FIELD` suffix to land on the record name.
349                let record_name = src.rsplit_once('.').map(|(r, _)| r).unwrap_or(src);
350                if self.has_name_no_resolve(record_name).await {
351                    let rec = self.get_record(record_name).await?;
352                    let inst = rec.read().await;
353                    Some(inst.common.time)
354                } else {
355                    // Non-local time source → CA link; pull the remote
356                    // `.TIME` through the external resolver (C
357                    // `dbGetTimeStamp` on a CA link), same as the
358                    // non-local TSEL `.TIME` adoption.
359                    let (secs, ns, _utag) = self
360                        .external_link_time(&format!("ca://{record_name}"))
361                        .await?;
362                    let secs = secs.max(0) as u64;
363                    let ns = (ns.max(0) as u32).min(999_999_999);
364                    Some(std::time::UNIX_EPOCH + std::time::Duration::new(secs, ns))
365                }
366            }
367            None => None,
368        };
369        Some((value, time))
370    }
371
372    /// Read value + alarm from a DB link. Returns (value, alarm) for MS/NMS propagation.
373    pub(crate) async fn read_link_with_alarm(
374        &self,
375        link: &crate::server::record::ParsedLink,
376    ) -> (Option<EpicsValue>, Option<LinkAlarm>) {
377        match link {
378            crate::server::record::ParsedLink::Db(db) => {
379                let pv_name = if db.field == "VAL" {
380                    db.record.clone()
381                } else {
382                    format!("{}.{}", db.record, db.field)
383                };
384                // C `dbInitLink` locality (`dbLink.c:118-130`): a target
385                // record present in this IOC is a DB link read from the
386                // local database; a non-local target is a CA link, so its
387                // value and raw remote alarm come from the external
388                // resolver — identical to the `Ca`/`Pva` arm below.
389                if !self.has_name_no_resolve(&db.record).await {
390                    return (
391                        self.resolve_external_pv(&pv_name).await,
392                        self.external_link_alarm(&pv_name).await,
393                    );
394                }
395                let value = self.get_pv(&pv_name).await.ok();
396                // Read source record's alarm state — alias-aware
397                // (epics-base PR #336) so a link target spelled with
398                // an alias still propagates MS/NMS alarm correctly.
399                let alarm = if let Some(rec) = self.get_record(&db.record).await {
400                    let inst = rec.read().await;
401                    Some(LinkAlarm {
402                        stat: inst.common.stat,
403                        sevr: inst.common.sevr,
404                        amsg: inst.common.amsg.clone(),
405                    })
406                } else {
407                    None
408                };
409                (value, alarm)
410            }
411            crate::server::record::ParsedLink::Constant(_) => (link.constant_value(), None),
412            // External Pva/Ca link: the value comes from the lset's
413            // cached snapshot, the alarm from the lset's accessors.
414            //
415            // PVA: the `?sevr=` modifier is stripped before epics-base-rs
416            // parses the link, so the lset retains and applies the
417            // `MS`/`NMS`/`MSI` gate itself — a returned `Some(sev)` is
418            // already gated and the caller folds it as `MaximizeStatus`.
419            //
420            // CA: the `MS`/`NMS`/`MSI`/`MSS` modifier is
421            // now carried in the `CaLink`, so the resolver returns the
422            // *raw* remote alarm and record processing applies the gate
423            // using `link.monitor_switch()`. Either way this fn just
424            // reads the raw/gated alarm; the switch pairing happens in
425            // `processing.rs`. Without this, a connected external link
426            // carrying a remote MINOR/MAJOR severity never folded into
427            // the owning record's LINK_ALARM (B2).
428            crate::server::record::ParsedLink::Pva(_)
429            | crate::server::record::ParsedLink::PvaJson(_)
430            | crate::server::record::ParsedLink::Ca(_) => {
431                let name = link
432                    .external_pv_name()
433                    .expect("Ca/Pva/PvaJson link carries a PV name");
434                let value = self.resolve_external_pv(&name).await;
435                let alarm = self.external_link_alarm(&name).await;
436                (value, alarm)
437            }
438            _ => (None, None),
439        }
440    }
441
442    /// Latched upstream timestamp from the lset, when the
443    /// link is configured with `time=true`. The lset gates internally
444    /// (returning `None` for links without the `time` option), so a
445    /// `Some` here is the authoritative remote timestamp the
446    /// processing path should adopt into the owning record's
447    /// `common.time` and `common.utag`. Mirrors pvxs
448    /// `pvalink_lset.cpp:427`.
449    ///
450    /// Returns `(seconds_since_epoch, nanoseconds, userTag)` exactly as
451    /// the lset reports them; the caller folds the time into the
452    /// record's `SystemTime` via `UNIX_EPOCH + Duration::new(...)` and
453    /// adopts the `userTag` into `common.utag`. The `userTag` is the
454    /// remote `timeStamp.userTag` widened without sign extension, or `0`
455    /// when the source carries none.
456    pub(crate) async fn external_link_time(&self, name: &str) -> Option<(i64, i32, u64)> {
457        let (scheme, body) = if let Some(rest) = name.strip_prefix("pva://") {
458            ("pva", rest)
459        } else if let Some(rest) = name.strip_prefix("ca://") {
460            ("ca", rest)
461        } else {
462            // Bare name — try every registered lset.
463            let registry = self.inner.link_sets.read().await;
464            for s in registry.schemes() {
465                if let Some(lset) = registry.get(&s) {
466                    if let Some(ts) = lset.time_stamp(name) {
467                        return Some(ts);
468                    }
469                }
470            }
471            return None;
472        };
473        let lset = self.inner.link_sets.read().await.get(scheme)?;
474        lset.time_stamp(body)
475    }
476
477    /// Build a [`LinkAlarm`] from the registered lset's alarm
478    /// accessors for an external (`pva://` / `ca://`) link, or `None`
479    /// when no lset is registered or the lset reports no alarm.
480    ///
481    /// The lset's `alarm_severity` is the gated severity (see
482    /// [`crate::server::database::LinkSet::alarm_severity`]); when it
483    /// is `Some`, the `stat` is `LINK_ALARM` and the message comes
484    /// from `alarm_message`.
485    async fn external_link_alarm(&self, name: &str) -> Option<LinkAlarm> {
486        let (scheme, body) = if let Some(rest) = name.strip_prefix("pva://") {
487            ("pva", rest)
488        } else if let Some(rest) = name.strip_prefix("ca://") {
489            ("ca", rest)
490        } else {
491            // Bare name — try every registered lset until one reports
492            // a severity (mirrors `resolve_external_pv`'s bare path).
493            let registry = self.inner.link_sets.read().await;
494            for s in registry.schemes() {
495                if let Some(lset) = registry.get(&s) {
496                    if let Some(sev) = lset.alarm_severity(name) {
497                        return Some(LinkAlarm {
498                            // prefer the remote STAT for MSS;
499                            // fall back to LINK_ALARM when the lset has none.
500                            stat: lset
501                                .alarm_status(name)
502                                .map(|s| s as u16)
503                                .unwrap_or(crate::server::recgbl::alarm_status::LINK_ALARM),
504                            sevr: crate::server::record::AlarmSeverity::from_u16(sev as u16),
505                            amsg: lset.alarm_message(name).unwrap_or_default(),
506                        });
507                    }
508                }
509            }
510            return None;
511        };
512        let lset = self.inner.link_sets.read().await.get(scheme)?;
513        let sev = lset.alarm_severity(body)?;
514        Some(LinkAlarm {
515            // remote STAT for MSS, else LINK_ALARM.
516            stat: lset
517                .alarm_status(body)
518                .map(|s| s as u16)
519                .unwrap_or(crate::server::recgbl::alarm_status::LINK_ALARM),
520            sevr: crate::server::record::AlarmSeverity::from_u16(sev as u16),
521            amsg: lset.alarm_message(body).unwrap_or_default(),
522        })
523    }
524
525    /// Ungated remote alarm snapshot for an external (`pva://` /
526    /// `ca://`) link — the DB-link inspection counterpart of
527    /// [`Self::external_link_alarm`].
528    ///
529    /// Where `external_link_alarm` returns the **gated** maximize-severity
530    /// contribution folded into the owning record's `LINK_ALARM` (pvxs
531    /// `pvaGetValue` applying the `MS`/`NMS`/`MSI` gate,
532    /// `pvalink_lset.cpp:424-431`), this returns the **ungated** remote
533    /// `(severity, status, message)` snapshot pvxs exposes through
534    /// `dbGetAlarm` / `dbGetAlarmMsg` (`pvaGetAlarmMsg`,
535    /// `pvalink_lset.cpp:542-575`). A default `NMS` link reports its
536    /// remote severity here even though it leaves the owning record
537    /// unraised.
538    ///
539    /// `None` when no lset is registered for the scheme, the link is not
540    /// connected, or the lset does not track remote alarms. Scheme
541    /// dispatch mirrors [`Self::external_link_alarm`].
542    pub async fn external_link_alarm_snapshot(
543        &self,
544        name: &str,
545    ) -> Option<crate::server::database::RemoteAlarm> {
546        let (scheme, body) = if let Some(rest) = name.strip_prefix("pva://") {
547            ("pva", rest)
548        } else if let Some(rest) = name.strip_prefix("ca://") {
549            ("ca", rest)
550        } else {
551            let registry = self.inner.link_sets.read().await;
552            for s in registry.schemes() {
553                if let Some(lset) = registry.get(&s) {
554                    if let Some(snap) = lset.remote_alarm(name) {
555                        return Some(snap);
556                    }
557                }
558            }
559            return None;
560        };
561        let lset = self.inner.link_sets.read().await.get(scheme)?;
562        lset.remote_alarm(body)
563    }
564
565    /// Remote display / control / valueAlarm metadata for an external
566    /// (`pva://` / `ca://`) link, resolved through the registered
567    /// lset's [`LinkSet::link_metadata`] hook.
568    ///
569    /// This is the DB-link-API entry point that exposes the linked PV
570    /// metadata pvxs's pvalink lset surfaces through its
571    /// `pvaGetDBFtype` / `pvaGetElements` / `pvaGetControlLimits` /
572    /// `pvaGetGraphicLimits` / `pvaGetAlarmLimits` / `pvaGetPrecision`
573    /// / `pvaGetUnits` getters
574    /// (`pvxs/ioc/pvalink_lset.cpp:700`). Scheme dispatch mirrors
575    /// [`Self::external_link_alarm`]: an explicit `pva://` / `ca://`
576    /// prefix selects the lset directly, a bare name tries every
577    /// registered lset until one reports metadata.
578    ///
579    /// `None` when no lset is registered for the scheme or the lset
580    /// has no cached value for the link (not yet connected).
581    pub async fn external_link_metadata(
582        &self,
583        name: &str,
584    ) -> Option<crate::server::database::LinkMetadata> {
585        let (scheme, body) = if let Some(rest) = name.strip_prefix("pva://") {
586            ("pva", rest)
587        } else if let Some(rest) = name.strip_prefix("ca://") {
588            ("ca", rest)
589        } else {
590            let registry = self.inner.link_sets.read().await;
591            for s in registry.schemes() {
592                if let Some(lset) = registry.get(&s) {
593                    if let Some(meta) = lset.link_metadata(name) {
594                        return Some(meta);
595                    }
596                }
597            }
598            return None;
599        };
600        let lset = self.inner.link_sets.read().await.get(scheme)?;
601        lset.link_metadata(body)
602    }
603
604    /// C `dbGetLink` PP rule: if a DB input link is `ProcessPassive`
605    /// and its source record is `Passive`-scanned, process the source
606    /// record before its value is read so the reader sees a freshly
607    /// computed value. No-op for non-PP links or non-passive sources.
608    ///
609    /// Shared by `read_link_value_soft` (single-INP path) and the
610    /// multi-input fetch loop (`INPA..INPL` for calc/sel/sub/aSub) so
611    /// both paths get the identical C-correct PP-processing behavior.
612    ///
613    /// The caller's `visited` set and `depth` are threaded through into
614    /// the source's processing cycle — NOT a fresh set / depth 0. This
615    /// is required for the cycle guard to span the PP hop: in C,
616    /// `calcRecord.c::process` sets `prec->pact = TRUE` *before*
617    /// `fetch_values()` (calcRecord.c:119-120), so when a PP input link
618    /// re-enters `dbProcess` on a record already mid-fetch, the
619    /// `if (precord->pact) goto all_done;` guard (dbAccess.c:537-557)
620    /// terminates the cycle after one bounce. The Rust port sets its
621    /// PACT `AtomicBool` only on `AsyncPending` *after* `record.process()`
622    /// returns, so it cannot catch a record mid-link-fetch. Threading
623    /// the caller's `visited` set makes the existing `visited.insert`
624    /// cycle guard (`process_record_with_links_inner`, processing.rs)
625    /// fire instead — an A↔B `PP` cycle bails when the second hop tries
626    /// to re-insert a name already on the chain. The FLNK path threads
627    /// `visited`/`depth` the same way (processing.rs FLNK dispatch).
628    pub(crate) async fn process_passive_db_source(
629        &self,
630        db: &crate::server::record::DbLink,
631        visited: &mut HashSet<String>,
632        depth: usize,
633    ) {
634        if db.policy != crate::server::record::LinkProcessPolicy::ProcessPassive {
635            return;
636        }
637        if let Some(src) = self.get_record(&db.record).await {
638            let is_passive =
639                src.read().await.common.scan == crate::server::record::ScanType::Passive;
640            if is_passive {
641                // recursive INP-link source processing within
642                // one chain — gate held by the foreign entry record.
643                let _ = self
644                    .process_record_with_links_recursive(&db.record, visited, depth + 1)
645                    .await;
646            }
647        }
648    }
649
650    /// Read a value from a parsed link for INP (only reads DB links when soft channel).
651    ///
652    /// `visited` / `depth` are the caller's processing-chain state — a PP
653    /// input link's source is processed *within* that same chain so the
654    /// `visited` cycle guard spans the PP hop (see
655    /// [`Self::process_passive_db_source`]).
656    pub async fn read_link_value_soft(
657        &self,
658        link: &crate::server::record::ParsedLink,
659        is_soft: bool,
660        visited: &mut HashSet<String>,
661        depth: usize,
662    ) -> Option<EpicsValue> {
663        match link {
664            crate::server::record::ParsedLink::Constant(_) => link.constant_value(),
665            crate::server::record::ParsedLink::Db(db) if is_soft => {
666                // PP: process source record if Passive before reading
667                self.process_passive_db_source(db, visited, depth).await;
668                self.read_db_link_value(db).await
669            }
670            crate::server::record::ParsedLink::Ca(_)
671            | crate::server::record::ParsedLink::Pva(_)
672            | crate::server::record::ParsedLink::PvaJson(_)
673                if is_soft =>
674            {
675                let name = link
676                    .external_pv_name()
677                    .expect("Ca/Pva/PvaJson link carries a PV name");
678                self.resolve_external_pv(&name).await
679            }
680            // lnkCalc evaluates regardless of `is_soft` — the input
681            // PVs may themselves be local DB targets (which need the
682            // soft path) or remote CA/PVA, but the calc evaluation
683            // is uniform either way.
684            crate::server::record::ParsedLink::Calc(calc) => self.evaluate_calc_link(calc).await,
685            _ => None,
686        }
687    }
688
689    /// Write a value through a DbLink, optionally processing the target if PP and Passive.
690    ///
691    /// `src_putf` carries the source record's `PUTF` bit so the target inherits
692    /// it the same way C `dbDbLink.c::processTarget` propagates it (lines 470-498):
693    ///
694    /// - target not pact: `target.putf = src_putf` (normal propagation),
695    /// - target pact AND `src_putf` AND target not on current process chain:
696    ///   `target.rpro = true`, `target.putf = false` so the in-flight cycle
697    ///   reprocesses on completion attributing the put to the originator,
698    /// - otherwise: no PUTF change (target is either being processed
699    ///   recursively by us, or wasn't triggered by a dbPutField).
700    ///
701    /// Without this, a CA WRITE_NOTIFY landing on an upstream calc/seq/dfanout
702    /// that fanned out via DB OUT links would see `target.putf = 0` on every
703    /// downstream record — breaking dbNotify completion attribution and any
704    /// device-support code that uses PUTF to distinguish operator-driven from
705    /// scan-driven processing.
706    pub(crate) async fn write_db_link_value(
707        &self,
708        link: &crate::server::record::DbLink,
709        value: EpicsValue,
710        src: OutLinkSrc<'_>,
711        visited: &mut HashSet<String>,
712        depth: usize,
713    ) {
714        let target_name = if link.field == "VAL" {
715            link.record.clone()
716        } else {
717            format!("{}.{}", link.record, link.field)
718        };
719        // C `dbInitLink` locality (`dbLink.c:118-130`): a target record
720        // not present in this IOC is a CA link, so its write is routed
721        // through the external put path (`dbCaPutLink`), not a local
722        // `dbPut`. The alarm-inheritance / PUTF / `processTarget`
723        // machinery below is the local-DB `dbDbPutValue` body
724        // (dbDbLink.c:372-393), which `dbCaPutLink` performs none of —
725        // so a non-local target returns right after the remote write.
726        // OUTPUT-side twin of the `read_db_link_value` locality fallback.
727        if !self.has_name_no_resolve(&link.record).await {
728            let op = Self::external_put_op(src.notify);
729            if let Err(e) = self.write_external_pv(&target_name, value, op).await {
730                eprintln!("OUT-link write to external PV '{target_name}' failed: {e}");
731            }
732            return;
733        }
734        // an OUT-link write-back is an internal step of the
735        // processing chain that already holds the entry record's
736        // advisory write gate (`dbScanLock` analogue). It must use the
737        // `_already_locked` write so it does not re-acquire a gate: a
738        // self-referencing OUT link (`SELF PP`) would otherwise
739        // dead-lock on the entry record's own non-reentrant gate. C
740        // `dbDbPutValue` writes the OUT-link target under the same
741        // lock set the chain already owns.
742        let put_result = self.put_pv_already_locked(&target_name, value).await;
743
744        // C `dbDbPutValue` (dbDbLink.c:382-383) folds the SOURCE
745        // record's alarm into the destination via `recGblInheritSevrMsg`,
746        // AFTER the `dbPut` and BEFORE `processTarget`. In this port the
747        // source's per-cycle alarm has already been committed by
748        // `rec_gbl_reset_alarms` before the OUT link dispatches, so
749        // `src_alarm` carries the source's *committed* stat/sevr/amsg —
750        // the same values C reads from the still-pending nsta/nsev/namsg
751        // at its (earlier) synchronous `writeValue` point. The inherited
752        // severity lands in the dest's PENDING nsev/nsta(/namsg for MSS);
753        // the dest commits it on its next `rec_gbl_reset_alarms` — its
754        // own process cycle, reached below for a `.PROC`/`PP` link, or a
755        // later independent scan otherwise. NMS (the common case) skips
756        // the dest lookup/lock entirely.
757        if link.monitor_switch != crate::server::record::MonitorSwitch::NoMaximize {
758            if let Some(target_rec) = self.get_record(&link.record).await {
759                let mut tg = target_rec.write().await;
760                inherit_sevr_msg(&mut tg.common, link.monitor_switch, src.alarm);
761            }
762        }
763
764        // C `dbDbPutValue` (dbDbLink.c:384-385) returns the put status
765        // immediately after the alarm inheritance and BEFORE the
766        // `.PROC`/`PP` `processTarget` branch: only a successful write
767        // reaches target processing. A failed OUT-link write (value
768        // conversion error, missing field, record put rejection — e.g.
769        // an empty array written into a scalar field) must therefore NOT
770        // trigger the target's process cycle, which would otherwise run
771        // the target on its stale field value and diverge from C on side
772        // effects, FLNK, alarms, and put-notify completion ordering. The
773        // alarm inheritance above already ran (C folds it regardless of
774        // status), matching the C ordering exactly.
775        if put_result.is_err() {
776            return;
777        }
778
779        // C `dbDbPutValue` (`dbDbLink.c:387-390`) processes the target
780        // when the destination field is `.PROC` **or** the link carries
781        // `pvlOptPP` (an explicit ` PP` token → `ProcessPassive`). The
782        // `.PROC` arm is independent of the PP flag, so it is checked
783        // here in the write path rather than encoded as a parse-time
784        // policy: a modifier-less link now defaults to `NoProcess`
785        // uniformly (INPUT and OUTPUT alike), and writing a value into a
786        // record's `.PROC` field still forces a process.
787        if link.field == "PROC"
788            || link.policy == crate::server::record::LinkProcessPolicy::ProcessPassive
789        {
790            // Alias-aware lookup: the link's target may be the alias
791            // form. `process_record_with_links` itself also resolves
792            // aliases at entry, so passing `link.record` raw is safe.
793            if let Some(target_rec) = self.get_record(&link.record).await {
794                // Apply C `processTarget` PUTF propagation rules before
795                // dispatching the target's process cycle.
796                let (target_scan, should_process) = {
797                    let mut tg = target_rec.write().await;
798                    let pact = tg.is_processing();
799                    let on_chain = visited.contains(&link.record);
800                    let scan = tg.common.scan;
801                    if !pact {
802                        tg.common.putf = src.putf;
803                        // C `dbNotifyAdd` (dbDbLink.c:460) lives inside
804                        // `processTarget`, which `dbDbPutValue` reaches
805                        // for a `.PROC` write or a `PP` link to a passive
806                        // target (dbDbLink.c:387-389). This Rust port only
807                        // processes the target on the passive branch
808                        // below, so gate the join on the same condition:
809                        // a target that will not be processed must NOT
810                        // join, or it would `enter` the wait-set without
811                        // ever `leave`ing it and hang the completion.
812                        if scan == ScanType::Passive {
813                            join_put_notify(&mut tg, src.notify);
814                        }
815                    } else if src.putf && !on_chain {
816                        tg.common.rpro = true;
817                        tg.common.putf = false;
818                    }
819                    (scan, !pact)
820                };
821                if should_process && target_scan == ScanType::Passive {
822                    // recursive OUT-link target processing within
823                    // one chain — gate held by the foreign entry record.
824                    let _ = self
825                        .process_record_with_links_recursive(&link.record, visited, depth + 1)
826                        .await;
827                }
828            }
829        }
830    }
831
832    /// Write a value to an external (`ca://` / `pva://`) OUT link
833    /// through the registered [`LinkSet`].
834    ///
835    /// This is the OUTPUT-side twin of [`Self::resolve_external_pv`]:
836    /// the input side dispatches a `ParsedLink::Ca`/`Pva` read through
837    /// `lset.get_value`, this dispatches a record's OUT-link write
838    /// through `lset.put_value`. Mirrors C `dbLink.c::dbPutLink`
839    /// (dbLink.c:434-448), which routes every link write — DB or CA —
840    /// through `plink->lset->putValue` and raises a link alarm
841    /// (`setLinkAlarm`) on failure.
842    ///
843    /// `name` may be a fully scheme-prefixed string (`pva://X`,
844    /// `ca://X`) or the bare body (the form stored in
845    /// `ParsedLink::Ca`/`Pva` after `record/link.rs` strips the
846    /// scheme). For a bare name every registered lset is tried in
847    /// turn — the first whose `put_value` succeeds wins.
848    ///
849    /// Returns `Ok(())` on a successful remote write, `Err(reason)`
850    /// when no lset is registered for the scheme or the lset rejects
851    /// the write (the caller folds that into a LINK alarm — it must
852    /// never panic).
853    ///
854    /// `op` carries the delivery semantics the lset must honour:
855    /// [`LinkPutOp::Async`] when the write is part of a put-notify /
856    /// blocking-put chain (mirrors C `dbPutLinkAsync` / pvxs
857    /// `pvaPutValueAsync`), [`LinkPutOp::Plain`] otherwise.
858    pub(crate) async fn write_external_pv(
859        &self,
860        name: &str,
861        value: EpicsValue,
862        op: LinkPutOp,
863    ) -> Result<(), String> {
864        let (scheme, body) = if let Some(rest) = name.strip_prefix("pva://") {
865            ("pva", rest)
866        } else if let Some(rest) = name.strip_prefix("ca://") {
867            ("ca", rest)
868        } else {
869            // Bare name — try every registered lset in turn, first
870            // accepting write wins (mirrors `resolve_external_pv`'s
871            // bare-name path).
872            let registry = self.inner.link_sets.read().await;
873            let schemes = registry.schemes();
874            if schemes.is_empty() {
875                return Err(format!("no link set registered for external link '{name}'"));
876            }
877            let mut last_err = String::new();
878            for s in schemes {
879                if let Some(lset) = registry.get(&s) {
880                    match lset.put_value(name, value.clone(), op) {
881                        Ok(()) => {
882                            // Production drain of any retry-queued OUT
883                            // writes on this lset now that a write has
884                            // reached it (the channel may have just
885                            // reconnected). pvxs replays the queued
886                            // put from record processing, not test code
887                            // (`pvalink_channel.cpp:220-263`).
888                            lset.flush_puts();
889                            return Ok(());
890                        }
891                        Err(e) => last_err = e,
892                    }
893                }
894            }
895            return Err(last_err);
896        };
897        let lset = self
898            .inner
899            .link_sets
900            .read()
901            .await
902            .get(scheme)
903            .ok_or_else(|| format!("no '{scheme}' link set registered for '{name}'"))?;
904        let result = lset.put_value(body, value, op);
905        if result.is_ok() {
906            lset.flush_puts();
907        }
908        result
909    }
910
911    /// Fire a forward link (FLNK) whose target is an external
912    /// (`pva://` / `ca://`) PV — the FWD-link counterpart of
913    /// [`Self::write_external_pv`]. Resolves the scheme (or tries every
914    /// registered lset for a bare name, first to accept wins, exactly as
915    /// the OUT-write path does) and delegates to [`LinkSet::scan_forward`].
916    ///
917    /// Mirrors C `dbScanFwdLink` → `plink->lset->scanForward`
918    /// (`dbLink.c:475-480`): the database hands the forward link to the
919    /// link set, which (for pvalink) runs `pvaScanForward`. Returns the
920    /// lset's `Err` unchanged so the caller can raise LINK/INVALID on the
921    /// owning record (pvxs `recGblSetSevrMsg(LINK_ALARM, INVALID_ALARM)`).
922    pub(crate) async fn scan_forward_external_pv(&self, name: &str) -> Result<(), String> {
923        let (scheme, body) = if let Some(rest) = name.strip_prefix("pva://") {
924            ("pva", rest)
925        } else if let Some(rest) = name.strip_prefix("ca://") {
926            ("ca", rest)
927        } else {
928            // Bare name — try every registered lset in turn, first
929            // accepting the forward wins (mirrors `write_external_pv`'s
930            // bare-name path so FWD and OUT route a bare target alike).
931            let registry = self.inner.link_sets.read().await;
932            let schemes = registry.schemes();
933            if schemes.is_empty() {
934                return Err(format!("no link set registered for forward link '{name}'"));
935            }
936            let mut last_err = String::new();
937            for s in schemes {
938                if let Some(lset) = registry.get(&s) {
939                    match lset.scan_forward(name) {
940                        Ok(()) => return Ok(()),
941                        Err(e) => last_err = e,
942                    }
943                }
944            }
945            return Err(last_err);
946        };
947        let lset = self
948            .inner
949            .link_sets
950            .read()
951            .await
952            .get(scheme)
953            .ok_or_else(|| format!("no '{scheme}' link set registered for '{name}'"))?;
954        lset.scan_forward(body)
955    }
956
957    /// Map a record's put-completion wait-set to the external-link put
958    /// op. A write that originates inside a put-notify / blocking-put
959    /// chain (the source record carries a completion wait-set) is
960    /// delivered as [`LinkPutOp::Async`] (the pvxs `pvaPutValueAsync` /
961    /// C `dbPutLinkAsync` path); a plain record-processing OUT write is
962    /// [`LinkPutOp::Plain`]. Single owner of the notify→op mapping so
963    /// the external-OUT dispatch sites cannot diverge.
964    fn external_put_op(src_notify: Option<&Arc<NotifyWaitSet>>) -> LinkPutOp {
965        if src_notify.is_some() {
966            LinkPutOp::Async
967        } else {
968            LinkPutOp::Plain
969        }
970    }
971
972    /// Write a value through a parsed OUT link, dispatching DB links
973    /// to [`Self::write_db_link_value`] and external (`ca://`/`pva://`)
974    /// links to [`Self::write_external_pv`].
975    ///
976    /// This is the OUTPUT-side counterpart of [`Self::read_link_value`]'s
977    /// scheme dispatch: the OUT-link write stage in `processing.rs`
978    /// must route a `ParsedLink::Ca`/`Pva` through the link set, not
979    /// only handle `ParsedLink::Db`. An external link with no
980    /// registered lset fails gracefully — the error is logged and the
981    /// record is left to its alarm state, never a panic.
982    ///
983    /// `Constant`/`Hw`/`Calc`/`None` OUT links are not writable
984    /// targets and are silently skipped (C `dbPutLink` returns
985    /// `S_db_noLSET` for a link with no lset — the same no-op).
986    pub(crate) async fn write_out_link_value(
987        &self,
988        link: &crate::server::record::ParsedLink,
989        value: EpicsValue,
990        src: OutLinkSrc<'_>,
991        visited: &mut HashSet<String>,
992        depth: usize,
993    ) {
994        match link {
995            crate::server::record::ParsedLink::Db(db) => {
996                self.write_db_link_value(db, value, src, visited, depth)
997                    .await;
998            }
999            crate::server::record::ParsedLink::Ca(_)
1000            | crate::server::record::ParsedLink::Pva(_)
1001            | crate::server::record::ParsedLink::PvaJson(_) => {
1002                let name = link
1003                    .external_pv_name()
1004                    .expect("Ca/Pva/PvaJson link carries a PV name");
1005                let op = Self::external_put_op(src.notify);
1006                if let Err(e) = self.write_external_pv(&name, value, op).await {
1007                    eprintln!("OUT-link write to external PV '{name}' failed: {e}");
1008                }
1009            }
1010            // Constant / Hw / Calc / None are not writable OUT-link
1011            // targets — no-op (C `dbPutLink` → `S_db_noLSET`).
1012            _ => {}
1013        }
1014    }
1015
1016    /// Read a record String field, defaulting to empty.
1017    fn field_str(instance: &RecordInstance, field: &str) -> String {
1018        match instance.record.get_field(field) {
1019            Some(EpicsValue::String(s)) => s.as_str_lossy().into_owned(),
1020            _ => String::new(),
1021        }
1022    }
1023
1024    /// Read a record numeric field as `i16`, defaulting to 0.
1025    fn field_i16(instance: &RecordInstance, field: &str) -> i16 {
1026        instance
1027            .record
1028            .get_field(field)
1029            .and_then(|v| v.to_f64())
1030            .unwrap_or(0.0) as i16
1031    }
1032
1033    /// Read a record numeric field as `u16`, defaulting to 0.
1034    ///
1035    /// Used for `DBF_USHORT` fields such as `SELN`: the native unsigned
1036    /// carrier returns its value directly, while any other DBR type is
1037    /// truncated through the `i64` integer view (C `dbPut` cast), so a
1038    /// value ≥ 32768 round-trips instead of saturating at `i16::MAX`.
1039    fn field_u16(instance: &RecordInstance, field: &str) -> u16 {
1040        match instance.record.get_field(field) {
1041            Some(EpicsValue::UShort(v)) => v,
1042            Some(other) => other.as_int_i64().unwrap_or(0) as u16,
1043            None => 0,
1044        }
1045    }
1046
1047    /// Apply a SELM-resolved out-of-range alarm to the record.
1048    ///
1049    /// C raises this alarm inside `process()` (before `recGblResetAlarms`)
1050    /// via `recGblSetSevr(prec, SOFT_ALARM, INVALID_ALARM)`. The Rust
1051    /// multi-output dispatch runs after the record's own alarm reset,
1052    /// so we apply the severity directly to `common.sevr/stat`, refresh
1053    /// the live STAT/SEVR fields, and post the monitor — matching the
1054    /// observable end state (record reads INVALID/SOFT_ALARM, a
1055    /// `DBE_ALARM` subscriber on STAT/SEVR is notified).
1056    async fn apply_selm_alarm(
1057        rec: &Arc<RwLock<RecordInstance>>,
1058        alarm: Option<(u16, AlarmSeverity)>,
1059    ) {
1060        let Some((stat, sevr)) = alarm else {
1061            return;
1062        };
1063        let posted = {
1064            let mut inst = rec.write().await;
1065            // Raise-only, mirroring recGblSetSevr.
1066            if (sevr as u16) > (inst.common.sevr as u16) {
1067                inst.common.sevr = sevr;
1068                inst.common.stat = stat;
1069                true
1070            } else {
1071                false
1072            }
1073        };
1074        if posted {
1075            let inst = rec.read().await;
1076            inst.notify_field("SEVR", crate::server::recgbl::EventMask::ALARM);
1077            inst.notify_field("STAT", crate::server::recgbl::EventMask::VALUE);
1078        }
1079    }
1080
1081    /// Multi-output dispatch for fanout, dfanout, seq record types.
1082    ///
1083    /// The per-record payload is a typed [`MultiOut`] — seq / sseq
1084    /// groups are kept as struct fields, NOT `\0`-packed strings
1085    /// (the pre-fix encoding could mis-split a link string that
1086    /// happened to contain an embedded NUL).
1087    pub(crate) async fn dispatch_multi_output(
1088        &self,
1089        rec: &Arc<RwLock<RecordInstance>>,
1090        visited: &mut HashSet<String>,
1091        depth: usize,
1092    ) {
1093        // Snapshot the source record's PUTF bit + put-notify wait-set so
1094        // every write_db_link_value call below propagates them to its
1095        // target — C `dbDbLink.c::processTarget` PUTF and `dbNotifyAdd`
1096        // wait-set invariants (see write_db_link_value doc). The
1097        // committed alarm travels the same way for `recGblInheritSevrMsg`
1098        // MS-class propagation into each OUT-link target.
1099        let (src_putf, src_notify, src_alarm) = {
1100            let guard = rec.read().await;
1101            (
1102                guard.common.putf,
1103                guard.notify.clone(),
1104                LinkAlarm {
1105                    stat: guard.common.stat,
1106                    sevr: guard.common.sevr,
1107                    amsg: guard.common.amsg.clone(),
1108                },
1109            )
1110        };
1111        // One snapshot threaded to every OUT-link write below.
1112        let out_src = OutLinkSrc {
1113            putf: src_putf,
1114            notify: src_notify.as_ref(),
1115            alarm: &src_alarm,
1116        };
1117
1118        // Resolve the SELL link into SELN before SELN is read below.
1119        // C `fanoutRecord.c:103`, `dfanoutRecord.c:126`,
1120        // `seqRecord.c:152` all call
1121        // `dbGetLink(&prec->sell, DBR_USHORT, &prec->seln, 0, 0)` at
1122        // the top of `process()`, every cycle. Only the `sel` record's
1123        // NVL->SELN binding was previously wired; fanout/dfanout/seq
1124        // never read the SELL link, so a SELL pointing at another
1125        // record's value field never updated SELN — the selection was
1126        // frozen at whatever SELN was initialised to. `sseq` reads its
1127        // own SELL→SELN in `SseqRecord::pre_input_link_actions` (the
1128        // async machine owns the whole cycle), so it is not handled here.
1129        {
1130            let sell = {
1131                let instance = rec.read().await;
1132                match instance.record.record_type() {
1133                    "fanout" | "dfanout" | "seq" => Some(Self::field_str(&instance, "SELL")),
1134                    _ => None,
1135                }
1136            };
1137            if let Some(sell) = sell {
1138                if !sell.is_empty() {
1139                    // C reads SELL via `dbGetLink(&prec->sell, DBR_USHORT,
1140                    // &prec->seln, 0, 0)` for any link type; the pre-fix
1141                    // port only read a `ParsedLink::Db` SELL, so a SELL
1142                    // sourced over CA/PVA or given as a constant never
1143                    // updated SELN.
1144                    let parsed = crate::server::record::parse_link_v2(&sell);
1145                    if let Some(val) = self.read_link_value_no_process(&parsed).await {
1146                        // C reads SELL with `dbGetLink(&prec->sell,
1147                        // DBR_USHORT, &prec->seln, 0, 0)`; the dbConvert GET
1148                        // macro stores `*pdst = (epicsUInt16) *psrc`
1149                        // (`dbConvert.c:63-70`) — a C cast (truncate-then-
1150                        // wrap mod 2^16), NOT a clamp. `SELL=-1` therefore
1151                        // yields `SELN=65535` (Specified → out-of-range
1152                        // INVALID, Mask → all-bits), where the old clamp
1153                        // produced `0` (drove link 0 / empty mask). SELN is
1154                        // a `DBF_USHORT` (u16) field; `select_link_indices_ex`
1155                        // consumes it as `u16`.
1156                        let seln = dbr_ushort_cast(&val);
1157                        let mut instance = rec.write().await;
1158                        let _ = instance.record.put_field("SELN", EpicsValue::UShort(seln));
1159                    }
1160                }
1161            }
1162        }
1163
1164        let dispatch_info: Option<(SelmResult, MultiOut, Option<EpicsValue>)> = {
1165            let instance = rec.read().await;
1166            match instance.record.record_type() {
1167                "fanout" => {
1168                    let selm = Self::field_i16(&instance, "SELM");
1169                    let seln = Self::field_u16(&instance, "SELN");
1170                    let offs = Self::field_i16(&instance, "OFFS");
1171                    let shft = Self::field_i16(&instance, "SHFT");
1172                    // C parity (fanoutRecord.c:39): 16 forward links
1173                    // LNK0..LNKF. LNK0 is the natural first slot.
1174                    let links: Vec<String> = [
1175                        "LNK0", "LNK1", "LNK2", "LNK3", "LNK4", "LNK5", "LNK6", "LNK7", "LNK8",
1176                        "LNK9", "LNKA", "LNKB", "LNKC", "LNKD", "LNKE", "LNKF",
1177                    ]
1178                    .iter()
1179                    .map(|f| Self::field_str(&instance, f))
1180                    .collect();
1181                    // SELM resolution with OFFS/SHFT bias (fanoutRecord.c).
1182                    let sel = select_link_indices_ex(
1183                        SelmKind::FanoutSeq,
1184                        selm,
1185                        seln,
1186                        offs,
1187                        shft,
1188                        links.len(),
1189                    );
1190                    Some((sel, MultiOut::Fanout(links), None))
1191                }
1192                "dfanout" => {
1193                    let selm = Self::field_i16(&instance, "SELM");
1194                    let seln = Self::field_u16(&instance, "SELN");
1195                    // IVOA / IVOV — invalid output handling, mirrors
1196                    // epics-base PR #688. When the record's SEVR is
1197                    // INVALID, IVOA selects: 0 = continue (use VAL as
1198                    // before), 1 = don't drive (suppress all OUT*),
1199                    // 2 = set outputs to IVOV.
1200                    let raw_val = instance.record.val();
1201                    let val =
1202                        if instance.common.sevr == crate::server::record::AlarmSeverity::Invalid {
1203                            let ivoa = instance
1204                                .record
1205                                .get_field("IVOA")
1206                                .and_then(|v| {
1207                                    if let EpicsValue::Short(s) = v {
1208                                        Some(s)
1209                                    } else {
1210                                        None
1211                                    }
1212                                })
1213                                .unwrap_or(0);
1214                            match ivoa {
1215                                1 => None, // suppress drive
1216                                2 => instance.record.get_field("IVOV").or(raw_val),
1217                                _ => raw_val, // 0 or unknown — Continue
1218                            }
1219                        } else {
1220                            raw_val
1221                        };
1222                    let links: Vec<String> = [
1223                        "OUTA", "OUTB", "OUTC", "OUTD", "OUTE", "OUTF", "OUTG", "OUTH", "OUTI",
1224                        "OUTJ", "OUTK", "OUTL", "OUTM", "OUTN", "OUTO", "OUTP",
1225                    ]
1226                    .iter()
1227                    .map(|f| Self::field_str(&instance, f))
1228                    .collect();
1229                    // dfanout Specified is 1-based; Mask has no SHFT
1230                    // (dfanoutRecord.c:307-339).
1231                    let sel =
1232                        select_link_indices_ex(SelmKind::Dfanout, selm, seln, 0, 0, links.len());
1233                    Some((sel, MultiOut::Dfanout(links), val))
1234                }
1235                "seq" => {
1236                    let selm = Self::field_i16(&instance, "SELM");
1237                    let seln = Self::field_u16(&instance, "SELN");
1238                    let offs = Self::field_i16(&instance, "OFFS");
1239                    let shft = Self::field_i16(&instance, "SHFT");
1240                    // C parity (seqRecord.c:86): 16 link groups 0..F,
1241                    // each DOLn / DOn (value storage) / DLYn / LNKn.
1242                    let dol_names = [
1243                        "DOL0", "DOL1", "DOL2", "DOL3", "DOL4", "DOL5", "DOL6", "DOL7", "DOL8",
1244                        "DOL9", "DOLA", "DOLB", "DOLC", "DOLD", "DOLE", "DOLF",
1245                    ];
1246                    let lnk_names = [
1247                        "LNK0", "LNK1", "LNK2", "LNK3", "LNK4", "LNK5", "LNK6", "LNK7", "LNK8",
1248                        "LNK9", "LNKA", "LNKB", "LNKC", "LNKD", "LNKE", "LNKF",
1249                    ];
1250                    let dly_names = [
1251                        "DLY0", "DLY1", "DLY2", "DLY3", "DLY4", "DLY5", "DLY6", "DLY7", "DLY8",
1252                        "DLY9", "DLYA", "DLYB", "DLYC", "DLYD", "DLYE", "DLYF",
1253                    ];
1254                    let do_names = [
1255                        "DO0", "DO1", "DO2", "DO3", "DO4", "DO5", "DO6", "DO7", "DO8", "DO9",
1256                        "DOA", "DOB", "DOC", "DOD", "DOE", "DOF",
1257                    ];
1258                    let groups: Vec<SeqGroup> = (0..16)
1259                        .map(|i| SeqGroup {
1260                            dol: Self::field_str(&instance, dol_names[i]),
1261                            lnk: Self::field_str(&instance, lnk_names[i]),
1262                            dly: instance
1263                                .record
1264                                .get_field(dly_names[i])
1265                                .and_then(|v| v.to_f64())
1266                                .unwrap_or(0.0),
1267                            dov: instance
1268                                .record
1269                                .get_field(do_names[i])
1270                                .and_then(|v| v.to_f64())
1271                                .unwrap_or(0.0),
1272                        })
1273                        .collect();
1274                    let sel = select_link_indices_ex(
1275                        SelmKind::FanoutSeq,
1276                        selm,
1277                        seln,
1278                        offs,
1279                        shft,
1280                        groups.len(),
1281                    );
1282                    Some((sel, MultiOut::Seq(groups), None))
1283                }
1284                _ => None,
1285            }
1286        };
1287
1288        let (sel, payload, val) = match dispatch_info {
1289            Some(info) => info,
1290            None => return,
1291        };
1292        debug_assert!(sel.indices.iter().all(|&i| i < payload.len()));
1293        // Single-owner invariant: every record type that produces a
1294        // `MultiOut` payload here MUST be listed in
1295        // `multi_output_dispatch_owned` so the generic
1296        // `multi_output_links` block in `processing.rs` skips it. If
1297        // this fires, the two lists have diverged and the skipped
1298        // type would be dispatched twice per cycle.
1299        debug_assert!(multi_output_dispatch_owned(
1300            rec.read().await.record.record_type()
1301        ));
1302
1303        // C raises SOFT_ALARM/INVALID_ALARM when SELN/OFFS/SHFT resolve
1304        // out of range (fanoutRecord.c:116, dfanoutRecord.c:317,
1305        // seqRecord.c:157). Apply it before dispatching the (empty)
1306        // selection.
1307        Self::apply_selm_alarm(rec, sel.alarm).await;
1308        let indices = sel.indices;
1309
1310        match payload {
1311            MultiOut::Fanout(links) => {
1312                for idx in indices {
1313                    let link_str = &links[idx];
1314                    if link_str.is_empty() {
1315                        continue;
1316                    }
1317                    let parsed = crate::server::record::parse_link_v2(link_str);
1318                    if let crate::server::record::ParsedLink::Db(ref db) = parsed {
1319                        // C `fanoutRecord.c:110/121/138` dispatches each
1320                        // selected LNKn via `dbScanFwdLink` →
1321                        // `dbDbScanFwdLink` → `dbScanPassive`
1322                        // (`dbDbLink.c:425-432`), which processes the
1323                        // target ONLY when its SCAN is Passive
1324                        // (`if (pto->scan != 0) return 0;`). A LNKn
1325                        // pointing at a Periodic/Event/I/O-Intr record
1326                        // must NOT be re-processed by the fanout — that
1327                        // record runs on its own scan. `dbScanPassive`
1328                        // then calls `processTarget`, which propagates
1329                        // PUTF (and sets RPRO on a busy target) exactly
1330                        // like the explicit FLNK path — so mirror that
1331                        // gate here instead of the previous
1332                        // unconditional `process_record_with_links`.
1333                        if let Some(target_rec) = self.get_record(&db.record).await {
1334                            let (target_scan, should_process) = {
1335                                let mut tg = target_rec.write().await;
1336                                let pact = tg.is_processing();
1337                                let on_chain = visited.contains(&db.record);
1338                                if !pact {
1339                                    tg.common.putf = src_putf;
1340                                } else if src_putf && !on_chain {
1341                                    tg.common.rpro = true;
1342                                    tg.common.putf = false;
1343                                }
1344                                (tg.common.scan, !pact)
1345                            };
1346                            if should_process && target_scan == ScanType::Passive {
1347                                // recursive link-target processing
1348                                // within one chain — gate held by the
1349                                // foreign entry record.
1350                                let _ = self
1351                                    .process_record_with_links_recursive(
1352                                        &db.record,
1353                                        visited,
1354                                        depth + 1,
1355                                    )
1356                                    .await;
1357                            }
1358                        }
1359                    }
1360                }
1361            }
1362            MultiOut::Dfanout(links) => {
1363                if let Some(ref val) = val {
1364                    for idx in indices {
1365                        let link_str = &links[idx];
1366                        if link_str.is_empty() {
1367                            continue;
1368                        }
1369                        // C `dfanoutRecord.c:323` drives each OUTn via
1370                        // `dbPutLink` → `dbDbPutValue`: an `DBF_OUTLINK`
1371                        // target is processed only when the link carries
1372                        // an explicit ` PP` token or the destination is
1373                        // `.PROC` (`dbDbLink.c:387-390`). A modifier-less
1374                        // OUTn is NPP — the value is written but the
1375                        // target is NOT re-processed (otherwise a
1376                        // Soft-Channel ai target's `convert()` would
1377                        // clobber the value just written). The NPP
1378                        // default and the `.PROC`/`PP` processing rule
1379                        // are both honoured by `parse_output_link_v2`
1380                        // (uniform NoProcess default) +
1381                        // `write_db_link_value` (write-path target
1382                        // processing), so no per-call downgrade is needed.
1383                        let parsed = crate::server::record::parse_output_link_v2(link_str);
1384                        match parsed {
1385                            crate::server::record::ParsedLink::Db(ref db) => {
1386                                self.write_db_link_value(db, val.clone(), out_src, visited, depth)
1387                                    .await;
1388                            }
1389                            // External `ca://`/`pva://` OUTn — C
1390                            // `dbPutLink` routes a CA-link write through
1391                            // the link set's `putValue` identically to a
1392                            // DB link (dbLink.c:434-448). PP has no
1393                            // meaning for an external write (the remote
1394                            // record processes on its own IOC), so route
1395                            // straight through the link set.
1396                            crate::server::record::ParsedLink::Ca(_)
1397                            | crate::server::record::ParsedLink::Pva(_)
1398                            | crate::server::record::ParsedLink::PvaJson(_) => {
1399                                let name = parsed
1400                                    .external_pv_name()
1401                                    .expect("Ca/Pva/PvaJson link carries a PV name");
1402                                let op = Self::external_put_op(src_notify.as_ref());
1403                                if let Err(e) = self.write_external_pv(&name, val.clone(), op).await
1404                                {
1405                                    eprintln!(
1406                                        "dfanout OUT-link write to external PV '{name}' failed: {e}"
1407                                    );
1408                                }
1409                            }
1410                            _ => {}
1411                        }
1412                    }
1413                }
1414            }
1415            MultiOut::Seq(groups) => {
1416                for idx in indices {
1417                    let grp = &groups[idx];
1418                    if grp.lnk.is_empty() {
1419                        continue;
1420                    }
1421                    // Per-group DLYn staggering — C `seqRecord.c`
1422                    // schedules each group after its delay. Groups
1423                    // process sequentially in index order, each after
1424                    // its own delay (callbackRequestDelayed chain).
1425                    if grp.dly > 0.0 {
1426                        tokio::time::sleep(std::time::Duration::from_secs_f64(grp.dly)).await;
1427                    }
1428                    // Value: read from DOLn link, else the stored DOn
1429                    // value (linkGrp.dov) — C uses DOn as the value
1430                    // when DOLn is a constant/empty link.
1431                    let value = if !grp.dol.is_empty() {
1432                        let dol_parsed = crate::server::record::parse_link_v2(&grp.dol);
1433                        self.read_link_value(&dol_parsed, visited, depth).await
1434                    } else {
1435                        Some(EpicsValue::Double(grp.dov))
1436                    };
1437                    if let Some(value) = value {
1438                        // C `seqRecord.c:264` drives each LNKn via
1439                        // `dbPutLink`, whose `DBF_OUTLINK` target is
1440                        // processed by `dbDbPutValue` (`dbDbLink.c:388`)
1441                        // only when the link carries an explicit `PP`
1442                        // modifier. A bare `LNKn` is NPP — the value is
1443                        // written but the target is NOT processed.
1444                        // `parse_output_link_v2` applies that
1445                        // OUT-link-correct NPP default (the dfanout arm
1446                        // above open-codes the same downgrade).
1447                        // LNKn may be a local DB link or an external
1448                        // `ca://`/`pva://` link — C `dbPutLink` routes
1449                        // both through the link set's `putValue`
1450                        // (dbLink.c:434-448).
1451                        let lnk_parsed = crate::server::record::parse_output_link_v2(&grp.lnk);
1452                        self.write_out_link_value(&lnk_parsed, value, out_src, visited, depth)
1453                            .await;
1454                    }
1455                }
1456            }
1457        }
1458    }
1459
1460    /// Post the software event named by an `event` record's `VAL`.
1461    ///
1462    /// Mirrors C `eventRecord.c:120` `postEvent(prec->epvt)` — every
1463    /// `process()` of an event record posts its event, waking the
1464    /// `SCAN="Event"` records whose `EVNT` resolves to that name.
1465    /// No-op for any other record type, or when `VAL` is empty /
1466    /// resolves to event 0 (`eventNameToHandle` returns NULL).
1467    pub(crate) async fn dispatch_event_record(&self, rec: &Arc<RwLock<RecordInstance>>) {
1468        let event_name = {
1469            let instance = rec.read().await;
1470            if instance.record.record_type() != "event" {
1471                return;
1472            }
1473            match instance.record.get_field("VAL") {
1474                Some(EpicsValue::String(s)) => s.as_str_lossy().into_owned(),
1475                _ => return,
1476            }
1477        };
1478        if event_name.trim().is_empty() {
1479            return;
1480        }
1481        // C `postEvent` queues callbacks on the scan ring buffer —
1482        // the event-scanned records run on a separate callback thread,
1483        // NOT recursively inside this process cycle. Spawn the routed
1484        // post so a chain of event records cannot recurse unboundedly
1485        // and the current cycle's FLNK/CP dispatch is not blocked.
1486        let db = self.clone();
1487        crate::runtime::task::spawn(async move {
1488            db.post_event_named(&event_name).await;
1489        });
1490    }
1491
1492    /// Register a CP link: when source_record changes, process target_record.
1493    ///
1494    /// Both names are normalised to canonical form so the cp_links
1495    /// map's key/value always match the canonical record name that
1496    /// `dispatch_cp_targets` uses for lookup. Without this, a user
1497    /// who wrote `INP="ALIAS_NAME CP"` in their .db file would
1498    /// register the CP edge under the alias key and then never see
1499    /// the target processed (the source record's canonical-name
1500    /// dispatch would miss).
1501    /// `passive_only` is `true` for a CPP edge (process the target only when
1502    /// its `SCAN` is Passive) and `false` for CP (always process). When the
1503    /// same source→target edge is registered from both a CP and a CPP link,
1504    /// CP dominates: the merged edge keeps `passive_only == false`, matching
1505    /// C, where an unconditional CP `CA_DBPROCESS` overrides any CPP gate on
1506    /// the same record.
1507    pub async fn register_cp_link(
1508        &self,
1509        source_record: &str,
1510        target_record: &str,
1511        passive_only: bool,
1512    ) {
1513        let source = self
1514            .resolve_alias(source_record)
1515            .await
1516            .unwrap_or_else(|| source_record.to_string());
1517        let target = self
1518            .resolve_alias(target_record)
1519            .await
1520            .unwrap_or_else(|| target_record.to_string());
1521        let mut cp = self.inner.cp_links.write().await;
1522        let targets = cp.entry(source).or_default();
1523        if let Some(existing) = targets.iter_mut().find(|t| t.record == target) {
1524            existing.passive_only = existing.passive_only && passive_only;
1525        } else {
1526            targets.push(super::CpTarget {
1527                record: target,
1528                passive_only,
1529            });
1530        }
1531    }
1532
1533    /// Get target edges to process when `source_record` changes (CP/CPP links).
1534    pub async fn get_cp_targets(&self, source_record: &str) -> Vec<super::CpTarget> {
1535        self.inner
1536            .cp_links
1537            .read()
1538            .await
1539            .get(source_record)
1540            .cloned()
1541            .unwrap_or_default()
1542    }
1543
1544    /// Register an EXTERNAL CP/CPP link: when the remote PV `external_pv`
1545    /// (a cross-IOC CA/PVA source, e.g. `OTHER:PV` from
1546    /// `INP="OTHER:PV CP CA"`) changes, process `target_record`.
1547    ///
1548    /// Twin of [`Self::register_cp_link`] for cross-IOC sources. The key is
1549    /// the **scheme-stripped external PV name** — it is not a local record,
1550    /// so it is NOT alias-resolved. It MUST equal the name the calink/pvalink
1551    /// monitor dispatches under: that monitor is opened through the lset,
1552    /// which strips the `ca://` / `pva://` scheme first, so its `pv_name`
1553    /// (passed to [`Self::dispatch_external_cp_targets`]) is the bare PV.
1554    /// Stripping the same schemes here — the set [`Self::resolve_external_pv`]
1555    /// already knows — guarantees the registry key and the dispatch key can
1556    /// never diverge. The `target_record` (the local holder) IS alias-resolved
1557    /// so the dispatch processes the canonical record. CP dominates CPP on a
1558    /// merged edge, identical to the local path.
1559    pub async fn register_external_cp_link(
1560        &self,
1561        external_pv: &str,
1562        target_record: &str,
1563        passive_only: bool,
1564    ) {
1565        let key = external_pv
1566            .strip_prefix("ca://")
1567            .or_else(|| external_pv.strip_prefix("pva://"))
1568            .unwrap_or(external_pv);
1569        let target = self
1570            .resolve_alias(target_record)
1571            .await
1572            .unwrap_or_else(|| target_record.to_string());
1573        let mut cp = self.inner.external_cp_links.write().await;
1574        let targets = cp.entry(key.to_string()).or_default();
1575        if let Some(existing) = targets.iter_mut().find(|t| t.record == target) {
1576            existing.passive_only = existing.passive_only && passive_only;
1577        } else {
1578            targets.push(super::CpTarget {
1579                record: target,
1580                passive_only,
1581            });
1582        }
1583    }
1584
1585    /// Get holder edges to process when the remote PV `external_pv` changes
1586    /// (external CA/PVA CP/CPP links).
1587    pub async fn get_external_cp_targets(&self, external_pv: &str) -> Vec<super::CpTarget> {
1588        self.inner
1589            .external_cp_links
1590            .read()
1591            .await
1592            .get(external_pv)
1593            .cloned()
1594            .unwrap_or_default()
1595    }
1596
1597    /// Every external PV name that has at least one CP/CPP holder edge.
1598    /// The calink/pvalink integration warms (opens a monitor for) each of
1599    /// these at iocInit so the remote source has a live subscription whose
1600    /// callback can drive [`Self::dispatch_external_cp_targets`] — a Passive
1601    /// CP holder is otherwise never read and its monitor never opens.
1602    pub async fn external_cp_pv_names(&self) -> Vec<String> {
1603        self.inner
1604            .external_cp_links
1605            .read()
1606            .await
1607            .keys()
1608            .cloned()
1609            .collect()
1610    }
1611
1612    /// Classify one parsed CP/CPP link, deciding the local-vs-external
1613    /// routing — this method is the single owner of that decision, so the
1614    /// CP trigger registry and the holder's value-read parse cache stay
1615    /// consistent.
1616    ///
1617    /// A link with no CP/CPP policy (`cp_passive_only() == None`), and
1618    /// every non-`Db`/`Ca` variant, is ignored.
1619    ///
1620    /// `Ca`: an external `ca://OTHER CP` / `OTHER CP CA` holder always
1621    /// drives the cross-IOC path — C `dbCa.c` `eventCallback` adds
1622    /// `CA_DBPROCESS` for every CP link (`dbCa.c:993-994`).
1623    ///
1624    /// `Db`: C `dbInitLink` (`dbLink.c:118-130`) makes any link carrying a
1625    /// `CP`/`CPP`/`CA` option a CA link, and `dbDbInitLink` keeps it local
1626    /// only when the named record exists in this IOC. So a CP/CPP `Db`
1627    /// link whose target is NOT a local record (e.g. `INP="other:pv CP"`,
1628    /// no explicit `CA`) must be served externally — both the calink
1629    /// trigger monitor (`ext_links`) AND the holder's value read. The read
1630    /// half is the `convert_to_ca` entry: it carries the field name and an
1631    /// equivalent [`CaLink`] so the caller rewrites the holder's cached
1632    /// parse from `Db` to `Ca`, routing the read through the external
1633    /// resolver. A local target keeps the local fast-path (`db_links`).
1634    async fn classify_cp_link(
1635        &self,
1636        field: &str,
1637        parsed: crate::server::record::ParsedLink,
1638        target_name: &str,
1639        db_links: &mut Vec<(String, String, bool)>,
1640        ext_links: &mut Vec<(String, String, bool)>,
1641        convert_to_ca: &mut Vec<(String, crate::server::record::CaLink)>,
1642    ) {
1643        match parsed {
1644            crate::server::record::ParsedLink::Db(db) => {
1645                let Some(passive_only) = db.policy.cp_passive_only() else {
1646                    return;
1647                };
1648                if self.has_name_no_resolve(&db.record).await {
1649                    db_links.push((db.record, target_name.to_string(), passive_only));
1650                } else {
1651                    // Reconstruct the CA channel name verbatim: `record`
1652                    // for a default-`VAL` link, `record.FIELD` otherwise —
1653                    // the same string the `CA`-modifier path would store
1654                    // in `CaLink::pv`.
1655                    let pv = if db.field == "VAL" {
1656                        db.record.clone()
1657                    } else {
1658                        format!("{}.{}", db.record, db.field)
1659                    };
1660                    ext_links.push((pv.clone(), target_name.to_string(), passive_only));
1661                    convert_to_ca.push((
1662                        field.to_string(),
1663                        crate::server::record::CaLink {
1664                            pv,
1665                            monitor_switch: db.monitor_switch,
1666                            policy: db.policy,
1667                        },
1668                    ));
1669                }
1670            }
1671            crate::server::record::ParsedLink::Ca(ca) => {
1672                if let Some(passive_only) = ca.policy.cp_passive_only() {
1673                    ext_links.push((ca.pv, target_name.to_string(), passive_only));
1674                }
1675            }
1676            _ => {}
1677        }
1678    }
1679
1680    /// Scan all records for CP/CPP input links and register them. Local
1681    /// `Db` links land in the local CP registry; external `Ca` links land
1682    /// in the external CP registry, whose holders are processed by the
1683    /// calink monitor callback.
1684    pub async fn setup_cp_links(&self) {
1685        let names = self.all_record_names().await;
1686        let mut db_links: Vec<(String, String, bool)> = Vec::new();
1687        let mut ext_links: Vec<(String, String, bool)> = Vec::new();
1688
1689        for target_name in &names {
1690            // Enumerate this record's link-bearing fields through the
1691            // single shared owner (`record_link_fields`) so the CA CP/CPP
1692            // setup here and the pvalink install scan can never diverge on
1693            // which fields count as links. `classify_cp_link` keeps only
1694            // the CP/CPP-policy links, routes local `Db` vs external `Ca`,
1695            // and — for a CP/CPP `Db` link to a non-local target — emits a
1696            // `convert_to_ca` entry so the holder's value read is rewired
1697            // to the external resolver (C `dbLink.c:118-130`).
1698            let mut convert_to_ca: Vec<(String, crate::server::record::CaLink)> = Vec::new();
1699            for (field, _raw, parsed) in self.record_link_fields(target_name).await {
1700                self.classify_cp_link(
1701                    &field,
1702                    parsed,
1703                    target_name,
1704                    &mut db_links,
1705                    &mut ext_links,
1706                    &mut convert_to_ca,
1707                )
1708                .await;
1709            }
1710            // Apply the `Db`→`Ca` parse-cache rewrite for non-local CP/CPP
1711            // links so the holder reads its value through the external
1712            // resolver — consistent with the external CP trigger registered
1713            // above (both halves use the same locality decision made in
1714            // `classify_cp_link`). Only the common-field caches are
1715            // rewritten; INPA.. / DOL.. links are re-parsed from their raw
1716            // strings each process cycle and so are not covered here.
1717            if !convert_to_ca.is_empty() {
1718                if let Some(rec_arc) = self.get_record(target_name).await {
1719                    let mut inst = rec_arc.write().await;
1720                    for (field, calink) in convert_to_ca {
1721                        let link = crate::server::record::ParsedLink::Ca(calink);
1722                        match field.as_str() {
1723                            "INP" => inst.parsed_inp = link,
1724                            "OUT" => inst.parsed_out = link,
1725                            "TSEL" => inst.parsed_tsel = link,
1726                            "SDIS" => inst.parsed_sdis = link,
1727                            _ => {}
1728                        }
1729                    }
1730                }
1731            }
1732        }
1733
1734        let db_count = db_links.len();
1735        for (source, target, passive_only) in db_links {
1736            self.register_cp_link(&source, &target, passive_only).await;
1737        }
1738        let ext_count = ext_links.len();
1739        for (external_pv, target, passive_only) in ext_links {
1740            self.register_external_cp_link(&external_pv, &target, passive_only)
1741                .await;
1742        }
1743        if db_count > 0 {
1744            eprintln!("iocInit: {db_count} CP link subscriptions");
1745        }
1746        // Warm external CP/CPP links. A Passive holder of an external CP
1747        // link is never scanned, so its link never opens lazily and the
1748        // calink monitor that drives `dispatch_external_cp_targets` is never
1749        // created (chicken-and-egg). Open each external CP PV now so its
1750        // monitor is live at iocInit — the C `dbCa.c` "add the link at init"
1751        // analogue (`dbCaAddLink`). `resolve_external_pv` routes through the
1752        // registered lset's lazy-open path (the same path a record read
1753        // uses); a no-op when no matching lset is installed (calink off).
1754        if ext_count > 0 {
1755            let ext_pvs = self.external_cp_pv_names().await;
1756            for pv in &ext_pvs {
1757                let _ = self.resolve_external_pv(pv).await;
1758            }
1759            eprintln!(
1760                "iocInit: {ext_count} external CP link subscriptions ({} PVs warmed)",
1761                ext_pvs.len()
1762            );
1763        }
1764    }
1765}
1766
1767#[cfg(test)]
1768mod out_link_put_fail_tests {
1769    use super::{LinkAlarm, OutLinkSrc};
1770    use crate::server::database::PvDatabase;
1771    use crate::server::record::{AlarmSeverity, DbLink, LinkProcessPolicy, MonitorSwitch};
1772    use crate::server::records::calc::CalcRecord;
1773    use crate::types::EpicsValue;
1774    use std::collections::HashSet;
1775
1776    /// C `dbDbPutValue` (dbDbLink.c:382-390) runs `dbPut`, folds the
1777    /// source alarm via `recGblInheritSevrMsg`, then `if (status) return
1778    /// status;` — only a *successful* write reaches the `.PROC`/`PP`
1779    /// `processTarget` branch. A failed OUT-link write must therefore NOT
1780    /// process the target. Here the write is an empty array into a scalar
1781    /// field, which `put_pv_already_locked` rejects with `InvalidValue`
1782    /// (the C dbPut nRequest=0 empty-array guard, field_io.rs).
1783    ///
1784    /// Observable: a passive `calc` target with `CALC = "7"` evaluates to
1785    /// `VAL = 7` on process and stays at its `Default` `VAL = 0` when not
1786    /// processed. The PP OUT link below carries a value the write
1787    /// rejects, so the fixed code returns before `processTarget` and
1788    /// `VAL` stays `0.0`; the pre-fix code processed the target
1789    /// unconditionally and `VAL` would become `7.0`.
1790    #[tokio::test]
1791    async fn pp_out_link_failed_write_does_not_process_target() {
1792        let db = PvDatabase::new();
1793        db.add_record("TGT", Box::new(CalcRecord::new("7")))
1794            .await
1795            .unwrap();
1796
1797        // Precondition: CALC not yet evaluated, VAL at its Default 0.0.
1798        assert!(
1799            matches!(db.get_pv("TGT.VAL").await.unwrap(), EpicsValue::Double(v) if v == 0.0),
1800            "calc VAL must start at its Default 0.0 before any process"
1801        );
1802
1803        let link = DbLink {
1804            record: "TGT".to_string(),
1805            field: "VAL".to_string(),
1806            policy: LinkProcessPolicy::ProcessPassive, // ` PP` token
1807            monitor_switch: MonitorSwitch::NoMaximize,
1808        };
1809        let alarm = LinkAlarm {
1810            stat: 0,
1811            sevr: AlarmSeverity::NoAlarm,
1812            amsg: String::new(),
1813        };
1814        let src = OutLinkSrc {
1815            putf: false,
1816            notify: None,
1817            alarm: &alarm,
1818        };
1819        let mut visited = HashSet::new();
1820
1821        // Empty array into the scalar VAL field: put_pv_already_locked
1822        // returns Err(InvalidValue) per the field_io.rs empty-array guard.
1823        db.write_db_link_value(&link, EpicsValue::DoubleArray(vec![]), src, &mut visited, 0)
1824            .await;
1825
1826        // Fixed: the failed write short-circuits before processTarget,
1827        // so CALC was never evaluated and VAL is still its Default 0.0.
1828        // Pre-fix: the target processed and VAL would be 7.0.
1829        assert!(
1830            matches!(db.get_pv("TGT.VAL").await.unwrap(), EpicsValue::Double(v) if v == 0.0),
1831            "a failed OUT-link write must NOT process the PP target \
1832             (VAL must stay 0.0, not become 7.0)"
1833        );
1834    }
1835}
1836
1837#[cfg(test)]
1838mod nonlocal_db_link_write_tests {
1839    use super::OutLinkSrc;
1840    use crate::server::database::{LinkPutOp, LinkSet, PvDatabase};
1841    use crate::server::record::{AlarmSeverity, DbLink, LinkProcessPolicy, MonitorSwitch};
1842    use crate::server::records::calc::CalcRecord;
1843    use crate::types::EpicsValue;
1844    use std::collections::HashSet;
1845    use std::sync::{Arc, Mutex};
1846
1847    /// A link set that records every `put_value` it receives so a test
1848    /// can assert a non-local OUT-link write reached the external (CA)
1849    /// put path instead of being dropped by a local `dbPut`.
1850    struct RecordingLset {
1851        puts: Arc<Mutex<Vec<(String, EpicsValue)>>>,
1852    }
1853    impl LinkSet for RecordingLset {
1854        fn is_connected(&self, _: &str) -> bool {
1855            true
1856        }
1857        fn get_value(&self, _: &str) -> Option<EpicsValue> {
1858            None
1859        }
1860        fn put_value(&self, name: &str, value: EpicsValue, _op: LinkPutOp) -> Result<(), String> {
1861            self.puts.lock().unwrap().push((name.to_string(), value));
1862            Ok(())
1863        }
1864    }
1865
1866    fn out_src(alarm: &super::LinkAlarm) -> OutLinkSrc<'_> {
1867        OutLinkSrc {
1868            putf: false,
1869            notify: None,
1870            alarm,
1871        }
1872    }
1873
1874    fn no_alarm() -> super::LinkAlarm {
1875        super::LinkAlarm {
1876            stat: 0,
1877            sevr: AlarmSeverity::NoAlarm,
1878            amsg: String::new(),
1879        }
1880    }
1881
1882    /// A plain OUT link whose target record is NOT local must write
1883    /// through the external put path — C `dbPutLink` routes a non-local
1884    /// (CA) link's write to `dbCaPutLink`, never a local `dbPut`. The
1885    /// pre-fix code called `put_pv_already_locked` on a name that does
1886    /// not exist locally; the write was silently dropped. The recording
1887    /// lset must now capture the value.
1888    #[tokio::test]
1889    async fn nonlocal_db_out_link_writes_through_external_put() {
1890        let db = PvDatabase::new();
1891        let puts = Arc::new(Mutex::new(Vec::new()));
1892        db.register_link_set("ca", Arc::new(RecordingLset { puts: puts.clone() }))
1893            .await;
1894
1895        // "OTHER:PV" is never added as a local record -> non-local.
1896        let link = DbLink {
1897            record: "OTHER:PV".to_string(),
1898            field: "VAL".to_string(),
1899            policy: LinkProcessPolicy::NoProcess,
1900            monitor_switch: MonitorSwitch::NoMaximize,
1901        };
1902        let alarm = no_alarm();
1903        let mut visited = HashSet::new();
1904        db.write_db_link_value(
1905            &link,
1906            EpicsValue::Double(42.0),
1907            out_src(&alarm),
1908            &mut visited,
1909            0,
1910        )
1911        .await;
1912
1913        let captured = puts.lock().unwrap();
1914        assert_eq!(
1915            captured.len(),
1916            1,
1917            "non-local OUT-link write must reach the external put path exactly once"
1918        );
1919        assert_eq!(captured[0].0, "OTHER:PV");
1920        assert!(matches!(captured[0].1, EpicsValue::Double(v) if v == 42.0));
1921    }
1922
1923    /// A local OUT-link write must NOT divert to the external put path —
1924    /// the locality dispatch only reroutes non-local targets. The local
1925    /// record receives the value; the lset records nothing.
1926    #[tokio::test]
1927    async fn local_db_out_link_writes_local_not_external() {
1928        let db = PvDatabase::new();
1929        let puts = Arc::new(Mutex::new(Vec::new()));
1930        db.register_link_set("ca", Arc::new(RecordingLset { puts: puts.clone() }))
1931            .await;
1932        db.add_record("TGT", Box::new(CalcRecord::new("0")))
1933            .await
1934            .unwrap();
1935
1936        let link = DbLink {
1937            record: "TGT".to_string(),
1938            field: "VAL".to_string(),
1939            policy: LinkProcessPolicy::NoProcess,
1940            monitor_switch: MonitorSwitch::NoMaximize,
1941        };
1942        let alarm = no_alarm();
1943        let mut visited = HashSet::new();
1944        db.write_db_link_value(
1945            &link,
1946            EpicsValue::Double(7.0),
1947            out_src(&alarm),
1948            &mut visited,
1949            0,
1950        )
1951        .await;
1952
1953        assert!(
1954            puts.lock().unwrap().is_empty(),
1955            "a local OUT-link write must not reach the external put path"
1956        );
1957        assert!(
1958            matches!(db.get_pv("TGT.VAL").await.unwrap(), EpicsValue::Double(v) if v == 7.0),
1959            "the local target must hold the written value"
1960        );
1961    }
1962
1963    /// A link set that records every `scan_forward` it receives so a test
1964    /// can assert a non-DB FLNK reached the external forward path
1965    /// (C `dbScanFwdLink` → `lset->scanForward`) instead of being dropped
1966    /// by the DB-only `flnk_name` filter. `connected=false` models a
1967    /// disconnected link (pvxs `pvaScanForward`'s `!valid()` gate).
1968    struct ForwardingLset {
1969        forwards: Arc<Mutex<Vec<String>>>,
1970        connected: bool,
1971    }
1972    impl LinkSet for ForwardingLset {
1973        fn is_connected(&self, _: &str) -> bool {
1974            self.connected
1975        }
1976        fn get_value(&self, _: &str) -> Option<EpicsValue> {
1977            None
1978        }
1979        fn scan_forward(&self, name: &str) -> Result<(), String> {
1980            self.forwards.lock().unwrap().push(name.to_string());
1981            if self.connected {
1982                Ok(())
1983            } else {
1984                Err("Disconn".into())
1985            }
1986        }
1987    }
1988
1989    /// `scan_forward_external_pv` must resolve the scheme and delegate to
1990    /// the registered lset's `scan_forward` — the FWD-link twin of
1991    /// `write_external_pv` for OUT writes (C `dbScanFwdLink` →
1992    /// `lset->scanForward`).
1993    #[tokio::test]
1994    async fn external_forward_link_dispatches_through_scan_forward() {
1995        let db = PvDatabase::new();
1996        let forwards = Arc::new(Mutex::new(Vec::new()));
1997        db.register_link_set(
1998            "pva",
1999            Arc::new(ForwardingLset {
2000                forwards: forwards.clone(),
2001                connected: true,
2002            }),
2003        )
2004        .await;
2005
2006        db.scan_forward_external_pv("pva://OTHER:PROC")
2007            .await
2008            .expect("a connected forward must succeed");
2009
2010        let captured = forwards.lock().unwrap();
2011        assert_eq!(captured.len(), 1);
2012        assert_eq!(captured[0], "OTHER:PROC");
2013    }
2014
2015    /// End-to-end: a record whose FLNK targets an external `pva://` PV
2016    /// must fire the link set's `scan_forward` when it processes — the
2017    /// non-DB FLNK dispatch the DB-only `flnk_name` filter previously
2018    /// dropped. C `recGblFwdLink` runs `dbScanFwdLink` for every FLNK
2019    /// regardless of link kind.
2020    #[tokio::test]
2021    async fn record_processing_fires_external_forward_link() {
2022        let db = PvDatabase::new();
2023        let forwards = Arc::new(Mutex::new(Vec::new()));
2024        db.register_link_set(
2025            "pva",
2026            Arc::new(ForwardingLset {
2027                forwards: forwards.clone(),
2028                connected: true,
2029            }),
2030        )
2031        .await;
2032        db.add_record("SRC", Box::new(CalcRecord::new("0")))
2033            .await
2034            .unwrap();
2035        if let Some(rec) = db.get_record("SRC").await {
2036            let mut inst = rec.write().await;
2037            inst.put_common_field("FLNK", EpicsValue::String("pva://TARGET".into()))
2038                .unwrap();
2039        }
2040
2041        let mut visited = HashSet::new();
2042        db.process_record_with_links("SRC", &mut visited, 0)
2043            .await
2044            .unwrap();
2045
2046        let captured = forwards.lock().unwrap();
2047        assert_eq!(
2048            captured.len(),
2049            1,
2050            "an external pva:// FLNK must fire scan_forward exactly once"
2051        );
2052        assert_eq!(captured[0], "TARGET");
2053    }
2054
2055    /// A disconnected non-retry external FLNK is NOT dropped silently: the
2056    /// lset returns Err and the owning record takes a *pending*
2057    /// LINK/INVALID alarm — pvxs `pvaScanForward`'s
2058    /// `recGblSetSevrMsg(LINK_ALARM, INVALID_ALARM, "Disconn")`, which
2059    /// writes `nsta`/`nsev`/`namsg` (promoted by the next
2060    /// `recGblResetAlarms`, matching the C late-set inside `recGblFwdLink`).
2061    #[tokio::test]
2062    async fn disconnected_external_forward_link_raises_pending_link_invalid() {
2063        let db = PvDatabase::new();
2064        let forwards = Arc::new(Mutex::new(Vec::new()));
2065        db.register_link_set(
2066            "pva",
2067            Arc::new(ForwardingLset {
2068                forwards: forwards.clone(),
2069                connected: false,
2070            }),
2071        )
2072        .await;
2073        db.add_record("SRC", Box::new(CalcRecord::new("0")))
2074            .await
2075            .unwrap();
2076        if let Some(rec) = db.get_record("SRC").await {
2077            let mut inst = rec.write().await;
2078            inst.put_common_field("FLNK", EpicsValue::String("pva://TARGET".into()))
2079                .unwrap();
2080        }
2081
2082        let mut visited = HashSet::new();
2083        db.process_record_with_links("SRC", &mut visited, 0)
2084            .await
2085            .unwrap();
2086
2087        assert_eq!(
2088            forwards.lock().unwrap().len(),
2089            1,
2090            "scan_forward is still attempted on a disconnected link"
2091        );
2092        let rec = db.get_record("SRC").await.unwrap();
2093        let inst = rec.read().await;
2094        assert_eq!(inst.common.nsev, AlarmSeverity::Invalid);
2095        assert_eq!(
2096            inst.common.nsta,
2097            crate::server::recgbl::alarm_status::LINK_ALARM
2098        );
2099        assert_eq!(inst.common.namsg, "Disconn");
2100    }
2101}
2102
2103#[cfg(test)]
2104mod cp_link_locality_tests {
2105    use crate::server::database::PvDatabase;
2106    use crate::server::record::ParsedLink;
2107    use crate::server::records::ai::AiRecord;
2108
2109    /// A CP/CPP link with no explicit `CA` modifier whose target is NOT a
2110    /// local record must be served as an external (CA) link — both the
2111    /// trigger and the value read. C `dbInitLink` (`dbLink.c:118-130`)
2112    /// makes any `CP`/`CPP` link a CA link, and `dbDbInitLink` keeps it
2113    /// local only when the named record exists in this IOC.
2114    ///
2115    /// Here `INP="OTHER:PV CP"` parses to `ParsedLink::Db` (bare name, no
2116    /// `CA`), but `OTHER:PV` is not local. After `setup_cp_links` the
2117    /// holder's `parsed_inp` must be rewritten to `ParsedLink::Ca` (so the
2118    /// read routes through `resolve_external_pv`) and `OTHER:PV` must be
2119    /// registered as an external CP trigger.
2120    #[tokio::test]
2121    async fn cp_link_to_nonlocal_target_forced_external() {
2122        let db = PvDatabase::new();
2123        db.add_record("HOLDER", Box::new(AiRecord::new(0.0)))
2124            .await
2125            .unwrap();
2126        {
2127            let rec = db.get_record("HOLDER").await.unwrap();
2128            rec.write().await.common.inp = "OTHER:PV CP".to_string();
2129        }
2130
2131        db.setup_cp_links().await;
2132
2133        let inp = db
2134            .get_record("HOLDER")
2135            .await
2136            .unwrap()
2137            .read()
2138            .await
2139            .parsed_inp
2140            .clone();
2141        match inp {
2142            ParsedLink::Ca(ca) => assert_eq!(
2143                ca.pv, "OTHER:PV",
2144                "non-local CP link must carry the verbatim PV name"
2145            ),
2146            other => panic!("non-local CP link must be forced to Ca, got {other:?}"),
2147        }
2148        assert!(
2149            db.external_cp_pv_names()
2150                .await
2151                .contains(&"OTHER:PV".to_string()),
2152            "non-local CP link must be registered as an external CP trigger"
2153        );
2154    }
2155
2156    /// A CP link whose target IS a local record keeps the local fast-path:
2157    /// `setup_cp_links` must NOT rewrite its `parsed_inp` to `Ca` and must
2158    /// NOT register it as an external CP link.
2159    #[tokio::test]
2160    async fn cp_link_to_local_target_stays_db() {
2161        let db = PvDatabase::new();
2162        db.add_record("SRC", Box::new(AiRecord::new(1.0)))
2163            .await
2164            .unwrap();
2165        db.add_record("HOLDER", Box::new(AiRecord::new(0.0)))
2166            .await
2167            .unwrap();
2168        {
2169            let rec = db.get_record("HOLDER").await.unwrap();
2170            let mut inst = rec.write().await;
2171            inst.common.inp = "SRC CP".to_string();
2172            // Seed the parse cache as load would, so the assertion proves
2173            // setup_cp_links leaves a local CP link untouched.
2174            inst.parsed_inp = crate::server::record::parse_link_v2("SRC CP");
2175        }
2176
2177        db.setup_cp_links().await;
2178
2179        let inp = db
2180            .get_record("HOLDER")
2181            .await
2182            .unwrap()
2183            .read()
2184            .await
2185            .parsed_inp
2186            .clone();
2187        assert!(
2188            matches!(inp, ParsedLink::Db(_)),
2189            "local CP link must stay a Db link, got {inp:?}"
2190        );
2191        assert!(
2192            !db.external_cp_pv_names().await.contains(&"SRC".to_string()),
2193            "a local CP target must not be registered as an external CP link"
2194        );
2195    }
2196}
2197
2198#[cfg(test)]
2199mod nonlocal_db_link_read_tests {
2200    use crate::server::database::PvDatabase;
2201    use crate::server::record::{ParsedLink, parse_link_v2};
2202    use crate::types::EpicsValue;
2203    use std::collections::HashSet;
2204    use std::sync::Arc;
2205
2206    /// C `dbInitLink` (`dbLink.c:118-130`) makes a PV link whose target is
2207    /// not a local record a CA link — even with NO `CP`/`CPP`/`CA`
2208    /// modifier (`dbDbInitLink` fails to resolve it locally and falls
2209    /// through to `dbCaAddLinkCallbackOpt`). So a plain `INP="OTHER:PV"`
2210    /// to a non-local target must read the remote value, not return
2211    /// `None`. Pre-fix the `Db` read arm read only the local DB (`get_pv`)
2212    /// and dropped the non-local target.
2213    #[tokio::test]
2214    async fn plain_nonlocal_db_link_reads_via_external_resolver() {
2215        let db = PvDatabase::new();
2216        // Stand-in for the calink/pvalink lset: resolve OTHER:PV remotely.
2217        db.set_external_resolver(Arc::new(|name: &str| {
2218            if name == "OTHER:PV" {
2219                Some(EpicsValue::Double(42.0))
2220            } else {
2221                None
2222            }
2223        }))
2224        .await;
2225
2226        let link = parse_link_v2("OTHER:PV");
2227        assert!(
2228            matches!(link, ParsedLink::Db(_)),
2229            "a bare non-scheme name parses to a Db link, got {link:?}"
2230        );
2231
2232        let mut visited = HashSet::new();
2233        let v = db.read_link_value(&link, &mut visited, 0).await;
2234        assert_eq!(
2235            v,
2236            Some(EpicsValue::Double(42.0)),
2237            "a plain non-local Db link must resolve through the external resolver (C dbCaAddLink fallback)"
2238        );
2239    }
2240
2241    /// A multi-input-style link re-parsed from its raw string each cycle
2242    /// (calc `INPA`..`INPL`, `DOL`) routes its value read through
2243    /// `read_link_with_alarm`; the same locality rule must hold there, so
2244    /// a non-local target reads the remote value and surfaces no
2245    /// local-record alarm.
2246    #[tokio::test]
2247    async fn nonlocal_db_link_value_and_alarm_via_external() {
2248        let db = PvDatabase::new();
2249        db.set_external_resolver(Arc::new(|name: &str| {
2250            if name == "OTHER:PV" {
2251                Some(EpicsValue::Double(5.0))
2252            } else {
2253                None
2254            }
2255        }))
2256        .await;
2257
2258        let link = parse_link_v2("OTHER:PV");
2259        let (value, alarm) = db.read_link_with_alarm(&link).await;
2260        assert_eq!(
2261            value,
2262            Some(EpicsValue::Double(5.0)),
2263            "non-local Db link value must come from the external resolver"
2264        );
2265        // No lset is registered (only the legacy resolver), so the bare
2266        // external alarm path reports None — never a fabricated local
2267        // record alarm for a record that does not exist in this IOC.
2268        assert!(
2269            alarm.is_none(),
2270            "non-local Db link must not fabricate a local-record alarm, got {alarm:?}"
2271        );
2272    }
2273
2274    /// Owner path: a Db link whose target IS a local record still reads
2275    /// the local database and never consults the external resolver.
2276    #[tokio::test]
2277    async fn local_db_link_reads_local_not_external() {
2278        let db = PvDatabase::new();
2279        db.add_pv("SRC", EpicsValue::Double(7.0)).await.unwrap();
2280        // A resolver returning a DIFFERENT value proves the local read
2281        // wins and the external path is not taken for a local target.
2282        db.set_external_resolver(Arc::new(|_name: &str| Some(EpicsValue::Double(-1.0))))
2283            .await;
2284
2285        let link = parse_link_v2("SRC");
2286        let mut visited = HashSet::new();
2287        let v = db.read_link_value(&link, &mut visited, 0).await;
2288        assert_eq!(
2289            v,
2290            Some(EpicsValue::Double(7.0)),
2291            "a local Db link must read the local DB, not the external resolver"
2292        );
2293    }
2294}