multicast-workflows 2.0.0

Durable Code Mode workflows attached to multicast CLIs as first-party commands
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
//! Durable admission and host-driven delivery of webhook and interval triggers.

#[cfg(all(feature = "native", not(target_arch = "wasm32")))]
use std::path::Path;
use std::sync::{Arc, Mutex, OnceLock};
#[cfg(all(test, feature = "native", not(target_arch = "wasm32")))]
use std::time::Duration;
use web_time::{SystemTime, UNIX_EPOCH};

use crate::database::{Connection, OptionalExtension, params};
use multicast_codemode::{CodeModeRunOptions, ExecutionStatus, WorkflowIdentity};
use serde::{Deserialize, Serialize};
use serde_json::Value;

use crate::{State, ledger, program};

/// An authenticated host delivery, deduplicated by its stable source event key.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct TriggerRequest {
    /// Stable event key, unique within this CLI's webhook admission namespace.
    pub key: String,
    /// Shipped or saved workflow name.
    pub workflow: String,
    /// Input validated before admission and again before execution.
    pub input: Value,
    /// Earliest start, in Unix milliseconds.
    pub not_before: u64,
    /// Absolute end-to-end deadline in Unix milliseconds, after `not_before`.
    pub deadline: u64,
}

/// A durable fixed-interval schedule; missed intervals coalesce to the latest due one.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct TriggerSchedule {
    /// Stable schedule identifier, at most 256 bytes.
    pub id: String,
    /// Workflow name, pinned to its current version when registered.
    pub workflow: String,
    /// Validated input used by every occurrence.
    pub input: Value,
    /// First occurrence in Unix milliseconds.
    pub first_at: u64,
    /// Positive interval in milliseconds.
    pub every_ms: u64,
    /// Positive deadline duration measured from each occurrence's due time.
    pub deadline_ms: u64,
}

/// Durable delivery receipt. Repeated admission returns the original receipt.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TriggerReceipt {
    /// `webhook` for host deliveries or `schedule` for interval occurrences.
    pub source: String,
    /// Delivery key, or a schedule identifier and its occurrence time.
    pub key: String,
    /// Named workflow.
    pub workflow: String,
    /// Program and input-schema version pinned at admission.
    pub version: String,
    /// Identifier committed before any execution pass starts.
    pub execution_id: Option<String>,
    /// `queued`, `preparing`, an execution status, `expired`, or `blocked`.
    pub status: String,
    /// Diagnostic for blocked, expired, or failed work.
    pub error: Option<String>,
    /// Earliest start in Unix milliseconds.
    pub not_before: u64,
    /// End-to-end deadline in Unix milliseconds.
    pub deadline: u64,
}

struct Queue {
    connection: Mutex<Connection>,
}

struct Delivery {
    request: TriggerRequest,
    receipt: TriggerReceipt,
}

/// Host boundary for authenticated webhooks and fixed-interval schedules.
///
/// Admission is durable and has no command effects. The host supplies its own
/// authentication, authorization, HTTP server, and polling lifetime. `tick`
/// serializes delivery across handle clones; unfinished work limits each workflow
/// to one execution, including approval and uncertain-outcome pauses. There is no
/// automatic approval, effect retry, or whole-workflow restart.
#[derive(Clone)]
pub struct WorkflowTriggers {
    state: Arc<State>,
    queue: Arc<OnceLock<Result<Queue, String>>>,
    tick_lock: Arc<tokio::sync::Mutex<()>>,
}

impl WorkflowTriggers {
    pub(super) fn new(state: Arc<State>) -> Self {
        Self {
            state,
            queue: Arc::default(),
            tick_lock: Arc::default(),
        }
    }

    fn queue(&self) -> Result<&Queue, String> {
        self.queue
            .get_or_init(|| {
                if let Some(host) = &self.state.host {
                    return host
                        .database(crate::WorkflowDatabaseKind::Triggers)
                        .and_then(Queue::from_database);
                }
                #[cfg(all(feature = "native", not(target_arch = "wasm32")))]
                {
                    Queue::open(&self.state.store_path.with_extension("triggers.sqlite"))
                }
                #[cfg(not(all(feature = "native", not(target_arch = "wasm32"))))]
                {
                    Err("A workflow host is required".into())
                }
            })
            .as_ref()
            .map_err(Clone::clone)
    }

