duroxide 0.2.0

Durable code execution framework for Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

//! Worker (activity) dispatcher implementation for Runtime
//!
//! This module contains the worker dispatcher logic that:
//! - Spawns concurrent activity workers
//! - Fetches and executes activity work items
//! - Handles activity completion and failure atomically
//! - Supports cooperative activity cancellation
//!
//! # Architecture
//!
//! The worker dispatcher spawns N concurrent worker tasks, each of which:
//! 1. Fetches activity work items from the provider
//! 2. Checks if the orchestration is still running (cancellation support)
//! 3. Spawns an activity manager task for lock renewal and cancellation detection
//! 4. Executes the activity handler

// Worker dispatcher uses Mutex locks - poison indicates a panic and should propagate
#![allow(clippy::expect_used)]
#![allow(clippy::unwrap_used)]
#![allow(clippy::clone_on_ref_ptr)]
//! 5. Handles completion, failure, or cancellation outcomes
//!
//! # Cancellation Flow
//!
//! When an orchestration reaches a terminal state while an activity is running:
//! 1. The activity manager detects the terminal state during lock renewal
//! 2. It signals the activity's cancellation token
//! 3. The worker dispatcher waits up to the grace period for the activity to complete
//! 4. If the activity doesn't complete, it's aborted and the work item is dropped

use crate::providers::{ProviderError, WorkItem, instrumented::instrument_provider_operation};
use std::sync::Arc;
use std::time::Duration;
use tokio::task::JoinHandle;
use tokio_util::sync::CancellationToken;
use tokio_util::task::{AbortOnDropHandle, TaskTracker};
use tracing::{error, warn};

use super::super::{ActivityAdmission, Runtime, registry};

// ============================================================================
// Types
// ============================================================================

/// Tracks distinct active sessions across all worker slots in a single runtime.
///
/// A single `SessionTracker` instance is shared by every `worker_concurrency`
/// slot spawned from the same `Runtime`. It maps session_id → in-flight
/// activity count. The number of keys gives the distinct session count,
/// which is compared against `max_sessions_per_runtime`. When a session's
/// activity count reaches 0 the entry is removed, freeing a session slot.
struct SessionTracker {
    inner: std::sync::Mutex<std::collections::HashMap<String, usize>>,
}

impl SessionTracker {
    fn new() -> Self {
        Self {
            inner: std::sync::Mutex::new(std::collections::HashMap::new()),
        }
    }

    /// Number of distinct sessions currently in flight.
    fn distinct_count(&self) -> usize {
        self.inner.lock().expect("SessionTracker lock poisoned").len()
    }

    /// Increment the in-flight activity count for `session_id`.
    /// Inserts a new entry if this is the first activity for the session.
    fn increment(&self, session_id: &str) {
        let mut map = self.inner.lock().expect("SessionTracker lock poisoned");
        *map.entry(session_id.to_string()).or_insert(0) += 1;
    }

    /// Decrement the count for `session_id`, removing the entry when it reaches 0.
    fn decrement(&self, session_id: &str) {
        let mut map = self.inner.lock().expect("SessionTracker lock poisoned");
        if let std::collections::hash_map::Entry::Occupied(mut entry) = map.entry(session_id.to_string()) {
            let count = entry.get_mut();
            *count -= 1;
            if *count == 0 {
                entry.remove();
            }
        }
    }
}

/// RAII guard that releases a session slot on drop.
///
/// Created via `SessionGuard::new()`. Increments the tracker's count for
/// the session on creation; decrements (and removes at zero) on drop.
struct SessionGuard {
    tracker: Arc<SessionTracker>,
    session_id: String,
}

impl SessionGuard {
    /// Create a guard that increments the tracker for `session_id`.
    fn new(tracker: &Arc<SessionTracker>, session_id: &str) -> Self {
        tracker.increment(session_id);
        Self {
            tracker: Arc::clone(tracker),
            session_id: session_id.to_string(),
        }
    }
}

impl Drop for SessionGuard {
    fn drop(&mut self) {
        self.tracker.decrement(&self.session_id);
    }
}

/// Outcome of activity execution, used for metrics and ack handling.
#[derive(Debug, Clone, Copy)]
enum ActivityOutcome {
    /// Activity completed successfully
    Success,
    /// Activity failed with an application error
    AppError,
    /// Orchestration was cancelled, activity result dropped
    Cancelled,
    /// Admission deferred without executing the handler
    Deferred(Duration),
}

enum ActivityInvocation {
    Completed(String),
    Deferred(Duration),
}

enum ActivityAckError {
    Failed(ProviderError),
    Uncertain(ProviderError),
}

/// Context for processing a single activity work item.
///
/// Groups together all the data needed to execute an activity,
/// reducing parameter count in helper functions.
struct ActivityWorkContext {
    /// The orchestration instance ID
    instance: String,
    /// The execution ID within the instance
    execution_id: u64,
    /// The activity's unique ID within the execution
    activity_id: u64,
    /// The activity handler name
    activity_name: String,
    /// Serialized input for the activity
    input: String,
    /// Lock token for the work item
    lock_token: String,
    /// Number of times this message has been fetched
    attempt_count: u32,
    /// Serialized work item (for poison message reporting)
    item_serialized: String,
    /// Worker ID for logging
    worker_id: String,
    /// Optional session ID for worker affinity routing
    session_id: Option<String>,
    /// Optional activity tag for worker specialization
    tag: Option<String>,
}

