Skip to main content

nmbrs_runtime/wrappers/
poll.rs

1// Copyright 2024-2026 Jonathan Shook
2// SPDX-License-Identifier: Apache-2.0
3
4//! Polling / await wrapper. Re-executes the inner op until its
5//! completion condition holds, or the timeout fires. The condition
6//! is the op's `until:` predicate when it declares one; otherwise
7//! `mode: await_empty`, an empty result. Used for waiting on backend
8//! state to settle: SAI index build, compactions, etc. A condition
9//! over part of a response is a capture plus `until:`.
10
11use std::sync::Arc;
12
13use crate::adapter::WrappingDispenser;
14use crate::adapter::{AdapterError, ExecutionError, OpDispenser, OpResult};
15use crate::wrapper_registry::{WrapperName, WrapperRegistration, WrapperSubject};
16
17/// SRD-32a wrapper name.
18pub const NAME: WrapperName = WrapperName::new("poll");
19
20/// Trigger: `poll:` may be a bare string (mode only, defaults
21/// for everything else) or a map carrying the full config —
22/// either form turns the wrapper on.
23fn triggers(s: WrapperSubject) -> bool {
24    let Some(template) = s.op() else {
25        return false;
26    };
27    template
28        .params
29        .get("poll")
30        .map(|v| v.is_string() || v.is_object())
31        .unwrap_or(false)
32}
33
34fn describe_assignment(s: WrapperSubject) -> Option<String> {
35    let template = s.op()?;
36    let poll_val = template.params.get("poll")?;
37    let (mode, interval, timeout): (String, u64, u64) = match poll_val {
38        v if v.is_string() => (v.as_str().unwrap().to_string(), 1000, 300_000),
39        v if v.is_object() => {
40            let m = v.as_object().unwrap();
41            let mode = m
42                .get("mode")
43                .and_then(|x| x.as_str())
44                .unwrap_or("await_empty")
45                .to_string();
46            let interval = m
47                .get("interval_ms")
48                .and_then(crate::wrapper_registrations::json_to_u64)
49                .unwrap_or(1000);
50            let timeout = m
51                .get("timeout_ms")
52                .and_then(crate::wrapper_registrations::json_to_u64)
53                .unwrap_or(300_000);
54            (mode, interval, timeout)
55        }
56        _ => return None,
57    };
58    Some(format!(
59        "poll: every {}ms, timeout {}ms, on `{mode}`",
60        interval, timeout
61    ))
62}
63
64inventory::submit! {
65    WrapperRegistration {
66        name: NAME,
67        owned_fields: &[
68            // `poll:` is the single discriminant for the poll
69            // wrapper; every knob (mode, until, interval_ms,
70            // timeout_ms, metric_name, max_error_retries) lives
71            // under it as a map. The
72            // flat `poll_*`-prefix surface was retired.
73            "poll",
74        ],
75        triggers,
76        requires_inner: &[super::traverse::NAME],
77        forbids_outer: &[],
78        mutually_exclusive_with: &[],
79        describe_assignment,
80        levels: &[crate::wrapper_registry::WrapperLevel::Op],
81    }
82}
83
84/// Wraps an inner dispenser and re-executes it until the result
85/// body is empty (zero rows). Used for awaiting conditions like
86/// SAI index compaction completing.
87///
88/// Configured via op params:
89/// - `poll_interval_ms`: delay between polls (default: 1000)
90/// - `timeout_ms`: maximum total wait (default: 300000 = 5 min)
91/// - `poll_condition`: when to stop: "empty" (default) = stop when 0 rows
92/// - `poll_max_error_retries`: how many retryable errors to swallow
93///   before propagating (default: 0 — strict: any inner error fails
94///   the poll immediately, per SRD-03 §"Status-Determination
95///   Invariant")
96///
97/// Per SRD-03 §"Status-Determination Invariant", this wrapper
98/// short-circuits on every non-positive case:
99///
100/// - **Positive case**: inner op returns `OpResult` with an empty
101///   body → poll succeeds, this dispenser returns success.
102/// - **Any other case**: inner op returns a non-retryable
103///   `ExecutionError`, OR a retryable error past the retry limit,
104///   OR the timeout fires while non-empty bodies are still coming
105///   back → this dispenser returns the error, the activity error
106///   router sees it, and (under default `errors:` policy) the
107///   phase + the run stop. Errors are never swallowed behind the
108///   poll.
109pub struct PollingDispenser {
110    inner: Arc<dyn OpDispenser>,
111    poll_interval: std::time::Duration,
112    timeout: std::time::Duration,
113    /// Cap on consecutive retryable inner-op errors before the
114    /// wrapper propagates upstream. `0` means strict: any
115    /// inner-op error fails the poll immediately.
116    max_error_retries: u32,
117    /// SRD-92 cooperative-stop view (same aspect as the `while:` and
118    /// `tries` wrappers). Checked at the top of every poll iteration
119    /// so a session/walk/daemon stop abandons the poll instead of
120    /// waiting out the cadence or timeout. Injected at wrap time.
121    stop: crate::session_signals::StopView,
122    /// Named metric for the poll elapsed time (e.g., "index_build_time").
123    metric_name: Option<String>,
124    /// `poll.memo` — optional template re-rendered after EVERY poll
125    /// iteration (against the wires, so this iteration's captures are
126    /// visible) and published to the activity memo. Without it, a
127    /// long await shows only the memo wrapper's static `before:` text
128    /// while the measured values sit unrendered in wires — the memo
129    /// is where the operator is looking, so the measurement belongs
130    /// there. When absent but `memo_state` is wired, a generic
131    /// `<base memo> — measured N row(s) …` suffix is published
132    /// instead, so every poll surfaces its live measurement without
133    /// workload changes.
134    each_memo: Option<String>,
135    /// The activity's memo slot (same ArcSwap the memo wrapper
136    /// writes). `None` in tests / callers that don't surface memos.
137    memo_state: Option<Arc<arc_swap::ArcSwap<String>>>,
138    /// `poll.progress` — optional template whose rendered value is
139    /// parsed as an `f64` completion fraction in `[0.0, 1.0]` and
140    /// published to the activity's derived-progress override each
141    /// iteration (e.g. `"{completion_ratio}"`). Drives the phase
142    /// completion bar for phases whose one long op measures its own
143    /// progress; cleared when the poll completes so the cycle-based
144    /// accounting takes back over.
145    progress_template: Option<String>,
146    /// Metrics of the owning activity — target of the
147    /// derived-progress override. `None` in bare tests.
148    /// The op's `gutter:` DURING form, re-published per poll
149    /// iteration against that poll's wires — a single long drain op
150    /// (`await_empty` over an hours-long compaction) keeps a live
151    /// cell instead of one publish at op end. The final-form/`final:`
152    /// semantics are untouched (the activity epilogue owns those).
153    each_gutter: Option<crate::wrappers::gutter::GutterTemplate>,
154    /// The activity's shared gutter slot; `None` in bare tests.
155    gutter_state: Option<Arc<arc_swap::ArcSwapOption<crate::wrappers::gutter::GutterSpec>>>,
156    /// The op's compiled `metrics:` GAUGE slots, re-published per
157    /// poll iteration (see `metrics::publish_gauges_lenient`).
158    /// Filled by the metrics wrapper's cascade arm AFTER this
159    /// dispenser is built (metrics wraps outside poll), hence the
160    /// late-bound swap; empty/`None` when the op has no metrics.
161    iteration_gauges:
162        Option<Arc<arc_swap::ArcSwapOption<Vec<crate::wrappers::metrics::MetricSlot>>>>,
163    /// When set, the poll is DONE the first time this predicate reads truthy,
164    /// and the row-count window is not consulted.
165    ///
166    /// The predicate itself lives in the executing node's kernel under
167    /// [`crate::wrappers::condition::UNTIL_BINDING`], put there by scope
168    /// synthesis. This wrapper never learns whether that kernel belongs to an
169    /// op template or a phase — it reads one wire through `ctx.wires`, and
170    /// scoping decides which binding answers.
171    until: bool,
172    /// Values written to the wires on the TERMINATING poll only,
173    /// as `(wire_name, expression)` pairs from `poll.on_done:`.
174    ///
175    /// A poll that watches remote work usually cannot observe that
176    /// work in a completed state: `system_views.compactions` (and
177    /// every view like it) lists what is RUNNING, so the observation
178    /// that means "done" is an empty result — the finished tier's
179    /// attributes are gone with it. The terminal sample is therefore
180    /// real ("nothing is running") but says nothing about the thing
181    /// that finished, and a `max(completion_ratio)` over the series
182    /// keeps reporting the last in-flight fraction for work that has
183    /// been done for an hour.
184    ///
185    /// `on_done` proxies the measurement the remote view cannot give
186    /// us: at termination these expressions are written to the wires
187    /// before the final publish, so the gauges fed by them record the
188    /// completed state as if it had been observed.
189    on_done: Vec<(String, String)>,
190    activity_metrics: Option<Arc<crate::activity::ActivityMetrics>>,
191    /// Externally visible metrics for the polling operation.
192    pub metrics: Arc<PollingMetrics>,
193}
194
195/// Metrics surfaced by the polling wrapper.
196pub struct PollingMetrics {
197    /// Total polls executed across all invocations.
198    pub polls_total: std::sync::atomic::AtomicU64,
199    /// Total time spent polling (milliseconds).
200    pub poll_elapsed_ms: std::sync::atomic::AtomicU64,
201    /// Whether the condition has been met (0 = waiting, 1 = done).
202    pub condition_met: std::sync::atomic::AtomicU64,
203    /// The last observed value from the poll condition (e.g., number of
204    /// remaining tasks). This is the metric that determines completion.
205    pub poll_metric: std::sync::atomic::AtomicU64,
206}
207
208impl PollingMetrics {
209    fn new() -> Self {
210        Self {
211            polls_total: std::sync::atomic::AtomicU64::new(0),
212            poll_elapsed_ms: std::sync::atomic::AtomicU64::new(0),
213            condition_met: std::sync::atomic::AtomicU64::new(0),
214            poll_metric: std::sync::atomic::AtomicU64::new(0),
215        }
216    }
217}
218
219impl PollingDispenser {
220    /// Wrap an inner dispenser with polling behavior.
221    /// Returns the wrapped dispenser and a handle to the metrics.
222    ///
223    /// `metric_name`: if set, the elapsed poll time is captured as a named
224    /// gauge (in seconds) for the summary report.
225    /// `max_error_retries`: cap on consecutive retryable inner errors
226    /// (default 0 = strict).
227    // reason: cohesive wrapper constructor — each argument is a distinct poll
228    // policy knob (interval, timeout, retry cap, metric name);
229    // bundling them into a struct would only relocate the same fields.
230    #[allow(clippy::too_many_arguments)]
231    pub fn wrap(
232        inner: Arc<dyn OpDispenser>,
233        poll_interval_ms: u64,
234        timeout_ms: u64,
235        max_error_retries: u32,
236        metric_name: Option<String>,
237    ) -> (Arc<dyn OpDispenser>, Arc<PollingMetrics>) {
238        Self::wrap_with_status(
239            inner,
240            poll_interval_ms,
241            timeout_ms,
242            max_error_retries,
243            metric_name,
244            None,
245            None,
246            None,
247            None,
248            None,
249            None,
250            None,
251            Vec::new(),
252            false,
253            crate::session_signals::StopView::default(),
254        )
255    }
256
257    /// As [`Self::wrap`], plus the live-status handles: the
258    /// per-iteration memo template + activity memo slot, and the
259    /// derived-progress template + activity metrics. See the field
260    /// docs (`each_memo`, `progress_template`) for semantics.
261    // pub(crate), not pub: the returned handles include `MetricSlot`, which is crate-private, and
262    // every caller (activity.rs wiring, `wrap` above) is in-crate. Declaring it `pub` leaked a
263    // private type through a public signature.
264    #[allow(clippy::too_many_arguments)]
265    pub(crate) fn wrap_with_status(
266        inner: Arc<dyn OpDispenser>,
267        poll_interval_ms: u64,
268        timeout_ms: u64,
269        max_error_retries: u32,
270        metric_name: Option<String>,
271        each_memo: Option<String>,
272        memo_state: Option<Arc<arc_swap::ArcSwap<String>>>,
273        progress_template: Option<String>,
274        activity_metrics: Option<Arc<crate::activity::ActivityMetrics>>,
275        each_gutter: Option<crate::wrappers::gutter::GutterTemplate>,
276        gutter_state: Option<Arc<arc_swap::ArcSwapOption<crate::wrappers::gutter::GutterSpec>>>,
277        iteration_gauges: Option<
278            Arc<arc_swap::ArcSwapOption<Vec<crate::wrappers::metrics::MetricSlot>>>,
279        >,
280        on_done: Vec<(String, String)>,
281        until: bool,
282        stop: crate::session_signals::StopView,
283    ) -> (Arc<dyn OpDispenser>, Arc<PollingMetrics>) {
284        let metrics = Arc::new(PollingMetrics::new());
285        let dispenser = Arc::new(Self {
286            inner,
287            poll_interval: std::time::Duration::from_millis(poll_interval_ms),
288            timeout: std::time::Duration::from_millis(timeout_ms),
289            max_error_retries,
290            metric_name,
291            each_memo,
292            memo_state,
293            progress_template,
294            activity_metrics,
295            each_gutter,
296            gutter_state,
297            iteration_gauges,
298            on_done,
299            until,
300            stop,
301            metrics: metrics.clone(),
302        });
303        (dispenser, metrics)
304    }
305
306    /// Per-iteration status publish: memo + derived progress.
307    ///
308    /// Runs after EVERY poll — including the terminating one, whose
309    /// observation is the one that detects completion and is no less
310    /// a measurement than the ones before it. Skipping it left every
311    /// series ending on the last incomplete sample, so a finished
312    /// unit of work read as 93% done forever.
313    ///
314    /// Idempotent by construction: every publish here is a set, not
315    /// an accumulate — `publish_gauges_lenient` handles gauges only,
316    /// and the memo / gutter / progress-override slots are
317    /// last-write-wins. Publishing the same iteration twice therefore
318    /// lands the same state; only the sample timestamp moves.
319    ///
320    /// Captures for this iteration are already on the wires.
321    /// Substitution failures degrade to a debug log — status must
322    /// never fail the poll.
323    fn publish_iteration_status(
324        &self,
325        wires: &dyn crate::wires::WireSource,
326        base_memo: &str,
327        row_count: u64,
328        polls: u64,
329        elapsed_secs: f64,
330    ) {
331        if let Some(memo) = &self.memo_state {
332            let rendered = self.each_memo.as_deref().and_then(|t| {
333                match crate::wires::substitute_via_wires(t, wires) {
334                    Ok(s) => Some(s),
335                    Err(e) => {
336                        crate::diag!(
337                            crate::observer::LogLevel::Debug,
338                            "poll.memo: substitution failed for '{t}': {e}"
339                        );
340                        None
341                    }
342                }
343            });
344            // Default (no template / render failure): keep the memo the
345            // operator already sees and append the measurement to it.
346            let text = rendered.unwrap_or_else(|| if self.until {
347                // A declared `until:` REPLACED the empty-result check, so quoting
348                // that check here would describe a gate that is not in effect —
349                // and worse, "measured 0 row(s) [awaiting empty]" reads as ALREADY
350                // SATISFIED while the poll keeps waiting, which is the most
351                // confusing thing a status line can say. Report the condition
352                // that is actually holding it, and the observation feeding it.
353                format!(
354                    "{base_memo} — waiting on `until:` (not yet satisfied) · \
355                     {row_count} row(s) observed · poll {polls}, {elapsed_secs:.0}s")
356            } else {
357                format!(
358                    "{base_memo} — measured {row_count} row(s) [awaiting empty] · poll {polls}, {elapsed_secs:.0}s")
359            });
360            memo.store(Arc::new(text));
361        }
362        // Gauges first: the gutter/memo templates may read metricsql
363        // over the very series these samples feed.
364        if let Some(handle) = &self.iteration_gauges
365            && let Some(slots) = handle.load_full()
366        {
367            crate::wrappers::metrics::publish_gauges_lenient(&slots, wires);
368        }
369        if let (Some(state), Some(declared)) = (&self.gutter_state, &self.each_gutter)
370            && let Some(spec) = crate::wrappers::gutter::render_spec(declared, wires)
371        {
372            state.store(Some(Arc::new(spec)));
373        }
374        if let (Some(metrics), Some(t)) =
375            (&self.activity_metrics, self.progress_template.as_deref())
376        {
377            match crate::wires::substitute_via_wires(t, wires) {
378                Ok(s) => match s.trim().parse::<f64>() {
379                    // Elapsed rides along so the display can derive the
380                    // measured-basis ETA (`elapsed × (1−f)/f`) — the
381                    // cycle-based ETA stands still for one long measured op.
382                    Ok(f) => metrics.set_progress_override_with_elapsed(f, elapsed_secs),
383                    Err(_) => {
384                        crate::diag!(
385                            crate::observer::LogLevel::Debug,
386                            "poll.progress: '{t}' rendered to non-numeric '{s}'"
387                        );
388                    }
389                },
390                Err(e) => {
391                    crate::diag!(
392                        crate::observer::LogLevel::Debug,
393                        "poll.progress: substitution failed for '{t}': {e}"
394                    );
395                }
396            }
397        }
398    }
399}
400
401/// Drop guard clearing the derived-progress override when the poll
402/// future ends — by completion, timeout, error, OR cancellation (a
403/// daemon drop mid-await). Without it a finished/cancelled poll's
404/// stale fraction would keep driving the phase bar.
405struct ProgressOverrideClear<'m>(Option<&'m crate::activity::ActivityMetrics>);
406
407impl Drop for ProgressOverrideClear<'_> {
408    fn drop(&mut self) {
409        if let Some(m) = self.0 {
410            m.set_progress_override(None);
411        }
412    }
413}
414
415impl WrappingDispenser for PollingDispenser {}
416
417impl OpDispenser for PollingDispenser {
418    fn execute<'a>(
419        &'a self,
420        cycle: u64,
421        ctx: &'a crate::fixture::ExecCtx<'a>,
422    ) -> std::pin::Pin<
423        Box<dyn std::future::Future<Output = Result<OpResult, ExecutionError>> + Send + 'a>,
424    > {
425        Box::pin(async move {
426            let start = std::time::Instant::now();
427            let mut polls = 0u64;
428            let mut retryable_errors_consumed: u32 = 0;
429            // Memo text as of poll start — the memo wrapper is OUTER,
430            // so its `before:` template is already published; the
431            // default per-iteration publish appends the measurement
432            // to this base rather than compounding onto itself.
433            //
434            // Stripping a previously-appended suffix is what makes that
435            // hold ACROSS executions too: within one poll the base is
436            // captured once, but a second execution of the same op would
437            // otherwise read back its own decorated text as the base and
438            // grow the memo without bound.
439            let base_memo: String = self
440                .memo_state
441                .as_ref()
442                .map(|m| strip_measurement_suffix(m.load().as_str()).to_string())
443                .unwrap_or_default();
444            let _progress_clear = ProgressOverrideClear(self.activity_metrics.as_deref());
445
446            loop {
447                // Session shutdown: abandon the poll. The cooperative
448                // drain waits for in-flight WORK, not for a poll
449                // cadence that may have minutes of timeout left —
450                // without this check a Ctrl-C leaves the drain stuck
451                // behind the next interval/retry sleep.
452                if self.stop.stopped() {
453                    return Err(ExecutionError::Op(AdapterError {
454                        error_name: "shutdown_cancelled".into(),
455                        message: format!(
456                            "session stop requested — poll abandoned after {} poll(s), {:.1}s",
457                            polls,
458                            start.elapsed().as_secs_f64()
459                        ),
460                        retryable: false,
461                    }));
462                }
463                // SRD-03 §"Status-Determination Invariant":
464                // every inner-op outcome other than the
465                // specific positive case (empty body, signalling
466                // "no remaining build tasks") short-circuits
467                // upstream as an error. Retryable errors get a
468                // bounded retry budget (`max_error_retries`);
469                // non-retryable errors never get retried — they
470                // propagate on the first occurrence.
471                let result = match self.inner.execute(cycle, ctx).await {
472                    Ok(r) => r,
473                    Err(e) => {
474                        let retryable = match &e {
475                            ExecutionError::Op(ad) => ad.retryable,
476                            ExecutionError::Adapter(_) => false,
477                        };
478                        if !retryable {
479                            return Err(e);
480                        }
481                        if retryable_errors_consumed >= self.max_error_retries {
482                            return Err(e);
483                        }
484                        retryable_errors_consumed += 1;
485                        let indent = crate::scene_tree::running_phase_indent();
486                        let color = crate::observer::use_color();
487                        let yellow = if color { "\x1b[33m" } else { "" };
488                        let reset = if color { "\x1b[0m" } else { "" };
489                        crate::diag!(
490                            crate::observer::LogLevel::Warn,
491                            "{indent}{yellow}poll retry {retryable_errors_consumed}/{}{reset} after retryable error: {}",
492                            self.max_error_retries,
493                            match &e {
494                                ExecutionError::Op(ad) => &ad.message,
495                                ExecutionError::Adapter(ad) => &ad.message,
496                            },
497                        );
498                        // Backoff before retry — same as the
499                        // between-polls cadence so a flapping
500                        // backend doesn't burn the retry budget
501                        // in a tight loop.
502                        tokio::time::sleep(self.poll_interval).await;
503                        continue;
504                    }
505                };
506                polls += 1;
507
508                // `mode: await_empty` — an empty result is done.
509                let row_count = result.body.as_ref().map_or(0, |body| body.element_count());
510                // A declared `until:` REPLACES the empty-result check: the
511                // workload stated the completion condition, so counting rows
512                // would be second-guessing it. An unresolved predicate is a
513                // wiring fault, not a false one — failing loudly beats
514                // spinning to the timeout with no explanation.
515                // Publish the poll's own progress as wires BEFORE evaluating the
516                // predicate, so an `until:` can bound its own patience. Without
517                // these a condition can only describe the observed world, never
518                // "and give up waiting for it" — which turns any never-satisfied
519                // predicate into a wait to `timeout_ms`. `poll_elapsed_ms` is
520                // the time spent polling THIS invocation; `poll_count` is the
521                // number of iterations completed.
522                //
523                // Written through the same `WireSource::write` path captures
524                // use, so the names resolve exactly like any other wire and an
525                // `extern poll_elapsed_ms: u64 = 0` declaration picks them up.
526                // A workload that never mentions them has no slot, the write
527                // is a no-op, and nothing changes.
528                let elapsed_ms = start.elapsed().as_millis() as u64;
529                ctx.wires
530                    .write("poll_elapsed_ms", polydat::ast::Value::U64(elapsed_ms));
531                ctx.wires
532                    .write("poll_count", polydat::ast::Value::U64(polls));
533                let is_done = if self.until {
534                    match crate::wrappers::condition::holds(
535                        ctx.wires,
536                        crate::wrappers::condition::UNTIL_BINDING,
537                    ) {
538                        Some(done) => done,
539                        None => {
540                            return Err(ExecutionError::Op(crate::adapter::AdapterError {
541                                error_name: "poll_until_unresolved".into(),
542                                message: format!(
543                                    "poll `until:` predicate did not resolve through \
544                                     ctx.wires (binding '{}') — scope synthesis should \
545                                     have lowered it into this node's kernel",
546                                    crate::wrappers::condition::UNTIL_BINDING
547                                ),
548                                retryable: false,
549                            }));
550                        }
551                    }
552                } else {
553                    row_count == 0
554                };
555
556                self.metrics
557                    .poll_metric
558                    .store(row_count, std::sync::atomic::Ordering::Relaxed);
559
560                if !is_done {
561                    // Per-poll progress goes to the durable
562                    // session log at Debug — direct `eprint!`
563                    // here would clobber the TUI's render
564                    // surface. The TUI surfaces poll progress
565                    // via the `poll_metric` gauge (live row
566                    // count) which is already updated above.
567                    let indent = crate::scene_tree::running_phase_indent();
568                    crate::diag!(
569                        crate::observer::LogLevel::Debug,
570                        "{indent}awaiting: {row_count} row(s), need 0 ({:.0}s elapsed)",
571                        start.elapsed().as_secs_f64()
572                    );
573                    // Live status: this iteration's captures are on the
574                    // wires; expose the poll's own counters alongside
575                    // them (slot-absent writes no-op) and publish the
576                    // measured values to the memo + the derived
577                    // phase-progress override.
578                    let _ = ctx
579                        .wires
580                        .write("poll_count", polydat::ast::Value::U64(polls));
581                    let _ = ctx.wires.write(
582                        "poll_elapsed_ms",
583                        polydat::ast::Value::U64(start.elapsed().as_millis() as u64),
584                    );
585                    self.publish_iteration_status(
586                        ctx.wires,
587                        &base_memo,
588                        row_count,
589                        polls,
590                        start.elapsed().as_secs_f64(),
591                    );
592                }
593                if is_done {
594                    // The terminating observation is a measurement too, and it
595                    // is the only one that carries the completion time. It used
596                    // to be dropped: the loop published on `!is_done` only, so
597                    // every series ended on the last INCOMPLETE sample and
598                    // finished work read as partially done forever.
599                    //
600                    // `on_done` first, then the publish: the wires it writes are
601                    // what the gauges read. This is the proxy for a completed
602                    // state a remote view cannot show (see the field docs) — the
603                    // terminal captures describe an empty result set, not the
604                    // work that just finished.
605                    let _ = ctx
606                        .wires
607                        .write("poll_count", polydat::ast::Value::U64(polls));
608                    let _ = ctx.wires.write(
609                        "poll_elapsed_ms",
610                        polydat::ast::Value::U64(start.elapsed().as_millis() as u64),
611                    );
612                    for (name, expr) in &self.on_done {
613                        match crate::wires::substitute_via_wires(expr, ctx.wires) {
614                            Ok(rendered) => match rendered.trim().parse::<f64>() {
615                                Ok(v) => {
616                                    let _ = ctx.wires.write(name, polydat::ast::Value::F64(v));
617                                }
618                                Err(_) => crate::diag!(
619                                    crate::observer::LogLevel::Debug,
620                                    "poll.on_done: '{name}: {expr}' rendered to \
621                                     non-numeric '{rendered}'"
622                                ),
623                            },
624                            Err(e) => crate::diag!(
625                                crate::observer::LogLevel::Debug,
626                                "poll.on_done: substitution failed for \
627                                 '{name}: {expr}': {e}"
628                            ),
629                        }
630                    }
631                    self.publish_iteration_status(
632                        ctx.wires,
633                        &base_memo,
634                        row_count,
635                        polls,
636                        start.elapsed().as_secs_f64(),
637                    );
638                }
639
640                if is_done {
641                    let elapsed = start.elapsed();
642                    let elapsed_secs = elapsed.as_secs_f64();
643                    self.metrics
644                        .polls_total
645                        .fetch_add(polls, std::sync::atomic::Ordering::Relaxed);
646                    self.metrics.poll_elapsed_ms.store(
647                        elapsed.as_millis() as u64,
648                        std::sync::atomic::Ordering::Relaxed,
649                    );
650                    self.metrics
651                        .condition_met
652                        .store(1, std::sync::atomic::Ordering::Relaxed);
653                    let indent = crate::scene_tree::running_phase_indent();
654                    let color = crate::observer::use_color();
655                    let dim = if color { "\x1b[2m" } else { "" };
656                    let green = if color { "\x1b[32m" } else { "" };
657                    let reset = if color { "\x1b[0m" } else { "" };
658                    crate::observer::log(
659                        crate::observer::LogLevel::Info,
660                        &format!(
661                            "{indent}{green}poll complete{reset}: {polls} polls {dim}in {elapsed_secs:.1}s{reset}"
662                        ),
663                    );
664                    // Captures land on the per-fiber kernel directly
665                    // via ctx.wires.write — wrappers above this layer
666                    // see the values through wires.get on the same
667                    // cycle. Slot-absent writes silently no-op
668                    // (closure-binding economy).
669                    let _ = ctx
670                        .wires
671                        .write("poll_count", polydat::ast::Value::U64(polls));
672                    let _ = ctx.wires.write(
673                        "poll_elapsed_ms",
674                        polydat::ast::Value::U64(elapsed.as_millis() as u64),
675                    );
676                    // Emit named metric. The recorded value is the
677                    // elapsed wait duration; if `metric_name` carries
678                    // a recognized unit suffix (`_ns` / `_us` / `_ms`
679                    // / `_s` / `_m` / `_h`), the seconds are
680                    // converted so the metric reads in the unit its
681                    // name advertises. Names without a recognized
682                    // suffix fall through as seconds (legacy
683                    // behaviour, used by e.g. `index_build_time`).
684                    if let Some(ref name) = self.metric_name {
685                        let value = duration_value_for_metric_name(name, elapsed_secs);
686                        let _ = ctx.wires.write(name, polydat::ast::Value::F64(value));
687                    }
688                    return Ok(OpResult {
689                        body: None,
690                        skipped: false,
691                    });
692                }
693
694                // Check timeout
695                if start.elapsed() > self.timeout {
696                    return Err(ExecutionError::Op(AdapterError {
697                        error_name: "poll_timeout".into(),
698                        message: format!(
699                            "polling timed out after {:.1}s ({} polls). Last result had rows.",
700                            start.elapsed().as_secs_f64(),
701                            polls
702                        ),
703                        retryable: false,
704                    }));
705                }
706
707                // Wait before next poll
708                tokio::time::sleep(self.poll_interval).await;
709            }
710        })
711    }
712    fn inner_dispenser(&self) -> Option<&dyn OpDispenser> {
713        Some(self.inner.as_ref())
714    }
715}
716
717/// Map a named metric's elapsed-time value to the numeric value the
718/// metric name advertises. The metric name suffix selects the unit
719/// (`_ns`, `_us`, `_ms`, `_s`, `_m`, `_h`); the elapsed seconds are
720/// scaled accordingly so a metric called `index_build_time_ms`
721/// reads in milliseconds.
722///
723/// Names without a recognised suffix fall through as seconds
724/// (preserves the historical contract — e.g. `index_build_time`
725/// used to be emitted raw in seconds and still is).
726///
727/// Longest suffixes are tested first so `_ms` doesn't tail-bind
728/// to a more-permissive `_s` rule by accident.
729pub(crate) fn duration_value_for_metric_name(name: &str, elapsed_secs: f64) -> f64 {
730    if name.ends_with("_ns") {
731        elapsed_secs * 1e9
732    } else if name.ends_with("_us") {
733        elapsed_secs * 1e6
734    } else if name.ends_with("_ms") {
735        elapsed_secs * 1e3
736    } else if name.ends_with("_s") {
737        elapsed_secs
738    } else if name.ends_with("_m") {
739        elapsed_secs / 60.0
740    } else if name.ends_with("_h") {
741        elapsed_secs / 3600.0
742    } else {
743        elapsed_secs
744    }
745}
746
747/// Read `poll.on_done:` — the wire values a terminating poll writes before
748/// its final publish. Values may be numbers or strings; strings are kept
749/// verbatim so they can be wire expressions (`"total"`) rather than only
750/// literals.
751///
752/// Ordered by key so the writes are deterministic across runs — a map
753/// iteration order that varied would make one `on_done` entry able to
754/// shadow another differently from run to run.
755pub(crate) fn parse_on_done(
756    cfg: Option<&serde_json::Map<String, serde_json::Value>>,
757) -> Vec<(String, String)> {
758    let Some(map) = cfg
759        .and_then(|m| m.get("on_done"))
760        .and_then(|v| v.as_object())
761    else {
762        return Vec::new();
763    };
764    let mut out: Vec<(String, String)> = map
765        .iter()
766        .map(|(k, v)| {
767            let text = match v {
768                serde_json::Value::String(s) => s.clone(),
769                other => other.to_string(),
770            };
771            (k.clone(), text)
772        })
773        .collect();
774    out.sort_by(|a, b| a.0.cmp(&b.0));
775    out
776}
777
778/// Drop the default per-iteration measurement suffix this wrapper appends,
779/// so re-deriving the base from a published memo is a fixed point.
780/// Matched on both halves of the default shape — a memo that merely
781/// contains an em-dash keeps it.
782fn strip_measurement_suffix(memo: &str) -> &str {
783    match memo.find(" — measured ") {
784        Some(i) if memo[i..].contains(" row(s) [awaiting empty] ") => &memo[..i],
785        _ => memo,
786    }
787}
788
789#[cfg(test)]
790mod on_done_config_tests {
791    use super::parse_on_done;
792
793    fn cfg(json: &str) -> serde_json::Map<String, serde_json::Value> {
794        match serde_json::from_str(json).expect("test json") {
795            serde_json::Value::Object(m) => m,
796            _ => panic!("expected an object"),
797        }
798    }
799
800    #[test]
801    fn absent_or_empty_yields_nothing() {
802        assert!(parse_on_done(None).is_empty());
803        assert!(parse_on_done(Some(&cfg(r#"{"mode":"await_empty"}"#))).is_empty());
804        assert!(parse_on_done(Some(&cfg(r#"{"on_done":{}}"#))).is_empty());
805    }
806
807    /// A YAML `completion_ratio: 1.0` arrives as a NUMBER, not a string — the
808    /// spelling an operator actually writes must not be silently dropped.
809    #[test]
810    fn numeric_and_string_values_both_read() {
811        let got = parse_on_done(Some(&cfg(
812            r#"{"on_done":{"completion_ratio":1.0,"progress":"total"}}"#,
813        )));
814        assert_eq!(
815            got,
816            vec![
817                ("completion_ratio".to_string(), "1.0".to_string()),
818                ("progress".to_string(), "total".to_string()),
819            ]
820        );
821    }
822
823    /// Deterministic order: two entries must be applied the same way on every
824    /// run, so a later write shadowing an earlier one is reproducible.
825    #[test]
826    fn entries_are_ordered_by_key() {
827        let got = parse_on_done(Some(&cfg(r#"{"on_done":{"z":1,"a":2,"m":3}}"#)));
828        let keys: Vec<&str> = got.iter().map(|(k, _)| k.as_str()).collect();
829        assert_eq!(keys, vec!["a", "m", "z"]);
830    }
831}
832
833#[cfg(test)]
834mod status_publish_tests {
835    use super::*;
836    use std::sync::Arc;
837
838    /// Minimal WireSource: one f64 wire named `completion_ratio`.
839    struct RatioWire(f64);
840    impl crate::wires::WireSource for RatioWire {
841        fn get(&self, name: &str) -> Option<polydat::ast::Value> {
842            (name == "completion_ratio").then(|| polydat::ast::Value::F64(self.0))
843        }
844        fn names(&self) -> Box<dyn Iterator<Item = String> + '_> {
845            Box::new(std::iter::once("completion_ratio".to_string()))
846        }
847    }
848
849    fn dispenser_with_status(
850        each_memo: Option<&str>,
851        progress: Option<&str>,
852        memo: &Arc<arc_swap::ArcSwap<String>>,
853        metrics: &Arc<crate::activity::ActivityMetrics>,
854    ) -> PollingDispenser {
855        struct NoopInner;
856        impl OpDispenser for NoopInner {
857            fn execute<'a>(
858                &'a self,
859                _cycle: u64,
860                _ctx: &'a crate::fixture::ExecCtx<'a>,
861            ) -> std::pin::Pin<
862                Box<dyn std::future::Future<Output = Result<OpResult, ExecutionError>> + Send + 'a>,
863            > {
864                Box::pin(async move {
865                    Ok(OpResult {
866                        body: None,
867                        skipped: false,
868                    })
869                })
870            }
871        }
872        PollingDispenser {
873            inner: Arc::new(NoopInner),
874            poll_interval: std::time::Duration::from_millis(1),
875            timeout: std::time::Duration::from_millis(10),
876            max_error_retries: 0,
877            metric_name: None,
878            each_memo: each_memo.map(String::from),
879            memo_state: Some(memo.clone()),
880            progress_template: progress.map(String::from),
881            activity_metrics: Some(metrics.clone()),
882            each_gutter: None,
883            gutter_state: None,
884            iteration_gauges: None,
885            on_done: Vec::new(),
886            until: false,
887            stop: crate::session_signals::StopView::default(),
888            metrics: Arc::new(PollingMetrics::new()),
889        }
890    }
891
892    /// A writable wire bag — the terminating-publish tests need
893    /// `write` to actually land, which `NullWireSource` refuses.
894    struct MapWires(std::sync::Mutex<std::collections::HashMap<String, polydat::ast::Value>>);
895    impl MapWires {
896        fn new(seed: &[(&str, f64)]) -> Self {
897            Self(std::sync::Mutex::new(
898                seed.iter()
899                    .map(|(k, v)| (k.to_string(), polydat::ast::Value::F64(*v)))
900                    .collect(),
901            ))
902        }
903    }
904    impl crate::wires::WireSource for MapWires {
905        fn get(&self, name: &str) -> Option<polydat::ast::Value> {
906            self.0.lock().unwrap().get(name).cloned()
907        }
908        fn names(&self) -> Box<dyn Iterator<Item = String> + '_> {
909            let v: Vec<String> = self.0.lock().unwrap().keys().cloned().collect();
910            Box::new(v.into_iter())
911        }
912        fn write(&self, name: &str, value: polydat::ast::Value) -> crate::wires::WriteOutcome {
913            self.0.lock().unwrap().insert(name.to_string(), value);
914            crate::wires::WriteOutcome::Stored
915        }
916    }
917
918    /// Run a poll to completion against `wires`. `NoopInner` returns an
919    /// empty body, so the FIRST poll is the terminating one — exactly the
920    /// iteration whose measurement used to be dropped.
921    fn run_to_done(d: &PollingDispenser, wires: &dyn crate::wires::WireSource) {
922        // The poll abandons on a session stop, and the stop flag is
923        // process-global: hold it clear against sibling tests that set it.
924        let _guard = crate::session_signals::STOP_GLOBAL_TEST_LOCK.blocking_lock();
925        crate::session_signals::clear_session_stop_for_test();
926        let fields = crate::adapter::ResolvedFields::new(Vec::new(), Vec::new());
927        let pulls = crate::fixture::ResolvedPulls::empty();
928        let ctx = crate::fixture::ExecCtx::with_wires(&fields, &pulls, wires);
929        let rt = tokio::runtime::Builder::new_current_thread()
930            .enable_time()
931            .build()
932            .expect("test runtime");
933        rt.block_on(d.execute(0, &ctx)).expect("poll completes");
934    }
935
936    /// The measurement that DETECTS completion must reach metrics like every
937    /// incomplete one before it. Without this the last sample published is the
938    /// final not-yet-done poll, so a finished unit of work reads as partially
939    /// done for as long as the series is kept.
940    #[test]
941    fn the_terminating_poll_publishes_its_measurement() {
942        let memo = Arc::new(arc_swap::ArcSwap::from_pointee(String::from("base")));
943        let metrics = test_metrics();
944        let mut d = dispenser_with_status(None, None, &memo, &metrics);
945        let (slot, gauge) =
946            crate::wrappers::metrics::test_gauge_slot("completion", "completion_ratio");
947        d.iteration_gauges = Some(Arc::new(arc_swap::ArcSwapOption::from_pointee(vec![slot])));
948        let wires = MapWires::new(&[("completion_ratio", 0.42)]);
949
950        run_to_done(&d, &wires);
951
952        assert_eq!(
953            gauge.get(),
954            0.42,
955            "the terminating poll's measurement must reach the gauge"
956        );
957    }
958
959    /// A remote view of in-flight work cannot show the finished item — it is
960    /// gone from the view, which is *why* the poll ended. `on_done` proxies
961    /// that unobservable completed state onto the final sample.
962    #[test]
963    fn on_done_proxies_the_completion_a_remote_view_cannot_show() {
964        let memo = Arc::new(arc_swap::ArcSwap::from_pointee(String::from("base")));
965        let metrics = test_metrics();
966        let mut d = dispenser_with_status(None, None, &memo, &metrics);
967        let (slot, gauge) =
968            crate::wrappers::metrics::test_gauge_slot("completion", "completion_ratio");
969        d.iteration_gauges = Some(Arc::new(arc_swap::ArcSwapOption::from_pointee(vec![slot])));
970        d.on_done = vec![("completion_ratio".into(), "1.0".into())];
971        // The last value the view ever showed: 42% done, then it vanished.
972        let wires = MapWires::new(&[("completion_ratio", 0.42)]);
973
974        run_to_done(&d, &wires);
975
976        assert_eq!(
977            gauge.get(),
978            1.0,
979            "on_done must override the stale in-flight value"
980        );
981    }
982
983    /// Idempotence: these publishes are sets, not accumulates, so the same
984    /// terminating observation applied twice lands the same state. That is what
985    /// makes it safe to publish the final measurement in addition to whatever
986    /// the cadence already emitted for the same moment.
987    #[test]
988    fn republishing_the_terminating_measurement_is_idempotent() {
989        let memo = Arc::new(arc_swap::ArcSwap::from_pointee(String::from("base")));
990        let metrics = test_metrics();
991        let mut d = dispenser_with_status(None, None, &memo, &metrics);
992        let (slot, gauge) =
993            crate::wrappers::metrics::test_gauge_slot("completion", "completion_ratio");
994        d.iteration_gauges = Some(Arc::new(arc_swap::ArcSwapOption::from_pointee(vec![slot])));
995        d.on_done = vec![("completion_ratio".into(), "1.0".into())];
996        let wires = MapWires::new(&[("completion_ratio", 0.42)]);
997
998        run_to_done(&d, &wires);
999        let first = gauge.get();
1000        let memo_after_first = memo.load_full();
1001        run_to_done(&d, &wires);
1002        let second = gauge.get();
1003
1004        assert_eq!(
1005            first, second,
1006            "a repeated terminal publish must not shift the value"
1007        );
1008        assert_eq!(
1009            *memo_after_first,
1010            *memo.load_full(),
1011            "a repeated terminal publish must not accumulate into the memo"
1012        );
1013    }
1014
1015    fn test_metrics() -> Arc<crate::activity::ActivityMetrics> {
1016        Arc::new(crate::activity::ActivityMetrics::new(
1017            &nmbrs_metrics::labels::Labels::default(),
1018        ))
1019    }
1020
1021    #[test]
1022    fn progress_template_publishes_override_and_memo_renders() {
1023        let memo = Arc::new(arc_swap::ArcSwap::from_pointee(String::from("base")));
1024        let metrics = test_metrics();
1025        let d = dispenser_with_status(
1026            Some("ratio {completion_ratio}"),
1027            Some("{completion_ratio}"),
1028            &memo,
1029            &metrics,
1030        );
1031        let wires = RatioWire(0.42);
1032        d.publish_iteration_status(&wires, "base", 1, 3, 15.0);
1033        assert_eq!(
1034            metrics.progress_override(),
1035            Some(0.42),
1036            "progress template must publish the derived override"
1037        );
1038        assert_eq!(memo.load().as_str(), "ratio 0.42");
1039    }
1040
1041    #[test]
1042    fn default_memo_suffix_without_template() {
1043        let memo = Arc::new(arc_swap::ArcSwap::from_pointee(String::from("waiting")));
1044        let metrics = test_metrics();
1045        let d = dispenser_with_status(None, None, &memo, &metrics);
1046        let wires = RatioWire(0.9);
1047        d.publish_iteration_status(&wires, "waiting", 4, 7, 33.0);
1048        assert!(
1049            memo.load().contains("measured 4 row(s)"),
1050            "default memo must carry the measurement: {}",
1051            memo.load()
1052        );
1053        assert_eq!(
1054            metrics.progress_override(),
1055            None,
1056            "no progress template -> no override"
1057        );
1058    }
1059
1060    #[test]
1061    fn iteration_status_republishes_gutter_during_form() {
1062        // SRD-92: an op with a `gutter:` DURING form inside a poll
1063        // drain refreshes its cell per poll iteration — the
1064        // GutterDispenser alone publishes only once, at the end of
1065        // the (potentially hours-long) drain op. Substitution runs
1066        // against the iteration's wires, so the cell tracks the
1067        // measured state exactly like the poll memo.
1068        let memo = Arc::new(arc_swap::ArcSwap::from_pointee(String::new()));
1069        let metrics = test_metrics();
1070        let gutter_state: Arc<arc_swap::ArcSwapOption<crate::wrappers::gutter::GutterSpec>> =
1071            Arc::new(arc_swap::ArcSwapOption::empty());
1072        let mut d = dispenser_with_status(None, None, &memo, &metrics);
1073        d.each_gutter = Some(crate::wrappers::gutter::GutterTemplate::new(
1074            crate::wrappers::gutter::GutterKind::Text,
1075            "ratio {completion_ratio}",
1076        ));
1077        d.gutter_state = Some(gutter_state.clone());
1078
1079        d.publish_iteration_status(&RatioWire(0.25), "waiting", 4, 1, 5.0);
1080        assert_eq!(
1081            gutter_state.load().as_deref(),
1082            Some(&crate::wrappers::gutter::GutterSpec::Text(
1083                "ratio 0.25".into()
1084            )),
1085            "first iteration publishes the rendered during form"
1086        );
1087
1088        // Next iteration's wires supersede the cell.
1089        d.publish_iteration_status(&RatioWire(0.75), "waiting", 2, 2, 10.0);
1090        assert_eq!(
1091            gutter_state.load().as_deref(),
1092            Some(&crate::wrappers::gutter::GutterSpec::Text(
1093                "ratio 0.75".into()
1094            )),
1095            "each iteration refreshes the cell"
1096        );
1097
1098        // A failed substitution must leave the last good value.
1099        d.each_gutter = Some(crate::wrappers::gutter::GutterTemplate::new(
1100            crate::wrappers::gutter::GutterKind::Spark,
1101            "{no_such_wire}",
1102        ));
1103        d.publish_iteration_status(&RatioWire(0.9), "waiting", 1, 3, 15.0);
1104        assert_eq!(
1105            gutter_state.load().as_deref(),
1106            Some(&crate::wrappers::gutter::GutterSpec::Text(
1107                "ratio 0.75".into()
1108            )),
1109            "render failure must not clobber the cell"
1110        );
1111    }
1112}
1113
1114#[cfg(test)]
1115mod poll_wire_tests {
1116    /// With a declared `until:`, the memo must NOT quote the empty-result check.
1117    /// "measured 0 row(s) [awaiting empty]" reads as satisfied while the poll is
1118    /// still waiting — the single most misleading thing a status line can say,
1119    /// and exactly what an operator saw during a 1m28s drain.
1120    #[test]
1121    fn until_memo_does_not_quote_the_unused_empty_check() {
1122        let src =
1123            std::fs::read_to_string(concat!(env!("CARGO_MANIFEST_DIR"), "/src/wrappers/poll.rs"))
1124                .expect("read own source");
1125        let until_arm = src
1126            .find("waiting on `until:` (not yet satisfied)")
1127            .expect("the until: memo arm must exist");
1128        let empty_arm = src
1129            .find("measured {row_count} row(s) [awaiting empty] ·")
1130            .expect("the empty-result memo arm must exist");
1131        assert!(
1132            until_arm < empty_arm,
1133            "the until: arm must be the FIRST branch, so a declared condition \
1134             never falls through to the empty-result text"
1135        );
1136        // And the two must be distinct branches of one `if self.until`.
1137        assert!(
1138            src.contains("if self.until {"),
1139            "the memo must branch on whether an until: was declared"
1140        );
1141    }
1142
1143    /// `poll_elapsed_ms` and `poll_count` must be WRITTEN before the predicate
1144    /// is evaluated, not after. A condition that bounds its own patience
1145    /// (`... || poll_elapsed_ms >= 60000`) is the only way to assert something
1146    /// that may never be observed without risking a wait to `timeout_ms` —
1147    /// which in the compaction drain is 48 hours. Publishing them a moment too
1148    /// late would leave the first evaluation reading 0 forever.
1149    #[test]
1150    fn poll_progress_wires_are_published_before_the_predicate() {
1151        let src =
1152            std::fs::read_to_string(concat!(env!("CARGO_MANIFEST_DIR"), "/src/wrappers/poll.rs"))
1153                .expect("read own source");
1154        // Needle tolerates rustfmt splitting the receiver from the call —
1155        // `ctx.wires\n    .write(...)` — which is exactly what broke the
1156        // original `ctx.wires.write("poll_elapsed_ms"` form.
1157        let write_at = src
1158            .find(".write(\"poll_elapsed_ms\"")
1159            .expect("poll_elapsed_ms must be published");
1160        let predicate_at = src
1161            .find("let is_done = if self.until {")
1162            .expect("predicate evaluation site");
1163        assert!(
1164            write_at < predicate_at,
1165            "the poll-progress wires must be written BEFORE the until: predicate \
1166             is evaluated, or a self-bounding condition reads a stale 0"
1167        );
1168        assert!(
1169            src.contains(".write(\"poll_count\""),
1170            "poll_count must be published alongside poll_elapsed_ms"
1171        );
1172    }
1173}