    /// Admits a delivery after the adapter authenticates and authorizes its caller.
    ///
    /// Keys are at most 256 bytes and serialized requests at most 1 MiB. A repeated
    /// key with identical request data returns its receipt; changed data returns
    /// `TRIGGER_KEY_CONFLICT`. Receipts persist without automatic pruning, so a
    /// process restart or completed execution does not reset deduplication.
    pub async fn enqueue(&self, request: TriggerRequest) -> Result<TriggerReceipt, String> {
        validate_request(&request)?;
        if let Some(existing) = self.queue()?.get("webhook", &request.key)? {
            return duplicate(existing, &request);
        }
        let workflow = self
            .state
            .resolve(&request.workflow)
            .await?
            .ok_or_else(|| format!("Workflow '{}' not found", request.workflow))?;
        program(&workflow, request.input.clone())?;
        if let Some(host) = &self.state.host {
            host.wake_at(request.not_before).await?;
        }
        self.queue()?
            .insert("webhook", &request, &workflow.version())
    }

    /// Registers an immutable, durable interval schedule.
    ///
    /// Repeating an identical registration preserves progress. Changed settings
    /// or workflow versions require removing the schedule and registering again.
    /// Removal stops future occurrences but retains already admitted receipts.
    pub async fn schedule(&self, schedule: TriggerSchedule) -> Result<(), String> {
        validate_key(&schedule.id)?;
        if schedule.every_ms == 0
            || schedule.deadline_ms == 0
            || schedule
                .first_at
                .checked_add(schedule.every_ms)
                .is_none_or(|value| value > i64::MAX as u64)
        {
            return Err("Schedule durations must be positive".into());
        }
        let request = TriggerRequest {
            key: schedule.id.clone(),
            workflow: schedule.workflow.clone(),
            input: schedule.input.clone(),
            not_before: schedule.first_at,
            deadline: schedule
                .first_at
                .checked_add(schedule.deadline_ms)
                .ok_or("Schedule deadline overflow")?,
        };
        validate_request(&request)?;
        let workflow = self
            .state
            .resolve(&schedule.workflow)
            .await?
            .ok_or("Scheduled workflow not found")?;
        program(&workflow, schedule.input.clone())?;
        if let Some(host) = &self.state.host {
            host.wake_at(schedule.first_at).await?;
        }
        self.queue()?.schedule(&schedule, &workflow.version())
    }

    /// Stops future occurrences while retaining admitted work and deduplication.
    pub fn remove_schedule(&self, id: &str) -> Result<bool, String> {
        Ok(self
            .queue()?
            .lock()?
            .execute("DELETE FROM schedules WHERE id = ?1", params![id])
            .map_err(sql)?
            != 0)
    }

    /// Reads a receipt by its source (`webhook` or `schedule`) and delivery key.
    pub fn receipt(&self, source: &str, key: &str) -> Result<Option<TriggerReceipt>, String> {
        Ok(self
            .queue()?
            .get(source, key)?
            .map(|delivery| delivery.receipt))
    }

    /// Returns the next due schedule, delivery, or deadline for host wakeups.
    /// Running deliveries are checked within one second; approval pauses keep
    /// their concurrency slot until a decision or their deadline.
    pub fn next_wake(&self) -> Result<Option<u64>, String> {
        let now = now_ms()?;
        self.queue()?.lock()?.query_row("SELECT MIN(wake) FROM (SELECT next_at AS wake FROM schedules UNION ALL SELECT CASE WHEN execution_id IS NULL THEN CASE WHEN EXISTS (SELECT 1 FROM deliveries busy WHERE busy.workflow=deliveries.workflow AND busy.execution_id IS NOT NULL AND busy.status IN ('preparing','running','paused','blocked')) THEN deadline ELSE MIN(deadline,MAX(?1,not_before)) END WHEN status IN ('preparing','running') THEN MIN(deadline,?1+1000) ELSE deadline END AS wake FROM deliveries WHERE status IN ('queued','preparing','running','paused'))", params![now], |row| row.get(0)).map_err(sql)
    }