// ============================================================================
// Runtime Implementation
// ============================================================================

impl Runtime {
    /// Start the worker dispatcher with N concurrent workers for executing activities.
    ///
    /// Each worker runs in a loop, fetching and processing activity work items.
    /// Workers share the same activity registry and cancellation token.
    ///
    /// Returns one handle per spawned task (workers plus the session manager). The caller
    /// must track them all: there is no supervisor task, because aborting a supervisor
    /// would only detach its children.
    pub(in crate::runtime) fn start_work_dispatcher(
        self: Arc<Self>,
        activities: Arc<registry::ActivityRegistry>,
    ) -> Vec<JoinHandle<()>> {
        let concurrency = self.options.worker_concurrency;
        let cancel = self.cancel.clone();

        let mut worker_handles = Vec::with_capacity(concurrency + 1);
        let mut session_owner_ids: Vec<String> = Vec::new();

        // Tracks distinct active sessions across all worker slots in this
        // runtime. When distinct_count() reaches max_sessions_per_runtime,
        // ALL slots stop claiming new sessions by switching to non-session mode.
        let session_tracker = Arc::new(SessionTracker::new());

        // Derive per-slot identities:
        //   worker_id      – unique per slot, used for logging/tracing
        //   session_owner  – identity used for session lock claims
        //
        // With a stable worker_node_id all slots share the same session
        // owner so any idle slot can serve any owned session.
        // Without one, each slot gets an ephemeral identity.
        let stable_node_id = self.options.worker_node_id.clone();

        for worker_idx in 0..concurrency {
            let rt = Arc::clone(&self);
            let activities = Arc::clone(&activities);
            let cancel = cancel.clone();
            let session_tracker_clone = Arc::clone(&session_tracker);

            let suffix = stable_node_id.as_deref().unwrap_or(&self.runtime_id);
            let worker_id = format!("work-{worker_idx}-{suffix}");
            let session_owner = stable_node_id.clone().unwrap_or_else(|| worker_id.clone());

            // Collect unique session owner IDs for the session manager
            if !session_owner_ids.contains(&session_owner) {
                session_owner_ids.push(session_owner.clone());
            }

            let handle = self.task_tracker.spawn(async move {
                let mut consecutive_retryable_errors: u32 = 0;

                loop {
                    if cancel.is_cancelled() {
                        break;
                    }

                    let min_interval = rt.options.dispatcher_min_poll_interval;
                    let start_time = std::time::Instant::now();

                    let work_found = match process_next_work_item(
                        &rt,
                        &activities,
                        &cancel,
                        &worker_id,
                        &session_owner,
                        &session_tracker_clone,
                    )
                    .await
                    {
                        Ok(found) => {
                            consecutive_retryable_errors = 0;
                            found
                        }
                        Err(e) => {
                            let backoff = if e.is_retryable() {
                                // Exponential backoff for retryable errors (database locks, etc.)
                                consecutive_retryable_errors += 1;
                                let backoff_ms = (100 * 2_u64.pow(consecutive_retryable_errors)).min(3000);
                                warn!(
                                    "Error fetching work item (retryable, attempt {}): {:?}, backing off {}ms",
                                    consecutive_retryable_errors, e, backoff_ms
                                );
                                Duration::from_millis(backoff_ms)
                            } else {
                                // Permanent errors - log and continue with normal polling
                                warn!("Error fetching work item (permanent): {:?}", e);
                                consecutive_retryable_errors = 0;
                                Duration::from_millis(100)
                            };

                            tokio::select! {
                                biased;
                                _ = cancel.cancelled() => break,
                                _ = tokio::time::sleep(backoff) => {}
                            }
                            continue;
                        }
                    };

                    // Enforce minimum polling interval to prevent hot loops
                    if !work_found && !enforce_min_poll_interval(start_time, min_interval, &cancel).await {
                        break;
                    }
                }
            });
            worker_handles.push(handle);
        }

        // Spawn a single session manager background task for heartbeat + cleanup
        let session_rt = Arc::clone(&self);
        let session_cancel = cancel.clone();
        let session_handle = self.task_tracker.spawn(async move {
            run_session_manager(session_rt, session_cancel, session_owner_ids).await;
        });
        worker_handles.push(session_handle);

        worker_handles
    }
}

