Skip to main content

epics_base_rs/server/database/
field_io.rs

1use std::collections::HashSet;
2
3use crate::error::{CaError, CaResult};
4use crate::server::snapshot::Snapshot;
5use crate::types::EpicsValue;
6
7use super::PvDatabase;
8
9/// C `dbPutField`'s put-disable gate (`dbAccess.c:1255-1257`):
10/// `precord->disp && paddr->pfield != &precord->disp` → `S_db_putDisabled`.
11///
12/// This is the FIRST gate an *external* put crosses. It precedes `dbPut` —
13/// so it precedes the `SPC_NOMOD` rejection of PACT/LCNT/PUTF — and it
14/// precedes the PROC-driven `dbProcess` (`dbAccess.c:1265-1277`), so
15/// `caput REC.PROC 1` on a `DISP=1` record is refused, not force-processed.
16///
17/// Single owner for both external put boundaries: the CA / `dbpf` route
18/// ([`PvDatabase::put_record_field_from_ca`]) and the QSRV precondition
19/// check ([`PvDatabase::check_external_put_preconditions`]). Internal puts
20/// (`put_pv`, link and processing writes — the `dbPut` analogue) deliberately
21/// do not cross it.
22fn check_put_disabled(
23    instance: &crate::server::record::RecordInstance,
24    field_upper: &str,
25) -> CaResult<()> {
26    if instance.common.disp != 0 && field_upper != "DISP" {
27        return Err(CaError::PutDisabled(field_upper.to_string()));
28    }
29    Ok(())
30}
31
32/// C's `dbPut` no-modify gate — the put-side consumer of the SPC_NOMOD
33/// declaration.
34///
35/// Two C rejections, both inside `dbPut` and therefore BELOW every put entry
36/// point (`dbPutField` for CA/`dbpf`, `dbPutLink` for a record's OUT link,
37/// `dbPutSpecial` for an internal one):
38///
39/// ```c
40/// /* dbAccess.c:1330-1332 */
41/// if (special == SPC_ATTRIBUTE) return S_db_noMod;
42/// /* dbAccess.c:123-126, via dbPut -> dbPutSpecial(paddr, 0) */
43/// if ((special == SPC_NOMOD) && (pass == 0)) return S_db_noMod;
44/// ```
45///
46/// INVARIANT: a field declared `special(SPC_NOMOD)` (or `SPC_ATTRIBUTE`) MUST
47/// NOT be modified by ANY runtime write, whatever route it arrives on — CA put,
48/// `dbpf`, QSRV, an internal `put_pv`, or a record's OUT link. A record's own
49/// `put_field` is NOT a gate: the hand-written array records write
50/// NELM/FTVL/NORD there because the *load* path (`dbLoadRecords` →
51/// `Record::put_field`) must set them — C likewise writes them through
52/// `dbStaticLib`'s `dbPutString`, which never crosses `dbPut`.
53///
54/// The declaration itself lives in [`RecordInstance::is_no_mod`], which C
55/// exposes as `dbChannelSpecial(...) == SPC_NOMOD` and reads from TWO places:
56/// this gate (`dbPut`, dbAccess.c:123-126) and `rsrvCheckPut`
57/// (camessage.c:2540-2551), which feeds the CA ACCESS_RIGHTS write bit. This
58/// function is the first consumer; `epics-ca-rs`'s `compute_access` is the
59/// second.
60///
61/// The one thing that legitimately changes ACKS/ACKT is C's alarm
62/// acknowledgement, and it does NOT come through here: `dbPut` dispatches on the
63/// DBR *request type* (`DBR_PUT_ACKT`/`DBR_PUT_ACKS`, `dbAccess.c:1331-1335`)
64/// ABOVE this gate, into [`RecordInstance::put_ackt`] /
65/// [`RecordInstance::put_acks`]. The wire route for that is
66/// [`PvDatabase::put_alarm_ack_from_ca`].
67///
68/// `field` must already be upper-cased.
69fn check_no_mod(instance: &crate::server::record::RecordInstance, field: &str) -> CaResult<()> {
70    if instance.is_no_mod(field) {
71        return Err(CaError::ReadOnlyField(field.to_string()));
72    }
73    Ok(())
74}
75
76/// Does an *external* put to `field` drive a processing cycle on this record?
77///
78/// C `dbPutField` (`dbAccess.c:1263-1268`) and pvxs `IOCSource::
79/// doPostProcessing` (`iocsource.cpp:397-403`) ask the same question with the
80/// same terms as C `processNotifyCommon` (dbNotify.c:243-246): the `PROC` field
81/// always, else a `pp(TRUE)` field on a Passive record. (`dbrType <
82/// DBR_PUT_ACKT` is subsumed: the alarm-ack fields are not `pp(TRUE)`.) A caller
83/// that FORCES processing (`record._options.process=true`) does not consult this
84/// at all — force is the caller's own term, not the record's.
85///
86/// `PROC` and `UDF` are the ONLY two `dbCommon` `pp(TRUE)` fields
87/// (`dbCommon.dbd.pod`: PROC line 243, UDF line 552); every other `pp(TRUE)`
88/// field is declared per record TYPE and reached through
89/// [`Record::processes_after_put`]. Because the two `dbCommon` fields are NOT in
90/// any type's `process_passive_fields()` table, they are named here directly:
91/// `PROC` unconditionally (force-process on any SCAN), `UDF` on the Passive
92/// branch (an ordinary `pp` field, so it processes only when `SCAN == 0`, unlike
93/// PROC). Both `dbCommon` `pp(TRUE)` fields are thus handled at this one owner
94/// gate, uniformly for every record type. A put to UDF is accepted+stored by
95/// `put_common_field`; this gate only adds the process cycle, after which the
96/// record recomputes alarms → NO_ALARM (C ends STAT/SEVR=NO_ALARM likewise).
97///
98/// Single owner of the rule: the single-record put route
99/// ([`PvDatabase::put_record_field_from_ca`]) tests it while it already holds
100/// the instance, and the QSRV group PUT — whose C twin is `doPostProcessing` —
101/// reaches it through [`PvDatabase::put_drives_processing`]. Neither can drift
102/// from C or from the other.
103///
104/// `field` must already be upper-cased.
105pub(crate) fn put_drives_processing_of(
106    instance: &crate::server::record::RecordInstance,
107    field: &str,
108) -> bool {
109    field == "PROC"
110        || (instance.common.scan == crate::server::record::ScanType::Passive
111            && (field == "UDF" || instance.record.processes_after_put(field)))
112}
113
114/// Drain the record's per-cycle post marks ([`Record::take_cycle_posted_fields`])
115/// into monitor posts — the put-path counterpart of the `db_post_events` calls a
116/// C `special()` makes by hand.
117///
118/// One owner, so the two put-path drains (the normal tail, and the failing
119/// `special()` above) cannot disagree about the mask mapping.
120fn emit_cycle_posts(instance: &mut crate::server::record::RecordInstance) {
121    use crate::server::record::{CyclePostMask, EventMask};
122    for (sf, cycle_mask) in instance.record.take_cycle_posted_fields() {
123        let mask = match cycle_mask {
124            CyclePostMask::Value => EventMask::VALUE,
125            // No `monitor_mask` exists on a put path (no alarm transition is
126            // being resolved), so both LOG-carrying variants reduce to C's
127            // literal `DBE_VALUE|DBE_LOG`.
128            CyclePostMask::ValueLog | CyclePostMask::MonitorValueLog => {
129                EventMask::VALUE | EventMask::LOG
130            }
131        };
132        instance.notify_field(sf, mask);
133    }
134}
135
136/// C `dbPutSpecial(paddr, 1)` — the after-put `special()`, paired with the drain
137/// of the link writes it queued ([`Record::take_special_actions`]).
138///
139/// The pairing is the point: `special()` and its drain are ONE step, so a queued
140/// action cannot survive the put that queued it — not even when `special()`
141/// returns an error (C's `dbPut` `goto done`), because the drain happens before
142/// the status is propagated. The caller executes `out` once the record lock is
143/// released, ahead of the put-driven process cycle, which is where C runs it
144/// (inside `dbPut`, before `dbPutField`'s `dbProcess`).
145///
146/// Every `dbPut` path in this module goes through here; nothing else may call
147/// `Record::special(field, true)`.
148///
149/// Returns the scan-index delta the after-put pass produced — non-`NoChange`
150/// only for the SIMM↔SSCN swap below, which the caller applies through
151/// `update_scan_index` once the record lock is down.
152fn special_after_put(
153    instance: &mut crate::server::record::RecordInstance,
154    field: &str,
155    out: &mut Vec<crate::server::record::ProcessAction>,
156) -> CaResult<crate::server::record::CommonFieldPutResult> {
157    let status = instance.record.special(field, true);
158    out.extend(instance.record.take_special_actions());
159    if status.is_err() {
160        // The POSTS `special()` made are drained on the failing path for the same
161        // reason its ACTIONS are: C's `special()` calls `db_post_events` BEFORE it
162        // returns nonzero — aCalcout's NUSE arm posts the clamped value with
163        // `DBE_VALUE` and only then `return (-1)` (`aCalcoutRecord.c:495-499`) —
164        // and `dbPut`'s `goto done` skips only dbPut's OWN post. A refused put
165        // that repaired a field must still tell the subscribers what it repaired.
166        emit_cycle_posts(instance);
167    }
168    status?;
169
170    // C `special()`'s CONSTANT-link re-seed (`calcoutRecord.c:367-378`,
171    // `sCalcoutRecord.c:512-517`, `aCalcoutRecord.c:534-540`,
172    // `transformRecord.c:714-719` — the four records whose C `special()` calls
173    // `recGblInitConstantLink`): a put that leaves an input link constant
174    // re-runs the load into that input's value field and posts it. Without it a
175    // constant link is load-once dead state — the link layer delivers nothing
176    // for a constant at process time, so `caput CO.INPB 7` would store the text
177    // and leave `B` at its `.db` value forever.
178    //
179    // The record only DECLARES the pairs (`special_reseed_input_links`); the
180    // load itself is the shared `rec_gbl_init_constant_link` owner, the same one
181    // the init seed uses. Records whose C `special()` does not re-seed (calc,
182    // sub, sel, aSub, swait, …) declare nothing and are untouched.
183    if let Some(value_field) =
184        crate::server::record::reseed_constant_input_link(&mut *instance.record, field)
185    {
186        // The mask is the C call site's, and they disagree — calcout posts a
187        // literal DBE_VALUE, transform DBE_VALUE|DBE_LOG. The record carries it.
188        let mask = instance.record.special_reseed_post_mask();
189        instance.notify_field(value_field, mask);
190    }
191
192    // C `special(SPC_MOD)` pass 1 on SIMM (`longinRecord.c:171-177` and the
193    // identical arm in all 21 SSCN-bearing records):
194    //   `recGblCheckSimm((dbCommon *)prec, &prec->sscn, prec->oldsimm, prec->simm);`
195    // Paired with `special_before_put`'s pass 0 (`recGblSaveSimm`), and gated
196    // per record type by `Record::uses_recgbl_simm_helpers`.
197    Ok(if field == "SIMM" {
198        instance.rec_gbl_check_simm()
199    } else {
200        crate::server::record::CommonFieldPutResult::NoChange
201    })
202}
203
204/// C `dbPutSpecial(paddr, 0)` — the before-put pass, run while the record lock
205/// is held and BEFORE the field's new value is stored.
206///
207/// The only `SPC_MOD` field in the record framework whose pass-0 does work is
208/// SIMM: `recGblSaveSimm` latches the outgoing simulation mode into OLDSIMM so
209/// the after-put pass can see the transition. Paired with
210/// [`special_after_put`]; every `dbPut` path in this module calls both.
211fn special_before_put(instance: &mut crate::server::record::RecordInstance, field: &str) {
212    if field == "SIMM" {
213        instance.rec_gbl_save_simm();
214    }
215}
216
217/// The `recGblResetAlarms` half of a C `monitor()` that a `special()` invokes
218/// (compress SPC_RESET, [`crate::server::record::Record::special_commits_alarms`]).
219///
220/// C's `monitor()` opens with `recGblResetAlarms(prec)` (compressRecord.c:103),
221/// committing `nsta`/`nsev` into `stat`/`sevr` — this is what clears the
222/// born-UDF alarm of a never-processed record the moment a reset field is put.
223/// Commits the alarm, posts any STAT/SEVR/AMSG/ACKS transition through the one
224/// owner ([`crate::server::database::processing::alarm_field_posts`]), and
225/// returns the `DBE_ALARM` mask C ORs into the value posts (`val_mask`,
226/// recGbl.c:213 — set iff any alarm-class field moved this cycle).
227///
228/// Shared by `dbPut`'s success tail and its rejected-conversion path: C runs
229/// `dbPutSpecial(paddr, 1)` on BOTH (dbAccess.c:83-88, "Always do special
230/// processing if needed", before the `goto done` that bails on a failed put).
231fn commit_special_reset_alarm(
232    instance: &mut crate::server::record::RecordInstance,
233) -> crate::server::recgbl::EventMask {
234    use crate::server::recgbl::EventMask;
235    let alarm_result = crate::server::recgbl::rec_gbl_reset_alarms(&mut instance.common);
236    for (af, mask) in
237        crate::server::database::processing::alarm_field_posts(&instance.common, &alarm_result)
238    {
239        instance.notify_field(af, mask);
240    }
241    if alarm_result.alarm_changed || alarm_result.amsg_changed {
242        EventMask::ALARM
243    } else {
244        EventMask::NONE
245    }
246}
247
248/// Coerce a write `value` to a record field's stored `target` type — C
249/// `dbConvert.c`'s `dbFastPutConvertRoutine[dbrType][field_type]` table.
250///
251/// The client-`dbPut` half of the shared converter
252/// [`crate::server::record::coerce_put_value`]; the internal-delivery half is
253/// `put_field_internal_default`. A `DBR_STRING` write to a `DBF_MENU` or
254/// `DBF_ENUM` field has a converter of its own in C (`putStringMenu`,
255/// `putStringEnum`) and must not fall through to `EpicsValue::convert_to`,
256/// which is field-blind and turns any unrecognised string into index 0 —
257/// C stores nothing and fails the put with `S_db_badChoice`.
258fn coerce_write_value(
259    record: &dyn crate::server::record::Record,
260    field: &str,
261    target: crate::types::DbFieldType,
262    value: EpicsValue,
263) -> CaResult<EpicsValue> {
264    crate::server::record::coerce_put_value(record, field, target, value)
265}
266
267/// What a `dbPut` of a given value means for a given field — the single owner
268/// of C `dbPut`'s value branch (`dbAccess.c:1345-1372`).
269enum PutRequest {
270    /// Write this value; already coerced to the field's native type.
271    Write(EpicsValue),
272    /// A zero-element request (`nRequest < 1`) into a **scalar** destination.
273    ///
274    /// C writes nothing, raises `LINK_ALARM`/`INVALID_ALARM` on the record, and
275    /// returns **success** — `status` stays 0, so the put is accepted and the
276    /// record's next `recGblResetAlarms` publishes the new alarm
277    /// (`dbAccess.c:1370-1372`, commit `12cfd418d`, whose subject is "fix dbPut
278    /// to *set* the target to INVALID/LINK alarm when writing empty arrays into
279    /// scalars" — not to reject the put).
280    EmptyIntoScalar,
281}
282
283/// Resolve a put into its C `dbPut` branch.
284///
285/// C picks the branch from the **destination's** element count
286/// (`dbAccess.c:1345` `no_elements > 1`): an array field clamps `nRequest` and
287/// converts — a zero-length request copies nothing and succeeds silently — while
288/// a scalar field with `nRequest < 1` takes the alarm branch. The test is on the
289/// request count and the destination, never on whether a type conversion happens
290/// to be needed.
291///
292/// [`FieldDesc`](crate::server::record::FieldDesc) carries no element count, so
293/// the destination's current value is the probe: an array-valued field reads
294/// back as an array variant. A field the record does not own (a `dbCommon`
295/// field, reached via `put_common_field`) reads back as `None` and is scalar,
296/// which is also what its `DBF_*` descriptor says in C.
297fn dbput_request(
298    record: &dyn crate::server::record::Record,
299    field: &str,
300    value: EpicsValue,
301) -> CaResult<PutRequest> {
302    let dest_is_array = record.get_field(field).is_some_and(|v| v.is_array());
303    if value.is_empty_array() && !dest_is_array {
304        return Ok(PutRequest::EmptyIntoScalar);
305    }
306    // The coercion target is the type the record STORES, not the type it
307    // SERVES — `put_field`'s arms match on what is stored. A `menu()` field is
308    // declared `DBF_MENU` and served as `DBR_ENUM` with its choices, but held as
309    // a bare `Short` choice index; coercing an incoming `Short` up to `Enum`
310    // because the `.dbd` says `DBF_MENU` would make its `Short` arm unreachable.
311    // Same rule as `put_field_internal_default` and `db_loader::apply_fields`.
312    // The `.dbd` type is the fallback for a field with no current value.
313    let target = record
314        .get_field(field)
315        .map(|v| v.db_field_type())
316        .or_else(|| crate::server::record::record_instance::declared_field_type_of(record, field));
317
318    // C `dbPut` clamps the request to the destination's element count —
319    // `if (no_elements < nRequest) nRequest = no_elements;` (dbAccess.c:1359),
320    // then converts `nRequest` elements. A multi-element request into a
321    // one-element destination therefore writes element 0 and SUCCEEDS; the
322    // surplus elements are dropped, not an error. Reduce the array to its
323    // first element here, so the record's typed `put_field` arm — and every
324    // `put_common_field` arm — sees the scalar C would have written instead of
325    // rejecting the array with a `TypeMismatch`.
326    //
327    // One array shape is exempt: a `CharArray` into a `DBF_STRING` field is how
328    // this port carries the dbChannel `$` char-array view of a string field
329    // (`dbChannel.c:486-505` re-types it to `DBF_CHAR[field_size]`, i.e. an
330    // ARRAY destination in C — its element count is 40, not 1). The `$` flag
331    // lives on the CA channel and never reaches this layer, so the char view is
332    // recognised by its shape and left to `convert_to`, which decodes the bytes
333    // back into the string field.
334    let is_char_string_view = matches!(value, EpicsValue::CharArray(_))
335        && target == Some(crate::types::DbFieldType::String);
336    let value = if !dest_is_array && value.is_array() && !is_char_string_view {
337        value.first_element().unwrap_or(value)
338    } else {
339        value
340    };
341
342    match target {
343        // A String target always runs the converter even on a type match: C's
344        // `putStringString` is not a no-op, it truncates to `field_size - 1`
345        // (see `coerce_put_value`).
346        Some(target)
347            if value.db_field_type() != target || target == crate::types::DbFieldType::String =>
348        {
349            Ok(PutRequest::Write(coerce_write_value(
350                record, field, target, value,
351            )?))
352        }
353        _ => Ok(PutRequest::Write(value)),
354    }
355}
356
357/// Apply C's [`PutRequest::EmptyIntoScalar`] effect: the field is left
358/// untouched and the record is driven to `LINK_ALARM`/`INVALID_ALARM`
359/// (`dbAccess.c:1371` `recGblSetSevr(precord, LINK_ALARM, INVALID_ALARM)`).
360fn set_empty_request_alarm(instance: &mut crate::server::record::RecordInstance) {
361    crate::server::recgbl::rec_gbl_set_sevr(
362        &mut instance.common,
363        crate::server::recgbl::alarm_status::LINK_ALARM,
364        crate::server::record::AlarmSeverity::Invalid,
365    );
366}
367
368/// What the put entry point owes the caller in the way of completion — the
369/// `dbPutField` / `dbPutNotify` split, plus the restart C's `dbNotify` state
370/// machine performs on a put-notify that had to wait for a PACT record.
371///
372/// The completion *sender* travels with the request: a restarted put must
373/// signal the ORIGINAL caller's receiver, which was handed out when the put
374/// first arrived and was deferred, so the restart cannot mint a fresh channel.
375enum NotifyRequest {
376    /// C `dbPutField` — process the record, build no `putNotify`.
377    None,
378    /// C `dbPutNotify` arriving fresh from a client: mint the wait-set channel.
379    New,
380    /// C `dbNotify.c:207-231` restart: the client's receiver already exists,
381    /// this replay carries its sender.
382    Deferred(crate::runtime::sync::oneshot::Sender<()>),
383}
384
385impl NotifyRequest {
386    fn wants_notify(&self) -> bool {
387        !matches!(self, NotifyRequest::None)
388    }
389
390    /// The completion sender, plus the receiver to hand back — `Some` only for
391    /// a fresh request; a restart's receiver went to the client at deferral.
392    #[allow(clippy::type_complexity)]
393    fn into_completion(
394        self,
395    ) -> Option<(
396        crate::runtime::sync::oneshot::Sender<()>,
397        Option<crate::runtime::sync::oneshot::Receiver<()>>,
398    )> {
399        match self {
400            NotifyRequest::None => None,
401            NotifyRequest::New => {
402                let (tx, rx) = crate::runtime::sync::oneshot::channel();
403                Some((tx, Some(rx)))
404            }
405            NotifyRequest::Deferred(tx) => Some((tx, None)),
406        }
407    }
408}
409
410/// Snapshot NORD before a `dbPut` writes the value field — C `put_array_info`
411/// opens with `epicsUInt32 nord = prec->nord;` (`waveformRecord.c:202-216`).
412///
413/// `None` for a put to any field but VAL, and for a record type that has no
414/// NORD (the comparison in [`post_array_info`] then reduces to "unchanged").
415fn array_nord_before_put(
416    instance: &crate::server::record::RecordInstance,
417    field: &str,
418) -> Option<EpicsValue> {
419    if field == "VAL" {
420        instance.record.get_field("NORD")
421    } else {
422        None
423    }
424}
425
426/// The tail of C `put_array_info`, and the SINGLE owner of the NORD post:
427///
428/// ```c
429/// if (nord != prec->nord)
430///     db_post_events(prec, &prec->nord, DBE_VALUE | DBE_LOG);
431/// ```
432///
433/// `put_array_info` is called from `dbPut`, so it is reached by EVERY put
434/// route — CA, `dbPutLink`, internal — and by none of them conditionally. The
435/// port's array records (waveform/aai/aao/subArray) re-derive NORD inside
436/// `put_field("VAL")`; this is the post half, and every `dbPut` body in this
437/// module calls it after the value write, passing the snapshot taken by
438/// [`array_nord_before_put`].
439///
440/// Note this post is NOT the process cycle's monitor post: the compiled softIoc
441/// on a 10-second-SCAN waveform posts `NORD = 3` the instant `caput -a WP 3
442/// 1 2 3` lands, and posts no VAL at all (waveform VAL is `pp(TRUE)`, so C
443/// suppresses the value-field post in `dbPut` and the scan is 10 seconds away).
444fn post_array_info(
445    instance: &mut crate::server::record::RecordInstance,
446    old_nord: &Option<EpicsValue>,
447    origin: u64,
448) {
449    let Some(old) = old_nord else { return };
450    let moved = instance
451        .record
452        .get_field("NORD")
453        .is_some_and(|new| new != *old);
454    if moved {
455        instance.notify_field_with_origin(
456            "NORD",
457            crate::server::recgbl::EventMask::VALUE | crate::server::recgbl::EventMask::LOG,
458            origin,
459        );
460    }
461}
462
463impl PvDatabase {
464    /// Get a PV value synchronously, from a thread that cannot `await`.
465    ///
466    /// Works from a plain thread with no runtime entered (an iocsh thread, a
467    /// driver's own thread) and from a multi-threaded runtime worker; see
468    /// [`crate::runtime::task::block_on_sync`] for which mechanism is used
469    /// where.
470    ///
471    /// Returns an error on a **current-thread** runtime, where blocking cannot
472    /// be made sound: parking that runtime's only thread halts the task holding
473    /// the database lock this call awaits. Such callers must `await`
474    /// [`Self::get_pv`] instead.
475    pub fn get_pv_blocking(&self, name: &str) -> CaResult<EpicsValue> {
476        crate::runtime::task::block_on_sync(self.get_pv(name)).unwrap_or_else(|_| {
477            Err(CaError::InvalidValue(
478                "get_pv_blocking cannot block a current-thread runtime; await get_pv() instead"
479                    .into(),
480            ))
481        })
482    }
483
484    /// Get the current value of a PV or record field.
485    /// Uses resolve_field for records (3-level priority).
486    pub async fn get_pv(&self, name: &str) -> CaResult<EpicsValue> {
487        let (base, field) = super::parse_pv_name(name);
488        let field = field.to_ascii_uppercase();
489
490        // Check simple PVs first (exact match)
491        if let Some(pv) = self.inner.simple_pvs.read().await.get(name) {
492            return Ok(pv.get().await);
493        }
494
495        // Records — alias-aware via `get_record` (epics-base PR #336).
496        if let Some(rec) = self.get_record(base).await {
497            let instance = rec.read().await;
498            return instance
499                .resolve_field(&field)
500                .ok_or_else(|| CaError::ChannelNotFound(name.to_string()));
501        }
502
503        Err(CaError::ChannelNotFound(name.to_string()))
504    }
505
506    /// Set a PV value or record field, notifying subscribers.
507    /// Tries record put_field first, then put_common_field as fallback.
508    ///
509    /// Acquires the record's advisory write gate.
510    pub async fn put_pv(&self, name: &str, value: EpicsValue) -> CaResult<()> {
511        self.put_pv_inner(name, value, true).await
512    }
513
514    /// `put_pv` variant for a caller already holding the
515    /// record's advisory write gate (QSRV atomic group PUT). See
516    /// [`Self::put_record_field_from_ca_already_locked`].
517    pub async fn put_pv_already_locked(&self, name: &str, value: EpicsValue) -> CaResult<()> {
518        self.put_pv_inner(name, value, false).await
519    }
520
521    /// C `IOCSource::doPreProcessing` gate (pvxs `iocsource.cpp:363-375`).
522    ///
523    /// Reject an *external* put (a PVA/CA client put routed through QSRV)
524    /// that C refuses before any write: a put to a `DISP=1` record's
525    /// non-DISP field (`S_db_putDisabled`) or to a read-only / `SPC_NOMOD`
526    /// field (`S_db_noMod`). No value is written — this is a precondition
527    /// check only. It mirrors the two gates inside
528    /// [`Self::put_record_field_from_ca`] (the Passive route) so the QSRV
529    /// `Force`/`Inhibit` routes — which go through [`Self::put_pv`] — enforce
530    /// the same preconditions. `put_pv` itself is the internal `dbPut`
531    /// analogue and deliberately does not gate DISP (internal
532    /// link/processing puts must bypass it), so the gate lives at the
533    /// external put boundary, exactly as C places `doPreProcessing` in the
534    /// source layer rather than in `dbPut`.
535    pub async fn check_external_put_preconditions(
536        &self,
537        record_name: &str,
538        field: &str,
539    ) -> CaResult<()> {
540        let field_upper = field.to_ascii_uppercase();
541        // A missing record is not a DISP/read-only precondition violation:
542        // stay silent and let the downstream put report the not-found (for
543        // QSRV, inside its own `asTrapWrite` bracket). C's `doPreProcessing`
544        // only runs against an established channel — the record is
545        // guaranteed present there — and a `BridgeChannel` likewise always
546        // binds a real record in production.
547        let Some(rec) = self.get_record(record_name).await else {
548            return Ok(());
549        };
550        let instance = rec.read().await;
551        // Read-only / SPC_NOMOD field, through the one gate owner
552        // ([`check_no_mod`]). C tests SPC_ATTRIBUTE *before* `disp`
553        // (iocsource.cpp:365-369), so a read-only field on a DISP=1 record
554        // reports S_db_noMod, not S_db_putDisabled; the two errors carry
555        // different wire text.
556        check_no_mod(&instance, &field_upper)?;
557        // DISP=1 blocks a put to any field except DISP itself — the shared
558        // gate owner, identical to the one the CA route crosses.
559        check_put_disabled(&instance, &field_upper)?;
560        Ok(())
561    }
562
563    /// pvxs `IOCSource::doPostProcessing`'s record-side terms
564    /// (`iocsource.cpp:397-403`): does a put to `record_name.field` drive a
565    /// processing cycle on its own?
566    ///
567    /// The QSRV group PUT asks this for a member whose write bypassed
568    /// [`Self::put_record_field_from_ca`] (a `+type:"proc"` trigger, or a
569    /// member that is `changing` but has no writable leaf), so that route
570    /// applies the SAME gate as a plain field put instead of processing
571    /// unconditionally. `false` for an unknown record — there is nothing to
572    /// process. Force (`record._options.process=true`) is the caller's term
573    /// and is not asked about here; see [`put_drives_processing_of`].
574    pub async fn put_drives_processing(&self, record_name: &str, field: &str) -> bool {
575        let field_upper = field.to_ascii_uppercase();
576        let Some(rec) = self.get_record(record_name).await else {
577            return false;
578        };
579        let instance = rec.read().await;
580        put_drives_processing_of(&instance, &field_upper)
581    }
582
583    async fn put_pv_inner(
584        &self,
585        name: &str,
586        value: EpicsValue,
587        acquire_gate: bool,
588    ) -> CaResult<()> {
589        let (base, field) = super::parse_pv_name(name);
590        let field = field.to_ascii_uppercase();
591
592        // Check simple PVs first
593        if let Some(pv) = self.inner.simple_pvs.read().await.get(name) {
594            pv.set(value).await;
595            return Ok(());
596        }
597
598        // Records — alias-aware (epics-base PR #336).
599        if let Some(rec) = self.get_record(base).await {
600            // `base` may be an alias; resolve to the canonical record
601            // name so scan-index updates target the right entry.
602            let canonical_base: String = self
603                .resolve_alias(base)
604                .await
605                .unwrap_or_else(|| base.to_string());
606            // advisory write gate (`dbScanLock` analogue) so a
607            // plain `put_pv` to a backing record cannot interleave
608            // with an atomic group transaction holding the same gate.
609            // Skipped when the caller already owns the gate.
610            let _record_gate = if acquire_gate {
611                Some(self.lock_record(&canonical_base).await)
612            } else {
613                None
614            };
615            let mut instance = rec.write().await;
616
617            // C `dbPut` refuses an SPC_NOMOD / SPC_ATTRIBUTE field before it
618            // converts anything (`dbAccess.c:1330-1332`). `put_pv` IS the
619            // `dbPut` analogue — it sits below `dbPutLink`, so this is what
620            // stops a record's OUT link from truncating a waveform's NELM.
621            // The refusal is returned to the caller; `write_out_link_value`
622            // (C `dbPutLink`) turns it into the writer's LINK/INVALID alarm.
623            check_no_mod(&instance, &field)?;
624
625            let request = dbput_request(&*instance.record, &field, value)?;
626
627            // Pre-write special hook (C EPICS dbPutSpecial pass=0).
628            // C `dbPut` runs it on EVERY entry path — dbPutField and
629            // dbPutLink alike (dbAccess.c) — so the OUT-link route
630            // through this body must call it too (motor's drive-field
631            // DMOV blink, motorRecord.cc:2582-2608, fires on put-links
632            // in C). A non-zero status aborts the put like C.
633            instance.record.special(&field, false)?;
634
635            // Capture the pre-put value so the metadata-cache
636            // invalidation (and the downstream `DBE_PROPERTY`
637            // emission) can be skipped when the put is a no-op —
638            // epics-base faac1df1.
639            let prev_value = instance.record.get_field(&field);
640            let old_nord = array_nord_before_put(&instance, &field);
641
642            // Link writes the record's `special()` makes itself (C runs them
643            // inside `dbPut`); executed below, once the record lock is released.
644            let mut special_actions = Vec::new();
645
646            // put_pv is C EPICS dbPut: write value + special/on_put.
647            // Does NOT post monitor events (use put_pv_and_post for that).
648            // Does NOT clear UDF or trigger processing.
649            use crate::server::record::CommonFieldPutResult;
650            let common_result = match request {
651                // C `dbAccess.c:1370-1372` — accept, write nothing, alarm.
652                PutRequest::EmptyIntoScalar => {
653                    set_empty_request_alarm(&mut instance);
654                    CommonFieldPutResult::NoChange
655                }
656                PutRequest::Write(value) => {
657                    special_before_put(&mut instance, &field);
658                    match instance.record.put_field(&field, value.clone()) {
659                        Ok(()) => {
660                            instance.record.on_put(&field);
661                            // C `dbPut` (dbAccess.c:1399-1405) keeps the value
662                            // it already stored but RETURNS the after-put
663                            // `dbPutSpecial(paddr, 1)` status, skipping the
664                            // field's monitor post and (in `dbPutField`) the
665                            // `pp(TRUE)` process. `calcRecord::special` uses
666                            // that to refuse an uncompilable CALC with
667                            // S_db_badField, so the status must not be dropped.
668                            special_after_put(&mut instance, &field, &mut special_actions)?
669                        }
670                        Err(CaError::FieldNotFound(_)) => {
671                            instance.put_common_field(&field, value)?
672                        }
673                        Err(e) => return Err(e),
674                    }
675                }
676            };
677
678            // C `dbPut` runs `dbPutSpecial(paddr, 1)` regardless of caller entry
679            // path, so a put via this internal route commits/writes the same
680            // `special()`-driven alarm the CA route does. State only — `put_pv`
681            // posts no monitors (its contract), so unlike the CA path these
682            // commit the alarm without the STAT/SEVR posts.
683            //
684            // compress SPC_RESET: `monitor()`'s `recGblResetAlarms` commits the
685            // born-UDF alarm (compressRecord.c:103).
686            if instance.record.special_commits_alarms(&field) {
687                let _ = crate::server::recgbl::rec_gbl_reset_alarms(&mut instance.common);
688            }
689            // histogram SGNL SPC_MOD: `add_count` writes stat/sevr directly and
690            // no monitor follows, so it sticks (histogramRecord.c:329-334).
691            if instance.record.special_checks_alarms(&field) {
692                let inst = &mut *instance;
693                inst.record.check_alarms(&mut inst.common);
694            }
695
696            // Invalidate metadata cache only if the metadata-class
697            // field's value actually changed (faac1df1).
698            instance.notify_field_written_if_changed(&field, prev_value.as_ref());
699
700            // The one post this body makes. `put_pv` is the `dbPutLink` route's
701            // `dbPut`, and C's `put_array_info` is reached from every `dbPut` —
702            // an OUT link that shortens a waveform posts NORD in C even when the
703            // link is NPP and the target never processes. The value-field post
704            // stays absent here (C suppresses it for a `pp(TRUE)` value field,
705            // and the port's other callers of `put_pv` rely on the process cycle
706            // for it); NORD has no such second path.
707            post_array_info(&mut instance, &old_nord, 0);
708
709            // The record lock must be down before the scan-index update and
710            // before the `special()` link writes below, which re-enter the
711            // database (they can process their target).
712            drop(instance);
713
714            // Update scan index if SCAN or PHAS changed
715            match common_result {
716                CommonFieldPutResult::ScanChanged {
717                    old_scan,
718                    new_scan,
719                    phas,
720                } => {
721                    self.update_scan_index(&canonical_base, old_scan, new_scan, phas, phas)
722                        .await;
723                }
724                CommonFieldPutResult::PhasChanged {
725                    scan: s,
726                    old_phas,
727                    new_phas,
728                } => {
729                    self.update_scan_index(&canonical_base, s, s, old_phas, new_phas)
730                        .await;
731                }
732                CommonFieldPutResult::NoChange => {}
733            }
734
735            // C `dbPut` runs `dbPutSpecial(paddr, 1)` to completion — the
736            // `dbPutLink` calls a `special()` makes included — before it returns
737            // to `dbPutField`. This is the last statement of the `dbPut`
738            // analogue, so it is that point.
739            self.run_special_actions(&canonical_base, &rec, special_actions)
740                .await;
741
742            // mirror the CA-write path's ASG-field notifier so
743            // restore scripts / autosave / admin tools that go via
744            // `put_pv` (not `put_record_field_from_ca`) also trigger
745            // per-client `reeval_access_rights`. C `dbAccess.c::
746            // dbPutSpecial` invokes the SPC_AS callback from dbPut
747            // regardless of caller entry path.
748            if field == "ASG" {
749                crate::server::access_security::notify_asg_field_changed();
750            }
751
752            return Ok(());
753        }
754
755        Err(CaError::ChannelNotFound(name.to_string()))
756    }
757
758    /// Write a value and post monitor events if changed.
759    /// Equivalent to C EPICS `dbPut` + `db_post_events(DBE_VALUE|DBE_LOG)`.
760    ///
761    /// Use for readback/status mirror PVs that are written by sequencer-style
762    /// code and need to be visible to CA monitors without triggering record
763    /// processing. Clears UDF/UDF_ALARM on primary field write.
764    ///
765    /// `origin`: writer ID for self-write filtering. Subscribers with the
766    /// same `ignore_origin` will skip this event. Pass 0 to disable.
767    pub async fn put_pv_and_post(&self, name: &str, value: EpicsValue) -> CaResult<()> {
768        self.put_pv_and_post_with_origin(name, value, 0).await
769    }
770
771    /// Push a monitor event holding the simple PV's *current* value
772    /// but with explicit alarm severity/status. Used by the gateway
773    /// to surface upstream-disconnect to downstream monitor
774    /// subscribers without dropping the shadow PV (which would force
775    /// downstream clients into ECA_DISCONN reconnect storms on every
776    /// transient hiccup). Returns `ChannelNotFound` for record-backed
777    /// PVs — those carry their own `common.sevr/stat` in record
778    /// processing.
779    pub async fn post_alarm(&self, name: &str, severity: u16, status: u16) -> CaResult<()> {
780        if let Some(pv) = self.inner.simple_pvs.read().await.get(name).cloned() {
781            pv.post_alarm(severity, status).await;
782            return Ok(());
783        }
784        Err(crate::error::CaError::ChannelNotFound(name.to_string()))
785    }
786
787    /// Propagate a full upstream snapshot (value + alarm status/severity +
788    /// IOC timestamp) to a simple shadow PV and fan out to downstream
789    /// monitor subscribers. Used by the CA gateway forwarding task to avoid
790    /// discarding the upstream alarm and timestamp decoded from the incoming
791    /// `DBR_TIME_*` frame. Returns `ChannelNotFound` for record-backed PVs
792    /// (those carry their own alarm engine and are not shadow PVs).
793    pub async fn put_pv_and_post_snapshot(&self, name: &str, snapshot: Snapshot) -> CaResult<()> {
794        if let Some(pv) = self.inner.simple_pvs.read().await.get(name).cloned() {
795            pv.set_snapshot(snapshot).await;
796            return Ok(());
797        }
798        Err(CaError::ChannelNotFound(name.to_string()))
799    }
800
801    /// Install upstream `DBR_CTRL_*` metadata (display / control limits,
802    /// enum labels) on a shadow simple PV WITHOUT posting an event.
803    ///
804    /// The CA gateway calls this once on upstream connect, after its initial
805    /// `DBR_CTRL_*` get, so a later downstream `DBR_CTRL_*` / `DBR_GR_*` read
806    /// returns the real limits instead of zeroed ones. No `DBE_PROPERTY`
807    /// monitor event fires — nothing has *changed* yet, this only seeds the
808    /// attribute cache. Mirrors C `gatePvData::getCB` → `runDataCB` →
809    /// `vc->setPvData(dd)` (`gatePv.cc:1693-1695`), which seeds the property
810    /// cache from the initial control get in both cache modes before any
811    /// monitor is enabled.
812    ///
813    /// Returns `ChannelNotFound` for record-backed PVs — those own their own
814    /// metadata via record processing and are not gateway shadow PVs.
815    pub async fn set_pv_metadata(&self, name: &str, snapshot: &Snapshot) -> CaResult<()> {
816        if let Some(pv) = self.inner.simple_pvs.read().await.get(name).cloned() {
817            pv.set_metadata(metadata_from_snapshot(snapshot));
818            return Ok(());
819        }
820        Err(CaError::ChannelNotFound(name.to_string()))
821    }
822
823    /// Refresh a shadow simple PV's upstream metadata AND post a
824    /// `DBE_PROPERTY` monitor event carrying `snapshot` to downstream
825    /// property subscribers.
826    ///
827    /// `snapshot` is the decoded upstream `DBR_CTRL_*` property event: it
828    /// carries the control value and the upstream `status` / `severity`,
829    /// and (because control DBR structs carry no timestamp) an undefined
830    /// timestamp the caller must NOT replace with a fresh wall-clock. The
831    /// gateway's property monitor calls this on every upstream
832    /// `DBE_PROPERTY` event, mirroring C `gatePvData::propEventCB` →
833    /// `runDataCB` + `setPvData` + `runValueDataCB` +
834    /// `vcPostEvent(propertyEventMask())` (`gatePv.cc:1571-1607`): the
835    /// attribute cache is refreshed and a property event is posted with the
836    /// upstream alarm state preserved (`setStatSevr`) and the undefined
837    /// control-DBR timestamp left as-is (`gatePv.cc:1594-1595`).
838    ///
839    /// Returns `ChannelNotFound` for record-backed PVs.
840    pub async fn post_pv_property(&self, name: &str, snapshot: Snapshot) -> CaResult<()> {
841        if let Some(pv) = self.inner.simple_pvs.read().await.get(name).cloned() {
842            pv.set_metadata(metadata_from_snapshot(&snapshot));
843            pv.post_property(snapshot).await;
844            return Ok(());
845        }
846        Err(CaError::ChannelNotFound(name.to_string()))
847    }
848
849    /// Like `put_pv_and_post` but with explicit origin tag.
850    pub async fn put_pv_and_post_with_origin(
851        &self,
852        name: &str,
853        value: EpicsValue,
854        origin: u64,
855    ) -> CaResult<()> {
856        let (base, field) = super::parse_pv_name(name);
857        let field = field.to_ascii_uppercase();
858
859        // Simple-PV path: PVs registered via `add_pv` (e.g. CA gateway
860        // shadow PVs, IOCsh stats PVs) are stored in `simple_pvs`,
861        // not `records`. Without this branch the function would
862        // silently return `ChannelNotFound` for every gateway-mirrored
863        // PV — `ProcessVariable::set` already does the
864        // notify-subscribers fan-out internally so all we need here is
865        // to delegate. The `origin` tag is a no-op for simple PVs
866        // because they don't yet plumb origin through `set`.
867        if let Some(pv) = self.inner.simple_pvs.read().await.get(name).cloned() {
868            let _ = origin; // simple PVs don't currently honor origin tagging
869            pv.set(value).await;
870            return Ok(());
871        }
872
873        if let Some(rec) = self.get_record(base).await {
874            // `put_pv_and_post` is a public record-write API —
875            // it must take the same advisory write gate
876            // (`dbScanLock` analogue) as `put_pv` /
877            // `put_record_field_from_ca`, or a gateway/sequencer
878            // write through this helper can still land between the
879            // member writes of a QSRV atomic group or a pvalink
880            // atomic scan epoch holding `lock_records`. `base` is
881            // alias-resolved to the canonical record name so an alias
882            // and its target share one gate. Held until return.
883            let canonical_base: String = self
884                .resolve_alias(base)
885                .await
886                .unwrap_or_else(|| base.to_string());
887            let _record_gate = self.lock_record(&canonical_base).await;
888
889            let mut instance = rec.write().await;
890
891            // Same `dbPut` gate as `put_pv` — this is the third `dbPut` body
892            // (value + monitor post), and C has ONE.
893            check_no_mod(&instance, &field)?;
894
895            let request = dbput_request(&*instance.record, &field, value)?;
896
897            // Pre-write special hook (C EPICS dbPutSpecial pass=0) —
898            // C `dbPut` runs it on every entry path; this is the third
899            // `dbPut` body and must match the other two.
900            instance.record.special(&field, false)?;
901
902            let old_value = instance.record.get_field(&field);
903            let old_stat = instance.common.stat;
904            let old_sevr = instance.common.sevr;
905            let old_nord = array_nord_before_put(&instance, &field);
906
907            // Link writes the record's `special()` makes itself (C runs them
908            // inside `dbPut`); executed below, once the record lock is released.
909            let mut special_actions = Vec::new();
910
911            // Write value + special/on_put
912            use crate::server::record::CommonFieldPutResult;
913            let common_result = match request {
914                // C `dbAccess.c:1370-1372` — accept, write nothing, alarm. UDF
915                // is NOT cleared: C clears it at `:1409` only when the value
916                // field was actually written, and this branch wrote nothing.
917                PutRequest::EmptyIntoScalar => {
918                    set_empty_request_alarm(&mut instance);
919                    CommonFieldPutResult::NoChange
920                }
921                PutRequest::Write(value) => {
922                    special_before_put(&mut instance, &field);
923                    match instance.record.put_field(&field, value.clone()) {
924                        Ok(()) => {
925                            instance.record.on_put(&field);
926                            // C returns the after-put special() status from
927                            // `dbPut` (dbAccess.c:1399-1405) — before the UDF
928                            // clear and the monitor post below, both of which
929                            // `goto done` skips on a non-zero status.
930                            let result =
931                                special_after_put(&mut instance, &field, &mut special_actions)?;
932                            // C `dbAccess.c::dbPut:1411` clears ONLY `precord->udf
933                            // = FALSE` on a value-field put, and nothing else. It
934                            // does NOT touch stat/sevr: the UDF_ALARM stays until
935                            // the record's own process cycle recomputes it
936                            // (`rec_gbl_check_udf` no longer raises it now udf is
937                            // clear, `rec_gbl_reset_alarms` commits the new state).
938                            // A value put that does not drive a process therefore
939                            // leaves the stale UDF alarm exactly as C does — the
940                            // earlier synchronous stat/sevr clear here diverged
941                            // from C and reported NO_ALARM where C keeps UDF/INVALID.
942                            if instance.record.is_udf_defining_put(&field) {
943                                instance.common.udf = 0;
944                            }
945                            result
946                        }
947                        Err(CaError::FieldNotFound(_)) => {
948                            instance.put_common_field(&field, value)?
949                        }
950                        Err(e) => return Err(e),
951                    }
952                }
953            };
954
955            // Invalidate metadata cache only if a metadata-class
956            // field actually changed value (faac1df1 — DBE_PROPERTY
957            // fires on real changes, not no-op writes).
958            instance.notify_field_written_if_changed(&field, old_value.as_ref());
959
960            // Post monitor events if value or alarm changed
961            let new_value = instance.record.get_field(&field);
962            let value_changed = old_value != new_value;
963            let alarm_changed =
964                old_stat != instance.common.stat || old_sevr != instance.common.sevr;
965            let nord_changed = old_nord.is_some() && instance.record.get_field("NORD") != old_nord;
966            if value_changed || alarm_changed || nord_changed {
967                // Update timestamp so the snapshot carries current time
968                instance.common.time = crate::runtime::general_time::get_current();
969                instance.cleanup_subscribers();
970                if value_changed || alarm_changed {
971                    instance.notify_field_with_origin(
972                        &field,
973                        crate::server::recgbl::EventMask::VALUE
974                            | crate::server::recgbl::EventMask::LOG
975                            | crate::server::recgbl::EventMask::ALARM,
976                        origin,
977                    );
978                }
979                // The NORD post, through the one owner. Without it a CA
980                // gateway forwarding upstream waveform monitors via
981                // put_pv_and_post would update VAL on the shadow PV but
982                // leave downstream NORD subscribers stuck at their last
983                // seen length — a frozen-element-count bug that surfaces
984                // in PyDM image views and similar consumers that compute
985                // height = element_count / width.
986                post_array_info(&mut instance, &old_nord, origin);
987            }
988
989            // The `special()` link writes re-enter the database, so the record
990            // lock goes down first. C makes them inside `dbPut`, before it
991            // returns to its caller.
992            drop(instance);
993
994            // Same scan-index owner every other `dbPut` path routes through:
995            // a SCAN put and the SIMM↔SSCN swap (`recGblCheckSimm`) both move
996            // the record between scan lists and must reach `update_scan_index`.
997            match common_result {
998                CommonFieldPutResult::ScanChanged {
999                    old_scan,
1000                    new_scan,
1001                    phas,
1002                } => {
1003                    self.update_scan_index(&canonical_base, old_scan, new_scan, phas, phas)
1004                        .await;
1005                }
1006                CommonFieldPutResult::PhasChanged {
1007                    scan: s,
1008                    old_phas,
1009                    new_phas,
1010                } => {
1011                    self.update_scan_index(&canonical_base, s, s, old_phas, new_phas)
1012                        .await;
1013                }
1014                CommonFieldPutResult::NoChange => {}
1015            }
1016
1017            self.run_special_actions(&canonical_base, &rec, special_actions)
1018                .await;
1019
1020            // same SPC_AS parity as `put_pv` / `put_pv_no_process`
1021            // / the CA-write path — a gateway mirroring `.ASG` via
1022            // `put_pv_and_post` must still trigger per-client
1023            // re-eval.
1024            if field == "ASG" {
1025                crate::server::access_security::notify_asg_field_changed();
1026            }
1027
1028            return Ok(());
1029        }
1030
1031        Err(CaError::ChannelNotFound(name.to_string()))
1032    }
1033
1034    /// Execute the link writes a record's `special()` queued
1035    /// ([`Record::take_special_actions`](crate::server::record::Record::take_special_actions)).
1036    ///
1037    /// The single consumer: every `dbPut` path in this module calls it once, at
1038    /// the end of the put and before any `pp(TRUE)` process cycle, which is
1039    /// where C runs them (`dbPut` → `dbPutSpecial(paddr, 1)` → `dbPutLink`,
1040    /// with `dbProcess` still ahead in `dbPutField`). The put is the root of the
1041    /// chain these writes start, so they get a fresh visited set, exactly like a
1042    /// client put entering `process_record_with_links`.
1043    ///
1044    /// Must be called with no record lock held: a `WriteDbLink` can process its
1045    /// target, which re-enters the database.
1046    async fn run_special_actions(
1047        &self,
1048        record_name: &str,
1049        rec: &std::sync::Arc<crate::runtime::sync::RwLock<crate::server::record::RecordInstance>>,
1050        actions: Vec<crate::server::record::ProcessAction>,
1051    ) {
1052        if actions.is_empty() {
1053            return;
1054        }
1055        let mut visited = HashSet::new();
1056        // A `WriteDbLink` here can land back in a `dbPut` (its target's), which
1057        // is the function that called us: the async cycle needs one boxed edge.
1058        Box::pin(self.execute_process_actions(record_name, rec, actions, &mut visited, 0)).await;
1059    }
1060
1061    /// CA client's unified entry point for record field put.
1062    /// Handles DISP/PROC/PACT/LCNT checks, field put, device write, and Passive process.
1063    ///
1064    /// Acquires the record's advisory write gate
1065    /// (`dbScanLock` analogue) for the duration of the write.
1066    pub async fn put_record_field_from_ca(
1067        &self,
1068        record_name: &str,
1069        field: &str,
1070        value: EpicsValue,
1071    ) -> CaResult<Option<crate::runtime::sync::oneshot::Receiver<()>>> {
1072        self.put_record_field_from_ca_inner(record_name, field, value, true, NotifyRequest::New)
1073            .await
1074    }
1075
1076    /// Variant for a caller that already owns the target
1077    /// record's advisory write gate — the QSRV atomic group PUT,
1078    /// which acquired every member-record gate up-front via
1079    /// [`Self::lock_records`]. The per-record `tokio::sync::Mutex`
1080    /// gate is NOT reentrant, so the atomic group path MUST use this
1081    /// `_already_locked` entry to avoid dead-locking on its own
1082    /// `ManyRecordWriteGuard`.
1083    pub async fn put_record_field_from_ca_already_locked(
1084        &self,
1085        record_name: &str,
1086        field: &str,
1087        value: EpicsValue,
1088    ) -> CaResult<Option<crate::runtime::sync::oneshot::Receiver<()>>> {
1089        self.put_record_field_from_ca_inner(record_name, field, value, false, NotifyRequest::New)
1090            .await
1091    }
1092
1093    /// Fire-and-forget variant — C `dbPutField` semantics: the put
1094    /// processes the record but creates NO put-notify wait-set (C
1095    /// builds a `putNotify` only in `dbPutNotify`, i.e. for
1096    /// WRITE_NOTIFY). A caller that does not await the returned
1097    /// receiver MUST use this entry: parking a wait-set whose receiver
1098    /// is dropped occupies `RecordInstance::notify` until the record's
1099    /// async work ends (a motor's whole motion), failing every
1100    /// legitimate WRITE_NOTIFY on the record with ECA_PUTCBINPROG in
1101    /// the meantime.
1102    pub async fn put_record_field_from_ca_no_notify(
1103        &self,
1104        record_name: &str,
1105        field: &str,
1106        value: EpicsValue,
1107    ) -> CaResult<()> {
1108        self.put_record_field_from_ca_inner(record_name, field, value, true, NotifyRequest::None)
1109            .await
1110            .map(|_| ())
1111    }
1112
1113    /// C `dbPut`'s alarm-acknowledge interception (`dbAccess.c:1331-1335`) —
1114    /// the ONLY route that may change ACKS/ACKT at runtime.
1115    ///
1116    /// ```c
1117    /// if (dbrType == DBR_PUT_ACKT && field_type <= DBF_DEVICE)
1118    ///     return putAckt(paddr, pbuffer, 1, 1, 0);
1119    /// else if (dbrType == DBR_PUT_ACKS && field_type <= DBF_DEVICE)
1120    ///     return putAcks(paddr, pbuffer, 1, 1, 0);
1121    /// ```
1122    ///
1123    /// The dispatch is on the DBR *request type*, not on the field: a CA client
1124    /// acknowledges by sending `DBR_PUT_ACKS` down its ordinary `REC` (VAL)
1125    /// channel. It sits ABOVE the `SPC_NOMOD` gate, which is why
1126    /// `caput REC.ACKS 2` is refused by C ("Write access denied", verified on
1127    /// softIoc 7.0.10) while `ca_put(DBR_PUT_ACKS, REC)` clears the alarm.
1128    ///
1129    /// The put-disable gate is still crossed: C tests `precord->disp` in
1130    /// `dbPutField`, above `dbPut` (`dbAccess.c:1255-1257`), so an ack to a
1131    /// `DISP=1` record is refused. `field` is the channel's field — only the
1132    /// DISP gate looks at it, exactly as in C.
1133    ///
1134    /// No process cycle: `dbPut` returns straight from `putAckt`/`putAcks`, and
1135    /// `dbPutField`'s reprocess condition requires `dbrType < DBR_PUT_ACKT`.
1136    pub async fn put_alarm_ack_from_ca(
1137        &self,
1138        record_name: &str,
1139        field: &str,
1140        ack: crate::server::record::AlarmAck,
1141        value: u16,
1142    ) -> CaResult<()> {
1143        let field_upper = field.to_ascii_uppercase();
1144        let rec = self
1145            .get_record(record_name)
1146            .await
1147            .ok_or_else(|| CaError::ChannelNotFound(record_name.to_string()))?;
1148        let canonical: String = self
1149            .resolve_alias(record_name)
1150            .await
1151            .unwrap_or_else(|| record_name.to_string());
1152        let _record_gate = self.lock_record(&canonical).await;
1153
1154        let mut instance = rec.write().await;
1155        check_put_disabled(&instance, &field_upper)?;
1156        match ack {
1157            crate::server::record::AlarmAck::Transient => instance.put_ackt(value),
1158            crate::server::record::AlarmAck::Severity => instance.put_acks(value),
1159        }
1160        Ok(())
1161    }
1162
1163    /// Fire-and-forget + caller-held gate: see
1164    /// [`Self::put_record_field_from_ca_no_notify`] and
1165    /// [`Self::put_record_field_from_ca_already_locked`].
1166    pub async fn put_record_field_from_ca_no_notify_already_locked(
1167        &self,
1168        record_name: &str,
1169        field: &str,
1170        value: EpicsValue,
1171    ) -> CaResult<()> {
1172        self.put_record_field_from_ca_inner(record_name, field, value, false, NotifyRequest::None)
1173            .await
1174            .map(|_| ())
1175    }
1176
1177    /// Process a record UNCONDITIONALLY with a put-notify wait-set, returning
1178    /// the completion receiver — the QSRV `record[process=true,block=true]`
1179    /// (Force + block) barrier.
1180    ///
1181    /// C `dbProcessNotify`: pvxs routes a blocking forced put through
1182    /// `dbProcessNotify` (`singlesource.cpp:360-369`), whose completion fires
1183    /// only after the record's whole processing chain — including async device
1184    /// work (a motor move, an asyn-backed AO) — settles. The value is written
1185    /// by the caller's preceding [`Self::put_pv`] (the `dbPut` analogue, no
1186    /// process); this entry then mints the wait-set, registers it into the
1187    /// record's `notify` slot so PACT records join it, and runs the full
1188    /// unconditional [`Self::process_record_with_links`] cycle (C `dbProcess`,
1189    /// the Force analogue). A fully synchronous chain returns `Ok(None)` (the
1190    /// wait-set already drained); an async record returns `Ok(Some(rx))` for
1191    /// the caller to await. A concurrent put-callback already in flight on the
1192    /// record is rejected with `PutCallbackInProgress`, matching the PROC path.
1193    pub async fn process_record_with_notify(
1194        &self,
1195        record_name: &str,
1196    ) -> CaResult<Option<crate::runtime::sync::oneshot::Receiver<()>>> {
1197        let (completion_tx, completion_rx) = crate::runtime::sync::oneshot::channel();
1198        let notify = crate::server::record::NotifyWaitSet::new(completion_tx);
1199        {
1200            // Collect-then-act: clone the handle under a brief map read, drop
1201            // the map lock before taking the per-record write lock.
1202            let rec_arc = {
1203                let recs = self.inner.records.read().await;
1204                recs.get(record_name).cloned()
1205            };
1206            let Some(rec_arc) = rec_arc else {
1207                return Err(CaError::ChannelNotFound(record_name.to_string()));
1208            };
1209            let mut guard = rec_arc.write().await;
1210            if guard.notify.is_some() {
1211                return Err(CaError::PutCallbackInProgress(record_name.to_string()));
1212            }
1213            guard.notify = Some(notify.clone());
1214        }
1215        let mut visited = HashSet::new();
1216        self.process_record_with_links(record_name, &mut visited, 0)
1217            .await?;
1218        // The wait-set fires the oneshot only after the whole FLNK/OUT chain
1219        // (sync + async) settles. Already-completed ⟹ fully synchronous ⟹
1220        // report immediate success; otherwise hand the receiver back to await
1221        // the deferred async completion.
1222        if notify.completed() {
1223            Ok(None)
1224        } else {
1225            Ok(Some(completion_rx))
1226        }
1227    }
1228
1229    /// C `dbPutField`'s put-driven process decision (`dbAccess.c:1264-1277`).
1230    ///
1231    /// Reached once the put has selected the record for processing — the `PROC`
1232    /// field, or a `pp(TRUE)` field on a Passive record. C then splits on PACT:
1233    ///
1234    /// * **async-active** — C sets `rpro = TRUE` and does NOT call `dbProcess`.
1235    ///   `recGblFwdLink` (`recGbl.c:296-300`) consumes RPRO when the device
1236    ///   round trip completes and queues `scanOnce`, so the value this put just
1237    ///   wrote still reaches the device, one cycle later. Calling `dbProcess`
1238    ///   here instead lands in dbProcess's own PACT guard, which bumps LCNT and
1239    ///   after MAX_LOCK raises SCAN_ALARM — an alarm C never raises for a client
1240    ///   put — while dropping the deferred reprocess entirely: on two rapid
1241    ///   puts to a Passive async output, C writes both values to the device and
1242    ///   the port wrote only the first.
1243    /// * **idle** — C sets `putf = TRUE` (the put-driven marker, cleared at the
1244    ///   tail of the process cycle / in `complete_async_record_inner`, both the
1245    ///   `recGblFwdLink:302` analogue) and calls `dbProcess`.
1246    ///
1247    /// Single owner of that decision for every external put: the `PROC`
1248    /// intercept and the `pp`-field route in
1249    /// [`Self::put_record_field_from_ca`] both go through it, so neither can
1250    /// drift from C's rule or from each other. The DB-link propagation path
1251    /// applies the same PACT→RPRO rule at its own targets (`processing.rs:3225`,
1252    /// `:4220`, `links.rs:829`).
1253    ///
1254    /// Two entries, one rule. `put_driven_process` acquires `record_name`'s
1255    /// advisory write gate (the `dbScanLock` analogue) itself;
1256    /// [`Self::put_driven_process_already_locked`] is for a caller that
1257    /// already owns it — `_record_gate` on the CA put path, or the QSRV
1258    /// atomic group's `lock_records` epoch. The gate `Mutex` is not
1259    /// reentrant, so a caller holding it MUST take the `_already_locked`
1260    /// entry.
1261    ///
1262    /// QSRV's group PUT is the second external caller (pvxs
1263    /// `IOCSource::doPostProcessing`, `iocsource.cpp:397-420`, whose PACT
1264    /// branch is this same RPRO deferral): it reaches the decision by its own
1265    /// route — `record._options.process`, a `+type:"proc"` member, a `pp` field
1266    /// — but once the answer is "process", the transition is this owner's, in
1267    /// both gate modes.
1268    /// The PACT (RPRO) branch is success, as it is in C: `dbPutField` returns
1269    /// the `dbProcess` status only on the branch that ran it.
1270    pub async fn put_driven_process(&self, record_name: &str) -> CaResult<()> {
1271        self.put_driven_process_inner(record_name, true).await
1272    }
1273
1274    /// [`Self::put_driven_process`] for a caller that already owns the
1275    /// record's advisory write gate.
1276    pub async fn put_driven_process_already_locked(&self, record_name: &str) -> CaResult<()> {
1277        self.put_driven_process_inner(record_name, false).await
1278    }
1279
1280    async fn put_driven_process_inner(
1281        &self,
1282        record_name: &str,
1283        acquire_gate: bool,
1284    ) -> CaResult<()> {
1285        {
1286            let Some(rec) = self.get_record(record_name).await else {
1287                return Ok(());
1288            };
1289            let mut instance = rec.write().await;
1290            if instance.is_processing() {
1291                instance.common.rpro = 1;
1292                return Ok(());
1293            }
1294            instance.common.putf = true;
1295        }
1296        let mut visited = HashSet::new();
1297        if acquire_gate {
1298            self.process_record_with_links(record_name, &mut visited, 0)
1299                .await
1300        } else {
1301            self.process_record_with_links_already_locked(record_name, &mut visited, 0)
1302                .await
1303        }
1304    }
1305
1306    /// C `dbNotifyCompletion` → restart (dbNotify.c:207-231, state
1307    /// `notifyRestartInProgress`): replay a put-notify that landed on a PACT
1308    /// record, now that the record is idle. The single owner that consumes a
1309    /// [`DeferredNotifyPut`]; called only from the async-completion tail.
1310    ///
1311    /// The replay goes back through the ordinary put entry, so if the record
1312    /// has ALREADY gone active again (a scan fired between the completion and
1313    /// this replay), the same PACT test defers it once more rather than writing
1314    /// into a busy record — the deferral is closed under its own restart.
1315    pub(crate) async fn restart_deferred_notify_put(
1316        &self,
1317        record_name: &str,
1318        put: crate::server::record::DeferredNotifyPut,
1319    ) {
1320        let crate::server::record::DeferredNotifyPut {
1321            field,
1322            value,
1323            completion,
1324        } = put;
1325        // The client already holds the receiver; a failure here (record gone,
1326        // field refused) must still release it, which dropping the sender does.
1327        let _ = self
1328            .put_record_field_from_ca_inner(
1329                record_name,
1330                &field,
1331                value,
1332                true,
1333                NotifyRequest::Deferred(completion),
1334            )
1335            .await;
1336    }
1337
1338    async fn put_record_field_from_ca_inner(
1339        &self,
1340        record_name: &str,
1341        field: &str,
1342        value: EpicsValue,
1343        acquire_gate: bool,
1344        notify_request: NotifyRequest,
1345    ) -> CaResult<Option<crate::runtime::sync::oneshot::Receiver<()>>> {
1346        let field = field.to_ascii_uppercase();
1347        let want_notify = notify_request.wants_notify();
1348
1349        // Get record Arc — alias-aware (epics-base PR #336) so a CA
1350        // client that connects via an alias name can put fields on
1351        // the canonical record.
1352        let rec = self
1353            .get_record(record_name)
1354            .await
1355            .ok_or_else(|| CaError::ChannelNotFound(record_name.to_string()))?;
1356        // Normalise to the canonical name for the rest of this
1357        // function — every subsequent call (PACT/LCNT lookup,
1358        // `process_record_with_links`, `update_scan_index`) uses the
1359        // raw records map and would miss when `record_name` is an
1360        // alias. Resolve once up front.
1361        let canonical_owned;
1362        let record_name: &str = if let Some(target) = self.resolve_alias(record_name).await {
1363            canonical_owned = target;
1364            &canonical_owned
1365        } else {
1366            record_name
1367        };
1368
1369        // take the record's advisory write gate — the
1370        // `dbScanLock(precord)` analogue. While a QSRV atomic group
1371        // PUT/GET holds this record's gate via `lock_records`, this
1372        // plain write blocks here, so a direct backing-record write
1373        // can no longer land between member writes of an atomic group
1374        // transaction. Held until the function returns. Skipped when
1375        // the caller (atomic group PUT) already owns the gate — the
1376        // gate `Mutex` is not reentrant.
1377        let _record_gate = if acquire_gate {
1378            Some(self.lock_record(record_name).await)
1379        } else {
1380            None
1381        };
1382
1383        // Special field intercepts (read lock, then drop)
1384        {
1385            let instance = rec.read().await;
1386
1387            // C `dbPutField` gate order (`dbAccess.c:1252-1277`): the DISP
1388            // put-disable gate runs BEFORE `dbPut` — hence before the
1389            // SPC_NOMOD rejection of PACT/LCNT/PUTF (`dbAccess.c:123`) — and
1390            // BEFORE the PROC-driven `dbProcess`. So on a `DISP=1` record
1391            // EVERY non-DISP field, PROC included, is refused with
1392            // `S_db_putDisabled` and the record does not process.
1393            check_put_disabled(&instance, &field)?;
1394
1395            // SPC_NOMOD / read-only fields: rejected inside C's `dbPut`, i.e.
1396            // after the DISP gate above and before the PROC-driven process
1397            // below. One gate owner for every route ([`check_no_mod`]).
1398            check_no_mod(&instance, &field)?;
1399        }
1400
1401        // C `aSubRecord.c::special` / `subRecord.c::special` (SPC_MOD on SNAM):
1402        // the put owner resolves the subroutine name against the registry — the
1403        // record's `special()` cannot, having no DB handle. A non-empty,
1404        // unregistered name will make the after-put `special()` refuse the
1405        // write (`S_db_BadSub` → `ECA_PUTFAIL`) AFTER the value is stored, so
1406        // the lookup is done up front here and its verdict applied inside the
1407        // write below. An empty name names no routine and is accepted.
1408        let snam_registry_reject = {
1409            let name_to_resolve: Option<String> = {
1410                let guard = rec.read().await;
1411                if guard.record.is_subroutine_name_field(&field) {
1412                    match &value {
1413                        EpicsValue::String(s) => {
1414                            let name = s.as_str_lossy();
1415                            (!name.is_empty()).then(|| name.into_owned())
1416                        }
1417                        _ => None,
1418                    }
1419                } else {
1420                    None
1421                }
1422            };
1423            match name_to_resolve {
1424                Some(name) => self.find_subroutine_named(&name).await.is_none(),
1425                None => false,
1426            }
1427        };
1428
1429        // C `processNotifyCommon` (dbNotify.c:225-231) tests PACT ABOVE the
1430        // put — `if (precord->pact) { ... pnotify->state =
1431        // notifyRestartCallbackRequested; ... return; }` — so a put-notify that
1432        // lands on a busy record writes NOTHING: no value, no RPRO, no join of
1433        // the in-flight cycle's wait-set. The whole put is replayed by the
1434        // `PactExit` the record's PACT release hands to its `recGblFwdLink`
1435        // tail (C `dbNotifyCompletion`). Joining the running cycle instead
1436        // completed the callback one cycle early, on work that never saw this
1437        // value.
1438        //
1439        // The PACT test and the park are ONE critical section (C holds
1440        // `dbScanLock` across both): a park on a record that left PACT in
1441        // between would sit in a slot no PACT release will ever take, which is
1442        // precisely the strand the `PactExit` invariant forbids. A record that
1443        // goes idle in the window falls through and takes the put the ordinary
1444        // way.
1445        //
1446        // A second put-notify onto a record that already owns one is C's
1447        // "another processNotify owns the record" (dbNotify.c:213-217); the port
1448        // reports it to the client as `PutCallbackInProgress` (C `S_db_Blocked`
1449        // / `ECA_PUTCBINPROG`) rather than queueing a restart list.
1450        //
1451        // A fire-and-forget `dbPutField` is NOT deferred: it writes and raises
1452        // RPRO (dbAccess.c:1263-1277). Only the notify route waits.
1453        //
1454        // C `dbProcessNotify` (dbNotify.c:337-353) handles a put-notify to a
1455        // DBF link field (INLINK/OUTLINK/FWDLINK) as a dedicated early case,
1456        // ABOVE the PACT logic and the whole `processNotifyCommon` machinery:
1457        // "Only dbPutField will change link fields. Also the record is not
1458        // processed as a result." It writes the value via `dbPutField`
1459        // (`putFieldType`) and fires the done callback IMMEDIATELY — it never
1460        // reaches the PACT test, never processes, never defers. So a link
1461        // field always takes the value even on a busy or permanently-parked
1462        // record: a bare `sub` (empty `SNAM`) parks PACT=TRUE forever
1463        // (subRecord.c:119-122), and parking its link-field put on a `PactExit`
1464        // that never comes drops the value — `caput <sub>.INPA '0'` then reads
1465        // back "" instead of C's "0". The ordinary write path below already
1466        // reproduces C's link semantics for these fields (writes the value;
1467        // `put_drives_processing_of` is false — no link field is `pp` or PROC —
1468        // so it processes nothing and returns immediate completion), so the
1469        // only correction the special case needs is to keep a link field OUT
1470        // of the notify PACT-defer park.
1471        let is_dbf_link_field = {
1472            let guard = rec.read().await;
1473            crate::types::dbf_link_class(guard.record.record_type(), &field).is_some()
1474        };
1475        if want_notify && !is_dbf_link_field {
1476            let mut guard = rec.write().await;
1477            if guard.is_processing() {
1478                let Some((completion, completion_rx)) = notify_request.into_completion() else {
1479                    // Unreachable: `want_notify` is exactly "this request
1480
1481                    // carries a completion".
1482                    return Ok(None);
1483                };
1484                guard
1485                    .park_notify_put(crate::server::record::DeferredNotifyPut {
1486                        field,
1487                        value,
1488                        completion,
1489                    })
1490                    .map_err(|_| CaError::PutCallbackInProgress(record_name.to_string()))?;
1491                return Ok(completion_rx);
1492            }
1493        }
1494
1495        // PROC intercept: trigger processing on any SCAN.
1496        // Falls through to the put_notify_tx registration below
1497        // so async records (motor, asyn-backed AO) signal real
1498        // completion; otherwise WRITE_NOTIFY would return ECA_NORMAL
1499        // before the device move actually finished.
1500        //
1501        // C `dbPutField` (dbAccess.c:1265) matches the proc field by pointer
1502        // with NO value check: any write to PROC — including 0 — processes the
1503        // record (when !pact). The standard `caput REC.PROC 0` / `dbpf REC.PROC
1504        // 0` force-process idiom must therefore not be skipped for a zero value.
1505        if field == "PROC" {
1506            // C `dbCommon.dbd` declares `field(PROC,DBF_UCHAR){ pp(TRUE) }`, so
1507            // a put to PROC does BOTH: `dbPut` stores the raw byte in
1508            // `prec->proc` (retained — C never resets it), AND `pp(TRUE)` drives
1509            // the reprocess below. The prior port kept only the reprocess and
1510            // dropped the byte, so `caput REC.PROC v; caget REC.PROC` always
1511            // read 0. Store the byte through the SAME `DBF_UCHAR` common-field
1512            // path DISP/RPRO use (coercion + signed readback: `caput PROC 255` →
1513            // `caget` = -1) in its own brief write lock so both the notify and
1514            // fire-and-forget paths take it, then fall through to force-process.
1515            // C `dbPut:1408` posts DBE_VALUE|DBE_LOG for the put field (PROC is
1516            // not the record's value field, so the pp-suppression never applies).
1517            // Store the raw PROC byte (C `dbChannelPut`). A bad conversion
1518            // (`caput REC.PROC 256` / non-numeric) refuses the store AND the
1519            // client's put — but, exactly as C's `putCallback` returns
1520            // `didPut = 1` while setting `notifyError` (`dbNotify.c:528-530`),
1521            // the PROC `pp(TRUE)`-driven `dbProcess` (`dbNotify.c:243-261`) still
1522            // runs on the NOTIFY path. This is the SAME rule the general put path
1523            // applies for a rejected pp-field conversion (`field_io.rs:1748-1806`,
1524            // "Cause B"); mirror it here so PROC does not diverge from UDF: carry
1525            // the refusal, force-process when `want_notify`, then hand the Err
1526            // back so the client still sees `ECA_PUTFAIL`.
1527            let proc_store: CaResult<()> = {
1528                let rec_arc = {
1529                    let recs = self.inner.records.read().await;
1530                    recs.get(record_name).cloned()
1531                };
1532                if let Some(rec_arc) = rec_arc {
1533                    let mut guard = rec_arc.write().await;
1534                    match guard.put_common_field("PROC", value) {
1535                        Ok(_) => {
1536                            guard.notify_field(
1537                                "PROC",
1538                                crate::server::recgbl::EventMask::VALUE
1539                                    | crate::server::recgbl::EventMask::LOG,
1540                            );
1541                            Ok(())
1542                        }
1543                        Err(e) => Err(e),
1544                    }
1545                } else {
1546                    Ok(())
1547                }
1548            };
1549            if let Err(e) = proc_store {
1550                // `want_notify` ⇒ C `ca_put_callback`: the PROC process runs
1551                // despite the rejected conversion (`didPut == 1`). Fire-and-forget
1552                // ⇒ C plain `dbPutField`, which returns before `dbProcess` on a
1553                // non-zero `dbPut` status (`dbAccess.c:1263-1264`), so it must NOT
1554                // process. Either way the client is answered `ECA_PUTFAIL`.
1555                if want_notify {
1556                    let _ = self.put_driven_process_already_locked(record_name).await;
1557                }
1558                return Err(e);
1559            }
1560            // A fire-and-forget caller parks nothing — C `dbPutField` on PROC
1561            // processes the record with no putNotify.
1562            let parked = if let Some((completion_tx, completion_rx)) =
1563                notify_request.into_completion()
1564            {
1565                let notify = crate::server::record::NotifyWaitSet::new(completion_tx);
1566                {
1567                    // Collect-then-act: clone the handle under a brief map
1568                    // read, drop the map lock before the per-record write.
1569                    let rec_arc = {
1570                        let recs = self.inner.records.read().await;
1571                        recs.get(record_name).cloned()
1572                    };
1573                    if let Some(rec_arc) = rec_arc {
1574                        let mut guard = rec_arc.write().await;
1575                        if guard.notify.is_some() {
1576                            return Err(CaError::PutCallbackInProgress(record_name.to_string()));
1577                        }
1578                        guard.notify = Some(notify.clone());
1579                    }
1580                }
1581                Some((notify, completion_rx))
1582            } else {
1583                None
1584            };
1585            // C `dbPutField:1265-1277`: PROC is one of the two fields that
1586            // selects the record for the put-driven process — with the same
1587            // PACT→RPRO deferral as a `pp` field. Both go through the single
1588            // owner (R19-43).
1589            //
1590            // The ALREADY-LOCKED entry, unconditionally — NOT `acquire_gate`
1591            // passed through. By the time control reaches here the record's
1592            // advisory gate is held on both paths: this function took it above
1593            // when `acquire_gate`, and the caller (an atomic group PUT) holds it
1594            // when not. The gate `Mutex` is not reentrant, so acquiring it again
1595            // here deadlocks every PROC put.
1596            let _ = self.put_driven_process_already_locked(record_name).await;
1597            // The wait-set fires the oneshot only after the whole
1598            // FLNK/OUT chain (sync + async) settles. If it has
1599            // already completed the chain was fully synchronous —
1600            // report immediate success; otherwise hand the receiver
1601            // to the CA layer to await the deferred completion.
1602            return match parked {
1603                Some((notify, completion_rx)) => {
1604                    if notify.completed() {
1605                        Ok(None)
1606                    } else {
1607                        Ok(completion_rx)
1608                    }
1609                }
1610                None => Ok(None),
1611            };
1612        }
1613
1614        // Normal field put (write lock) — C `dbPut`, which does NOT touch
1615        // `putf`: the marker is raised only where C raises it, at the
1616        // put-driven process decision (`put_driven_process`).
1617        //
1618        // Link writes the record's `special()` makes itself. C runs them inside
1619        // `dbPut`, so they land BEFORE the `pp(TRUE)` process below — a record
1620        // wired to scaler `.COUTP` is processed with the scaler not yet armed
1621        // (scalerRecord.c:623-624, before the `:637` REQSTART).
1622        let mut special_actions = Vec::new();
1623        let mut instance = rec.write().await;
1624
1625        // C `db_put_process` (db_access.c:1025-1043) returns 1 (didPut) even
1626        // when the internal `dbChannelPut` FAILS — a rejected conversion, an
1627        // SPC_NOMOD refusal, or an after-put `special()` error all set
1628        // `ppn->status = notifyError` yet still `return 1` — so
1629        // `processNotifyCommon` (dbNotify.c:243-246) still runs `dbProcess`
1630        // when the gate passes. The whole put write is therefore wrapped so
1631        // that ANY failure inside it — `dbput_request`, `special()` pass 0,
1632        // `put_field`, `special_after_put`, `put_common_field` — is caught at
1633        // ONE place below: on the notify path we evaluate the SAME process gate
1634        // the success path uses and process the record as a side effect, then
1635        // hand the original Err back to the client. On the failing conversion
1636        // path no field is written — `dbChannelPut` wrote nothing either.
1637        //
1638        // On SUCCESS this closure is just C `dbPut`: the monitor posts at its
1639        // tail run only when the put fully succeeded (C's `goto done` skips
1640        // them on failure).
1641        let block_result: CaResult<crate::server::record::CommonFieldPutResult> = (|| {
1642            // Coerce value to the field's native DBR type (e.g. String → Double for ao.VAL).
1643            // This matches C EPICS db_put_field() which converts from the CA client's type
1644            // to the record field's native type.
1645            let request = dbput_request(&*instance.record, &field, value)?;
1646
1647            // Pre-write special hook (C EPICS dbPutSpecial pass=0)
1648            instance.record.special(&field, false)?;
1649            special_before_put(&mut instance, &field);
1650
1651            // Capture pre-put value for faac1df1 idempotent-write suppression.
1652            let prev_value = instance.record.get_field(&field);
1653            let old_nord = array_nord_before_put(&instance, &field);
1654
1655            // Try record-specific field first; fall back to common on FieldNotFound.
1656            // For record-owned fields, call on_put() and special() after successful put,
1657            // matching what put_common_field() does for common fields.
1658            use crate::server::record::CommonFieldPutResult;
1659            let common_result = match request {
1660                // C `dbAccess.c:1370-1372` — a zero-element request into a
1661                // scalar field: nothing is written, the record is driven to
1662                // LINK/INVALID, and `dbPut` returns 0. The client's put
1663                // SUCCEEDS; the record's process cycle below commits the alarm
1664                // and posts it, which is how a C IOC surfaces `caput -a`
1665                // of an empty array.
1666                PutRequest::EmptyIntoScalar => {
1667                    set_empty_request_alarm(&mut instance);
1668                    CommonFieldPutResult::NoChange
1669                }
1670                PutRequest::Write(value) => {
1671                    match instance.record.put_field(&field, value.clone()) {
1672                        Ok(()) => {
1673                            instance.record.on_put(&field);
1674                            // C returns the after-put special() status from
1675                            // `dbPut` (dbAccess.c:1399-1405); `if (status)
1676                            // goto done` then skips both the UDF clear below
1677                            // and the field's monitor post, and `dbPutField`
1678                            // skips the process. Propagating the error here
1679                            // reproduces all three.
1680                            let result =
1681                                special_after_put(&mut instance, &field, &mut special_actions)?;
1682                            // C `aSubRecord.c::special` / `subRecord.c::special`
1683                            // (SPC_MOD on SNAM): the name was stored by
1684                            // `put_field` above (C keeps `prec->snam`), but an
1685                            // unregistered name makes `special(after)` return
1686                            // `S_db_BadSub`. The registry is the DB's,
1687                            // unreachable from the record's `special()`, so the
1688                            // lookup was performed up front and its refusal is
1689                            // applied here — the same point C's `dbPut` returns
1690                            // the after-put `special()` status: value kept, no
1691                            // field monitor post, no `pp` process, client sees
1692                            // `ECA_PUTFAIL` ("Channel write request failed").
1693                            if snam_registry_reject {
1694                                return Err(CaError::BadField("SNAM: Subroutine not found".into()));
1695                            }
1696                            // C `dbAccess.c::dbPut:1410-1411` clears
1697                            // `precord->udf = FALSE` synchronously when the
1698                            // put target is the record-type's primary value
1699                            // field (`dbIsValueField`), and clears NOTHING
1700                            // else. The clear happens BEFORE `dbProcess` runs,
1701                            // so any reader between the put and the process
1702                            // cycle sees the new value with a consistent
1703                            // udf=false — but stat/sevr keep their old
1704                            // UDF_ALARM until the process cycle recomputes
1705                            // them. A value put that drives no process leaves
1706                            // the stale UDF alarm, matching C; the process
1707                            // path's own `rec_gbl_check_udf` (now a no-op with
1708                            // udf clear) + `rec_gbl_reset_alarms` clears it
1709                            // when the record does process. The earlier
1710                            // synchronous stat/sevr clear here diverged from C.
1711                            if instance.record.is_udf_defining_put(&field) {
1712                                instance.common.udf = 0;
1713                            }
1714                            result
1715                        }
1716                        Err(CaError::FieldNotFound(_)) => {
1717                            instance.put_common_field(&field, value)?
1718                        }
1719                        Err(e) => return Err(e),
1720                    }
1721                }
1722            };
1723
1724            // C `add_count` writes stat/sevr DIRECTLY during a SGNL SPC_MOD
1725            // `special()` (histogramRecord.c:329-334); with no monitor on the
1726            // special path that write STICKS and a later caget observes it
1727            // (STAT=SOFT on inverted limits). `check_alarms` performs that
1728            // direct write. Unlike the process path — where the cycle's
1729            // `recGblResetAlarms` erases it — this special-only put runs no
1730            // process, so it persists, matching C. Gated on
1731            // `special_checks_alarms` (histogram SGNL only). No STAT post: C's
1732            // `add_count` posts nothing, and the special path has no monitor.
1733            if instance.record.special_checks_alarms(&field) {
1734                let inst = &mut *instance;
1735                inst.record.check_alarms(&mut inst.common);
1736            }
1737
1738            // Invalidate metadata cache only if the metadata-class
1739            // field's value actually changed (faac1df1).
1740            instance.notify_field_written_if_changed(&field, prev_value.as_ref());
1741
1742            // `putf` is neither set nor cleared anywhere in this block: C's
1743            // `dbPut` does not touch it. It is raised in `put_driven_process`
1744            // (C `dbAccess.c:1274`) immediately before `dbProcess`, stays TRUE
1745            // for the whole process cycle — including an async device round
1746            // trip — and is cleared by the `recGblFwdLink:302` analogue at the
1747            // cycle's tail (`processing.rs:2997` / `complete_async_record_inner`)
1748            // or by the disable-alarm bail (`dbAccess.c:576`).
1749
1750            instance.cleanup_subscribers();
1751            // C `dbPut:1408-1414` posts DBE_VALUE|DBE_LOG for the put field
1752            // unless `(isValueField && pfldDes->process_passive)` — the
1753            // immediate post is suppressed for the value field ONLY when that
1754            // field is `pp(TRUE)`, because then the reprocess cycle
1755            // (`dbPutField:1265-1268`) re-posts it via the deadband snapshot.
1756            // For a value field that is NOT `pp` (calc/calcout/aSub VAL), C
1757            // posts here and does not reprocess; the port must do the same,
1758            // because the `should_process` gate below skips the cycle for a
1759            // non-`pp` value field — without this post a direct VAL put would
1760            // fire no monitor at all.
1761            // (ACKT/ACKS have no arm here: they are SPC_NOMOD, refused by the
1762            // gate above. Alarm acknowledgement arrives as a DBR request type,
1763            // through [`Self::put_alarm_ack_from_ca`].)
1764            //
1765            // Suppress the immediate value-field post only when this put
1766            // will itself drive a reprocess (the cycle re-posts the field).
1767            // `process_passive_fields()` is total/fail-safe: a put to a
1768            // non-pp field — including any field of an unmodeled type
1769            // (`&[]`) — does not reprocess, so it is not suppressed here.
1770            let suppress_value_field_post = field == instance.record.primary_field()
1771                && instance
1772                    .record
1773                    .process_passive_fields()
1774                    .iter()
1775                    .any(|f| f.eq_ignore_ascii_case(&field));
1776            if !suppress_value_field_post {
1777                instance.notify_field(
1778                    &field,
1779                    crate::server::recgbl::EventMask::VALUE | crate::server::recgbl::EventMask::LOG,
1780                );
1781            }
1782
1783            // The NORD post, through the one owner — C reaches `put_array_info`
1784            // from `dbPut`, so the CA route posts it exactly like the internal
1785            // one. It is NOT covered by the value-field post above: for a
1786            // waveform that post is suppressed (VAL is `pp(TRUE)`), and it is
1787            // not covered by the process cycle either — a `caput -a` to a
1788            // slow-scanned or passive-but-unprocessed waveform posts NORD now
1789            // and VAL only at the next scan.
1790            post_array_info(&mut instance, &old_nord, 0);
1791
1792            // Fields a `special()` changed as a side effect of this put
1793            // (e.g. compress RES reset zeroing NUSE/VAL) get their monitors
1794            // posted here, mirroring the explicit `db_post_events` a C
1795            // `special()` makes — these fields are not pp(TRUE), so no
1796            // process cycle would otherwise post them. Each post carries
1797            // VALUE|LOG unless the record names the field in
1798            // `value_only_change_fields()` — a record whose C `special()`
1799            // posts the field with a literal `DBE_VALUE` (e.g. table SET,
1800            // tableRecord.c:659) gets the LOG bit stripped, honoring the
1801            // same value-only contract as the change-detection path.
1802            //
1803            // C's `monitor()` runs `recGblResetAlarms(prec)` BEFORE those
1804            // `db_post_events`, and OR-adds the alarm bit it returns into the
1805            // value posts (compressRecord.c:103-110). The port mirrors that
1806            // order: commit the alarm here (posting any STAT/SEVR/AMSG/ACKS
1807            // transition through the one owner, `alarm_field_posts`) and carry
1808            // the resulting DBE_ALARM into the side-effect posts below. Records
1809            // whose `special()` does not run `monitor()` return false and skip
1810            // this entirely (no spurious alarm commit on an unrelated put).
1811            let side_effect_alarm_mask = if instance.record.special_commits_alarms(&field) {
1812                commit_special_reset_alarm(&mut instance)
1813            } else {
1814                crate::server::recgbl::EventMask::NONE
1815            };
1816
1817            let side_effect_value_only = instance.record.value_only_change_fields();
1818            for sf in instance.record.monitor_side_effect_fields(&field) {
1819                use crate::server::recgbl::EventMask;
1820                let mask = if side_effect_value_only
1821                    .iter()
1822                    .any(|f| f.eq_ignore_ascii_case(sf))
1823                {
1824                    EventMask::VALUE
1825                } else {
1826                    EventMask::VALUE | EventMask::LOG
1827                };
1828                instance.notify_field(sf, mask | side_effect_alarm_mask);
1829            }
1830
1831            // The same `special()` posts, but named by the WRITER instead of
1832            // by a static table: a record whose put handler re-derived a
1833            // partner field marks it — with the mask of the C call site that
1834            // posts it, and only when that field's own comparison moved
1835            // (sseq `special()` posts the re-rendered `STRn` after a `DOn`
1836            // put, `DBE_VALUE`, `only if (strcmp(str, plinkGroup->s))`,
1837            // sseqRecord.c:1108-1116). A static field-name list cannot
1838            // express "only if it changed", so it over-posts; the mark can.
1839            emit_cycle_posts(&mut instance);
1840
1841            Ok(common_result)
1842        })();
1843
1844        // Cause B: a put-NOTIFY whose write was rejected must still process.
1845        // C `db_put_process` returned 1 (didPut) despite the failure above, so
1846        // `processNotifyCommon` runs `dbProcess` whenever the gate passes.
1847        // Reuse the SAME `put_drives_processing_of` gate the success tail uses,
1848        // process the record as a side effect, then return the ORIGINAL Err —
1849        // the CA layer maps it to PUTFAIL (C `notifyError`) and `put_accepted`
1850        // stays False, while STAT/SEVR recompute to match C. The notify path
1851        // ONLY: a plain `dbPutField` failure processes nothing (dbAccess.c:1263
1852        // processes only when `dbPut` status==0), so `want_notify == false`
1853        // keeps its Err-without-process behavior. The instance write lock must
1854        // drop before `put_driven_process_already_locked` re-acquires it.
1855        let common_result = match block_result {
1856            Ok(cr) => {
1857                drop(instance);
1858                cr
1859            }
1860            Err(e) => {
1861                // C `dbPut:83-88` runs `dbPutSpecial(paddr, 1)` UNCONDITIONALLY
1862                // ("Always do special processing if needed") — even when the
1863                // conversion above failed — before the `goto done` that skips
1864                // the udf clear and the field's monitor post. For a compress
1865                // SPC_RESET field that means `special()` still runs `monitor()`
1866                // → `recGblResetAlarms`, committing the born-UDF alarm to
1867                // NO_ALARM though the RES/N put is rejected (a caget then sees
1868                // stat/sevr=NO_ALARM with udf still 1, matching C softIoc).
1869                // Run the after-put `special()` and its alarm commit here, then
1870                // hand back the ORIGINAL Err so the client still sees PUTFAIL.
1871                // Gated on `special_commits_alarms` (compress only) so no other
1872                // special record runs its after-put hook on a failed conversion.
1873                if instance.record.special_commits_alarms(&field) {
1874                    let _ = instance.record.special(&field, true);
1875                    let alarm_mask = commit_special_reset_alarm(&mut instance);
1876                    let value_only = instance.record.value_only_change_fields();
1877                    for sf in instance.record.monitor_side_effect_fields(&field) {
1878                        use crate::server::recgbl::EventMask;
1879                        let mask = if value_only.iter().any(|f| f.eq_ignore_ascii_case(sf)) {
1880                            EventMask::VALUE
1881                        } else {
1882                            EventMask::VALUE | EventMask::LOG
1883                        };
1884                        instance.notify_field(sf, mask | alarm_mask);
1885                    }
1886                }
1887                // The same `dbPutSpecial(paddr, 1)`-on-reject rule for a field
1888                // whose special() writes stat/sevr DIRECTLY (histogram SGNL →
1889                // add_count): C still runs add_count when the SGNL conversion
1890                // fails, so its stuck STAT=SOFT on inverted limits appears even
1891                // for a rejected `caput .SGNL notanumber`. `check_alarms` makes
1892                // that direct write; no process follows, so it persists.
1893                if instance.record.special_checks_alarms(&field) {
1894                    let inst = &mut *instance;
1895                    inst.record.check_alarms(&mut inst.common);
1896                }
1897                // The same `dbPutSpecial(paddr, 1)`-on-reject rule for a field
1898                // whose special() clears UDF: C `mbboDirectRecord.c::special`
1899                // (after==1, B0..B1F, line 290) sets `prec->udf = FALSE`, and
1900                // that special runs UNCONDITIONALLY in `dbPut` (dbAccess.c:1401,
1901                // "Always do special processing") even when the value conversion
1902                // failed — BEFORE the `if (status) goto done`. So a rejected
1903                // `caput -c mbboDirect.Bn 256`/`notanumber` still clears UDF, and
1904                // the notify-process that follows recomputes STAT/SEVR to
1905                // NO_ALARM instead of the born-UDF INVALID (verified live against
1906                // the C softIoc: fresh record → rejected Bn put → NO_ALARM,
1907                // udf=0). The success path clears UDF for this same field set via
1908                // `is_udf_defining_put` (the `udf = 0` at the tail of the put
1909                // body). The primary VAL field is EXCLUDED here: its UDF clear is
1910                // `isValueField` (dbAccess.c:1408), which runs AFTER the status
1911                // check, so a rejected VAL put keeps UDF — matching C. Only
1912                // mbboDirect overrides `is_udf_defining_put` to add non-primary
1913                // fields, so this is a no-op for every other record type.
1914                if instance.record.is_udf_defining_put(&field)
1915                    && field != instance.record.primary_field()
1916                {
1917                    instance.common.udf = 0;
1918                }
1919                if want_notify && put_drives_processing_of(&instance, &field) {
1920                    drop(instance);
1921                    let _ = self.put_driven_process_already_locked(record_name).await;
1922                }
1923                return Err(e);
1924            }
1925        };
1926        // ASG-field change re-evaluation hook. C
1927        // `asDbLib.c:107-110,144` `asSpcAsCallback` invokes
1928        // `asChangeGroup` → `asAddMemberPvt` → `asComputePvt` for
1929        // every `ASGCLIENT` on `dbPut record.ASG NEW_ASG`. Pre-fix
1930        // Rust mutated `common.asg` directly with no notification,
1931        // so the wire ACCESS_RIGHTS the client saw still reflected
1932        // the OLD ASG until something else triggered re-eval. Now we
1933        // fire a process-wide notifier that the CA server folds into
1934        // its per-client `reeval_access_rights` path.
1935        if field == "ASG" {
1936            crate::server::access_security::notify_asg_field_changed();
1937        }
1938        // record lock released
1939
1940        // C `dbPutField` reaches `dbProcess` only after `dbPut` — and therefore
1941        // after `dbPutSpecial(paddr, 1)` and every `dbPutLink` it made — has run
1942        // to completion. Execute them here, ahead of the `pp(TRUE)` process.
1943        self.run_special_actions(record_name, &rec, std::mem::take(&mut special_actions))
1944            .await;
1945
1946        // Update scan index if SCAN or PHAS changed
1947        match common_result {
1948            crate::server::record::CommonFieldPutResult::ScanChanged {
1949                old_scan,
1950                new_scan,
1951                phas,
1952            } => {
1953                self.update_scan_index(record_name, old_scan, new_scan, phas, phas)
1954                    .await;
1955            }
1956            crate::server::record::CommonFieldPutResult::PhasChanged {
1957                scan: s,
1958                old_phas,
1959                new_phas,
1960            } => {
1961                self.update_scan_index(record_name, s, s, old_phas, new_phas)
1962                    .await;
1963            }
1964            crate::server::record::CommonFieldPutResult::NoChange => {}
1965        }
1966
1967        // C `dbAccess.c::dbPutField:1263-1268` re-processes the
1968        // record on a put only when the put field is `pp(TRUE)` AND the
1969        // record is Passive (`SCAN == 0`). (The `PROC` field has its own
1970        // always-process intercept above, matching C's
1971        // `pfield == &precord->proc`; alarm-ack fields like ACKT/ACKS are
1972        // not `pp(TRUE)` so they fall out here, matching C's
1973        // `dbrType < DBR_PUT_ACKT`.) Processing on every put would
1974        // double-process scanned records and spuriously process puts to
1975        // non-`pp` fields (extra FLNK / monitors / device writes /
1976        // timestamps). `process_passive_fields()` is total and fail-safe: an
1977        // unmodeled type returns `&[]` (and warns once), so it processes on
1978        // `PROC` only — spurious processing is opt-in (a type must declare its
1979        // pp set), never the default.
1980        let should_process = {
1981            let instance = rec.read().await;
1982            put_drives_processing_of(&instance, &field)
1983        };
1984
1985        if !should_process {
1986            // No processing cycle, so C never raises `putf` (and this put did
1987            // not either). Report immediate (synchronous) completion to a
1988            // WRITE_NOTIFY caller.
1989            return Ok(None);
1990        }
1991
1992        // Set up the put-notify wait-set BEFORE processing. The wait-set
1993        // fires `completion_tx` only after the originating record AND
1994        // every FLNK/OUT chain target it triggers (sync or async) has
1995        // completed — C `dbNotify.c` `processNotify`/`dbNotifyCompletion`.
1996        // Refuse a second concurrent WRITE_NOTIFY on the same record:
1997        // C EPICS returns S_db_Blocked / ECA_PUTCBINPROG, and silently
1998        // overwriting the wait-set would drop the prior Sender, waking
1999        // the prior caller's rx with RecvError that the CA dispatcher
2000        // treats as success.
2001        //
2002        // A fire-and-forget put parks NOTHING — C builds a `putNotify`
2003        // only in `dbPutNotify`; `dbPutField` processes the record with
2004        // no notify state at all. It therefore neither conflicts with
2005        // nor disturbs a WRITE_NOTIFY already parked on the record.
2006        let parked = if let Some((completion_tx, completion_rx)) = notify_request.into_completion()
2007        {
2008            let notify = crate::server::record::NotifyWaitSet::new(completion_tx);
2009            {
2010                // Collect-then-act: clone the handle under a brief map read,
2011                // drop the map lock before the per-record write.
2012                let rec_arc = {
2013                    let recs = self.inner.records.read().await;
2014                    recs.get(record_name).cloned()
2015                };
2016                if let Some(rec_arc) = rec_arc {
2017                    let mut guard = rec_arc.write().await;
2018                    if guard.notify.is_some() {
2019                        return Err(CaError::PutCallbackInProgress(record_name.to_string()));
2020                    }
2021                    guard.notify = Some(notify.clone());
2022                }
2023            }
2024            Some((notify, completion_rx))
2025        } else {
2026            None
2027        };
2028
2029        // When a CA put writes directly to VAL on an INPUT record whose
2030        // VAL is the engineering value, the built-in `RVAL → VAL`
2031        // `convert()` must be suppressed for the put-driven process —
2032        // re-deriving VAL from a stale RVAL would clobber the value the
2033        // operator just wrote (the soft ai preset-NaN case, processing.rs
2034        // ~line 677). The framework expresses this by calling
2035        // `set_device_did_compute(true)`.
2036        //
2037        // This MUST be gated on `soft_channel_skips_convert()`. Output
2038        // records (mbbo/mbbo_direct/bo/ao) implement
2039        // `set_device_did_compute` as "skip the VAL → RVAL output
2040        // convert" — the OPPOSITE direction. C `mbboRecord.c::process`
2041        // (line 217), `mbboDirectRecord.c::process` (line 198) and
2042        // `boRecord.c::process` (line 207) call `convert()`
2043        // unconditionally on every non-pact process; a CA VAL-put on an
2044        // output record MUST recompute RVAL/ORAW. Suppressing it there
2045        // left RVAL/ORAW/ORBV stale. Output records return the default
2046        // `false` from `soft_channel_skips_convert()`, so this gate
2047        // matches the identical gates in processing.rs (line 694) and
2048        // record_instance.rs (line 1381).
2049        if field == "VAL" {
2050            // Collect-then-act: clone the handle under a brief map read, drop
2051            // the map lock before the per-record write.
2052            let rec_arc = {
2053                let recs = self.inner.records.read().await;
2054                recs.get(record_name).cloned()
2055            };
2056            if let Some(rec_arc) = rec_arc {
2057                let mut guard = rec_arc.write().await;
2058                if guard.record.soft_channel_skips_convert() {
2059                    guard.record.set_device_did_compute(true);
2060                }
2061            }
2062        }
2063
2064        // Process the record after field put — through the single owner of C's
2065        // `dbPutField:1269-1277` decision, so an async-active record takes the
2066        // RPRO deferral instead of a doomed re-entrant `dbProcess`.
2067        let _ = self.put_driven_process_already_locked(record_name).await;
2068
2069        // Is the ORIGINATING record itself still async-pending? Its
2070        // wait-set membership is taken + `leave`d at its own completion
2071        // (sync-end, or later in `complete_async_record_inner`), so a
2072        // lingering `notify` on its instance means its device round-trip
2073        // is still in flight. This gates only the originating record's
2074        // PUTF clear — independent of whether downstream chain targets
2075        // are still pending.
2076        //
2077        // A fire-and-forget put parked nothing, and a `notify` it sees
2078        // on the instance belongs to some other caller's WRITE_NOTIFY —
2079        // not evidence about THIS put. Fall through to the guarded
2080        // clear; its `!is_processing()` gate already preserves PUTF
2081        // across an async-pending device round-trip.
2082        let originating_pending = want_notify && {
2083            let rec = self.inner.records.read().await;
2084            if let Some(rec_arc) = rec.get(record_name) {
2085                rec_arc.read().await.notify.is_some()
2086            } else {
2087                false
2088            }
2089        };
2090
2091        // C `recGbl.c::recGblFwdLink:302` clears `putf = FALSE` after
2092        // the forward-link dispatch — the marker only lives for the
2093        // duration of the put's processing cycle. For SYNCHRONOUS
2094        // completions (PACT was cleared by the time
2095        // `process_record_with_links` returns) clear it here. For
2096        // async-pending records, the clearing happens later in
2097        // `complete_async_record_inner` (which runs FLNK as part of
2098        // the completion path) so the PUTF marker survives the
2099        // device-write round trip.
2100        if !originating_pending {
2101            // Collect-then-act: clone the handle under a brief map read, drop
2102            // the map lock before the per-record write.
2103            let rec_arc = {
2104                let recs = self.inner.records.read().await;
2105                recs.get(record_name).cloned()
2106            };
2107            if let Some(rec_arc) = rec_arc {
2108                let mut guard = rec_arc.write().await;
2109                if !guard.is_processing() {
2110                    guard.common.putf = false;
2111                }
2112            }
2113        }
2114
2115        // CA completion gates on the WHOLE chain, not just the
2116        // originating record: the put-notify must not report
2117        // done until every FLNK/OUT target it drove — including an async
2118        // FLNK target that the originating record's sync cycle merely
2119        // kicked off — has settled. `completed()` is true iff the
2120        // wait-set drained to zero during this call (fully synchronous
2121        // chain); otherwise the receiver fires later from the last
2122        // chain member's `leave`.
2123        match parked {
2124            Some((notify, completion_rx)) => {
2125                if notify.completed() {
2126                    Ok(None)
2127                } else {
2128                    Ok(completion_rx)
2129                }
2130            }
2131            None => Ok(None),
2132        }
2133    }
2134
2135    /// Put a PV value without triggering process (for restore).
2136    pub async fn put_pv_no_process(&self, name: &str, value: EpicsValue) -> CaResult<()> {
2137        let (base, field) = super::parse_pv_name(name);
2138        let field = field.to_ascii_uppercase();
2139
2140        if let Some(pv) = self.inner.simple_pvs.read().await.get(name) {
2141            pv.set(value).await;
2142            return Ok(());
2143        }
2144
2145        // Records — alias-aware (epics-base PR #336).
2146        if let Some(rec) = self.get_record(base).await {
2147            // `put_pv_no_process` is a public record-write API
2148            // (autosave restore). It must take the advisory write gate
2149            // (`dbScanLock` analogue) so an autosave restore cannot
2150            // land between the member writes of a QSRV atomic group or
2151            // a pvalink atomic scan epoch holding `lock_records`.
2152            // `base` is alias-resolved so an alias and its target
2153            // share one gate. Held until return.
2154            let canonical_base: String = self
2155                .resolve_alias(base)
2156                .await
2157                .unwrap_or_else(|| base.to_string());
2158            let _record_gate = self.lock_record(&canonical_base).await;
2159
2160            let mut instance = rec.write().await;
2161            let prev_value = instance.record.get_field(&field);
2162            match instance.record.put_field(&field, value.clone()) {
2163                Ok(()) => {}
2164                Err(CaError::FieldNotFound(_)) => {
2165                    instance.put_common_field(&field, value)?;
2166                }
2167                Err(e) => return Err(e),
2168            }
2169            // Invalidate metadata cache only if the metadata-class
2170            // field actually changed (faac1df1).
2171            instance.notify_field_written_if_changed(&field, prev_value.as_ref());
2172            // same SPC_AS parity as `put_pv` / the CA-write
2173            // path — autosave-style restores writing `.ASG` at IOC
2174            // startup must still trigger per-client re-eval.
2175            if field == "ASG" {
2176                crate::server::access_security::notify_asg_field_changed();
2177            }
2178            return Ok(());
2179        }
2180
2181        Err(CaError::ChannelNotFound(name.to_string()))
2182    }
2183}
2184
2185/// Project a decoded `DBR_CTRL_*` / `DBR_GR_*` snapshot's metadata fields
2186/// (display / control limits, enum labels) into the shadow-PV
2187/// [`PvMetadata`](crate::server::pv::PvMetadata) the CA gateway installs.
2188/// A non-metadata (TIME/STS) snapshot carries `None` in all three, which
2189/// clears the shadow metadata — but the gateway only ever feeds this a
2190/// control-class snapshot, matching C `setPvData` replacing the attribute
2191/// gdd wholesale from the control get/event.
2192fn metadata_from_snapshot(snapshot: &Snapshot) -> crate::server::pv::PvMetadata {
2193    crate::server::pv::PvMetadata {
2194        display: snapshot.display.clone(),
2195        control: snapshot.control.clone(),
2196        enums: snapshot.enums.clone(),
2197    }
2198}
2199
2200#[cfg(test)]
2201mod tests {
2202    use super::super::PvDatabase;
2203    use crate::types::EpicsValue;
2204
2205    /// Regression: prior to fixing B1, `put_pv_and_post` walked only
2206    /// `inner.records` and returned `ChannelNotFound` for everything
2207    /// `add_pv`-registered. The CA gateway's monitor forwarder uses
2208    /// `add_pv` then expects `put_pv_and_post` to fan-out to
2209    /// downstream subscribers — without the simple-PV branch, every
2210    /// upstream event was silently dropped and the gateway delivered
2211    /// no monitors.
2212    #[tokio::test]
2213    async fn put_pv_and_post_handles_simple_pv() {
2214        let db = PvDatabase::new();
2215        db.add_pv("gw:test", EpicsValue::Double(0.0)).await.unwrap();
2216
2217        // Should NOT return ChannelNotFound.
2218        db.put_pv_and_post("gw:test", EpicsValue::Double(42.0))
2219            .await
2220            .expect("simple PV put_pv_and_post must succeed");
2221
2222        // Value actually landed.
2223        let pv = db.find_pv("gw:test").await.expect("PV exists");
2224        assert!(matches!(pv.get().await, EpicsValue::Double(v) if v == 42.0));
2225    }
2226
2227    /// Regression: `get_pv`, `put_pv`, `put_pv_and_post`,
2228    /// and `put_pv_no_process` all bypassed `get_record` and walked
2229    /// `self.inner.records` directly, so alias names from epics-base
2230    /// PR #336 silently returned `ChannelNotFound`. A later fix closed
2231    /// `get_record` but the same defect was hiding in field_io.rs.
2232    /// All four CA-server-and-bridge entry points must accept aliases.
2233    #[tokio::test]
2234    async fn field_io_entry_points_accept_aliases() {
2235        use crate::server::records::ai::AiRecord;
2236
2237        let db = PvDatabase::new();
2238        db.add_record("CANON", Box::new(AiRecord::new(0.0)))
2239            .await
2240            .unwrap();
2241        db.add_alias("ALT", "CANON").await.unwrap();
2242
2243        // get_pv via alias
2244        db.put_pv("CANON.VAL", EpicsValue::Double(1.5))
2245            .await
2246            .unwrap();
2247        let v = db.get_pv("ALT.VAL").await.unwrap();
2248        assert!(matches!(v, EpicsValue::Double(x) if x == 1.5));
2249
2250        // put_pv via alias
2251        db.put_pv("ALT.VAL", EpicsValue::Double(7.0)).await.unwrap();
2252        let v = db.get_pv("CANON.VAL").await.unwrap();
2253        assert!(matches!(v, EpicsValue::Double(x) if x == 7.0));
2254
2255        // put_pv_and_post via alias
2256        db.put_pv_and_post("ALT.VAL", EpicsValue::Double(11.0))
2257            .await
2258            .unwrap();
2259        let v = db.get_pv("CANON.VAL").await.unwrap();
2260        assert!(matches!(v, EpicsValue::Double(x) if x == 11.0));
2261
2262        // put_pv_no_process via alias
2263        db.put_pv_no_process("ALT.VAL", EpicsValue::Double(13.0))
2264            .await
2265            .unwrap();
2266        let v = db.get_pv("ALT.VAL").await.unwrap();
2267        assert!(matches!(v, EpicsValue::Double(x) if x == 13.0));
2268    }
2269
2270    /// A `DBR_STRING` menu label written to a `DBF_MENU` field resolves
2271    /// against THAT field's own menu (C `dbConvert` `putStringMenu`), not the
2272    /// field-blind global table that `EpicsValue::convert_to` would consult.
2273    /// Covers the `put_pv` (`put_pv_inner`) and `put_pv_and_post` coercion
2274    /// sites; the CA field-put path (`put_record_field_from_ca_inner`) shares
2275    /// the identical `coerce_write_value` helper.
2276    #[tokio::test]
2277    async fn write_path_menu_label_resolves_against_field_menu() {
2278        use crate::server::records::sel::SelRecord;
2279
2280        let db = PvDatabase::new();
2281        db.add_record("SEL", Box::new(SelRecord::default()))
2282            .await
2283            .unwrap();
2284
2285        // put_pv (put_pv_inner): "Specified" is selSELM index 0, NOT the
2286        // menuFanout index 1 the global table would have returned.
2287        db.put_pv("SEL.SELM", EpicsValue::String("Specified".into()))
2288            .await
2289            .unwrap();
2290        assert_eq!(db.get_pv("SEL.SELM").await.unwrap(), EpicsValue::Enum(0));
2291
2292        // put_pv_and_post: a later choice, proving the whole menu.
2293        db.put_pv_and_post("SEL.SELM", EpicsValue::String("High Signal".into()))
2294            .await
2295            .unwrap();
2296        assert_eq!(db.get_pv("SEL.SELM").await.unwrap(), EpicsValue::Enum(1));
2297
2298        // A bare numeric string still resolves (C epicsParseUInt16 fallback).
2299        db.put_pv("SEL.SELM", EpicsValue::String("2".into()))
2300            .await
2301            .unwrap();
2302        assert_eq!(db.get_pv("SEL.SELM").await.unwrap(), EpicsValue::Enum(2));
2303    }
2304
2305    /// `set_pv_metadata` installs the upstream `DBR_CTRL_*` metadata on a
2306    /// shadow simple PV WITHOUT posting any event (the CA gateway's
2307    /// connect-time seed). A later GET-class read must then see the
2308    /// installed limits/units, and a `DBE_PROPERTY` subscriber must NOT
2309    /// have received anything (nothing *changed* yet). An unknown / record
2310    /// name is rejected with `ChannelNotFound`.
2311    #[tokio::test]
2312    async fn set_pv_metadata_installs_without_posting() {
2313        use crate::error::CaError;
2314        use crate::server::snapshot::{DisplayInfo, Snapshot};
2315        use crate::types::DbFieldType;
2316        use std::time::SystemTime;
2317
2318        let db = PvDatabase::new();
2319        db.add_pv("gw:meta", EpicsValue::Double(0.0)).await.unwrap();
2320
2321        // A DBE_PROPERTY subscriber attached BEFORE the seed — it must stay
2322        // empty, because seeding metadata is not a property *change*.
2323        const DBE_PROPERTY: u16 = 8;
2324        let pv = db.find_pv("gw:meta").await.expect("PV exists");
2325        let mut prop_rx = pv
2326            .add_subscriber(1, DbFieldType::Double, DBE_PROPERTY)
2327            .await
2328            .expect("subscriber added");
2329
2330        // Build a CTRL-class snapshot carrying display metadata.
2331        let mut ctrl = Snapshot::new(EpicsValue::Double(0.0), 0, 0, SystemTime::UNIX_EPOCH);
2332        ctrl.display = Some(DisplayInfo {
2333            units: "mm".into(),
2334            precision: 3,
2335            upper_disp_limit: 10.0,
2336            lower_disp_limit: -10.0,
2337            ..Default::default()
2338        });
2339
2340        db.set_pv_metadata("gw:meta", &ctrl)
2341            .await
2342            .expect("simple PV set_pv_metadata must succeed");
2343
2344        // The metadata landed on the shadow PV.
2345        let installed = pv.metadata();
2346        assert_eq!(
2347            installed.display.expect("display metadata installed").units,
2348            "mm"
2349        );
2350
2351        // No event was posted (seed != change).
2352        assert!(
2353            prop_rx.try_recv().is_err(),
2354            "set_pv_metadata must not post a DBE_PROPERTY event"
2355        );
2356
2357        // Unknown / non-simple PV is rejected.
2358        assert!(matches!(
2359            db.set_pv_metadata("no:such:pv", &ctrl).await,
2360            Err(CaError::ChannelNotFound(_))
2361        ));
2362    }
2363
2364    /// `post_pv_property` refreshes the shadow metadata AND posts a
2365    /// `DBE_PROPERTY` event carrying the supplied snapshot's metadata,
2366    /// upstream status/severity, and (undefined control-DBR) timestamp — to
2367    /// `DBE_PROPERTY` subscribers only. This is the DB-routing layer the
2368    /// gateway's property monitor drives on every upstream `DBE_PROPERTY`
2369    /// event. An unknown / record name is rejected with `ChannelNotFound`.
2370    #[tokio::test]
2371    async fn post_pv_property_refreshes_and_posts_property_event() {
2372        use crate::error::CaError;
2373        use crate::server::snapshot::{DisplayInfo, Snapshot};
2374        use crate::types::{DbFieldType, WallTime};
2375
2376        const DBE_PROPERTY: u16 = 8;
2377        const DBE_VALUE: u16 = 1;
2378        const MAJOR: u16 = 2;
2379        const HIGH: u16 = 3;
2380
2381        let db = PvDatabase::new();
2382        db.add_pv("gw:prop", EpicsValue::Double(0.0)).await.unwrap();
2383        let pv = db.find_pv("gw:prop").await.expect("PV exists");
2384
2385        let mut prop_rx = pv
2386            .add_subscriber(1, DbFieldType::Double, DBE_PROPERTY)
2387            .await
2388            .expect("property subscriber added");
2389        let mut val_rx = pv
2390            .add_subscriber(2, DbFieldType::Double, DBE_VALUE)
2391            .await
2392            .expect("value subscriber added");
2393
2394        // Upstream CTRL event: metadata + MAJOR/HIGH alarm + a fixed past
2395        // timestamp that is unmistakably not a fresh wall clock.
2396        let upstream_ts = WallTime::from_unix(2_000_000, 0);
2397        let mut ctrl = Snapshot::new(EpicsValue::Double(5.0), HIGH, MAJOR, upstream_ts);
2398        ctrl.display = Some(DisplayInfo {
2399            units: "V".into(),
2400            precision: 1,
2401            ..Default::default()
2402        });
2403
2404        db.post_pv_property("gw:prop", ctrl)
2405            .await
2406            .expect("simple PV post_pv_property must succeed");
2407
2408        // The metadata was refreshed on the shadow PV.
2409        assert_eq!(
2410            pv.metadata().display.expect("metadata refreshed").units,
2411            "V"
2412        );
2413
2414        // The DBE_PROPERTY subscriber received the metadata-bearing event,
2415        // with the upstream alarm and timestamp preserved.
2416        let ev = prop_rx
2417            .try_recv()
2418            .expect("DBE_PROPERTY subscriber receives the property event");
2419        assert_eq!(
2420            ev.snapshot.display.expect("event carries metadata").units,
2421            "V"
2422        );
2423        assert_eq!(
2424            ev.snapshot.alarm.severity, MAJOR,
2425            "upstream severity preserved"
2426        );
2427        assert_eq!(ev.snapshot.alarm.status, HIGH, "upstream status preserved");
2428        assert_eq!(
2429            ev.snapshot.timestamp, upstream_ts,
2430            "control-DBR timestamp preserved, not a fresh wall clock"
2431        );
2432
2433        // The DBE_VALUE-only subscriber must NOT receive a property event.
2434        assert!(
2435            val_rx.try_recv().is_err(),
2436            "DBE_VALUE-only subscriber must not receive a property post"
2437        );
2438
2439        // Unknown / non-simple PV is rejected.
2440        let again = Snapshot::new(EpicsValue::Double(0.0), 0, 0, WallTime::UNIX_EPOCH);
2441        assert!(matches!(
2442            db.post_pv_property("no:such:pv", again).await,
2443            Err(CaError::ChannelNotFound(_))
2444        ));
2445    }
2446
2447    /// Regression: `put_record_field_from_ca` (the CA
2448    /// server's main put fast path) must accept aliases. Pre-fix it
2449    /// only consulted `inner.records` directly. Also exercises the
2450    /// canonical-name normalisation that protects subsequent
2451    /// `process_record_with_links` / `update_scan_index` calls.
2452    #[tokio::test]
2453    async fn put_record_field_from_ca_accepts_alias() {
2454        use crate::server::records::ai::AiRecord;
2455
2456        let db = PvDatabase::new();
2457        db.add_record("CANON", Box::new(AiRecord::new(0.0)))
2458            .await
2459            .unwrap();
2460        db.add_alias("ALT", "CANON").await.unwrap();
2461
2462        // Put VAL via the alias name.
2463        let _ = db
2464            .put_record_field_from_ca("ALT", "VAL", EpicsValue::Double(2.5))
2465            .await
2466            .expect("put via alias must succeed");
2467
2468        // Read back via canonical to confirm the value landed on the
2469        // right record.
2470        let v = db.get_pv("CANON.VAL").await.unwrap();
2471        assert!(matches!(v, EpicsValue::Double(x) if x == 2.5));
2472    }
2473
2474    /// Regression: a DBR_PUT_ACKT alarm-acknowledge put posts a record-wide
2475    /// DBE_ALARM (C `dbAccess.c:1299` putAckt
2476    /// `db_post_events(precord, NULL, DBE_ALARM)`), so an alarm-mask monitor
2477    /// on ANY field is notified — and a DBE_VALUE-only monitor is not.
2478    /// Pre-fix the ack field posted only itself with DBE_VALUE|DBE_LOG, so no
2479    /// alarm-mask subscriber observed the acknowledgement, and the post fired
2480    /// on every put regardless of whether `ackt` changed.
2481    #[tokio::test]
2482    async fn alarm_ack_put_posts_record_wide_dbe_alarm() {
2483        use crate::server::recgbl::EventMask;
2484        use crate::server::records::ai::AiRecord;
2485        use crate::types::DbFieldType;
2486
2487        let db = PvDatabase::new();
2488        db.add_record("A:REC", Box::new(AiRecord::new(1.0)))
2489            .await
2490            .unwrap();
2491        let rec = db.get_record("A:REC").await.expect("record exists");
2492
2493        let (mut alarm_rx, mut value_rx) = {
2494            let mut inst = rec.write().await;
2495            let a = inst
2496                .add_subscriber("VAL", 1, DbFieldType::Double, EventMask::ALARM.bits())
2497                .expect("alarm subscriber");
2498            let v = inst
2499                .add_subscriber("VAL", 2, DbFieldType::Double, EventMask::VALUE.bits())
2500                .expect("value subscriber");
2501            (a, v)
2502        };
2503
2504        // The client acknowledges through its ordinary VAL channel with a
2505        // DBR_PUT_ACKT request type (C `dbAccess.c:1331`). ACKT defaults YES
2506        // (true), so writing 0 (disable transient acknowledgement) is a real
2507        // change.
2508        db.put_alarm_ack_from_ca(
2509            "A:REC",
2510            "VAL",
2511            crate::server::record::AlarmAck::Transient,
2512            0,
2513        )
2514        .await
2515        .expect("ackt put");
2516
2517        // The alarm-mask monitor on VAL receives the record-wide DBE_ALARM.
2518        assert!(
2519            alarm_rx.try_recv().is_ok(),
2520            "DBE_ALARM subscriber must receive the record-wide alarm post"
2521        );
2522        // The DBE_VALUE-only monitor on VAL must NOT: VAL's value is unchanged.
2523        assert!(
2524            value_rx.try_recv().is_err(),
2525            "DBE_VALUE-only subscriber must not receive the alarm post"
2526        );
2527
2528        // Re-putting the same ACKT value is a no-op: C putAckt returns early
2529        // on an unchanged ackt, so no further alarm post fires.
2530        db.put_alarm_ack_from_ca(
2531            "A:REC",
2532            "VAL",
2533            crate::server::record::AlarmAck::Transient,
2534            0,
2535        )
2536        .await
2537        .expect("ackt re-put");
2538        assert!(
2539            alarm_rx.try_recv().is_err(),
2540            "unchanged ACKT must post nothing"
2541        );
2542    }
2543
2544    /// `post_property_fields` writes each field through the internal put and
2545    /// posts a `DBE_PROPERTY` monitor — the C
2546    /// `db_post_events(precord, &precord->val, DBE_PROPERTY)` that asyn's
2547    /// runtime enum re-propagation drives (devAsynInt32.c callbackEnum). A
2548    /// `DBE_VALUE`-only subscriber on the same field must NOT receive it:
2549    /// re-keying enum strings is a property change, not a value change.
2550    #[tokio::test]
2551    async fn post_property_fields_writes_and_posts_dbe_property_only() {
2552        use crate::server::recgbl::EventMask;
2553        use crate::server::records::mbbi::MbbiRecord;
2554        use crate::types::DbFieldType;
2555
2556        let db = PvDatabase::new();
2557        db.add_record("M:ENUM", Box::new(MbbiRecord::new(0)))
2558            .await
2559            .unwrap();
2560        let rec = db.get_record("M:ENUM").await.expect("record exists");
2561
2562        let (mut prop_rx, mut val_rx) = {
2563            let mut inst = rec.write().await;
2564            let p = inst
2565                .add_subscriber("ZRST", 1, DbFieldType::String, EventMask::PROPERTY.bits())
2566                .expect("property subscriber");
2567            let v = inst
2568                .add_subscriber("ZRST", 2, DbFieldType::String, EventMask::VALUE.bits())
2569                .expect("value subscriber");
2570            (p, v)
2571        };
2572
2573        let posted = db
2574            .post_property_fields(
2575                "M:ENUM",
2576                vec![("ZRST".to_string(), EpicsValue::String("LABEL".into()))],
2577            )
2578            .await
2579            .expect("post_property_fields succeeds");
2580        assert_eq!(posted, vec!["ZRST".to_string()]);
2581
2582        // The field landed on the record.
2583        assert_eq!(
2584            db.get_pv("M:ENUM.ZRST").await.unwrap(),
2585            EpicsValue::String("LABEL".into())
2586        );
2587
2588        // The DBE_PROPERTY subscriber received the event; the DBE_VALUE-only
2589        // subscriber did not (mask 0x08 vs 0x01, no intersection).
2590        assert!(
2591            prop_rx.try_recv().is_ok(),
2592            "DBE_PROPERTY subscriber must receive the property post"
2593        );
2594        assert!(
2595            val_rx.try_recv().is_err(),
2596            "DBE_VALUE-only subscriber must not receive a property post"
2597        );
2598    }
2599
2600    /// Regression: a direct CA put to a record whose value field VAL is NOT
2601    /// `pp(TRUE)` (calc / calcout / aSub) must still fire a DBE_VALUE monitor.
2602    /// C `dbAccess.c::dbPut:1408-1414` posts the value field immediately
2603    /// unless it is `pp(TRUE)`. The port previously suppressed the immediate
2604    /// post for every `VAL` and — with the `should_process` gate — skipped
2605    /// the reprocess cycle for a non-`pp` VAL, so the operator's write fired
2606    /// no monitor at all. calc's VAL is not in its `pp` field set, so the
2607    /// immediate post is the only event that can fire.
2608    #[tokio::test]
2609    async fn ca_put_to_non_pp_val_posts_monitor() {
2610        use crate::server::database::db_access::DbSubscription;
2611        use crate::server::records::calc::CalcRecord;
2612
2613        let db = PvDatabase::new();
2614        db.add_record("CALC1", Box::new(CalcRecord::new("0")))
2615            .await
2616            .unwrap();
2617
2618        let mut sub = DbSubscription::subscribe(&db, "CALC1.VAL")
2619            .await
2620            .expect("subscribe to CALC1.VAL");
2621
2622        db.put_record_field_from_ca("CALC1", "VAL", EpicsValue::Double(5.0))
2623            .await
2624            .expect("CA put to CALC1.VAL must succeed");
2625
2626        let got = tokio::time::timeout(std::time::Duration::from_secs(1), sub.recv_f64())
2627            .await
2628            .expect("a DBE_VALUE monitor must fire for a direct VAL put to a non-pp record");
2629        assert_eq!(got, Some(5.0));
2630    }
2631
2632    /// R8-22 (record-field path): a record monitor whose event queue runs short
2633    /// of room during a burst must receive its EARLIER DISTINCT queued updates
2634    /// and then a tail entry carrying the latest value. C `db_queue_event_log`
2635    /// replaces only `*pLastLog` (`dbEvent.c:812-820`); the earlier entries stay
2636    /// queued and each is delivered by `event_read`.
2637    ///
2638    /// Each non-pp `VAL` put posts exactly one DBE_VALUE monitor with the put
2639    /// value and does NOT reprocess (see `ca_put_to_non_pp_val_posts_monitor`),
2640    /// so N distinct puts produce a strictly increasing 1..=N stream.
2641    ///
2642    /// Before the fix the producer parked the newest value in a side coalesce
2643    /// slot and `next_event`, finding it set, discarded the whole queued backlog
2644    /// — the burst came out as one event instead of {1..=appended-1, N}.
2645    #[tokio::test]
2646    async fn r8_22_db_burst_keeps_earlier_distinct_updates() {
2647        use crate::server::database::db_access::DbSubscription;
2648        use crate::server::event_queue::{event_que_size, events_per_que};
2649        use crate::server::records::calc::CalcRecord;
2650
2651        let db = PvDatabase::new();
2652        db.add_record("CALC1", Box::new(CalcRecord::new("0")))
2653            .await
2654            .unwrap();
2655        let mut sub = DbSubscription::subscribe(&db, "CALC1.VAL")
2656            .await
2657            .expect("subscribe to CALC1.VAL");
2658
2659        // With no consumer draining, the first `appended` puts take ring entries
2660        // and every later put replaces the tail entry in place.
2661        let appended = event_que_size() - events_per_que();
2662        let burst = appended + 40;
2663        for i in 1..=burst {
2664            db.put_record_field_from_ca("CALC1", "VAL", EpicsValue::Double(i as f64))
2665                .await
2666                .expect("CA put to CALC1.VAL must succeed");
2667        }
2668
2669        // Drain every immediately-available delivery; the recv past the
2670        // last event has nothing queued and times out, ending collection.
2671        let mut seq = Vec::new();
2672        while let Ok(Some(v)) =
2673            tokio::time::timeout(std::time::Duration::from_millis(200), sub.recv_f64()).await
2674        {
2675            seq.push(v);
2676        }
2677        let want: Vec<f64> = (1..appended)
2678            .map(|i| i as f64)
2679            .chain(std::iter::once(burst as f64))
2680            .collect();
2681        assert_eq!(
2682            seq, want,
2683            "record burst delivery must be {{earlier distinct backlog…, coalesced tail}}"
2684        );
2685    }
2686}