    /// Refreshes unfinished receipts and delivers at most `limit` due executions.
    ///
    /// `limit` must be 1..=100. Calls serialize across clones and the Code Mode
    /// store enforces single-process ownership. The host must keep polling for
    /// deadlines to be enforced while stopped or paused. A running delivery is
    /// cancelled at its deadline while this call is alive; cancellation cannot
    /// undo a command effect already committed by its destination.
    pub async fn tick(&self, limit: usize) -> Result<Vec<TriggerReceipt>, String> {
        if !(1..=100).contains(&limit) {
            return Err("Trigger tick limit must be 1..=100".into());
        }
        let _guard = self.tick_lock.lock().await;
        // Acquire the execution store's exclusive owner before claiming delivery.
        let service = self.state.service().await?;
        let queue = self.queue()?;
        let now = now_ms()?;
        if self.next_wake()?.is_some_and(|wake| wake <= now)
            && let Some(host) = &self.state.host
        {
            host.wake_at(now.saturating_add(1000)).await?;
        }
        queue.materialize(now_ms()?)?;
        let mut changed = Vec::new();
        for delivery in queue.active()? {
            if delivery.receipt.execution_id.is_some() {
                changed.push(self.deliver(delivery).await?);
            }
        }
        for _ in 0..limit {
            let Some(mut delivery) = queue.claim(now_ms()?)? else {
                break;
            };
            let Some(workflow) = self.state.resolve(&delivery.request.workflow).await? else {
                queue.finish(
                    &delivery.receipt,
                    "blocked",
                    Some("Workflow no longer exists"),
                )?;
                changed.push(
                    queue
                        .get(&delivery.receipt.source, &delivery.receipt.key)?
                        .unwrap()
                        .receipt,
                );
                continue;
            };
            if workflow.version() != delivery.receipt.version {
                queue.finish(
                    &delivery.receipt,
                    "blocked",
                    Some("Workflow version changed; review a new delivery"),
                )?;
                changed.push(
                    queue
                        .get(&delivery.receipt.source, &delivery.receipt.key)?
                        .unwrap()
                        .receipt,
                );
                continue;
            }
            let (_, code) = program(&workflow, delivery.request.input.clone())?;
            let execution = service.prepare(code).await?;
            // A crash before binding leaves only an idle execution with no effects.
            // Once bound, every restart recovers this identifier, never a new run.
            queue.bind(&delivery.receipt, &execution.id)?;
            delivery.receipt.execution_id = Some(execution.id);
            if let Some(ledger) = self.state.ledger() {
                crate::warn_ledger(ledger.start(&ledger::RunStart {
                    execution_id: delivery.receipt.execution_id.as_deref().unwrap(),
                    workflow: &workflow.name,
                    origin: workflow.origin,
                    version: &workflow.version(),
                    at: execution.created_at,
                }));
            }
            changed.push(self.deliver(delivery).await?);
        }
        Ok(changed)
    }

    async fn deliver(&self, delivery: Delivery) -> Result<TriggerReceipt, String> {
        let queue = self.queue()?;
        let receipt = &delivery.receipt;
        let id = receipt.execution_id.as_deref().ok_or("Unbound trigger")?;
        let service = self.state.service().await?;
        let mut execution = match service.execution(id.into()).await {
            Ok(execution) => execution,
            Err(error) => {
                queue.finish(
                    receipt,
                    "blocked",
                    Some(&format!(
                        "Bound execution unavailable; reconcile without restarting: {error}"
                    )),
                )?;
                return Ok(queue.get(&receipt.source, &receipt.key)?.unwrap().receipt);
            }
        };
        let unfinished = matches!(
            execution.status,
            ExecutionStatus::Running | ExecutionStatus::Paused
        );
        let now = now_ms()?;
        if unfinished && now >= receipt.deadline {
            execution = service.cancel(id.into()).await?;
        } else if execution.status == ExecutionStatus::Running {
            let options = CodeModeRunOptions {
                workflow: Some(WorkflowIdentity {
                    name: receipt.workflow.clone(),
                    version: receipt.version.clone(),
                }),
                ..CodeModeRunOptions::default()
            };
            let run = async {
                let execution = service.recover(id.into(), options).await?;
                self.state.settle(service, execution).await
            };
            let deadline = self.state.sleep(receipt.deadline - now);
            futures_util::pin_mut!(run, deadline);
            execution = match futures_util::future::select(run, deadline).await {
                futures_util::future::Either::Left((result, _)) => result?,
                futures_util::future::Either::Right(((), _)) => service.cancel(id.into()).await?,
            };
        }
        self.state.record(&execution);
        queue.finish(
            receipt,
            ledger::status_name(execution.status),
            execution.error.as_deref(),
        )?;
        Ok(queue.get(&receipt.source, &receipt.key)?.unwrap().receipt)
    }
}