/// Process the next available work item from the queue.
///
/// Returns:
/// - `Ok(true)` if work was found and processed
/// - `Ok(false)` if no work was available
/// - `Err(e)` if fetch failed (caller handles backoff)
async fn process_next_work_item(
    rt: &Arc<Runtime>,
    activities: &Arc<registry::ActivityRegistry>,
    cancel: &CancellationToken,
    worker_id: &str,
    session_worker_id: &str,
    session_tracker: &Arc<SessionTracker>,
) -> Result<bool, crate::providers::ProviderError> {
    // Check session capacity: if at limit, only fetch non-session items
    let at_session_capacity = session_tracker.distinct_count() >= rt.options.max_sessions_per_runtime;

    let session_config = if at_session_capacity {
        None
    } else {
        Some(crate::providers::SessionFetchConfig {
            owner_id: session_worker_id.to_string(),
            lock_timeout: rt.options.session_lock_timeout,
        })
    };

    // Only the fetch is raced against cancellation. Once an item is locked, the
    // activity runs to completion so it can be acked.
    let fetch = rt.history_store.fetch_work_item(
        rt.options.worker_lock_timeout,
        rt.options.dispatcher_long_poll_timeout,
        session_config.as_ref(),
        &rt.options.worker_tag_filter,
    );

    let fetched = tokio::select! {
        biased;
        _ = cancel.cancelled() => return Ok(false),
        result = fetch => result?,
    };

    let (item, token, attempt_count) = match fetched {
        Some(result) => result,
        None => return Ok(false),
    };

    let item_serialized = serde_json::to_string(&item).unwrap_or_default();

    match item {
        WorkItem::ActivityExecute {
            instance,
            execution_id,
            id,
            name,
            input,
            session_id,
            tag,
        } => {
            // If this is a session-bound item, acquire a session slot via a guard.
            // The guard releases the slot on drop (when activity processing completes).
            // Multiple activities on the same session share one slot.
            let _session_guard = if let Some(ref sid) = session_id {
                let guard = SessionGuard::new(session_tracker, sid);
                // Re-check capacity after acquiring. The pre-fetch check is a hint
                // to avoid unnecessary fetches, but two workers can race past it.
                // If we're now over capacity (another worker won the race for a
                // different session), abandon this item so it retries later.
                if session_tracker.distinct_count() > rt.options.max_sessions_per_runtime {
                    drop(guard);
                    tracing::debug!(
                        target: "duroxide::runtime",
                        session_id = %sid,
                        worker_id = %worker_id,
                        "Session capacity exceeded after fetch (race), abandoning work item"
                    );
                    let _ = rt
                        .history_store
                        .abandon_work_item(&token, Some(Duration::from_millis(100)), true)
                        .await;
                    return Ok(true);
                }
                Some(guard)
            } else {
                None
            };

            let ctx = ActivityWorkContext {
                instance,
                execution_id,
                activity_id: id,
                activity_name: name,
                input,
                lock_token: token,
                attempt_count,
                item_serialized,
                worker_id: worker_id.to_string(),
                session_id,
                tag,
            };

            // Cancellation is detected during lock renewal (lock stealing).
            if ctx.attempt_count > rt.options.max_attempts {
                // Handle poison messages
                handle_poison_message(rt, &ctx).await;
            } else {
                // Execute activity with cancellation support
                execute_activity(rt, activities, ctx).await;
            }
        }
        other => {
            error!(?other, "unexpected WorkItem in Worker dispatcher; state corruption");
            panic!("unexpected WorkItem in Worker dispatcher");
        }
    }

    Ok(true)
}

/// Enforce minimum polling interval to prevent hot loops.
///
/// Returns `false` if cancellation was signalled while waiting, meaning the caller
/// should stop polling.
async fn enforce_min_poll_interval(
    start_time: std::time::Instant,
    min_interval: Duration,
    cancel: &CancellationToken,
) -> bool {
    let elapsed = start_time.elapsed();
    if elapsed < min_interval {
        tokio::select! {
            biased;
            _ = cancel.cancelled() => return false,
            _ = tokio::time::sleep(min_interval - elapsed) => {}
        }
    } else {
        tokio::task::yield_now().await;
    }
    true
}

// ============================================================================
// Activity Processing
// ============================================================================

/// Handle a poison message (activity fetched too many times).
async fn handle_poison_message(rt: &Arc<Runtime>, ctx: &ActivityWorkContext) {
    warn!(
        instance = %ctx.instance,
        activity_name = %ctx.activity_name,
        activity_id = ctx.activity_id,
        attempt_count = ctx.attempt_count,
        max_attempts = rt.options.max_attempts,
        "Activity message exceeded max attempts, marking as poison"
    );

    let error = crate::ErrorDetails::Poison {
        attempt_count: ctx.attempt_count,
        max_attempts: rt.options.max_attempts,
        message_type: crate::PoisonMessageType::Activity {
            instance: ctx.instance.clone(),
            execution_id: ctx.execution_id,
            activity_name: ctx.activity_name.clone(),
            activity_id: ctx.activity_id,
        },
        message: ctx.item_serialized.clone(),
    };

    let _ = rt
        .history_store
        .ack_work_item(
            &ctx.lock_token,
            Some(WorkItem::ActivityFailed {
                instance: ctx.instance.clone(),
                execution_id: ctx.execution_id,
                id: ctx.activity_id,
                details: error,
            }),
        )
        .await;

    rt.record_activity_poison();
}

// ============================================================================
// Activity Execution
// ============================================================================

