Skip to main content

excel_api/
runtime.rs

1//! Idempotent XLL lifecycle runtime.
2
3use core::fmt;
4use std::sync::{Arc, Mutex, OnceLock};
5
6use crate::excel_call::{CallCapability, ExcelCallBackend, ExcelCallError, SdkExcel12vBackend};
7use crate::{AddInDescriptor, AsyncSubmitError, ExcelString, LifecycleContext};
8
9#[derive(Clone, Copy)]
10struct RegisteredEntry {
11    id: f64,
12    name: &'static str,
13    kind: RegistrationKind,
14}
15
16#[derive(Clone, Copy, Eq, PartialEq)]
17enum RegistrationKind {
18    Worksheet,
19    Command,
20}
21
22/// Observable state of one XLL runtime lifecycle generation.
23#[derive(Clone, Copy, Debug, Eq, PartialEq)]
24pub enum RuntimePhase {
25    /// No Excel callback backend is linked and no registrations are tracked.
26    Uninitialized,
27    /// Initialization owns the transition and is registering functions.
28    Initializing,
29    /// Registrations and the current runtime generation are active.
30    Initialized,
31    /// Close owns the transition and is retiring active resources.
32    Closing,
33    /// Excel registrations remain and close must be retried. Async scheduling
34    /// is disabled and the callback backend remains linked for cleanup only.
35    CleanupRequired,
36}
37
38/// Counters retained by [`Runtime`] for lifecycle diagnostics.
39#[derive(Clone, Debug, Default, Eq, PartialEq)]
40pub struct RuntimeDiagnostics {
41    /// Number of calls to [`Runtime::initialize`].
42    pub initialization_attempts: usize,
43    /// Initialization transitions that completed successfully.
44    pub successful_initializations: usize,
45    /// Idempotent initialize calls while already initialized.
46    pub duplicate_initializations: usize,
47    /// Number of calls to [`Runtime::close`].
48    pub close_attempts: usize,
49    /// Close transitions that unlinked the backend.
50    pub successful_closes: usize,
51    /// Total successfully registered functions and commands.
52    pub registrations: usize,
53    /// Number of attempted Excel unregister calls.
54    pub unregister_attempts: usize,
55    /// Number of rollback unregister attempts after initialization failure.
56    pub rollback_attempts: usize,
57}
58
59#[derive(Clone, Copy, Debug, Eq, PartialEq)]
60/// Outcome for an idempotent lifecycle operation.
61pub enum LifecycleOutcome {
62    /// This call completed the requested lifecycle transition.
63    Completed,
64    /// The runtime was already at the requested stable state.
65    AlreadyInState,
66}
67
68#[derive(Clone, Debug, Eq, PartialEq)]
69/// A lifecycle transition could not be completed safely.
70pub enum LifecycleError {
71    /// Another lifecycle transition owns the runtime in this phase.
72    Busy(RuntimePhase),
73    /// Async generation activation failed.
74    Async(AsyncSubmitError),
75    /// A typed Excel lifecycle call failed.
76    Excel(ExcelCallError),
77    /// Registration failed and one or more compensating calls also failed.
78    RegistrationRollback {
79        /// Original registration failure.
80        primary: ExcelCallError,
81        /// Failed compensating delete-name or unregister calls.
82        cleanup: Vec<ExcelCallError>,
83    },
84    /// Closing could not unregister all remaining registrations.
85    CloseFailed {
86        /// Exact errors retained for a later cleanup retry.
87        errors: Vec<ExcelCallError>,
88    },
89}
90
91impl fmt::Display for LifecycleError {
92    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
93        match self {
94            Self::Busy(phase) => write!(f, "runtime is busy in {phase:?}"),
95            Self::Async(error) => write!(f, "asynchronous runtime activation failed: {error}"),
96            Self::Excel(error) => write!(f, "lifecycle Excel call failed: {error}"),
97            Self::RegistrationRollback { primary, cleanup } => write!(
98                f,
99                "registration failed ({primary}); {} rollback calls failed",
100                cleanup.len()
101            ),
102            Self::CloseFailed { errors } => {
103                write!(f, "{} unregister calls failed during close", errors.len())
104            }
105        }
106    }
107}
108impl std::error::Error for LifecycleError {}
109
110impl From<ExcelCallError> for LifecycleError {
111    fn from(value: ExcelCallError) -> Self {
112        Self::Excel(value)
113    }
114}
115
116struct RuntimeState {
117    phase: RuntimePhase,
118    module: Option<ExcelString>,
119    worksheet_registrations: Vec<RegisteredEntry>,
120    command_registrations: Vec<RegisteredEntry>,
121    diagnostics: RuntimeDiagnostics,
122    calculation_canceled_registered: bool,
123    calculation_ended_registered: bool,
124    async_generation_active: bool,
125    dispatcher_generation_active: bool,
126}
127
128impl Default for RuntimeState {
129    fn default() -> Self {
130        Self {
131            phase: RuntimePhase::Uninitialized,
132            module: None,
133            worksheet_registrations: Vec::new(),
134            command_registrations: Vec::new(),
135            diagnostics: RuntimeDiagnostics::default(),
136            calculation_canceled_registered: false,
137            calculation_ended_registered: false,
138            async_generation_active: false,
139            dispatcher_generation_active: false,
140        }
141    }
142}
143
144/// Coordinates Excel linking, registration, and orderly XLL close.
145///
146/// A runtime is process-local application state, not a callback context. Its
147/// transition methods must be called through genuine Excel lifecycle thunks.
148pub struct Runtime {
149    backend: Arc<dyn ExcelCallBackend>,
150    sdk_backend: Option<Arc<SdkExcel12vBackend>>,
151    state: Mutex<RuntimeState>,
152}
153
154impl fmt::Debug for Runtime {
155    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
156        f.debug_struct("Runtime")
157            .field("phase", &self.phase())
158            .finish_non_exhaustive()
159    }
160}
161
162impl Runtime {
163    /// Creates the process-local runtime using the production Excel12v backend.
164    ///
165    /// The backend remains unlinked until [`Self::initialize`] runs from a
166    /// genuine lifecycle callback.
167    pub fn production() -> Self {
168        let backend = production_backend();
169        Self {
170            backend: backend.clone(),
171            sdk_backend: Some(backend),
172            state: Mutex::new(RuntimeState::default()),
173        }
174    }
175
176    #[cfg(test)]
177    fn with_backend(backend: Arc<dyn ExcelCallBackend>) -> Self {
178        Self {
179            backend,
180            sdk_backend: None,
181            state: Mutex::new(RuntimeState::default()),
182        }
183    }
184
185    /// Installs Excel's `Excel12v` callback entry point in the SDK backend.
186    ///
187    /// Generated lifecycle thunks call this before initialization; passing an
188    /// entry point does not itself link the backend or make arbitrary calls legal.
189    pub fn set_excel12_entry_point(&self, callback: excel_api_sys::Excel12EntryPtFn) {
190        if let Some(backend) = &self.sdk_backend {
191            backend.set_entry_point(callback);
192        }
193    }
194
195    fn lock(&self) -> std::sync::MutexGuard<'_, RuntimeState> {
196        self.state
197            .lock()
198            .unwrap_or_else(std::sync::PoisonError::into_inner)
199    }
200
201    /// Returns the current lifecycle phase.
202    pub fn phase(&self) -> RuntimePhase {
203        self.lock().phase
204    }
205    /// Returns a copied snapshot of process-local lifecycle counters.
206    pub fn diagnostics(&self) -> RuntimeDiagnostics {
207        self.lock().diagnostics.clone()
208    }
209    /// Returns worksheet-function registration identifiers currently tracked.
210    ///
211    /// The IDs are meaningful only while the current runtime generation remains
212    /// active and must not be used to issue raw unregister calls directly.
213    pub fn registration_ids(&self) -> Vec<f64> {
214        self.lock()
215            .worksheet_registrations
216            .iter()
217            .map(|entry| entry.id)
218            .collect()
219    }
220
221    /// Runs an M17 compatibility-spike operation with a lifecycle capability.
222    ///
223    /// This bridge is compiled only for the isolated xlcOnTime research XLL.
224    /// It does not make lifecycle use of an XLM command a stable or generally
225    /// supported capability.
226    ///
227    /// # Safety
228    ///
229    /// The caller must be synchronously executing on the callback thread in a
230    /// genuine Excel-issued lifecycle callback. A linked backend alone is not
231    /// evidence that this precondition holds.
232    ///
233    /// Safe code cannot invoke this bridge:
234    ///
235    /// ```compile_fail
236    /// let runtime = excel_api::Runtime::production();
237    /// runtime.experimental_with_lifecycle_context(|_| ());
238    /// ```
239    #[cfg(feature = "xlcontime-research")]
240    #[doc(hidden)]
241    pub unsafe fn experimental_with_lifecycle_context<R>(
242        &self,
243        body: impl FnOnce(&LifecycleContext<'_>) -> R,
244    ) -> Result<R, ExcelCallError> {
245        if !self.backend.is_linked() {
246            return Err(ExcelCallError::BackendUnavailable);
247        }
248        let capability = CallCapability::new(self.backend.as_ref());
249        let context = LifecycleContext::new(&capability);
250        Ok(body(&context))
251    }
252
253    /// Links Excel, installs a fresh generation, and registers `add_in`.
254    ///
255    /// Call only from an Excel-issued open/lifecycle callback. On partial
256    /// registration failure this performs bounded rollback; a rollback failure
257    /// leaves [`RuntimePhase::CleanupRequired`] so [`Self::close`] can retry.
258    pub fn initialize(&self, add_in: &AddInDescriptor) -> Result<LifecycleOutcome, LifecycleError> {
259        let _callback = crate::dispatcher::enter_callback();
260        add_in
261            .validate()
262            .map_err(|error| LifecycleError::Excel(ExcelCallError::Registration(error)))?;
263        {
264            let mut state = self.lock();
265            state.diagnostics.initialization_attempts += 1;
266            match state.phase {
267                RuntimePhase::Initialized => {
268                    state.diagnostics.duplicate_initializations += 1;
269                    return Ok(LifecycleOutcome::AlreadyInState);
270                }
271                RuntimePhase::Uninitialized => state.phase = RuntimePhase::Initializing,
272                phase => return Err(LifecycleError::Busy(phase)),
273            }
274        }
275
276        let has_async = add_in
277            .functions
278            .iter()
279            .any(|function| function.is_asynchronous());
280        if let Err(error) = self.backend.link() {
281            self.lock().phase = RuntimePhase::Uninitialized;
282            return Err(error.into());
283        }
284        if has_async {
285            if let Err(error) = crate::async_udf::activate(self.backend.clone()) {
286                self.backend.unlink();
287                self.lock().phase = RuntimePhase::Uninitialized;
288                return Err(LifecycleError::Async(error));
289            }
290            self.lock().async_generation_active = true;
291        }
292        let dispatcher_active = crate::dispatcher::activate();
293        self.lock().dispatcher_generation_active = dispatcher_active;
294
295        let capability = CallCapability::new(self.backend.as_ref());
296        let context = LifecycleContext::new(&capability);
297        let module = match context.get_module_name() {
298            Ok(module) => module,
299            Err(error) => {
300                if dispatcher_active {
301                    crate::dispatcher::shutdown();
302                }
303                if has_async {
304                    crate::async_udf::shutdown();
305                }
306                self.backend.unlink();
307                let mut state = self.lock();
308                state.phase = RuntimePhase::Uninitialized;
309                state.async_generation_active = false;
310                state.dispatcher_generation_active = false;
311                return Err(error.into());
312            }
313        };
314
315        if has_async {
316            if let Err(error) = self.ensure_async_events(&context) {
317                if dispatcher_active {
318                    crate::dispatcher::shutdown();
319                }
320                crate::async_udf::shutdown();
321                self.backend.unlink();
322                let mut state = self.lock();
323                state.phase = RuntimePhase::Uninitialized;
324                state.async_generation_active = false;
325                state.dispatcher_generation_active = false;
326                return Err(error.into());
327            }
328        }
329
330        let mut registered = Vec::with_capacity(add_in.functions.len());
331        for function in add_in.functions {
332            match context.register(&module, function) {
333                Ok(id) => registered.push(id),
334                Err(primary) => {
335                    let mut cleanup = Vec::new();
336                    for (index, id) in registered.iter().copied().enumerate().rev() {
337                        if let Err(error) =
338                            context.delete_defined_name(add_in.functions[index].excel_name)
339                        {
340                            cleanup.push(error);
341                        }
342                        if let Err(error) = context.unregister(id) {
343                            cleanup.push(error);
344                        }
345                    }
346                    if has_async {
347                        crate::async_udf::shutdown();
348                    }
349                    if dispatcher_active {
350                        crate::dispatcher::shutdown();
351                    }
352                    if cleanup.is_empty() {
353                        self.backend.unlink();
354                    }
355                    let mut state = self.lock();
356                    state.diagnostics.rollback_attempts += registered.len();
357                    state.async_generation_active = false;
358                    state.dispatcher_generation_active = false;
359                    if cleanup.is_empty() {
360                        state.phase = RuntimePhase::Uninitialized;
361                        state.module = None;
362                        state.worksheet_registrations.clear();
363                        state.command_registrations.clear();
364                    } else {
365                        // Keep the backend and conservative cleanup metadata
366                        // alive; a later close can retry anything Excel may
367                        // still consider registered.
368                        state.phase = RuntimePhase::CleanupRequired;
369                        state.module = Some(module);
370                        state.worksheet_registrations = add_in.functions[..registered.len()]
371                            .iter()
372                            .zip(registered.iter().copied())
373                            .map(|(function, id)| RegisteredEntry {
374                                id,
375                                name: function.excel_name,
376                                kind: RegistrationKind::Worksheet,
377                            })
378                            .collect();
379                        state.command_registrations.clear();
380                    }
381                    return Err(LifecycleError::RegistrationRollback { primary, cleanup });
382                }
383            }
384        }
385
386        let mut command_registered = Vec::with_capacity(add_in.commands.len());
387        for command in add_in.commands {
388            match context.register_command(&module, command) {
389                Ok(id) => command_registered.push(id),
390                Err(primary) => {
391                    let mut cleanup = Vec::new();
392                    for (index, id) in command_registered.iter().copied().enumerate().rev() {
393                        if let Err(error) =
394                            context.delete_defined_name(add_in.commands[index].excel_name)
395                        {
396                            cleanup.push(error);
397                        }
398                        if let Err(error) = context.unregister(id) {
399                            cleanup.push(error);
400                        }
401                    }
402                    for (index, id) in registered.iter().copied().enumerate().rev() {
403                        if let Err(error) =
404                            context.delete_defined_name(add_in.functions[index].excel_name)
405                        {
406                            cleanup.push(error);
407                        }
408                        if let Err(error) = context.unregister(id) {
409                            cleanup.push(error);
410                        }
411                    }
412                    if has_async {
413                        crate::async_udf::shutdown();
414                    }
415                    if dispatcher_active {
416                        crate::dispatcher::shutdown();
417                    }
418                    if cleanup.is_empty() {
419                        self.backend.unlink();
420                    }
421                    let mut state = self.lock();
422                    state.diagnostics.rollback_attempts +=
423                        command_registered.len() + registered.len();
424                    state.async_generation_active = false;
425                    state.dispatcher_generation_active = false;
426                    if cleanup.is_empty() {
427                        state.phase = RuntimePhase::Uninitialized;
428                        state.module = None;
429                        state.worksheet_registrations.clear();
430                        state.command_registrations.clear();
431                    } else {
432                        state.phase = RuntimePhase::CleanupRequired;
433                        state.module = Some(module);
434                        state.worksheet_registrations = registered
435                            .iter()
436                            .copied()
437                            .zip(add_in.functions.iter())
438                            .map(|(id, function)| RegisteredEntry {
439                                id,
440                                name: function.excel_name,
441                                kind: RegistrationKind::Worksheet,
442                            })
443                            .collect();
444                        state.command_registrations = command_registered
445                            .iter()
446                            .copied()
447                            .zip(add_in.commands.iter())
448                            .map(|(id, command)| RegisteredEntry {
449                                id,
450                                name: command.excel_name,
451                                kind: RegistrationKind::Command,
452                            })
453                            .collect();
454                    }
455                    return Err(LifecycleError::RegistrationRollback { primary, cleanup });
456                }
457            }
458        }
459
460        let mut state = self.lock();
461        state.phase = RuntimePhase::Initialized;
462        state.module = Some(module);
463        state.diagnostics.registrations += registered.len() + command_registered.len();
464        state.worksheet_registrations = registered
465            .iter()
466            .copied()
467            .zip(add_in.functions.iter())
468            .map(|(id, function)| RegisteredEntry {
469                id,
470                name: function.excel_name,
471                kind: RegistrationKind::Worksheet,
472            })
473            .collect();
474        state.command_registrations = command_registered
475            .iter()
476            .copied()
477            .zip(add_in.commands.iter())
478            .map(|(id, command)| RegisteredEntry {
479                id,
480                name: command.excel_name,
481                kind: RegistrationKind::Command,
482            })
483            .collect();
484        state.diagnostics.successful_initializations += 1;
485        Ok(LifecycleOutcome::Completed)
486    }
487
488    fn ensure_async_events(&self, context: &LifecycleContext<'_>) -> Result<(), ExcelCallError> {
489        let (canceled, ended) = {
490            let state = self.lock();
491            (
492                state.calculation_canceled_registered,
493                state.calculation_ended_registered,
494            )
495        };
496        if !canceled {
497            context.register_event(
498                "excel_api_calculation_canceled",
499                excel_api_sys::xleventCalculationCanceled,
500            )?;
501            self.lock().calculation_canceled_registered = true;
502        }
503        if !ended {
504            context.register_event(
505                "excel_api_calculation_ended",
506                excel_api_sys::xleventCalculationEnded,
507            )?;
508            self.lock().calculation_ended_registered = true;
509        }
510        Ok(())
511    }
512
513    /// Retires dispatcher and async generations, unregisters, then unlinks Excel.
514    ///
515    /// This must run from a genuine lifecycle callback. Failed unregister calls
516    /// retain conservative cleanup state and return [`LifecycleError::CloseFailed`];
517    /// retrying `close` never reactivates old generations.
518    pub fn close(&self) -> Result<LifecycleOutcome, LifecycleError> {
519        let _callback = crate::dispatcher::enter_callback();
520        let (registrations, drain_async, drain_dispatcher) = {
521            let mut state = self.lock();
522            state.diagnostics.close_attempts += 1;
523            match state.phase {
524                RuntimePhase::Uninitialized => return Ok(LifecycleOutcome::AlreadyInState),
525                RuntimePhase::Initialized => {
526                    state.phase = RuntimePhase::Closing;
527                    let mut entries = state.command_registrations.clone();
528                    entries.extend(state.worksheet_registrations.iter().copied());
529                    let drain_async = state.async_generation_active;
530                    let drain_dispatcher = state.dispatcher_generation_active;
531                    state.async_generation_active = false;
532                    state.dispatcher_generation_active = false;
533                    (entries, drain_async, drain_dispatcher)
534                }
535                RuntimePhase::CleanupRequired => {
536                    state.phase = RuntimePhase::Closing;
537                    let mut entries = state.command_registrations.clone();
538                    entries.extend(state.worksheet_registrations.iter().copied());
539                    (entries, false, false)
540                }
541                phase => return Err(LifecycleError::Busy(phase)),
542            }
543        };
544
545        // Remove and synchronously retire cooperative dispatch before any
546        // registration or callback entry point can disappear. Shutdown waits
547        // only for work already executing in a real callback; it never waits
548        // for a future pump.
549        if drain_dispatcher {
550            crate::dispatcher::shutdown();
551        }
552        // Disable and drain asynchronous work before registrations or the
553        // Excel callback entry point can disappear.
554        if drain_async {
555            crate::async_udf::shutdown();
556        }
557
558        let capability = CallCapability::new(self.backend.as_ref());
559        let context = LifecycleContext::new(&capability);
560        let mut failed = Vec::new();
561        let mut errors = Vec::new();
562        for RegisteredEntry { id, name, kind } in registrations.iter().rev().copied() {
563            if let Err(error) = context.delete_defined_name(name) {
564                errors.push(error);
565            }
566            if let Err(error) = context.unregister(id) {
567                failed.push(RegisteredEntry { id, name, kind });
568                errors.push(error);
569            }
570        }
571        let mut state = self.lock();
572        state.diagnostics.unregister_attempts += registrations.len();
573        if errors.is_empty() {
574            self.backend.unlink();
575            state.phase = RuntimePhase::Uninitialized;
576            state.module = None;
577            state.worksheet_registrations.clear();
578            state.command_registrations.clear();
579            state.diagnostics.successful_closes += 1;
580            Ok(LifecycleOutcome::Completed)
581        } else {
582            failed.reverse();
583            state.phase = RuntimePhase::CleanupRequired;
584            state.worksheet_registrations = failed
585                .iter()
586                .copied()
587                .filter(|entry| entry.kind == RegistrationKind::Worksheet)
588                .collect();
589            state.command_registrations = failed
590                .into_iter()
591                .filter(|entry| entry.kind == RegistrationKind::Command)
592                .collect();
593            Err(LifecycleError::CloseFailed { errors })
594        }
595    }
596}
597
598pub(crate) fn production_backend() -> Arc<SdkExcel12vBackend> {
599    static BACKEND: OnceLock<Arc<SdkExcel12vBackend>> = OnceLock::new();
600    BACKEND
601        .get_or_init(|| Arc::new(SdkExcel12vBackend::new()))
602        .clone()
603}
604
605impl Default for Runtime {
606    fn default() -> Self {
607        Self::production()
608    }
609}
610
611#[cfg(test)]
612mod tests {
613    use super::*;
614    use crate::{
615        ExcelArgumentType, ExcelReturnType, FunctionFlags, FunctionRegistration, FunctionSignature,
616    };
617    use core::ffi::c_int;
618    use excel_api_sys::{LPXLOPER12, XLOPER12, XLOPER12Value};
619    use std::{collections::HashMap, sync::Mutex};
620
621    #[derive(Default)]
622    struct MockState {
623        linked: bool,
624        calls: Vec<(i32, usize)>,
625        type_texts: Vec<String>,
626        unregistered: Vec<f64>,
627        allocations: HashMap<usize, Box<[u16]>>,
628        next_id: f64,
629        fail_registration: Option<usize>,
630        fail_unregistration: usize,
631        fail_event: Option<usize>,
632        register_count: usize,
633        event_count: usize,
634        event_ids: Vec<i32>,
635        unregister_linked: Vec<bool>,
636        free_calls: usize,
637    }
638
639    #[derive(Default)]
640    struct MockBackend {
641        state: Mutex<MockState>,
642    }
643
644    impl MockBackend {
645        fn failing_registration(index: usize) -> Self {
646            let mock = Self::default();
647            mock.state.lock().unwrap().fail_registration = Some(index);
648            mock
649        }
650    }
651
652    impl ExcelCallBackend for MockBackend {
653        fn link(&self) -> Result<(), ExcelCallError> {
654            self.state.lock().unwrap().linked = true;
655            Ok(())
656        }
657        fn unlink(&self) {
658            self.state.lock().unwrap().linked = false;
659        }
660        fn is_linked(&self) -> bool {
661            self.state.lock().unwrap().linked
662        }
663
664        unsafe fn excel12v_raw(
665            &self,
666            function: i32,
667            result: *mut XLOPER12,
668            count: c_int,
669            arguments: *mut LPXLOPER12,
670        ) -> i32 {
671            let mut state = self.state.lock().unwrap();
672            state.calls.push((function, count as usize));
673            if function == excel_api_sys::xlGetName {
674                let mut text: Box<[u16]> = [vec![15], "C:\\test\\add.xll".encode_utf16().collect()]
675                    .concat()
676                    .into_boxed_slice();
677                let pointer = text.as_mut_ptr();
678                state.allocations.insert(pointer as usize, text);
679                // SAFETY: the runtime supplies a live result root.
680                unsafe {
681                    *result = XLOPER12 {
682                        val: XLOPER12Value { str: pointer },
683                        xltype: excel_api_sys::xltypeStr,
684                    };
685                }
686            } else if function == excel_api_sys::xlfRegister {
687                state.register_count += 1;
688                if state.fail_registration == Some(state.register_count) {
689                    return excel_api_sys::xlretFailed;
690                }
691                // SAFETY: registration always supplies at least three initialized argument roots.
692                let type_root = unsafe { *arguments.add(2) };
693                // SAFETY: the third root is a counted string kept live by CallArguments.
694                let type_pointer = unsafe { (*type_root).val.str };
695                // SAFETY: counted prefix and payload are initialized.
696                let length = unsafe { *type_pointer } as usize;
697                // SAFETY: the payload has `length` code units.
698                let units = unsafe { core::slice::from_raw_parts(type_pointer.add(1), length) };
699                state.type_texts.push(String::from_utf16(units).unwrap());
700                state.next_id += 1.0;
701                // SAFETY: the runtime supplies a live result root.
702                unsafe {
703                    *result = XLOPER12 {
704                        val: XLOPER12Value { num: state.next_id },
705                        xltype: excel_api_sys::xltypeNum,
706                    };
707                }
708            } else if function == excel_api_sys::xlfUnregister {
709                let linked = state.linked;
710                state.unregister_linked.push(linked);
711                if state.fail_unregistration > 0 {
712                    state.fail_unregistration -= 1;
713                    return excel_api_sys::xlretFailed;
714                }
715                // SAFETY: unregister supplies one number root.
716                let id = unsafe { (**arguments).val.num };
717                state.unregistered.push(id);
718                // SAFETY: the runtime supplies a live result root.
719                unsafe {
720                    *result = XLOPER12 {
721                        val: XLOPER12Value { xbool: 1 },
722                        xltype: excel_api_sys::xltypeBool,
723                    };
724                }
725            } else if function == excel_api_sys::xlfSetName {
726                // SAFETY: the runtime supplies a live result root.
727                unsafe {
728                    *result = XLOPER12 {
729                        val: XLOPER12Value { xbool: 1 },
730                        xltype: excel_api_sys::xltypeBool,
731                    };
732                }
733            } else if function == excel_api_sys::xlEventRegister {
734                state.event_count += 1;
735                if state.fail_event == Some(state.event_count) {
736                    return excel_api_sys::xlretFailed;
737                }
738                // SAFETY: event registration supplies a string followed by an integer.
739                let event = unsafe { (**arguments.add(1)).val.w };
740                state.event_ids.push(event);
741                // SAFETY: the runtime supplies a live result root.
742                unsafe {
743                    *result = XLOPER12 {
744                        val: XLOPER12Value {
745                            w: state.event_count as i32,
746                        },
747                        xltype: excel_api_sys::xltypeInt,
748                    };
749                }
750            } else if function == excel_api_sys::xlFree {
751                state.free_calls += 1;
752                // SAFETY: xlFree receives one live C-API result root.
753                let root = unsafe { *arguments };
754                // SAFETY: root remains live for this synchronous call.
755                if unsafe { (*root).xltype & excel_api_sys::XLTYPE_MASK }
756                    == excel_api_sys::xltypeStr
757                {
758                    // SAFETY: active union member is string.
759                    let address = unsafe { (*root).val.str } as usize;
760                    state.allocations.remove(&address);
761                }
762            }
763            excel_api_sys::xlretSuccess
764        }
765    }
766
767    const EMPTY: &[ExcelArgumentType] = &[];
768    static FUNCTIONS: &[FunctionRegistration] = &[
769        FunctionRegistration::new(
770            "one",
771            "ONE",
772            FunctionSignature::new(ExcelReturnType::Xloper12, EMPTY),
773        )
774        .arguments(&[], &[]),
775        FunctionRegistration::new(
776            "two",
777            "TWO",
778            FunctionSignature::new(ExcelReturnType::Xloper12, EMPTY),
779        )
780        .arguments(&[], &[])
781        .flags(FunctionFlags {
782            volatile: false,
783            thread_safe: true,
784            macro_type: false,
785            cluster_safe: false,
786        }),
787    ];
788    static ADD_IN: AddInDescriptor = AddInDescriptor::new("test", "test", FUNCTIONS);
789
790    const ASYNC_ARGS: &[ExcelArgumentType] =
791        &[ExcelArgumentType::Number, ExcelArgumentType::AsyncHandle];
792    static ASYNC_FUNCTIONS: &[FunctionRegistration] = &[FunctionRegistration::new(
793        "async_one",
794        "ASYNC.ONE",
795        FunctionSignature::new(ExcelReturnType::AsyncVoid, ASYNC_ARGS),
796    )
797    .arguments(&["value"], &["Value"])
798    .flags(FunctionFlags {
799        volatile: false,
800        thread_safe: true,
801        macro_type: false,
802        cluster_safe: false,
803    })];
804    static ASYNC_ADD_IN: AddInDescriptor =
805        AddInDescriptor::new("async test", "async test", ASYNC_FUNCTIONS);
806
807    fn install_test_executor() {
808        crate::async_udf::reset_generations_for_test();
809        let executor = crate::ThreadPoolExecutor::new(1, 4).unwrap();
810        assert!(crate::install_async_executor(Arc::new(executor), 4).is_ok());
811    }
812
813    fn async_test_guard() -> std::sync::MutexGuard<'static, ()> {
814        static GUARD: OnceLock<Mutex<()>> = OnceLock::new();
815        GUARD
816            .get_or_init(|| Mutex::new(()))
817            .lock()
818            .unwrap_or_else(std::sync::PoisonError::into_inner)
819    }
820
821    struct RuntimeTestGuard {
822        _runtime: std::sync::MutexGuard<'static, ()>,
823        _dispatcher: std::sync::MutexGuard<'static, ()>,
824    }
825
826    fn runtime_test_guard() -> RuntimeTestGuard {
827        static GUARD: OnceLock<Mutex<()>> = OnceLock::new();
828        let runtime = GUARD
829            .get_or_init(|| Mutex::new(()))
830            .lock()
831            .unwrap_or_else(std::sync::PoisonError::into_inner);
832        let dispatcher = crate::dispatcher::TEST_SERIAL
833            .lock()
834            .unwrap_or_else(std::sync::PoisonError::into_inner);
835        RuntimeTestGuard {
836            _runtime: runtime,
837            _dispatcher: dispatcher,
838        }
839    }
840
841    #[test]
842    fn duplicate_sequences_register_once_and_close_is_idempotent() {
843        let _runtime = runtime_test_guard();
844        let backend = Arc::new(MockBackend::default());
845        let runtime = Runtime::with_backend(backend.clone());
846        assert_eq!(runtime.initialize(&ADD_IN), Ok(LifecycleOutcome::Completed));
847        assert_eq!(
848            runtime.initialize(&ADD_IN),
849            Ok(LifecycleOutcome::AlreadyInState)
850        );
851        assert_eq!(runtime.registration_ids(), vec![1.0, 2.0]);
852        assert_eq!(runtime.close(), Ok(LifecycleOutcome::Completed));
853        assert_eq!(runtime.close(), Ok(LifecycleOutcome::AlreadyInState));
854        let state = backend.state.lock().unwrap();
855        assert_eq!(state.type_texts, ["Q", "Q$"]);
856        assert_eq!(state.unregistered, [2.0, 1.0]);
857        assert_eq!(state.unregister_linked, [true, true]);
858        assert!(!state.linked);
859        assert!(state.allocations.is_empty());
860        assert_eq!(state.free_calls, 7); // xlGetName, registrations, name deletion, unregisters.
861    }
862
863    #[test]
864    fn partial_registration_rolls_back_and_retry_succeeds() {
865        let _runtime = runtime_test_guard();
866        let backend = Arc::new(MockBackend::failing_registration(2));
867        let runtime = Runtime::with_backend(backend.clone());
868        assert!(matches!(
869            runtime.initialize(&ADD_IN),
870            Err(LifecycleError::RegistrationRollback { .. })
871        ));
872        assert_eq!(runtime.phase(), RuntimePhase::Uninitialized);
873        assert_eq!(backend.state.lock().unwrap().unregistered, [1.0]);
874        backend.state.lock().unwrap().fail_registration = None;
875        assert_eq!(runtime.initialize(&ADD_IN), Ok(LifecycleOutcome::Completed));
876    }
877
878    #[test]
879    fn unavailable_backend_restores_uninitialized_state() {
880        let _runtime = runtime_test_guard();
881        let runtime = Runtime::with_backend(Arc::new(
882            crate::excel_call::test_support::UnavailableBackend,
883        ));
884        assert_eq!(
885            runtime.initialize(&ADD_IN),
886            Err(LifecycleError::Excel(ExcelCallError::BackendUnavailable))
887        );
888        assert_eq!(runtime.phase(), RuntimePhase::Uninitialized);
889    }
890
891    #[test]
892    fn async_events_register_once_across_close_and_reopen() {
893        let _runtime = runtime_test_guard();
894        let _guard = async_test_guard();
895        install_test_executor();
896        let backend = Arc::new(MockBackend::default());
897        let runtime = Runtime::with_backend(backend.clone());
898        assert_eq!(
899            runtime.initialize(&ASYNC_ADD_IN),
900            Ok(LifecycleOutcome::Completed)
901        );
902        assert_eq!(runtime.close(), Ok(LifecycleOutcome::Completed));
903        let executor = crate::ThreadPoolExecutor::new(1, 4).unwrap();
904        assert!(crate::install_async_executor(Arc::new(executor), 4).is_ok());
905        assert_eq!(
906            runtime.initialize(&ASYNC_ADD_IN),
907            Ok(LifecycleOutcome::Completed)
908        );
909        assert_eq!(runtime.close(), Ok(LifecycleOutcome::Completed));
910        let state = backend.state.lock().unwrap();
911        assert_eq!(state.event_count, 2);
912        assert_eq!(
913            state.event_ids,
914            [
915                excel_api_sys::xleventCalculationCanceled,
916                excel_api_sys::xleventCalculationEnded,
917            ]
918        );
919        crate::async_udf::reset_generations_for_test();
920    }
921
922    #[test]
923    fn failed_second_event_registration_retries_only_missing_event() {
924        let _runtime = runtime_test_guard();
925        let _guard = async_test_guard();
926        install_test_executor();
927        let backend = Arc::new(MockBackend::default());
928        backend.state.lock().unwrap().fail_event = Some(2);
929        let runtime = Runtime::with_backend(backend.clone());
930        assert!(matches!(
931            runtime.initialize(&ASYNC_ADD_IN),
932            Err(LifecycleError::Excel(_))
933        ));
934        assert_eq!(runtime.phase(), RuntimePhase::Uninitialized);
935        backend.state.lock().unwrap().fail_event = None;
936        let executor = crate::ThreadPoolExecutor::new(1, 4).unwrap();
937        assert!(crate::install_async_executor(Arc::new(executor), 4).is_ok());
938        assert_eq!(
939            runtime.initialize(&ASYNC_ADD_IN),
940            Ok(LifecycleOutcome::Completed)
941        );
942        assert_eq!(backend.state.lock().unwrap().event_count, 3);
943        assert_eq!(runtime.close(), Ok(LifecycleOutcome::Completed));
944        crate::async_udf::reset_generations_for_test();
945    }
946
947    #[test]
948    fn close_failure_is_cleanup_required_and_retry_can_reopen() {
949        let _runtime = runtime_test_guard();
950        let _guard = async_test_guard();
951        install_test_executor();
952        let backend = Arc::new(MockBackend::default());
953        let runtime = Runtime::with_backend(backend.clone());
954        assert_eq!(
955            runtime.initialize(&ASYNC_ADD_IN),
956            Ok(LifecycleOutcome::Completed)
957        );
958        backend.state.lock().unwrap().fail_unregistration = 1;
959        assert!(matches!(
960            runtime.close(),
961            Err(LifecycleError::CloseFailed { .. })
962        ));
963        assert_eq!(runtime.phase(), RuntimePhase::CleanupRequired);
964        assert!(matches!(
965            runtime.initialize(&ASYNC_ADD_IN),
966            Err(LifecycleError::Busy(RuntimePhase::CleanupRequired))
967        ));
968        assert_eq!(runtime.close(), Ok(LifecycleOutcome::Completed));
969        assert_eq!(runtime.phase(), RuntimePhase::Uninitialized);
970        let executor = crate::ThreadPoolExecutor::new(1, 4).unwrap();
971        assert!(crate::install_async_executor(Arc::new(executor), 4).is_ok());
972        assert_eq!(
973            runtime.initialize(&ASYNC_ADD_IN),
974            Ok(LifecycleOutcome::Completed)
975        );
976        assert_eq!(runtime.close(), Ok(LifecycleOutcome::Completed));
977        crate::async_udf::reset_generations_for_test();
978    }
979
980    #[test]
981    fn initialization_failure_after_events_shuts_generation_and_reuses_events() {
982        let _runtime = runtime_test_guard();
983        let _guard = async_test_guard();
984        install_test_executor();
985        let backend = Arc::new(MockBackend::failing_registration(1));
986        let runtime = Runtime::with_backend(backend.clone());
987        assert!(matches!(
988            runtime.initialize(&ASYNC_ADD_IN),
989            Err(LifecycleError::RegistrationRollback { .. })
990        ));
991        assert_eq!(runtime.phase(), RuntimePhase::Uninitialized);
992        backend.state.lock().unwrap().fail_registration = None;
993        let executor = crate::ThreadPoolExecutor::new(1, 4).unwrap();
994        assert!(crate::install_async_executor(Arc::new(executor), 4).is_ok());
995        assert_eq!(
996            runtime.initialize(&ASYNC_ADD_IN),
997            Ok(LifecycleOutcome::Completed)
998        );
999        assert_eq!(backend.state.lock().unwrap().event_count, 2);
1000        assert_eq!(runtime.close(), Ok(LifecycleOutcome::Completed));
1001        crate::async_udf::reset_generations_for_test();
1002    }
1003
1004    #[test]
1005    fn dispatcher_shutdown_precedes_cleanup_required_and_backend_unlink() {
1006        let _runtime = runtime_test_guard();
1007        crate::dispatcher::reset_generations_for_test();
1008        assert_eq!(
1009            crate::install_dispatcher(crate::DispatchConfig::default()),
1010            Ok(())
1011        );
1012        let backend = Arc::new(MockBackend::default());
1013        let runtime = Runtime::with_backend(backend.clone());
1014        assert_eq!(runtime.initialize(&ADD_IN), Ok(LifecycleOutcome::Completed));
1015        let ticket = crate::enqueue_dispatch(crate::DispatchOperation::EchoOwned(
1016            crate::ExcelValue::Integer(7),
1017        ))
1018        .unwrap();
1019        backend.state.lock().unwrap().fail_unregistration = 1;
1020        assert!(matches!(
1021            runtime.close(),
1022            Err(LifecycleError::CloseFailed { .. })
1023        ));
1024        assert_eq!(runtime.phase(), RuntimePhase::CleanupRequired);
1025        assert_eq!(
1026            ticket.try_result(),
1027            Some(Err(crate::DispatchCompletionError::DispatcherShutdown))
1028        );
1029        assert_eq!(
1030            crate::enqueue_dispatch(crate::DispatchOperation::EchoOwned(
1031                crate::ExcelValue::Integer(8)
1032            ))
1033            .unwrap_err(),
1034            crate::DispatchEnqueueError::NoActiveGeneration
1035        );
1036        assert!(backend.state.lock().unwrap().linked);
1037        assert_eq!(runtime.close(), Ok(LifecycleOutcome::Completed));
1038        assert!(!backend.state.lock().unwrap().linked);
1039        crate::dispatcher::reset_generations_for_test();
1040    }
1041}