fn now_ms() -> Result<u64, String> {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map_err(|error| error.to_string())?
        .as_millis()
        .try_into()
        .map_err(|_| "Clock overflow".into())
}

fn validate_key(key: &str) -> Result<(), String> {
    if key.is_empty() || key.len() > 256 {
        Err("Trigger key must contain 1..=256 bytes".into())
    } else {
        Ok(())
    }
}

fn validate_request(request: &TriggerRequest) -> Result<(), String> {
    validate_key(&request.key)?;
    if request.not_before >= request.deadline || request.deadline > i64::MAX as u64 {
        return Err(
            "Trigger deadline must follow notBefore and fit a signed 64-bit timestamp".into(),
        );
    }
    if serde_json::to_vec(request)
        .map_err(|error| error.to_string())?
        .len()
        > 1024 * 1024
    {
        return Err("Trigger request exceeds 1 MiB".into());
    }
    Ok(())
}

fn duplicate(delivery: Delivery, request: &TriggerRequest) -> Result<TriggerReceipt, String> {
    if delivery.request == *request {
        Ok(delivery.receipt)
    } else {
        Err("TRIGGER_KEY_CONFLICT: event key already has different request data".into())
    }
}

fn sql(error: crate::database::Error) -> String {
    format!("Trigger store: {error}")
}