/// Execute an activity with full cancellation support.
async fn execute_activity(rt: &Arc<Runtime>, activities: &Arc<registry::ActivityRegistry>, ctx: ActivityWorkContext) {
    // Distinct from the runtime shutdown signal: cancelling this token means
    // "the orchestration is terminal, discard the result", which is not what a
    // runtime shutdown implies.
    let cancellation_token = CancellationToken::new();

    let manager_handle = spawn_activity_manager(
        &rt.task_tracker,
        Arc::clone(&rt.history_store),
        ctx.lock_token.clone(),
        rt.options.worker_lock_timeout,
        rt.options.worker_lock_renewal_buffer,
        rt.options.activity_cancellation_grace_period,
        cancellation_token.clone(),
    );

    let activity_ctx = match build_activity_context(rt, &ctx, cancellation_token.clone()).await {
        Ok(activity_ctx) => activity_ctx,
        Err(error) => {
            warn!(
                instance = %ctx.instance,
                execution_id = ctx.execution_id,
                activity_id = ctx.activity_id,
                worker_id = %ctx.worker_id,
                %error,
                "worker: activity metadata read failed, abandoning work item"
            );
            abandon_after_activity_failure(rt, &ctx, Duration::from_millis(100), false).await;
            return;
        }
    };

    let start_time = std::time::Instant::now();

    let (ack_result, outcome) = match activities.resolve_handler(&ctx.activity_name) {
        Some((_version, handler)) => {
            run_activity_with_cancellation(
                rt,
                &ctx,
                handler,
                activity_ctx,
                cancellation_token,
                manager_handle,
                start_time,
            )
            .await
        }
        None => {
            abandon_unregistered_activity(rt, &ctx).await;
            // Early return after abandonment - no ack_result needed since we abandoned
            return;
        }
    };

    handle_activity_outcome(rt, &ctx, ack_result, outcome).await;
}

/// Build the ActivityContext with orchestration metadata.
async fn build_activity_context(
    rt: &Arc<Runtime>,
    ctx: &ActivityWorkContext,
    cancellation_token: CancellationToken,
) -> Result<crate::ActivityContext, crate::providers::ProviderError> {
    let metadata = if let Some(admin) = rt.history_store.as_management_capability() {
        match instrument_provider_operation(
            rt.metrics_provider(),
            "get_instance_info",
            admin.get_instance_info(&ctx.instance),
        )
        .await
        {
            Ok(info) if info.current_execution_id == ctx.execution_id && info.orchestration_version != "unknown" => {
                Some((info.orchestration_name, info.orchestration_version))
            }
            Ok(_) => None,
            Err(error) => {
                warn!(
                    instance = %ctx.instance,
                    execution_id = ctx.execution_id,
                    %error,
                    "Failed to read activity metadata; falling back to execution history"
                );
                None
            }
        }
    } else {
        None
    };
    let (orch_name, orch_version) = match metadata {
        Some(metadata) => metadata,
        None => {
            let history = rt
                .history_store
                .read_with_execution(&ctx.instance, ctx.execution_id)
                .await?;
            history
                .iter()
                .find_map(|event| match &event.kind {
                    crate::EventKind::OrchestrationStarted { name, version, .. } => {
                        Some((name.clone(), version.clone()))
                    }
                    _ => None,
                })
                .unwrap_or_else(|| {
                    warn!(
                        instance = %ctx.instance,
                        execution_id = ctx.execution_id,
                        "Orchestration metadata missing for activity"
                    );
                    ("unknown".to_string(), "unknown".to_string())
                })
        }
    };

    Ok(crate::ActivityContext::new_with_cancellation(
        ctx.instance.clone(),
        ctx.execution_id,
        orch_name,
        orch_version,
        ctx.activity_name.clone(),
        ctx.activity_id,
        ctx.worker_id.clone(),
        ctx.session_id.clone(),
        ctx.tag.clone(),
        cancellation_token,
        Arc::clone(&rt.history_store),
    ))
}

