Repository navigation
Expand file tree
/
Copy pathasync_task.rs
More file actions
1948 lines (1826 loc) · 74.1 KB
/
Copy pathasync_task.rs
File metadata and controls
1948 lines (1826 loc) · 74.1 KB
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
// APCore Protocol — Async task manager for background module execution
// Spec reference: docs/features/async-tasks.md
// Issue #34: Pluggable TaskStore, retry with exponential backoff, Reaper TTL cleanup.
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use async_trait::async_trait;
use dashmap::DashMap;
use parking_lot::Mutex;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use tokio::sync::{watch, OwnedSemaphorePermit, Semaphore};
use tokio::task::JoinHandle;
use tracing::{debug, error, warn};
use uuid::Uuid;
use crate::cancel::CancelToken;
use crate::context::Context;
use crate::errors::{ErrorCode, ModuleError};
use crate::executor::Executor;
/// Status of an async task.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum TaskStatus {
#[default]
Pending,
Running,
Completed,
Failed,
Cancelled,
}
impl TaskStatus {
fn is_terminal(self) -> bool {
matches!(self, Self::Completed | Self::Failed | Self::Cancelled)
}
fn is_active(self) -> bool {
matches!(self, Self::Pending | Self::Running)
}
}
/// Metadata and result tracking for a submitted async task.
///
/// Marked `#[non_exhaustive]` (issue #24) so a future spec revision can add a
/// field without a major version bump. That works by **removing struct-literal
/// construction from every crate but this one** — `..Default::default()`
/// included, since it is itself a struct expression (`error[E0639]`). From a
/// downstream crate, start from `Default::default()` and assign the fields you
/// need; there is no builder for this type. See
/// `api-surface-conventions.md` §9.1. `task_id` and `module_id`
/// default to empty strings and SHOULD be set explicitly.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[non_exhaustive]
pub struct TaskInfo {
pub task_id: String,
pub module_id: String,
pub status: TaskStatus,
pub submitted_at: f64,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub started_at: Option<f64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub completed_at: Option<f64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub result: Option<serde_json::Value>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub error: Option<String>,
#[serde(default)]
pub retry_count: u32,
#[serde(default)]
pub max_retries: u32,
}
/// Returns the current time as seconds since the UNIX epoch.
fn now_secs() -> f64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs_f64()
}
// ---------------------------------------------------------------------------
// TaskStore
// ---------------------------------------------------------------------------
/// Pluggable backing store for [`TaskInfo`] records.
///
/// Implementations decouple task state from in-process memory and enable
/// distributed deployments. The default backend is [`InMemoryTaskStore`].
///
/// Concrete implementations include `RedisTaskStore` and `SqlTaskStore`
/// (provided as optional add-ons in downstream crates).
#[async_trait]
pub trait TaskStore: Send + Sync {
/// Persist a task record (create or overwrite).
async fn save(&self, task: &TaskInfo) -> Result<(), ModuleError>;
/// Look up a task by id; returns `None` if no record exists.
async fn get(&self, id: &str) -> Result<Option<TaskInfo>, ModuleError>;
/// List all tasks, optionally filtered by exact status match.
async fn list(&self, status: Option<TaskStatus>) -> Result<Vec<TaskInfo>, ModuleError>;
/// Remove a task record. No-op if `id` is absent.
async fn delete(&self, id: &str) -> Result<(), ModuleError>;
/// Return all terminal-state tasks whose `completed_at` is strictly less
/// than `before_timestamp` (Unix seconds). Pending and Running tasks MUST
/// NOT be returned by this method.
async fn list_expired(&self, before_timestamp: f64) -> Result<Vec<TaskInfo>, ModuleError>;
/// Whether accessors can safely poll this store inline inside Tokio.
///
/// Opt in only if `get`, `list`, `list_expired`, and `delete` always
/// complete without suspending or using runtime services such as timers.
fn supports_inline_sync(&self) -> bool {
false
}
/// Identifier of the concrete store type, used by tooling to expose the
/// active backend (matches the type name; e.g. `"InMemoryTaskStore"`).
///
/// Defaults to the implementing type's own name, without its module path.
fn store_type_name(&self) -> &'static str {
let full = std::any::type_name::<Self>();
let base = full.split('<').next().unwrap_or(full);
base.rsplit("::").next().unwrap_or(base)
}
}
/// Default in-memory [`TaskStore`] backed by [`DashMap`] for lock-free
/// concurrent access.
///
/// # Insertion order (D-82)
///
/// `list` and `list_expired` return records in **submission order**. `DashMap`
/// has no insertion order of its own, so each record is stamped with a
/// monotonic sequence number on first save and the listings sort on that.
/// Sorting on `task_id` — which this store used to do — is not a substitute:
/// the id is a UUID v4, so it is random with respect to submission, and
/// `list_tasks()[0]` returned the lexicographically smallest UUID rather than
/// the first-submitted task.
#[derive(Default)]
pub struct InMemoryTaskStore {
/// `task_id -> (insertion sequence, record)`.
tasks: DashMap<String, (u64, TaskInfo)>,
/// Monotonic counter stamped onto each record the first time it is saved.
next_seq: std::sync::atomic::AtomicU64,
}
impl InMemoryTaskStore {
pub fn new() -> Self {
Self::default()
}
}
#[async_trait]
impl TaskStore for InMemoryTaskStore {
async fn save(&self, task: &TaskInfo) -> Result<(), ModuleError> {
use dashmap::mapref::entry::Entry;
match self.tasks.entry(task.task_id.clone()) {
// An overwrite keeps the record's original position: a status
// transition is not a re-submission.
Entry::Occupied(mut occupied) => {
occupied.get_mut().1 = task.clone();
}
Entry::Vacant(vacant) => {
let seq = self
.next_seq
.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
vacant.insert((seq, task.clone()));
}
}
Ok(())
}
async fn get(&self, id: &str) -> Result<Option<TaskInfo>, ModuleError> {
Ok(self.tasks.get(id).map(|entry| entry.value().1.clone()))
}
async fn list(&self, status: Option<TaskStatus>) -> Result<Vec<TaskInfo>, ModuleError> {
let mut out: Vec<(u64, TaskInfo)> = self
.tasks
.iter()
.filter(|entry| match status {
Some(s) => entry.value().1.status == s,
None => true,
})
.map(|entry| entry.value().clone())
.collect();
// D-82: insertion (submission) order is normative.
out.sort_by_key(|(seq, _)| *seq);
Ok(out.into_iter().map(|(_, info)| info).collect())
}
async fn delete(&self, id: &str) -> Result<(), ModuleError> {
self.tasks.remove(id);
Ok(())
}
async fn list_expired(&self, before_timestamp: f64) -> Result<Vec<TaskInfo>, ModuleError> {
let mut out: Vec<(u64, TaskInfo)> = self
.tasks
.iter()
.filter(|entry| {
let info = &entry.value().1;
if !info.status.is_terminal() {
return false;
}
match info.completed_at {
Some(ts) => ts < before_timestamp,
None => false,
}
})
.map(|entry| entry.value().clone())
.collect();
out.sort_by_key(|(seq, _)| *seq);
Ok(out.into_iter().map(|(_, info)| info).collect())
}
fn store_type_name(&self) -> &'static str {
"InMemoryTaskStore"
}
fn supports_inline_sync(&self) -> bool {
true
}
}
// ---------------------------------------------------------------------------
// RetryConfig
// ---------------------------------------------------------------------------
/// Retry policy applied per task on failure.
///
/// Marked `#[non_exhaustive]` (issue #24) so a future spec revision can add a
/// field without a major version bump. That works by **removing struct-literal
/// construction from every crate but this one** — `..Default::default()`
/// included, since it is itself a struct expression (`error[E0639]`). From a
/// downstream crate, start from `Default::default()` and assign the fields you
/// need; there is no builder for this type. See
/// `api-surface-conventions.md` §9.1.
#[derive(Debug, Clone, Copy)]
#[non_exhaustive]
pub struct RetryConfig {
/// Maximum number of retry attempts after the initial execution. `0` disables retry.
pub max_retries: u32,
/// Base delay between retries in milliseconds.
pub retry_delay_ms: u64,
/// Multiplicative factor applied at each attempt (`1.0` = constant, `2.0` = exponential doubling).
pub backoff_multiplier: f64,
/// Upper bound on the computed retry delay, in milliseconds.
pub max_retry_delay_ms: u64,
}
impl Default for RetryConfig {
/// Spec-aligned default (D-14): `max_retries = 0` matches both
/// `apcore-python` and `apcore-typescript`. Retries are explicitly opt-in;
/// this prevents the SDK from silently re-running failed tasks behind the
/// caller's back. The 1s base delay / 2.0× backoff / 60s ceiling stay
/// useful when callers DO opt into retries, so they're preserved.
fn default() -> Self {
Self {
max_retries: 0,
retry_delay_ms: 1000,
backoff_multiplier: 2.0,
max_retry_delay_ms: 60_000,
}
}
}
impl RetryConfig {
/// Compute the retry delay for the given attempt index (`0`-based).
///
/// Formula: `min(retry_delay_ms * (backoff_multiplier ^ attempt), max_retry_delay_ms)`.
///
/// Returns whole milliseconds: the fractional part is truncated, where
/// apcore-python and apcore-typescript return a float (D-61). The two
/// differ by under 1 ms, and only for a non-integer product.
///
/// Cross-language: this is the canonical name across `apcore-python` and
/// `apcore-typescript` (sync alignment D-08).
#[must_use]
pub fn compute_delay_ms(&self, attempt: u32) -> u64 {
// Use f64 arithmetic to apply the backoff factor, then clamp to the cap.
// The `as f64` casts are intentional: retry delays are bounded small
// integers in practice (sub-second to minutes), so precision loss is a
// non-issue.
#[allow(clippy::cast_precision_loss)]
let base = self.retry_delay_ms as f64;
// `powf` accepts an f64 exponent and avoids the i32 cast lint while
// producing the same result for non-negative integer attempt values.
let raw = base * self.backoff_multiplier.powf(f64::from(attempt));
#[allow(clippy::cast_precision_loss)]
let cap = self.max_retry_delay_ms as f64;
let capped = raw.min(cap);
// Saturate negative or NaN values to zero, then truncate.
if !capped.is_finite() || capped <= 0.0 {
return 0;
}
#[allow(clippy::cast_sign_loss, clippy::cast_possible_truncation)]
let out = capped as u64;
out
}
}
// ---------------------------------------------------------------------------
// Reaper
// ---------------------------------------------------------------------------
/// Configuration for the [`AsyncTaskManager`] background reaper.
///
/// Marked `#[non_exhaustive]` (issue #24) so a future spec revision can add a
/// field without a major version bump. That works by **removing struct-literal
/// construction from every crate but this one** — `..Default::default()`
/// included, since it is itself a struct expression (`error[E0639]`). From a
/// downstream crate, start from `Default::default()` and assign the fields you
/// need; there is no builder for this type. See
/// `api-surface-conventions.md` §9.1.
#[derive(Debug, Clone, Copy)]
#[non_exhaustive]
pub struct ReaperConfig {
/// Age threshold (seconds) before a terminal task becomes eligible for deletion.
pub ttl_seconds: f64,
/// Sweep interval (milliseconds) between reaper runs.
pub sweep_interval_ms: u64,
}
impl Default for ReaperConfig {
fn default() -> Self {
Self {
ttl_seconds: 3600.0,
sweep_interval_ms: 300_000,
}
}
}
/// Handle returned by [`AsyncTaskManager::start_reaper`] to control the
/// background reaper task.
///
/// Call [`ReaperHandle::stop`] to signal cancellation and await termination.
/// Dropping the handle DETACHES the reaper: the sweep loop keeps running, so
/// the manager's single-reaper guard deliberately stays set — dropping a handle
/// is not a way to stop a reaper, and must not let a second sweep loop start
/// alongside the first. [`AsyncTaskManager::stop_reaper`] (which
/// [`AsyncTaskManager::shutdown`] calls) stops a detached reaper.
#[derive(Debug)]
pub struct ReaperHandle {
handle: JoinHandle<()>,
stop_tx: watch::Sender<bool>,
stop_slot: Arc<Mutex<Option<watch::Sender<bool>>>>,
}
impl ReaperHandle {
/// Signal the reaper to stop and await its clean shutdown.
pub async fn stop(self) {
// Receivers may have already been dropped — ignore the send error.
let _ = self.stop_tx.send(true);
if let Err(err) = self.handle.await {
if !err.is_cancelled() {
warn!("reaper task join failed: {err}");
}
}
let mut slot = self.stop_slot.lock();
// The manager may have stopped this generation and started another
// while the old handle was still awaiting its final sweep.
if slot
.as_ref()
.is_some_and(|sender| sender.same_channel(&self.stop_tx))
{
slot.take();
}
}
}
// ---------------------------------------------------------------------------
// AsyncTaskManager
// ---------------------------------------------------------------------------
struct TaskHandle {
join: JoinHandle<()>,
transition: Arc<tokio::sync::Mutex<()>>,
// Shared with the worker's normal deregistration path, so cancellation
// cannot reinsert a handle after that worker has already removed itself.
finished: Arc<AtomicBool>,
}
#[cfg(test)]
impl From<JoinHandle<()>> for TaskHandle {
fn from(join: JoinHandle<()>) -> Self {
Self {
join,
transition: Arc::default(),
finished: Arc::new(AtomicBool::new(false)),
}
}
}
/// Manages background execution of modules via tokio tasks.
///
/// Bounds concurrency with a semaphore, persists task state through a
/// pluggable [`TaskStore`], and supports retry with exponential backoff and
/// an opt-in [`ReaperHandle`] for TTL-based cleanup.
///
/// Synchronous accessors drive store operations on a temporary runtime when
/// called outside Tokio. Within Tokio, synchronous accessors require a store
/// supporting inline synchronous calls, such as [`InMemoryTaskStore`]. Use
/// the `_async` methods for I/O-backed stores inside a runtime and for stores
/// with resources bound to a specific runtime.
pub struct AsyncTaskManager {
executor: Arc<Executor>,
max_tasks: usize,
store: Arc<dyn TaskStore>,
handles: Arc<Mutex<HashMap<String, TaskHandle>>>,
execution_tokens: Arc<Mutex<HashMap<String, crate::cancel::CancelToken>>>,
cancellation_lock: tokio::sync::Mutex<()>,
semaphore: Arc<Semaphore>,
// Serialises the capacity-check + save sequence in `submit_with_retry`.
// Without this guard, two concurrent submits can both observe
// `store.list().len() < max_tasks` and both `save()` — exceeding the cap.
/// Async-aware admission lock — held across `check_capacity_and_save.await`
/// so concurrent submitters serialize through the capacity check + save.
/// `tokio::sync::Mutex` (rather than `parking_lot::Mutex`) because the
/// guard is alive across an `.await` point in `submit_with_retry`; a
/// sync mutex's `!Send` guard would block `tokio::spawn` of any code
/// path that touches `submit` (D10-003 alignment).
admission_lock: Arc<tokio::sync::Mutex<()>>,
/// Single-reaper guard and stop sender. Retained so [`Self::shutdown`]
/// can stop the current reaper even if its handle was dropped.
reaper_stop: Arc<Mutex<Option<watch::Sender<bool>>>>,
}
impl AsyncTaskManager {
/// Create a new manager backed by the default [`InMemoryTaskStore`].
///
/// # Arguments
///
/// * `executor` — Executor used to invoke modules.
/// * `max_concurrent` — Maximum simultaneously running tasks (semaphore size).
/// * `max_tasks` — Maximum tracked task records (rejects further submits).
pub fn new(executor: Arc<Executor>, max_concurrent: usize, max_tasks: usize) -> Self {
Self::with_store(
executor,
max_concurrent,
max_tasks,
Arc::new(InMemoryTaskStore::new()),
)
}
/// Create a manager with a caller-provided [`TaskStore`] implementation.
pub fn with_store(
executor: Arc<Executor>,
max_concurrent: usize,
max_tasks: usize,
store: Arc<dyn TaskStore>,
) -> Self {
// A task's module can make nested calls like any other.
executor.enable_nested_calls();
Self {
executor,
max_tasks,
store,
handles: Arc::new(Mutex::new(HashMap::new())),
execution_tokens: Arc::new(Mutex::new(HashMap::new())),
cancellation_lock: tokio::sync::Mutex::new(()),
semaphore: Arc::new(Semaphore::new(max_concurrent)),
admission_lock: Arc::new(tokio::sync::Mutex::new(())),
reaper_stop: Arc::new(Mutex::new(None)),
}
}
/// Identifier of the underlying store backend.
pub fn store_type_name(&self) -> &'static str {
self.store.store_type_name()
}
/// Borrow the underlying [`TaskStore`] handle (for direct interaction or
/// custom maintenance routines).
pub fn store(&self) -> Arc<dyn TaskStore> {
Arc::clone(&self.store)
}
/// Submit a module call for background execution. See [`Self::submit_with_retry`].
///
/// Async (D10-003): the spec async-tasks.md contract declares submit
/// async, matching apcore-python `async def submit` and apcore-typescript
/// `async submit`. Awaiting submit is required so the capacity check
/// + store.save are observed atomically before the task ID is returned.
pub async fn submit(
&self,
module_id: &str,
inputs: serde_json::Value,
context: Option<Context<serde_json::Value>>,
) -> Result<String, ModuleError> {
self.submit_with_retry(module_id, inputs, context, None)
.await
}
/// Submit a module call with optional retry policy.
///
/// Returns the generated task ID (UUID v4). Spawns a background tokio task
/// that will acquire a concurrency permit before invoking the executor.
/// On failure, when `retry` is supplied, the task is rescheduled after
/// the policy-derived backoff delay until `max_retries` is exhausted.
pub async fn submit_with_retry(
&self,
module_id: &str,
inputs: serde_json::Value,
context: Option<Context<serde_json::Value>>,
retry: Option<RetryConfig>,
) -> Result<String, ModuleError> {
// Construct the initial TaskInfo and reserve a slot in the store.
// Concurrent submits are serialised through `admission_lock` so the
// capacity check and subsequent save below are atomic.
let task_id = Uuid::new_v4().to_string();
let max_retries = retry.as_ref().map_or(0, |r| r.max_retries);
let info = TaskInfo {
task_id: task_id.clone(),
module_id: module_id.to_string(),
status: TaskStatus::Pending,
submitted_at: now_secs(),
started_at: None,
completed_at: None,
result: None,
error: None,
retry_count: 0,
max_retries,
};
// Capacity check + persist must be atomic with respect to other
// concurrent submits. tokio::sync::Mutex's guard is `Send` so
// submit_with_retry is itself Send-safe and can be spawned via
// tokio::spawn — required for the async `pub async fn submit`
// entry point to compose with the broader async runtime.
{
let _admit = self.admission_lock.lock().await;
check_capacity_and_save(&*self.store, self.max_tasks, &info).await?;
}
let handles = Arc::clone(&self.handles);
let execution_tokens = Arc::clone(&self.execution_tokens);
let mut context = context.unwrap_or_else(Context::anonymous);
let execution_token = context.cancel_token.as_ref().map_or_else(
crate::cancel::CancelToken::new,
crate::cancel::CancelToken::child,
);
context.cancel_token = Some(execution_token.clone());
execution_tokens
.lock()
.insert(task_id.clone(), execution_token.clone());
let semaphore = Arc::clone(&self.semaphore);
let executor = Arc::clone(&self.executor);
let store_for_run = Arc::clone(&self.store);
let mid = module_id.to_string();
let tid = task_id.clone();
// The spawned task can finish BEFORE the parent registers its
// `JoinHandle` — a fast failure such as MODULE_NOT_FOUND, with a free
// semaphore permit and an immediately-ready `InMemoryTaskStore`, reaches
// the `remove` below while this thread is still between `spawn` and
// `insert` on a multi-threaded runtime. The removal then found nothing
// and a stale handle was inserted for an already-terminal task, so
// `cancel()` would later `abort()` a finished task and `handles` grew
// without bound.
//
// `finished` closes the window: the task sets it BEFORE taking the
// `handles` lock, and the parent reads it while HOLDING that lock. So
// either the parent observes the flag and never inserts, or its insert
// is ordered before the task's remove. Neither interleaving leaves a
// stale entry.
let finished = Arc::new(std::sync::atomic::AtomicBool::new(false));
let finished_in_task = Arc::clone(&finished);
let transition = Arc::new(tokio::sync::Mutex::new(()));
let transition_in_task = Arc::clone(&transition);
let handle = tokio::spawn(async move {
run_task(
tid.clone(),
mid,
inputs,
context,
retry,
executor,
semaphore,
store_for_run,
transition_in_task,
)
.await;
// The store may already expose a timeout while the invocation is
// still cleaning up cooperatively. Keep bookkeeping until actual
// completion, including after cleanup() has deleted its record.
execution_token.drain().await;
finished_in_task.store(true, std::sync::atomic::Ordering::SeqCst);
handles.lock().remove(&tid);
execution_tokens.lock().remove(&tid);
});
{
let mut registered = self.handles.lock();
if finished.load(std::sync::atomic::Ordering::SeqCst) {
// Already terminal: registering now would strand the entry.
drop(handle);
} else {
registered.insert(
task_id.clone(),
TaskHandle {
join: handle,
transition,
finished,
},
);
}
}
Ok(task_id)
}
/// Return the current snapshot of a task, or `None` if unknown.
///
/// # Errors
///
/// Propagates the store's error (D-81). `Ok(None)` means the store
/// answered and has no such task; a store outage is an `Err`, never a
/// "not found". Returns [`ErrorCode::GeneralInvalidInput`] when the store
/// requires async access inside Tokio. Await [`Self::get_status_async`].
pub fn get_status(&self, task_id: &str) -> Result<Option<TaskInfo>, ModuleError> {
self.run_store_sync(self.get_status_async(task_id), "get_status_async")
}
/// Async variant of [`Self::get_status`] for network-backed stores.
///
/// # Errors
///
/// Propagates the store's error (D-81).
pub async fn get_status_async(&self, task_id: &str) -> Result<Option<TaskInfo>, ModuleError> {
self.store.get(task_id).await
}
/// Return the result of a completed task or an error if not found / not
/// completed.
///
/// # Errors
///
/// The store's own error is propagated unchanged (D-81); a task that is
/// absent or not yet complete is reported as
/// [`ErrorCode::GeneralInternalError`]. Returns
/// [`ErrorCode::GeneralInvalidInput`] when the store requires async access inside Tokio.
/// In that case await [`Self::get_result_async`].
pub fn get_result(&self, task_id: &str) -> Result<serde_json::Value, ModuleError> {
self.run_store_sync(self.get_result_async(task_id), "get_result_async")
}
/// Async variant of [`Self::get_result`] for network-backed stores.
///
/// # Errors
///
/// As [`Self::get_result`].
pub async fn get_result_async(&self, task_id: &str) -> Result<serde_json::Value, ModuleError> {
let info = self.store.get(task_id).await?.ok_or_else(|| {
ModuleError::new(
ErrorCode::GeneralInternalError,
format!("Task not found: {task_id}"),
)
})?;
if info.status != TaskStatus::Completed {
return Err(ModuleError::new(
ErrorCode::GeneralInternalError,
format!("Task {task_id} is not completed (status={:?})", info.status),
));
}
Ok(info.result.unwrap_or(serde_json::Value::Null))
}
/// Cancel a pending or running task. Returns `true` if cancellation was applied.
///
/// Async (D10-004): spec async-tasks.md cancel contract declares the
/// method async. Python (`async def cancel`) and TypeScript
/// (`async cancel`) already comply; Rust now matches via
/// `pub async fn cancel`. Drain semantics typically require await.
///
/// # Errors
///
/// Propagates the store's error (D-81). This is the case the decision
/// calls out as worst: this method used to swallow a failed `save` and
/// still return `true`, telling the caller the task was terminated while
/// it kept running. The cancellation OUTCOME is still the boolean —
/// `Ok(false)` for an unknown or already-terminal task.
pub async fn cancel(&self, task_id: &str) -> Result<bool, ModuleError> {
let _cancellation = self.cancellation_lock.lock().await;
let transition = self
.handles
.lock()
.get(task_id)
.map(|handle| Arc::clone(&handle.transition));
let _transition = match &transition {
Some(lock) => Some(lock.lock().await),
None => None,
};
let Some(info) = self.store.get(task_id).await? else {
return Ok(false);
};
if !info.status.is_active() {
return Ok(false);
}
self.stop_local_task(task_id).await;
// State may have changed while the physical execution was draining.
let Some(mut updated) = self.store.get(task_id).await? else {
return Ok(false);
};
if !updated.status.is_active() {
return Ok(false);
}
updated.status = TaskStatus::Cancelled;
updated.completed_at = Some(now_secs());
self.store.save(&updated).await?;
Ok(true)
}
async fn stop_local_task(&self, task_id: &str) {
// A caller can drop cancel()/shutdown() at either await. Return any
// unfinished join to the manager rather than detaching its teardown.
struct PendingJoin<'a> {
task_id: &'a str,
handles: &'a Mutex<HashMap<String, TaskHandle>>,
handle: Option<TaskHandle>,
}
impl Drop for PendingJoin<'_> {
fn drop(&mut self) {
if let Some(handle) = self.handle.take() {
let mut handles = self.handles.lock();
if !handle.finished.load(Ordering::SeqCst) && !handle.join.is_finished() {
handles.insert(self.task_id.to_owned(), handle);
}
}
}
}
let mut pending = PendingJoin {
task_id,
handles: &self.handles,
handle: self.handles.lock().remove(task_id),
};
if let Some(handle) = pending.handle.as_mut() {
handle.join.abort();
let _ = (&mut handle.join).await;
}
pending.handle.take();
// Keep the token registered until the physical invocation tree has
// drained, even when this particular cancellation waiter is dropped.
let execution_token = self.execution_tokens.lock().get(task_id).cloned();
if let Some(token) = execution_token {
token.cancel();
token.abort_owned_executions().await;
self.execution_tokens.lock().remove(task_id);
}
}
/// Signal this manager's reaper to stop and release the single-reaper
/// guard, whether or not its [`ReaperHandle`] is still held.
///
/// Returns `true` when a reaper was running. Idempotent. Mirrors
/// apcore-python `AsyncTaskManager.stop_reaper`; apcore-typescript stops
/// its sweep timer in the same place.
///
/// Does not await the sweep loop's final iteration — hold the
/// [`ReaperHandle`] and call [`ReaperHandle::stop`] when that matters.
pub fn stop_reaper(&self) -> bool {
let mut slot = self.reaper_stop.lock();
let Some(stop_tx) = slot.take() else {
return false;
};
let _ = stop_tx.send(true);
true
}
/// Cancel all pending and running tasks, and stop the reaper.
///
/// The reaper stop is what apcore-python's `shutdown` does first
/// (`await self.stop_reaper()`) and what apcore-typescript's clears; this
/// SDK left a started reaper sweeping after `shutdown()` returned.
///
/// Every active task is attempted even after one cancellation fails, and the
/// first failure is returned once they all have been (D-122). The two
/// failure modes are not symmetric: if the store is unreachable every
/// cancellation fails and stopping early reaches the same outcome sooner,
/// but if ONE task fails, stopping leaves every remaining task uncancelled
/// when they could have been cancelled. An uncancelled task in a shared
/// store is a lasting cost — it holds a `max_tasks` slot for every manager
/// sharing that store, and outlives the process that could have cancelled
/// it — while a slower shutdown is transient. This method is already an
/// unbounded wait by contract and takes no timeout, so a caller needing a
/// bound already imposes one.
///
/// # Errors
///
/// Propagates the store's error (D-81): the `list` failure immediately, or
/// the first `cancel` failure after every active task has been attempted.
/// The reaper is stopped before the store is touched, so a store outage
/// still leaves the reaper stopped.
pub async fn shutdown(&self) -> Result<(), ModuleError> {
self.stop_reaper();
let mut first_error: Option<ModuleError> = None;
let mut task_ids: Vec<String> = self.handles.lock().keys().cloned().collect();
task_ids.extend(self.execution_tokens.lock().keys().cloned());
match self.store.list(None).await {
Ok(tasks) => task_ids.extend(
tasks
.into_iter()
.filter_map(|info| info.status.is_active().then_some(info.task_id)),
),
Err(error) => first_error = Some(error),
}
task_ids.sort();
task_ids.dedup();
for task_id in task_ids {
if let Err(err) = self.cancel(&task_id).await {
if first_error.is_none() {
first_error = Some(err);
}
}
// Explicit shutdown owns physical teardown even for terminal
// records with late cleanup, or when the store is unavailable.
let _cancellation = self.cancellation_lock.lock().await;
self.stop_local_task(&task_id).await;
}
first_error.map_or(Ok(()), Err)
}
/// Return all tasks, optionally filtered by status. Synchronous wrapper.
///
/// The list is in submission order (D-82). An empty `Ok` list means the
/// store answered and nothing matched.
///
/// # Errors
///
/// Propagates the store's error (D-81) rather than reporting "no tasks"
/// for a store that is merely unreachable. Returns
/// [`ErrorCode::GeneralInvalidInput`] when the store requires async access inside Tokio.
/// In that case await [`Self::list_tasks_async`].
pub fn list_tasks(&self, status: Option<TaskStatus>) -> Result<Vec<TaskInfo>, ModuleError> {
self.run_store_sync(self.list_tasks_async(status), "list_tasks_async")
}
/// Async variant of [`Self::list_tasks`] for network-backed stores.
///
/// # Errors
///
/// Propagates the store's error (D-81).
pub async fn list_tasks_async(
&self,
status: Option<TaskStatus>,
) -> Result<Vec<TaskInfo>, ModuleError> {
self.store.list(status).await
}
/// Remove terminal-state tasks older than `max_age_seconds`. Returns the
/// count of removed tasks. Synchronous wrapper.
///
/// # Errors
///
/// Propagates the store's error (D-81). A failed `delete` aborts the sweep
/// rather than being counted as a removal that never happened. Returns
/// [`ErrorCode::GeneralInvalidInput`] when the store requires async access inside Tokio.
/// In that case await [`Self::cleanup_async`].
pub fn cleanup(&self, max_age_seconds: f64) -> Result<usize, ModuleError> {
self.run_store_sync(self.cleanup_async(max_age_seconds), "cleanup_async")
}
/// Async variant of [`Self::cleanup`] for network-backed stores.
///
/// # Errors
///
/// As [`Self::cleanup`].
pub async fn cleanup_async(&self, max_age_seconds: f64) -> Result<usize, ModuleError> {
let now = now_secs();
let to_remove: Vec<String> = self
.store
.list(None)
.await?
.into_iter()
.filter(|info| info.status.is_terminal())
.filter(|info| {
let ref_time = info.completed_at.unwrap_or(info.submitted_at);
(now - ref_time) >= max_age_seconds
})
.map(|info| info.task_id)
.collect();
let count = to_remove.len();
for id in &to_remove {
self.store.delete(id).await?;
self.handles.lock().remove(id);
// A reported timeout may still be cleaning up cooperatively.
// Keep its scope until shutdown/cancel has actually drained it.
self.execution_tokens
.lock()
.retain(|task_id, token| task_id != id || token.has_active_executions());
}
Ok(count)
}
/// Total tracked task count across all states.
///
/// # Errors
///
/// Propagates the store's error (D-81) rather than reporting `0` for a
/// store that is merely unreachable. Returns
/// [`ErrorCode::GeneralInvalidInput`] when the store requires async access inside Tokio.
/// In that case await [`Self::task_count_async`].
pub fn task_count(&self) -> Result<usize, ModuleError> {
self.run_store_sync(self.task_count_async(), "task_count_async")
}
/// Count all tracked tasks on the caller's runtime.
///
/// # Errors
///
/// Propagates the store's error (D-81).
pub async fn task_count_async(&self) -> Result<usize, ModuleError> {
Ok(self.store.list(None).await?.len())
}
fn run_store_sync<T>(
&self,
operation: impl std::future::Future<Output = Result<T, ModuleError>>,
async_method: &str,
) -> Result<T, ModuleError> {
use std::pin::pin;
use std::task::{Context, Poll, Waker};
if tokio::runtime::Handle::try_current().is_err() {
let runtime = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.map_err(|error| {
ModuleError::new(
ErrorCode::GeneralInternalError,
format!("Failed to start a runtime for TaskStore: {error}"),
)
})?;
return runtime.block_on(operation);
}
// Poll only stores that declare their operations can run inline.
// Starting I/O here could require services the host runtime lacks.
if self.store.supports_inline_sync() {
let mut context = Context::from_waker(Waker::noop());
if let Poll::Ready(result) = pin!(operation).poll(&mut context) {
return result;
}
}
let guidance = format!(
"Await {async_method}() inside Tokio with a TaskStore that cannot complete inline."
);
Err(ModuleError::invalid_input(&guidance).with_ai_guidance(guidance))
}
/// Start the opt-in background reaper. Returns a [`ReaperHandle`] used to
/// stop the reaper gracefully.
///
/// At most one reaper may be running per manager. Calling `start_reaper`
/// while another reaper is still live returns
/// `Err(ModuleError { code: ReaperAlreadyRunning, .. })`. Call
/// [`ReaperHandle::stop`] (or drop the handle) before starting a new one.
///
/// **Cross-language note (A-C-004/A-C-005):** apcore-python and
/// apcore-typescript now also raise `ModuleError`/`ModuleError` with this
/// same code for a double `start_reaper`, matching Rust. They previously
/// raised an untyped `RuntimeError` / plain `Error`, which a caller
/// writing `except ModuleError` could not catch.
///
/// # Errors
/// Returns `ModuleError` with [`ErrorCode::ReaperAlreadyRunning`] when a
/// reaper from a prior `start_reaper` call has not yet been stopped.
pub fn start_reaper(&self, config: ReaperConfig) -> Result<ReaperHandle, ModuleError> {
let mut slot = self.reaper_stop.lock();
if slot.is_some() {
return Err(ModuleError::new(
ErrorCode::ReaperAlreadyRunning,
"AsyncTaskManager reaper is already running; call stop() first",
));
}
let store = Arc::clone(&self.store);
let (stop_tx, mut stop_rx) = watch::channel(false);
let interval = Duration::from_millis(config.sweep_interval_ms);
let ttl = config.ttl_seconds;
let handle = tokio::spawn(async move {
loop {
tokio::select! {
biased;
changed = stop_rx.changed() => {
if changed.is_err() || *stop_rx.borrow() {
debug!("reaper received stop signal");