impl Queue {
    #[cfg(all(feature = "native", not(target_arch = "wasm32")))]
    fn open(path: &Path) -> Result<Self, String> {
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent).map_err(|error| error.to_string())?;
        }
        let connection = Connection::open(path).map_err(sql)?;
        Self::initialize(&connection)?;
        Ok(Self {
            connection: Mutex::new(connection),
        })
    }

    fn from_database(database: Arc<dyn crate::WorkflowDatabase>) -> Result<Self, String> {
        let connection = Connection::new(database);
        Self::initialize(&connection)?;
        Ok(Self {
            connection: Mutex::new(connection),
        })
    }

    fn initialize(connection: &Connection) -> Result<(), String> {
        connection.execute_batch("CREATE TABLE IF NOT EXISTS deliveries (source TEXT NOT NULL, key TEXT NOT NULL, body TEXT NOT NULL, version TEXT NOT NULL, status TEXT NOT NULL, execution_id TEXT, error TEXT, workflow TEXT NOT NULL, not_before INTEGER NOT NULL, deadline INTEGER NOT NULL, PRIMARY KEY(source,key));
            CREATE TABLE IF NOT EXISTS schedules (id TEXT PRIMARY KEY, body TEXT NOT NULL, version TEXT NOT NULL, next_at INTEGER NOT NULL);").map_err(sql)
    }

    fn lock(&self) -> Result<std::sync::MutexGuard<'_, Connection>, String> {
        self.connection.lock().map_err(|error| error.to_string())
    }

    fn get(&self, source: &str, key: &str) -> Result<Option<Delivery>, String> {
        self.lock()?.query_row("SELECT source,key,body,version,status,execution_id,error FROM deliveries WHERE source=?1 AND key=?2", params![source,key], row).optional().map_err(sql)
    }

    fn insert(
        &self,
        source: &str,
        request: &TriggerRequest,
        version: &str,
    ) -> Result<TriggerReceipt, String> {
        let body = serde_json::to_string(request).map_err(|error| error.to_string())?;
        self.lock()?.execute("INSERT OR IGNORE INTO deliveries(source,key,body,version,status,workflow,not_before,deadline) VALUES(?1,?2,?3,?4,'queued',?5,?6,?7)", params![source,request.key,body,version,request.workflow,request.not_before,request.deadline]).map_err(sql)?;
        duplicate(self.get(source, &request.key)?.unwrap(), request)
    }

    fn schedule(&self, schedule: &TriggerSchedule, version: &str) -> Result<(), String> {
        let body = serde_json::to_string(schedule).map_err(|error| error.to_string())?;
        let connection = self.lock()?;
        connection
            .execute(
                "INSERT OR IGNORE INTO schedules(id,body,version,next_at) VALUES(?1,?2,?3,?4)",
                params![schedule.id, body, version, schedule.first_at],
            )
            .map_err(sql)?;
        let existing: (String, String) = connection
            .query_row(
                "SELECT body,version FROM schedules WHERE id=?1",
                params![&schedule.id],
                |row| Ok((row.get(0)?, row.get(1)?)),
            )
            .map_err(sql)?;
        if existing == (body, version.into()) {
            Ok(())
        } else {
            Err("TRIGGER_SCHEDULE_CONFLICT: remove the old schedule before replacing it".into())
        }
    }

    fn materialize(&self, now: u64) -> Result<(), String> {
        let connection = self.lock()?;
        connection.transaction(|transaction| {
        let due: Vec<(String, String, u64)> = transaction
            .prepare("SELECT body,version,next_at FROM schedules WHERE next_at<=?1")
            .map_err(sql)?
            .query_map(params![now], |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)))
            .map_err(sql)?
            .collect::<Result<_, _>>()
            .map_err(sql)?;
        for (body, version, next) in due {
            let schedule: TriggerSchedule =
                serde_json::from_str(&body).map_err(|error| error.to_string())?;
            let occurrence = next + ((now - next) / schedule.every_ms) * schedule.every_ms;
            let next = occurrence
                .checked_add(schedule.every_ms)
                .filter(|value| *value <= i64::MAX as u64)
                .ok_or("Schedule timestamp overflow")?;
            let request = TriggerRequest {
                key: format!("{}:{occurrence}", schedule.id),
                workflow: schedule.workflow,
                input: schedule.input,
                not_before: occurrence,
                deadline: occurrence
                    .checked_add(schedule.deadline_ms)
                    .filter(|value| *value <= i64::MAX as u64)
                    .ok_or("Schedule deadline overflow")?,
            };
            let body = serde_json::to_string(&request).map_err(|error| error.to_string())?;
            transaction.execute("INSERT OR IGNORE INTO deliveries(source,key,body,version,status,workflow,not_before,deadline) VALUES('schedule',?1,?2,?3,'queued',?4,?5,?6)", params![request.key,body,version,request.workflow,request.not_before,request.deadline]).map_err(sql)?;
            transaction
                .execute(
                    "UPDATE schedules SET next_at=?1 WHERE id=?2",
                    params![next, schedule.id],
                )
                .map_err(sql)?;
        }
        Ok(())
        }).map_err(sql)
    }

    fn active(&self) -> Result<Vec<Delivery>, String> {
        self.lock()?.prepare("SELECT source,key,body,version,status,execution_id,error FROM deliveries WHERE execution_id IS NOT NULL AND status IN ('preparing','running','paused','blocked') ORDER BY rowid").map_err(sql)?.query_map(params![],row).map_err(sql)?.collect::<Result<_,_>>().map_err(sql)
    }

    fn claim(&self, now: u64) -> Result<Option<Delivery>, String> {
        let connection = self.lock()?;
        connection.transaction(|transaction| {
        transaction.execute("UPDATE deliveries SET status='expired',error='Deadline elapsed before execution' WHERE execution_id IS NULL AND status IN ('queued','preparing') AND deadline<=?1",params![now]).map_err(sql)?;
        let delivery = transaction.query_row("SELECT source,key,body,version,status,execution_id,error FROM deliveries d WHERE execution_id IS NULL AND status IN ('queued','preparing') AND not_before<=?1 AND NOT EXISTS (SELECT 1 FROM deliveries busy WHERE busy.workflow=d.workflow AND busy.execution_id IS NOT NULL AND busy.status IN ('preparing','running','paused','blocked')) ORDER BY not_before,rowid LIMIT 1", params![now],row).optional().map_err(sql)?;
        if let Some(delivery) = &delivery {
            transaction
                .execute(
                    "UPDATE deliveries SET status='preparing' WHERE source=?1 AND key=?2",
                    params![delivery.receipt.source, delivery.receipt.key],
                )
                .map_err(sql)?;
        }
        Ok(delivery)
        }).map_err(sql)
    }

    fn bind(&self, receipt: &TriggerReceipt, id: &str) -> Result<(), String> {
        let count = self.lock()?.execute("UPDATE deliveries SET execution_id=?1,status='running' WHERE source=?2 AND key=?3 AND execution_id IS NULL AND status='preparing'",params![id,receipt.source,receipt.key]).map_err(sql)?;
        if count == 1 {
            Ok(())
        } else {
            Err("Trigger binding lost ownership".into())
        }
    }

    fn finish(
        &self,
        receipt: &TriggerReceipt,
        status: &str,
        error: Option<&str>,
    ) -> Result<(), String> {
        self.lock()?
            .execute(
                "UPDATE deliveries SET status=?1,error=?2 WHERE source=?3 AND key=?4",
                params![status, error, receipt.source, receipt.key],
            )
            .map_err(sql)?;
        Ok(())
    }
}