/// Run an activity with cancellation support using `tokio::select!`.
async fn run_activity_with_cancellation(
    rt: &Arc<Runtime>,
    ctx: &ActivityWorkContext,
    handler: Arc<dyn crate::runtime::ActivityHandler>,
    activity_ctx: crate::ActivityContext,
    cancellation_token: CancellationToken,
    _manager_handle: AbortOnDropHandle<()>,
    start_time: std::time::Instant,
) -> (Result<(), ActivityAckError>, ActivityOutcome) {
    let input = ctx.input.clone();
    let activity_id = ctx.activity_id;
    // Abort-on-drop so the invocation cannot outlive this task if the worker is
    // aborted mid-activity during shutdown.
    let mut activity_handle = AbortOnDropHandle::new(rt.task_tracker.spawn(async move {
        let _admission_guard = match handler.try_admit(&activity_ctx, &input)? {
            ActivityAdmission::Admit(guard) => guard,
            ActivityAdmission::Defer(delay) if delay.is_zero() => {
                return Err("Activity admission deferral requires a positive retry delay".to_string());
            }
            ActivityAdmission::Defer(delay) => {
                return Ok(ActivityInvocation::Deferred(
                    delay.clamp(Duration::from_millis(1), ActivityAdmission::MAX_DEFER_DELAY),
                ));
            }
        };
        tracing::debug!(
            target: "duroxide::runtime",
            instance_id = %activity_ctx.instance_id(),
            execution_id = activity_ctx.execution_id(),
            activity_name = %activity_ctx.activity_name(),
            activity_id,
            worker_id = %activity_ctx.worker_id(),
            activity_tag = ?activity_ctx.tag(),
            "Activity started"
        );
        handler
            .invoke(activity_ctx, input)
            .await
            .map(ActivityInvocation::Completed)
    }));

    tokio::select! {
        joined = &mut activity_handle => {
            // Keep the renewal guard until acknowledgement finishes, not just invocation.
            // Handle normal activity completion (success, error, or panic)
            match joined {
                Ok(Ok(ActivityInvocation::Completed(result))) => {
                    handle_activity_success(rt, ctx, result, start_time).await
                }
                Ok(Ok(ActivityInvocation::Deferred(delay))) => {
                    tracing::debug!(
                        instance = %ctx.instance,
                        activity_name = %ctx.activity_name,
                        activity_id = ctx.activity_id,
                        retry_after_ms = delay.as_millis(),
                        "Activity admission deferred"
                    );
                    let result = rt.history_store
                        .abandon_work_item(&ctx.lock_token, Some(delay), true)
                        .await;
                    (result.map_err(ActivityAckError::Failed), ActivityOutcome::Deferred(delay))
                }
                Ok(Err(error)) => handle_activity_error(rt, ctx, error, start_time).await,
                Err(join_error) => handle_activity_error(rt, ctx, join_error.to_string(), start_time).await,
            }
        }
        _ = cancellation_token.cancelled() => {
            // Handle cancellation: wait grace period, then drop result
            let grace = rt.options.activity_cancellation_grace_period;

            tracing::info!(
                target: "duroxide::runtime",
                instance = %ctx.instance,
                execution_id = %ctx.execution_id,
                activity_name = %ctx.activity_name,
                activity_id = %ctx.activity_id,
                worker_id = %ctx.worker_id,
                activity_tag = ?ctx.tag,
                grace_ms = %grace.as_millis(),
                "Orchestration terminated, waiting for activity grace period"
            );

            // Wait for activity to finish within grace period, or abort it
            let finished_in_time = tokio::time::timeout(grace, &mut activity_handle).await.is_ok();
            if !finished_in_time {
                tracing::debug!(
                    target: "duroxide::runtime",
                    instance_id = %ctx.instance,
                    activity_name = %ctx.activity_name,
                    activity_id = %ctx.activity_id,
                    "Activity did not finish within grace period; aborting"
                );
                activity_handle.abort();
                let _ = activity_handle.await;
            }

            let duration_seconds = start_time.elapsed().as_secs_f64();
            rt.record_activity_execution(&ctx.activity_name, "cancelled", duration_seconds, 0, ctx.tag.as_deref());

            // Renewal errors can falsely signal cancellation; retrying ack(None) could delete live work.
            let result = rt.history_store.ack_work_item(&ctx.lock_token, None).await;
            if let Err(e) = &result {
                tracing::warn!(
                    target: "duroxide::runtime",
                    instance = %ctx.instance,
                    activity_id = %ctx.activity_id,
                    error = %e,
                    "Failed to ack cancelled activity work item"
                );
            }
            (result.map_err(ActivityAckError::Failed), ActivityOutcome::Cancelled)
        }
    }
}

// ============================================================================
// Activity Completion Handlers
// ============================================================================

/// Maximum number of attempts when acking an activity completion.
const MAX_ACK_ATTEMPTS: u32 = 5;

/// Ack an activity completion, retrying transient provider failures with exponential backoff.
///
/// Activities have at-least-once semantics, so an ack failure is not a correctness
/// violation — but it is expensive: the caller abandons the work item, the activity is
/// redelivered, and the handler runs again. Retryable provider errors (database lock
/// contention, transient connection failures) usually clear within milliseconds, so
/// retrying here avoids most redundant re-executions. Unlike fetch retries, these
/// retries are bounded and retain the activity's lock renewal.
async fn ack_activity_completion_with_retry(
    rt: &Arc<Runtime>,
    ctx: &ActivityWorkContext,
    completion: WorkItem,
) -> Result<(), ActivityAckError> {
    let mut attempt = 1;
    loop {
        match rt
            .history_store
            .ack_work_item(&ctx.lock_token, Some(completion.clone()))
            .await
        {
            Ok(()) => return Ok(()),
            Err(e) if e.is_retryable() && attempt < MAX_ACK_ATTEMPTS => {
                let backoff_ms = 50 * 2_u64.pow(attempt);
                warn!(
                    instance = %ctx.instance,
                    execution_id = ctx.execution_id,
                    activity_id = ctx.activity_id,
                    worker_id = %ctx.worker_id,
                    attempt = attempt,
                    max_attempts = MAX_ACK_ATTEMPTS,
                    error = %e,
                    "worker: ack failed (retryable), backing off {}ms",
                    backoff_ms
                );
                tokio::time::sleep(Duration::from_millis(backoff_ms)).await;
                attempt += 1;
            }
            // A missing token after a transient error can mean the earlier ack committed.
            // ProviderError cannot distinguish that from lock loss or other permanent errors.
            Err(e) if !e.is_retryable() && attempt > 1 => return Err(ActivityAckError::Uncertain(e)),
            Err(e) => return Err(ActivityAckError::Failed(e)),
        }
    }
}

/// Handle successful activity completion.
async fn handle_activity_success(
    rt: &Arc<Runtime>,
    ctx: &ActivityWorkContext,
    result: String,
    start_time: std::time::Instant,
) -> (Result<(), ActivityAckError>, ActivityOutcome) {
    let duration_ms = start_time.elapsed().as_millis() as u64;
    let duration_seconds = duration_ms as f64 / 1000.0;

    tracing::debug!(
        target: "duroxide::runtime",
        instance_id = %ctx.instance,
        execution_id = %ctx.execution_id,
        activity_name = %ctx.activity_name,
        activity_id = %ctx.activity_id,
        worker_id = %ctx.worker_id,
        activity_tag = ?ctx.tag,
        outcome = "success",
        duration_ms = %duration_ms,
        result_size = %result.len(),
        "Activity completed"
    );

    rt.record_activity_execution(&ctx.activity_name, "success", duration_seconds, 0, ctx.tag.as_deref());

    let ack_result = ack_activity_completion_with_retry(
        rt,
        ctx,
        WorkItem::ActivityCompleted {
            instance: ctx.instance.clone(),
            execution_id: ctx.execution_id,
            id: ctx.activity_id,
            result,
        },
    )
    .await;

    (ack_result, ActivityOutcome::Success)
}

/// Handle activity application error.
async fn handle_activity_error(
    rt: &Arc<Runtime>,
    ctx: &ActivityWorkContext,
    error: String,
    start_time: std::time::Instant,
) -> (Result<(), ActivityAckError>, ActivityOutcome) {
    let duration_ms = start_time.elapsed().as_millis() as u64;
    let duration_seconds = duration_ms as f64 / 1000.0;

    tracing::warn!(
        target: "duroxide::runtime",
        instance_id = %ctx.instance,
        execution_id = %ctx.execution_id,
        activity_name = %ctx.activity_name,
        activity_id = %ctx.activity_id,
        worker_id = %ctx.worker_id,
        activity_tag = ?ctx.tag,
        outcome = "app_error",
        duration_ms = %duration_ms,
        error = %error,
        "Activity failed (application error)"
    );

    rt.record_activity_execution(&ctx.activity_name, "app_error", duration_seconds, 0, ctx.tag.as_deref());

    let ack_result = ack_activity_completion_with_retry(
        rt,
        ctx,
        WorkItem::ActivityFailed {
            instance: ctx.instance.clone(),
            execution_id: ctx.execution_id,
            id: ctx.activity_id,
            details: crate::ErrorDetails::Application {
                kind: crate::AppErrorKind::ActivityFailed,
                message: error,
                retryable: false,
            },
        },
    )
    .await;

    (ack_result, ActivityOutcome::AppError)
}

/// Abandon unregistered activity with exponential backoff for rolling deployment support.
///
/// The poison message handling will eventually fail the activity if genuinely missing.
async fn abandon_unregistered_activity(rt: &Arc<Runtime>, ctx: &ActivityWorkContext) {
    let backoff = rt.options.unregistered_backoff.delay(ctx.attempt_count);
    let remaining_attempts = rt.options.attempts_until_poison(ctx.attempt_count);

    tracing::warn!(
        target: "duroxide::runtime",
        instance = %ctx.instance,
        execution_id = %ctx.execution_id,
        activity_name = %ctx.activity_name,
        activity_id = %ctx.activity_id,
        worker_id = %ctx.worker_id,
        activity_tag = ?ctx.tag,
        attempt_count = %ctx.attempt_count,
        max_attempts = %rt.options.max_attempts,
        remaining_attempts = %remaining_attempts,
        backoff_secs = %backoff.as_secs_f32(),
        "Activity not registered, abandoning with {:.1}s backoff (will poison in {} more attempts)",
        backoff.as_secs_f32(),
        remaining_attempts
    );

    // Abandon with delay - poison handling will eventually terminate if genuinely missing
    let _ = rt
        .history_store
        .abandon_work_item(&ctx.lock_token, Some(backoff), false)
        .await;
}

// ============================================================================
// Outcome Handling
// ============================================================================

/// Handle the final outcome of activity execution.
async fn handle_activity_outcome(
    rt: &Arc<Runtime>,
    ctx: &ActivityWorkContext,
    ack_result: Result<(), ActivityAckError>,
    outcome: ActivityOutcome,
) {
    match ack_result {
        Ok(()) => match outcome {
            ActivityOutcome::Success => rt.record_activity_success(),
            ActivityOutcome::AppError => rt.record_activity_app_error(),
            ActivityOutcome::Deferred(_) => {
                rt.record_activity_admission_deferral(&ctx.activity_name, ctx.tag.as_deref())
            }
            ActivityOutcome::Cancelled => {}
        },
        Err(ActivityAckError::Uncertain(e)) => {
            warn!(
                instance = %ctx.instance,
                execution_id = ctx.execution_id,
                activity_id = ctx.activity_id,
                worker_id = %ctx.worker_id,
                ack_outcome = "uncertain",
                error = %e,
                "worker: acknowledgement outcome uncertain after retry; an earlier attempt may have committed or the lock may have been lost"
            );
            rt.record_activity_ack_uncertain();
        }
        Err(ActivityAckError::Failed(e)) => {
            warn!(
                instance = %ctx.instance,
                execution_id = ctx.execution_id,
                activity_id = ctx.activity_id,
                worker_id = %ctx.worker_id,
                error = %e,
                outcome = ?outcome,
                "worker: activity acknowledgment or deferral failed, abandoning work item"
            );
            let (delay, ignore_attempt) = match outcome {
                ActivityOutcome::Deferred(delay) => (delay, true),
                _ => (Duration::from_millis(100), false),
            };
            if abandon_after_activity_failure(rt, ctx, delay, ignore_attempt).await
                && matches!(outcome, ActivityOutcome::Deferred(_))
            {
                rt.record_activity_admission_deferral(&ctx.activity_name, ctx.tag.as_deref());
            }
        }
    }
}