fn row(row: &crate::database::Row) -> crate::database::Result<Delivery> {
    let body: String = row.get(2)?;
    let request: TriggerRequest = serde_json::from_str(&body)
        .map_err(|error| crate::database::Error::Message(error.to_string()))?;
    let receipt = TriggerReceipt {
        source: row.get(0)?,
        key: row.get(1)?,
        workflow: request.workflow.clone(),
        version: row.get(3)?,
        execution_id: row.get(5)?,
        status: row.get(4)?,
        error: row.get(6)?,
        not_before: request.not_before,
        deadline: request.deadline,
    };
    Ok(Delivery { request, receipt })
}

#[cfg(all(test, feature = "native", not(target_arch = "wasm32")))]
mod tests {
    use super::*;
    use multicast::cli::Cli;
    use multicast::command::{
        CommandContext, CommandDef, CommandHandler, McpAnnotations, McpCommandOptions,
    };
    use multicast::output::CommandResult;
    use serde_json::json;
    use std::sync::atomic::{AtomicUsize, Ordering};

    #[test]
    fn journal_mode_initialization_waits_for_a_concurrent_reader() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("queue.sqlite");
        let reader = rusqlite::Connection::open(&path).unwrap();
        reader
            .execute_batch("CREATE TABLE control (value INTEGER); BEGIN;")
            .unwrap();
        assert_eq!(
            reader
                .query_row("SELECT COUNT(*) FROM control", [], |row| row
                    .get::<_, i64>(0))
                .unwrap(),
            0
        );
        let (sender, receiver) = std::sync::mpsc::channel();
        let worker = std::thread::spawn(move || {
            let result = (|| {
                let connection = Connection::open(&path).map_err(sql)?;
                Queue::initialize(&connection)?;
                connection
                    .query_row("PRAGMA journal_mode", params![], |row| row.get::<String>(0))
                    .map_err(sql)
            })();
            sender.send(result).unwrap();
        });
        assert!(matches!(
            receiver.recv_timeout(Duration::from_millis(100)),
            Err(std::sync::mpsc::RecvTimeoutError::Timeout)
        ));
        reader.execute_batch("COMMIT").unwrap();
        assert_eq!(
            receiver
                .recv_timeout(Duration::from_secs(6))
                .unwrap()
                .unwrap(),
            "wal"
        );
        worker.join().unwrap();
    }

    struct Read(Arc<AtomicUsize>);
    #[async_trait::async_trait]
    impl CommandHandler for Read {
        async fn run(&self, _: CommandContext) -> CommandResult {
            self.0.fetch_add(1, Ordering::SeqCst);
            CommandResult::Ok {
                data: json!(73),
                cta: None,
                exit_code: None,
            }
        }
    }

    fn host(path: &Path, calls: &Arc<AtomicUsize>, code: &str) -> WorkflowTriggers {
        let cli = Cli::create("preparation").command(
            "observe",
            CommandDef::build("observe", Read(calls.clone()))
                .mcp(McpCommandOptions {
                    annotations: Some(McpAnnotations {
                        read_only_hint: Some(true),
                        ..Default::default()
                    }),
                    ..Default::default()
                })
                .done(),
        );
        crate::Workflows::new()
            .store_path(path)
            .shipped("job", "Observe", json!({"type":"object"}), code)
            .attach_with_triggers(cli)
            .unwrap()
            .1
    }

    fn request(key: &str) -> TriggerRequest {
        TriggerRequest {
            key: key.into(),
            workflow: "job".into(),
            input: json!({}),
            not_before: 0,
            deadline: now_ms().unwrap() + 30_000,
        }
    }

    #[tokio::test]
    async fn wakeups_cover_due_work_paused_deadlines_and_schedules_without_busy_polling() {
        let dir = tempfile::tempdir().unwrap();
        let calls = Arc::default();
        let host = host(
            &dir.path().join("state.sqlite"),
            &calls,
            "async () => preparation.observe({})",
        );
        assert_eq!(host.next_wake().unwrap(), None);
        let now = now_ms().unwrap();
        let mut first = request("first");
        first.not_before = now + 60_000;
        first.deadline = now + 120_000;
        host.enqueue(first.clone()).await.unwrap();
        assert_eq!(host.next_wake().unwrap(), Some(first.not_before));
        let queue = host.queue().unwrap();
        let claimed = queue.claim(first.not_before).unwrap().unwrap();
        queue.bind(&claimed.receipt, "bound-execution").unwrap();
        queue.finish(&claimed.receipt, "paused", None).unwrap();
        let mut second = request("second");
        second.deadline = now + 180_000;
        host.enqueue(second).await.unwrap();
        // The queued delivery cannot take the paused workflow's slot.
        assert_eq!(host.next_wake().unwrap(), Some(first.deadline));
        host.schedule(TriggerSchedule {
            id: "earlier".into(),
            workflow: "job".into(),
            input: json!({}),
            first_at: now + 30_000,
            every_ms: 60_000,
            deadline_ms: 10_000,
        })
        .await
        .unwrap();
        assert_eq!(host.next_wake().unwrap(), Some(now + 30_000));
        assert!(host.remove_schedule("earlier").unwrap());
        assert_eq!(host.next_wake().unwrap(), Some(first.deadline));
        queue.finish(&claimed.receipt, "cancelled", None).unwrap();
        let wake = host.next_wake().unwrap().unwrap();
        assert!(wake >= now && wake <= now_ms().unwrap());
        assert_eq!(calls.load(Ordering::SeqCst), 0);
    }

    #[tokio::test]
    async fn admission_rejects_invalid_keys_inputs_timestamps_and_payloads() {
        let dir = tempfile::tempdir().unwrap();
        let calls = Arc::default();
        let host = host(
            &dir.path().join("state.sqlite"),
            &calls,
            "async () => preparation.observe({})",
        );
        let mut invalid = vec![
            request(""),
            request(&"x".repeat(257)),
            request(&"é".repeat(129)),
        ];
        let mut input = request("invalid-input");
        input.input = Value::Null;
        invalid.push(input);
        let mut time = request("invalid-time");
        time.not_before = time.deadline;
        invalid.push(time);
        let mut overflow = request("overflow-time");
        overflow.deadline = u64::MAX;
        invalid.push(overflow);
        let mut large = request("oversized");
        large.input = json!({"payload":"x".repeat(1_048_576)});
        invalid.push(large);
        for request in invalid {
            let key = request.key.clone();
            assert!(host.enqueue(request).await.is_err(), "accepted {key}");
            assert!(
                host.receipt("webhook", &key).unwrap().is_none(),
                "persisted {key}"
            );
        }
        assert_eq!(calls.load(Ordering::SeqCst), 0);
        let accepted = request(&"é".repeat(128));
        assert_eq!(host.enqueue(accepted).await.unwrap().status, "queued");
        let mut accepted = request("large-valid");
        accepted.input = json!({"payload":"x".repeat(1_000_000)});
        assert_eq!(host.enqueue(accepted).await.unwrap().status, "queued");
        assert_eq!(calls.load(Ordering::SeqCst), 0);
    }

    #[tokio::test]
    async fn schedules_and_tick_limits_reject_invalid_values_before_delivery() {
        let dir = tempfile::tempdir().unwrap();
        let calls = Arc::default();
        let host = host(
            &dir.path().join("state.sqlite"),
            &calls,
            "async () => preparation.observe({})",
        );
        let valid = TriggerSchedule {
            id: "schedule".into(),
            workflow: "job".into(),
            input: json!({}),
            first_at: now_ms().unwrap() + 60_000,
            every_ms: 1000,
            deadline_ms: 500,
        };
        let mut zero_interval = valid.clone();
        zero_interval.every_ms = 0;
        let mut zero_deadline = valid.clone();
        zero_deadline.deadline_ms = 0;
        let mut overflow = valid.clone();
        overflow.first_at = i64::MAX as u64;
        let mut bad_input = valid.clone();
        bad_input.input = Value::Null;
        for schedule in [zero_interval, zero_deadline, overflow, bad_input] {
            assert!(host.schedule(schedule).await.is_err());
        }
        assert!(!host.remove_schedule("schedule").unwrap());
        assert!(host.tick(0).await.is_err());
        assert!(host.tick(101).await.is_err());
        host.schedule(valid).await.unwrap();
        assert!(host.tick(100).await.unwrap().is_empty());
        assert_eq!(calls.load(Ordering::SeqCst), 0);
    }

    #[tokio::test]
    async fn preparation_has_no_effects_and_binding_reuses_the_same_execution() {
        let dir = tempfile::tempdir().unwrap();
        let calls = Arc::default();
        let host = host(
            &dir.path().join("state.sqlite"),
            &calls,
            "async () => preparation.observe({})",
        );
        host.enqueue(request("bound-window")).await.unwrap();
        let delivery = host
            .queue()
            .unwrap()
            .claim(now_ms().unwrap())
            .unwrap()
            .unwrap();
        let workflow = host.state.resolve("job").await.unwrap().unwrap();
        let (_, code) = program(&workflow, json!({})).unwrap();
        let prepared = host
            .state
            .service()
            .await
            .unwrap()
            .prepare(code)
            .await
            .unwrap();
        assert_eq!(prepared.status, ExecutionStatus::Running);
        assert!(prepared.log.is_empty());
        assert_eq!(calls.load(Ordering::SeqCst), 0);
        host.queue()
            .unwrap()
            .bind(&delivery.receipt, &prepared.id)
            .unwrap();
        let receipts = host.tick(1).await.unwrap();
        assert_eq!(
            receipts[0].execution_id.as_deref(),
            Some(prepared.id.as_str())
        );
        assert_eq!(receipts[0].status, "completed");
        assert_eq!(calls.load(Ordering::SeqCst), 1);
        host.tick(1).await.unwrap();
        assert_eq!(calls.load(Ordering::SeqCst), 1);
    }

    #[tokio::test]
    async fn abandoned_unbound_preparation_is_safe_to_replace() {
        let dir = tempfile::tempdir().unwrap();
        let calls = Arc::default();
        let host = host(
            &dir.path().join("state.sqlite"),
            &calls,
            "async () => preparation.observe({})",
        );
        host.enqueue(request("unbound-window")).await.unwrap();
        host.queue()
            .unwrap()
            .claim(now_ms().unwrap())
            .unwrap()
            .unwrap();
        let orphan = host
            .state
            .service()
            .await
            .unwrap()
            .prepare("async () => preparation.observe({})".into())
            .await
            .unwrap();
        assert_eq!(calls.load(Ordering::SeqCst), 0);
        let receipts = host.tick(1).await.unwrap();
        assert_eq!(receipts[0].status, "completed");
        assert_ne!(
            receipts[0].execution_id.as_deref(),
            Some(orphan.id.as_str())
        );
        assert_eq!(calls.load(Ordering::SeqCst), 1);
        assert!(
            host.state
                .service()
                .await
                .unwrap()
                .execution(orphan.id)
                .await
                .unwrap()
                .log
                .is_empty()
        );
    }

    #[tokio::test]
    async fn changed_program_blocks_before_a_new_execution() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("state.sqlite");
        let calls = Arc::default();
        let old = host(&path, &calls, "async () => preparation.observe({})");
        old.enqueue(request("version")).await.unwrap();
        drop(old);
        let new = host(
            &path,
            &calls,
            "async () => { await preparation.observe({}); return 74; }",
        );
        let receipts = new.tick(1).await.unwrap();
        assert_eq!(receipts[0].status, "blocked");
        assert!(receipts[0].execution_id.is_none());
        assert_eq!(calls.load(Ordering::SeqCst), 0);
    }

    #[tokio::test]
    async fn missing_bound_execution_blocks_without_a_replacement() {
        let dir = tempfile::tempdir().unwrap();
        let calls = Arc::default();
        let host = host(
            &dir.path().join("state.sqlite"),
            &calls,
            "async () => preparation.observe({})",
        );
        host.enqueue(request("missing")).await.unwrap();
        let delivery = host
            .queue()
            .unwrap()
            .claim(now_ms().unwrap())
            .unwrap()
            .unwrap();
        host.queue()
            .unwrap()
            .bind(&delivery.receipt, "missing-execution")
            .unwrap();
        let receipts = host.tick(1).await.unwrap();
        assert_eq!(receipts[0].status, "blocked");
        assert_eq!(
            receipts[0].execution_id.as_deref(),
            Some("missing-execution")
        );
        assert_eq!(calls.load(Ordering::SeqCst), 0);
        host.enqueue(request("after-missing")).await.unwrap();
        let refreshed = host.tick(1).await.unwrap();
        assert_eq!(refreshed.len(), 1);
        assert_eq!(refreshed[0].key, "missing");
        assert_eq!(refreshed[0].status, "blocked");
        assert_eq!(
            host.receipt("webhook", "after-missing")
                .unwrap()
                .unwrap()
                .status,
            "queued"
        );
        assert_eq!(calls.load(Ordering::SeqCst), 0);
    }
}