async fn abandon_after_activity_failure(
    rt: &Arc<Runtime>,
    ctx: &ActivityWorkContext,
    delay: Duration,
    ignore_attempt: bool,
) -> bool {
    let result = rt
        .history_store
        .abandon_work_item(&ctx.lock_token, Some(delay), ignore_attempt)
        .await;
    if let Err(error) = &result {
        warn!(
            instance = %ctx.instance,
            activity_id = ctx.activity_id,
            %error,
            "Failed to abandon activity work item; waiting for lock expiry"
        );
    }
    rt.record_activity_infra_error();
    result.is_ok()
}

// ============================================================================
// Activity Manager (Lock Renewal + Cancellation Detection)
// ============================================================================

/// Calculate the renewal interval based on lock timeout and buffer settings.
///
/// - If timeout >= 15s: renew at `(timeout - buffer)`, minimum 1s
/// - If timeout < 15s: renew at `0.5 * timeout`, minimum 1s
fn calculate_renewal_interval(lock_timeout: Duration, buffer: Duration) -> Duration {
    if lock_timeout >= Duration::from_secs(15) {
        let buffer = buffer.min(lock_timeout);
        lock_timeout
            .checked_sub(buffer)
            .unwrap_or(Duration::from_secs(1))
            .max(Duration::from_secs(1))
    } else {
        let half = (lock_timeout.as_secs_f64() * 0.5).ceil().max(1.0);
        Duration::from_secs_f64(half)
    }
}

/// Spawn a background task to manage an in-flight activity.
///
/// Handles: lock renewal, cancellation detection, and cancellation signaling.
fn spawn_activity_manager(
    task_tracker: &TaskTracker,
    store: Arc<dyn crate::providers::Provider>,
    token: String,
    lock_timeout: Duration,
    buffer: Duration,
    grace_period: Duration,
    cancellation_token: CancellationToken,
) -> AbortOnDropHandle<()> {
    let renewal_interval = calculate_renewal_interval(lock_timeout, buffer);

    tracing::debug!(
        target: "duroxide::runtime::worker",
        lock_token = %token,
        lock_timeout_secs = %lock_timeout.as_secs(),
        renewal_interval_secs = %renewal_interval.as_secs(),
        grace_period_secs = %grace_period.as_secs(),
        "Spawning activity manager"
    );

    // Note: grace_period is passed but not used here - the grace period waiting
    // is handled by handle_activity_cancellation() after this task signals cancellation.
    // This task's only jobs are: (1) renew locks, (2) detect terminal state and signal.
    let _ = grace_period;

    // Deliberately does not observe the runtime shutdown signal: the activity it is
    // renewing may still be running, and releasing the lock early would let another
    // node steal the work item and execute it twice. The owning worker stops this
    // task instead (this handle aborts on drop).
    AbortOnDropHandle::new(task_tracker.spawn(async move {
        let mut interval = tokio::time::interval(renewal_interval);
        interval.tick().await; // Skip first immediate tick

        loop {
            interval.tick().await;

            match store.renew_work_item_lock(&token, lock_timeout).await {
                Ok(()) => {
                    // Lock renewed successfully - orchestration is still running
                    tracing::trace!(
                        target: "duroxide::runtime::worker",
                        lock_token = %token,
                        extend_secs = %lock_timeout.as_secs(),
                        "Work item lock renewed"
                    );
                }
                Err(e) => {
                    // Lock renewal failed - activity was cancelled (lock stolen) or lock expired
                    tracing::info!(
                        target: "duroxide::runtime::worker",
                        lock_token = %token,
                        error = %e,
                        "Lock renewal failed, signaling activity cancellation (lock was stolen or expired)"
                    );
                    cancellation_token.cancel();
                    break;
                }
            }
        }

        tracing::debug!(
            target: "duroxide::runtime::worker",
            lock_token = %token,
            "Activity manager stopped"
        );
    }))
}

// ============================================================================
// Session Manager (Lock Renewal + Cleanup)
// ============================================================================

/// Background task that periodically:
/// 1. Renews session locks for all non-idle sessions owned by this runtime's workers
/// 2. Cleans up orphaned session rows (expired locks, no pending work items)
async fn run_session_manager(rt: Arc<Runtime>, cancel: CancellationToken, worker_ids: Vec<String>) {
    let renewal_interval =
        calculate_renewal_interval(rt.options.session_lock_timeout, rt.options.session_lock_renewal_buffer);
    let cleanup_interval = rt.options.session_cleanup_interval;

    let mut renewal_ticker = tokio::time::interval(renewal_interval);
    renewal_ticker.tick().await; // Skip immediate first tick

    let mut cleanup_ticker = tokio::time::interval(cleanup_interval);
    cleanup_ticker.tick().await; // Skip immediate first tick

    // Pre-compute the &str slice for the batched provider call
    let owner_refs: Vec<&str> = worker_ids.iter().map(|s| s.as_str()).collect();

    tracing::debug!(
        target: "duroxide::runtime::worker",
        renewal_interval_secs = %renewal_interval.as_secs(),
        cleanup_interval_secs = %cleanup_interval.as_secs(),
        worker_count = %worker_ids.len(),
        "Session manager started"
    );

    loop {
        tokio::select! {
            biased;
            // Cancellation is observed directly rather than via a polling ticker, so
            // shutdown is prompt even when renewal/cleanup intervals are minutes long.
            _ = cancel.cancelled() => break,
            _ = renewal_ticker.tick() => {
                // Single batched call for all worker IDs
                match rt.history_store.renew_session_lock(
                    &owner_refs,
                    rt.options.session_lock_timeout,
                    rt.options.session_idle_timeout,
                ).await {
                    Ok(count) => {
                        if count > 0 {
                            tracing::trace!(
                                target: "duroxide::runtime::worker",
                                sessions_renewed = %count,
                                "Session locks renewed"
                            );
                        }
                    }
                    Err(e) => {
                        tracing::warn!(
                            target: "duroxide::runtime::worker",
                            error = %e,
                            "Session lock renewal failed"
                        );
                    }
                }
            }
            _ = cleanup_ticker.tick() => {
                match rt.history_store.cleanup_orphaned_sessions(
                    rt.options.session_idle_timeout,
                ).await {
                    Ok(count) => {
                        if count > 0 {
                            tracing::debug!(
                                target: "duroxide::runtime::worker",
                                sessions_cleaned = %count,
                                "Orphaned sessions cleaned up"
                            );
                        }
                    }
                    Err(e) => {
                        tracing::warn!(
                            target: "duroxide::runtime::worker",
                            error = %e,
                            "Session cleanup failed"
                        );
                    }
                }
            }
        }
    }

    tracing::debug!(
        target: "duroxide::runtime::worker",
        "Session manager stopped"
    );
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn attempts_until_poison_counts_the_poisoning_fetch() {
        let options = crate::runtime::RuntimeOptions {
            max_attempts: 10,
            ..Default::default()
        };
        assert_eq!(options.attempts_until_poison(1), 10);
        assert_eq!(options.attempts_until_poison(10), 1, "the next fetch poisons");
        let widest = crate::runtime::RuntimeOptions {
            max_attempts: u32::MAX,
            ..Default::default()
        };
        assert_eq!(widest.attempts_until_poison(u32::MAX), 1, "no overflow at the limit");
    }

    #[test]
    fn tracker_starts_empty() {
        let tracker = SessionTracker::new();
        assert_eq!(tracker.distinct_count(), 0);
    }

    #[test]
    fn guard_increments_and_decrements() {
        let tracker = Arc::new(SessionTracker::new());
        {
            let _g = SessionGuard::new(&tracker, "s1");
            assert_eq!(tracker.distinct_count(), 1);
        }
        // Guard dropped — session removed
        assert_eq!(tracker.distinct_count(), 0);
    }

    #[test]
    fn same_session_counts_as_one() {
        let tracker = Arc::new(SessionTracker::new());
        let _g1 = SessionGuard::new(&tracker, "s1");
        let _g2 = SessionGuard::new(&tracker, "s1");
        // Two activities, but same session → 1 distinct
        assert_eq!(tracker.distinct_count(), 1);
    }

    #[test]
    fn different_sessions_counted_separately() {
        let tracker = Arc::new(SessionTracker::new());
        let _g1 = SessionGuard::new(&tracker, "s1");
        let _g2 = SessionGuard::new(&tracker, "s2");
        assert_eq!(tracker.distinct_count(), 2);
    }

    #[test]
    fn drop_one_of_two_same_session_keeps_session() {
        let tracker = Arc::new(SessionTracker::new());
        let _g1 = SessionGuard::new(&tracker, "s1");
        {
            let _g2 = SessionGuard::new(&tracker, "s1");
            assert_eq!(tracker.distinct_count(), 1);
        }
        // g2 dropped, but g1 still alive → session still present
        assert_eq!(tracker.distinct_count(), 1);
    }

    #[test]
    fn drop_all_removes_session() {
        let tracker = Arc::new(SessionTracker::new());
        {
            let _g1 = SessionGuard::new(&tracker, "s1");
            let _g2 = SessionGuard::new(&tracker, "s1");
            let _g3 = SessionGuard::new(&tracker, "s2");
            assert_eq!(tracker.distinct_count(), 2);
        }
        // All dropped
        assert_eq!(tracker.distinct_count(), 0);
    }

    #[test]
    fn mixed_acquire_release_sequence() {
        let tracker = Arc::new(SessionTracker::new());
        let g1 = SessionGuard::new(&tracker, "a");
        let g2 = SessionGuard::new(&tracker, "b");
        let g3 = SessionGuard::new(&tracker, "a");
        assert_eq!(tracker.distinct_count(), 2); // a, b

        drop(g1);
        assert_eq!(tracker.distinct_count(), 2); // a(1), b(1) — a still has g3

        drop(g3);
        assert_eq!(tracker.distinct_count(), 1); // b only

        drop(g2);
        assert_eq!(tracker.distinct_count(), 0);
    }
}