apoc 0.9.1

Agentic process control for LLMs
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
//! Stale-state cleanup shared by the daemon's periodic pass and `apoc gc`.
//!
//! One pass closes orphaned executions, reports or stops unowned background
//! work whose lifetime elapsed, and deletes terminal history past retention.
//! A dry run reads only. Isolated daemons also exit once they sit idle.
use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};

use super::*;

/// Default period of the daemon's cleanup pass: ten minutes.
pub const DEFAULT_GC_INTERVAL_MS: u64 = 10 * 60 * 1_000;
/// Default age after which terminal history is deleted.
pub const DEFAULT_GC_RETENTION_DAYS: u64 = 30;
/// Default lifetime of an unowned background execution since its last touch.
pub const DEFAULT_UNOWNED_LIFETIME_MS: u64 = 24 * 60 * 60 * 1_000;
/// Default idle time before an isolated daemon exits: thirty minutes.
pub const DEFAULT_IDLE_EXIT_MS: u64 = 30 * 60 * 1_000;

const ORPHAN_GRACE_MS: u64 = 60_000;
const BATCH: usize = 200;
const DEFAULT_MAX_BATCHES: usize = 50;
const SAMPLE: usize = 10;
const COUNT_CAP: usize = 10_000;
const RECLAIM_PAGES: u64 = 16_384;
const DAY_MS: u64 = 24 * 60 * 60 * 1_000;

/// What the cleanup pass does with unowned background executions whose
/// lifetime elapsed.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum UnownedPolicy {
    /// List them without acting.
    #[default]
    Report,
    /// Cancel them through typed cancellation with `EXECUTION_EXPIRED`.
    Stop,
    /// Skip the check.
    Off,
}

/// Cleanup configuration resolved once when the daemon opens.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct GcConfig {
    /// Period of the background pass; zero disables it.
    pub interval_ms: u64,
    /// Age in days after which terminal history is deleted; zero disables it.
    pub retention_days: u64,
    /// Handling of expired unowned background executions.
    pub unowned: UnownedPolicy,
    /// Default lifetime of an unowned background execution.
    pub unowned_lifetime_ms: u64,
    /// Time a nonterminal execution must sit untouched before it can be an orphan.
    pub orphan_grace_ms: u64,
    /// Retention batches one pass may delete, per category.
    pub max_batches: usize,
}

impl Default for GcConfig {
    fn default() -> Self {
        Self {
            interval_ms: DEFAULT_GC_INTERVAL_MS,
            retention_days: DEFAULT_GC_RETENTION_DAYS,
            unowned: UnownedPolicy::Report,
            unowned_lifetime_ms: DEFAULT_UNOWNED_LIFETIME_MS,
            orphan_grace_ms: ORPHAN_GRACE_MS,
            max_batches: DEFAULT_MAX_BATCHES,
        }
    }
}

fn env_u64(name: &str, default: u64) -> u64 {
    match std::env::var(name) {
        Ok(value) => value.trim().parse().unwrap_or_else(|_| {
            eprintln!("[apoc] ignoring {name}={value:?}: expected a non-negative integer");
            default
        }),
        Err(_) => default,
    }
}

impl GcConfig {
    /// Reads `APOC_GC_INTERVAL_MS`, `APOC_GC_RETENTION_DAYS`, and
    /// `APOC_GC_UNOWNED`. An invalid value keeps its default and is reported
    /// on the daemon log instead of preventing startup.
    pub fn from_env() -> Self {
        let defaults = Self::default();
        let unowned = match std::env::var("APOC_GC_UNOWNED") {
            Ok(value) => match value.trim() {
                "report" => UnownedPolicy::Report,
                "stop" => UnownedPolicy::Stop,
                "off" => UnownedPolicy::Off,
                other => {
                    eprintln!(
                        "[apoc] ignoring APOC_GC_UNOWNED={other:?}: expected report, stop, or off"
                    );
                    defaults.unowned
                }
            },
            Err(_) => defaults.unowned,
        };
        Self {
            interval_ms: env_u64("APOC_GC_INTERVAL_MS", defaults.interval_ms),
            retention_days: env_u64("APOC_GC_RETENTION_DAYS", defaults.retention_days),
            orphan_grace_ms: env_u64("APOC_GC_ORPHAN_GRACE_MS", defaults.orphan_grace_ms),
            unowned_lifetime_ms: match env_u64(
                "APOC_GC_UNOWNED_LIFETIME_MS",
                defaults.unowned_lifetime_ms,
            ) {
                0 => defaults.unowned_lifetime_ms,
                value => value,
            },
            unowned,
            ..defaults
        }
    }
}

/// Reads `APOC_DAEMON_IDLE_EXIT_MS`; zero disables idle exit.
pub fn idle_exit_ms_from_env() -> u64 {
    env_u64("APOC_DAEMON_IDLE_EXIT_MS", DEFAULT_IDLE_EXIT_MS)
}

/// Whether `config` names anything other than the per-user default state and
/// socket. Only such a daemon may exit on its own; the default never does.
pub fn is_isolated(config: &CoreConfig) -> bool {
    let default_state = dirs::data_dir().map(|path| path.join("apoc"));
    let default_runtime = std::env::temp_dir().join(format!("apoc-{}", unsafe { libc::geteuid() }));
    default_state.as_ref() != Some(&config.state_dir) || config.runtime_dir != default_runtime
}

/// Findings and actions for one cleanup category.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct GcCategory {
    /// Matching records found, at most the count cap.
    pub found: usize,
    /// Whether more records matched than were counted.
    pub capped: bool,
    /// Records this pass acted on; zero for a dry run.
    pub acted: usize,
    /// Bounded sample of matching identifiers.
    pub sample: Vec<String>,
}

/// Database space after a cleanup pass.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct GcSpace {
    /// SQLite auto-vacuum mode: none, full, or incremental.
    pub auto_vacuum: String,
    /// Free pages SQLite reuses before it grows the file.
    pub freelist_pages: u64,
    /// Pages returned to the operating system by this pass.
    pub reclaimed_pages: u64,
}

/// Result of one cleanup pass.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct GcReport {
    /// Whether the pass acted; a dry run changes nothing.
    pub applied: bool,
    /// Pass start in Unix milliseconds.
    pub started_at: u64,
    /// Pass completion in Unix milliseconds.
    pub completed_at: u64,
    /// Retention age in days; zero means retention is disabled.
    pub retention_days: u64,
    /// Handling of expired unowned background executions.
    pub unowned_policy: UnownedPolicy,
    /// Nonterminal executions whose processes or supervisor are gone.
    pub orphans: GcCategory,
    /// Unowned background executions untouched past their lifetime.
    pub unowned_expired: GcCategory,
    /// Terminal executions past retention, deleted with dependent rows.
    pub executions: GcCategory,
    /// Terminal invocation records past retention.
    pub invocations: GcCategory,
    /// Process events past retention that belong to no execution.
    pub process_events: GcCategory,
    /// Database space bookkeeping.
    pub space: GcSpace,
}

/// Per-category counts reported by daemon status.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct GcCounts {
    /// Orphaned executions.
    pub orphans: usize,
    /// Expired unowned background executions.
    pub unowned_expired: usize,
    /// Executions past retention.
    pub executions: usize,
    /// Invocation records past retention.
    pub invocations: usize,
    /// Unowned process events past retention.
    pub process_events: usize,
}

/// Cleanup state reported by daemon status, kept in memory.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct GcStatus {
    /// Period of the background pass; zero means it is disabled.
    pub interval_ms: u64,
    /// Retention age in days; zero means retention is disabled.
    pub retention_days: u64,
    /// Handling of expired unowned background executions.
    pub unowned_policy: UnownedPolicy,
    /// Applied passes since the daemon started.
    pub passes: u64,
    /// Completion of the last applied pass in Unix milliseconds.
    pub last_completed_at: Option<u64>,
    /// Error from the last applied pass, if it failed.
    pub last_error: Option<String>,
    /// Records the last applied pass acted on.
    pub last: GcCounts,
    /// Records the last applied pass found but left in place.
    pub pending: GcCounts,
}

#[derive(Serialize, Deserialize)]
pub(super) struct GcReplay {
    fingerprint: String,
    report: Option<GcReport>,
}

#[derive(Deserialize)]
pub(super) struct GcParams {
    #[serde(default)]
    apply: bool,
    #[serde(default)]
    idempotency_key: Option<String>,
    #[serde(default)]
    max_batches: Option<usize>,
}

/// Counts open RPC connections and the last moment the daemon was busy.
#[derive(Clone)]
pub(super) struct Activity {
    connections: Arc<AtomicUsize>,
    last_active_at: Arc<AtomicU64>,
}

impl Activity {
    pub(super) fn new(at: u64) -> Self {
        Self {
            connections: Arc::new(AtomicUsize::new(0)),
            last_active_at: Arc::new(AtomicU64::new(at)),
        }
    }

    /// Marks one connection open until the returned guard drops.
    pub(super) fn connection(&self) -> ConnectionGuard {
        self.connections.fetch_add(1, Ordering::AcqRel);
        self.last_active_at.store(now_ms(), Ordering::Release);
        ConnectionGuard(self.clone())
    }
}

pub(super) struct ConnectionGuard(Activity);

impl Drop for ConnectionGuard {
    fn drop(&mut self) {
        self.0.last_active_at.store(now_ms(), Ordering::Release);
        self.0.connections.fetch_sub(1, Ordering::AcqRel);
    }
}

fn sample<I: IntoIterator<Item = String>>(ids: I) -> Vec<String> {
    ids.into_iter().take(SAMPLE).collect()
}

impl Daemon {
    /// Runs one cleanup pass. With `apply` false it only reads.
    pub(crate) async fn collect_garbage(
        &self,
        apply: bool,
        config: &GcConfig,
        controller: &ProcessController,
    ) -> Result<GcReport, String> {
        let _pass = self.gc_lock.lock().await;
        let started_at = now_ms();
        let budget = BATCH.saturating_mul(config.max_batches.max(1));

        let mut orphans = self
            .executions
            .reconcile_orphans(apply, config.orphan_grace_ms, budget)
            .await?;
        let idle_before = now_ms().saturating_sub(config.orphan_grace_ms);
        let code = self
            .reconcile_code_orphans(
                apply,
                idle_before,
                budget.saturating_sub(orphans.len()),
                controller,
            )
            .await?;
        orphans.extend(code);
        let owned = self
            .reconcile_owner_orphans(
                apply,
                idle_before,
                budget.saturating_sub(orphans.len()),
                controller,
            )
            .await?;
        orphans.extend(owned);
        let orphans = GcCategory {
            found: orphans.len(),
            capped: orphans.len() >= budget,
            acted: if apply { orphans.len() } else { 0 },
            sample: sample(
                orphans
                    .into_iter()
                    .map(|(id, cause)| format!("{id} {cause}")),
            ),
        };

        let mut unowned_expired = GcCategory::default();
        if config.unowned != UnownedPolicy::Off {
            let (expired, found, capped) =
                self.store.expired_lifetimes(now_ms(), budget, COUNT_CAP)?;
            unowned_expired.found = found;
            unowned_expired.capped = capped;
            unowned_expired.sample = sample(expired.iter().map(|item| item.id.clone()));
            if apply && config.unowned == UnownedPolicy::Stop {
                for item in expired {
                    // A caller may have touched it since the query; decide on
                    // the current lifetime, not the listed one.
                    let Some((Some(lifetime_ms), touched_at)) =
                        self.store.execution_lifetime(&item.id)?
                    else {
                        continue;
                    };
                    let now = now_ms();
                    if touched_at.saturating_add(lifetime_ms) > now {
                        continue;
                    }
                    self.polls.notify_cancel(&item.id)?;
                    let details = serde_json::json!({
                        "lifetime_ms": lifetime_ms,
                        "last_touched_at": touched_at,
                        "expired_at": now
                    });
                    match Box::pin(self.executions.expire(
                        &item.id,
                        details,
                        Duration::from_secs(5),
                        controller,
                    ))
                    .await
                    {
                        Ok(_) => unowned_expired.acted += 1,
                        Err(error) => {
                            tracing::warn!(id = %item.id, error = %error, "could not stop an expired execution");
                        }
                    }
                }
            }
        }

        let mut executions = GcCategory::default();
        let mut invocations = GcCategory::default();
        let mut process_events = GcCategory::default();
        if config.retention_days > 0 {
            let cutoff = now_ms().saturating_sub(config.retention_days.saturating_mul(DAY_MS));
            (executions.found, executions.capped) =
                self.store.count_retention_executions(cutoff, COUNT_CAP)?;
            executions.sample = sample(self.store.retention_execution_candidates(cutoff, SAMPLE)?);
            (invocations.found, invocations.capped) =
                self.store.count_retention_invocations(cutoff, COUNT_CAP)?;
            invocations.sample =
                sample(self.store.retention_invocation_candidates(cutoff, SAMPLE)?);
            (process_events.found, process_events.capped) = self
                .store
                .count_retention_process_events(cutoff, COUNT_CAP)?;
            process_events.sample = sample(
                self.store
                    .retention_process_event_candidates(cutoff, SAMPLE)?,
            );
            if apply {
                let runs = self
                    .store
                    .path()
                    .parent()
                    .unwrap_or_else(|| Path::new("."))
                    .join("runs");
                for _ in 0..config.max_batches.max(1) {
                    let ids = self.store.retention_execution_candidates(cutoff, BATCH)?;
                    if ids.is_empty() {
                        break;
                    }
                    let deleted = self.store.delete_execution_history(&ids)?;
                    executions.acted += deleted.executions;
                    for id in &ids {
                        let directory = runs.join(id);
                        if directory.exists()
                            && let Err(error) = std::fs::remove_dir_all(&directory)
                        {
                            tracing::warn!(path = %directory.display(), error = %error, "could not remove retained run logs");
                        }
                    }
                    if deleted.executions == 0 {
                        break;
                    }
                    tokio::task::yield_now().await;
                }
                for _ in 0..config.max_batches.max(1) {
                    let ids = self.store.retention_invocation_candidates(cutoff, BATCH)?;
                    if ids.is_empty() {
                        break;
                    }
                    let deleted = self.store.delete_invocations(&ids)?;
                    invocations.acted += deleted;
                    if deleted == 0 {
                        break;
                    }
                    tokio::task::yield_now().await;
                }
                for _ in 0..config.max_batches.max(1) {
                    let ids = self
                        .store
                        .retention_process_event_candidates(cutoff, BATCH)?;
                    if ids.is_empty() {
                        break;
                    }
                    let deleted = self.store.delete_process_events(&ids)?;
                    process_events.acted += deleted;
                    if deleted == 0 {
                        break;
                    }
                    tokio::task::yield_now().await;
                }
            }
        }
        let reclaimed = self
            .store
            .reclaim_space(if apply { RECLAIM_PAGES } else { 0 })?;
        let report = GcReport {
            applied: apply,
            started_at,
            completed_at: now_ms(),
            retention_days: config.retention_days,
            unowned_policy: config.unowned,
            orphans,
            unowned_expired,
            executions,
            invocations,
            process_events,
            space: GcSpace {
                auto_vacuum: reclaimed.auto_vacuum,
                freelist_pages: reclaimed.freelist_pages,
                reclaimed_pages: reclaimed.reclaimed_pages,
            },
        };
        if apply {
            self.record_gc(Ok(&report));
        }
        Ok(report)
    }

    /// Closes Code Mode programs that no actor of this daemon owns any longer,
    /// because the actor was replaced or lost, so nothing will ever advance or
    /// finish them. A program the store already records as finished is only
    /// synchronized, truthfully.
    async fn reconcile_code_orphans(
        &self,
        apply: bool,
        idle_before: u64,
        limit: usize,
        controller: &ProcessController,
    ) -> Result<Vec<(String, &'static str)>, String> {
        let mut found = Vec::new();
        for record in self.store.recoverable_execution_records()? {
            if found.len() >= limit {
                break;
            }
            if !matches!(record.spec.program, ExecutionProgram::Javascript { .. })
                || record.updated_at >= idle_before
            {
                continue;
            }
            let state = self.code.read().await.get(record.id.clone()).await.ok();
            if let Some(state) = state.filter(|state| code_terminal(state.status)) {
                if apply {
                    self.record_code_execution(&state, controller, None, None, None)?;
                }
                found.push((record.id, "terminal_program_unsynchronized"));
                continue;
            }
            if self.code.read().await.owns(&record.id).await {
                continue;
            }
            let id = record.id.clone();
            if apply {
                self.close_code_orphan(record, controller).await?;
            }
            found.push((id, "code_actor_lost"));
        }
        Ok(found)
    }

    /// Cancels the program's execution-owned children through typed
    /// cancellation, then fails the program with `EXECUTION_INTERRUPTED`,
    /// never `completed`, and releases its lease.
    async fn close_code_orphan(
        &self,
        mut record: crate::model::Execution,
        controller: &ProcessController,
    ) -> Result<(), String> {
        let details = serde_json::json!({ "cause": "code_actor_lost", "owner_id": record.id });
        for child in self.store.execution_children(&record.id)? {
            if child.spec.owner_kind != LeaseOwnerKind::Execution
                || matches!(
                    child.status,
                    ExecutionStatus::Completed
                        | ExecutionStatus::Failed
                        | ExecutionStatus::Canceled
                )
            {
                continue;
            }
            self.polls.notify_cancel(&child.id)?;
            Box::pin(self.executions.cancel_with_cause(
                &child.id,
                "EXECUTION_OWNER_GONE",
                "execution.owner_gone",
                details.clone(),
                Duration::from_secs(5),
                controller,
            ))
            .await?;
        }
        self.store.interrupt_code_execution(
            &record.id,
            "INTERRUPTED: no Code Mode actor owns this program any longer",
        )?;
        let now = now_ms();
        record.status = ExecutionStatus::Failed;
        record.updated_at = now;
        for pass in &mut record.passes {
            if pass.completed_at.is_none() {
                pass.completed_at = Some(now);
                pass.status = ExecutionStatus::Failed;
                pass.error_code = Some("EXECUTION_INTERRUPTED".to_string());
            }
        }
        record.result = Some(serde_json::json!({
            "error_code": "EXECUTION_INTERRUPTED",
            "error": "No Code Mode actor owns this program any longer, so it cannot finish",
            "cause": "code_actor_lost"
        }));
        self.store.put_execution_record(&record)?;
        self.store
            .release_lease(&format!("execution/{}", record.id))?;
        self.lifecycle_event(
            "execution.failed",
            &format!("execution/{}", record.id),
            controller,
            Some(record.id.clone()),
            None,
            record.result.clone().unwrap_or_default(),
        )?;
        Ok(())
    }

    /// Cancels nonterminal work whose owning execution finished or vanished,
    /// or whose owning session closed or expired, through typed cancellation
    /// with `EXECUTION_OWNER_GONE`.
    async fn reconcile_owner_orphans(
        &self,
        apply: bool,
        idle_before: u64,
        limit: usize,
        controller: &ProcessController,
    ) -> Result<Vec<(String, &'static str)>, String> {
        let found = self.executions.owner_orphans(idle_before, limit)?;
        if apply {
            for (id, cause) in &found {
                self.polls.notify_cancel(id)?;
                Box::pin(self.executions.cancel_with_cause(
                    id,
                    "EXECUTION_OWNER_GONE",
                    "execution.owner_gone",
                    serde_json::json!({ "cause": cause }),
                    Duration::from_secs(5),
                    controller,
                ))
                .await?;
            }
        }
        Ok(found)
    }

    fn record_gc(&self, outcome: Result<&GcReport, &str>) {
        let Ok(mut status) = self.gc_status.lock() else {
            return;
        };
        status.passes += 1;
        status.last_completed_at = Some(now_ms());
        match outcome {
            Ok(report) => {
                let counts = |pick: fn(&GcCategory) -> usize| GcCounts {
                    orphans: pick(&report.orphans),
                    unowned_expired: pick(&report.unowned_expired),
                    executions: pick(&report.executions),
                    invocations: pick(&report.invocations),
                    process_events: pick(&report.process_events),
                };
                status.last_error = None;
                status.last = counts(|category| category.acted);
                status.pending = counts(|category| category.found.saturating_sub(category.acted));
            }
            Err(error) => status.last_error = Some(error.to_string()),
        }
    }

    /// Snapshot of cleanup state for daemon status. Reads memory only.
    pub(super) fn gc_status(&self) -> Option<GcStatus> {
        self.gc_status.lock().ok().map(|status| status.clone())
    }

    /// Answers `apoc gc`: a dry run reads only; `apply` needs an idempotency
    /// key, and a repeated key returns the recorded report.
    pub(super) async fn gc_command(
        &self,
        params: Value,
        controller: &ProcessController,
    ) -> Result<GcReport, String> {
        let params = parse::<GcParams>(params)?;
        let mut config = self.gc_config.clone();
        if let Some(max_batches) = params.max_batches {
            if max_batches == 0 {
                return Err("GC_INVALID_LIMIT: max_batches must be at least 1".to_string());
            }
            config.max_batches = max_batches;
        }
        if !params.apply {
            return self.collect_garbage(false, &config, controller).await;
        }
        let key = params
            .idempotency_key
            .filter(|key| !key.trim().is_empty())
            .ok_or_else(|| {
                "GC_IDEMPOTENCY_KEY_REQUIRED: gc --apply requires an idempotency key".to_string()
            })?;
        let fingerprint = format!(
            "sha256:{:x}",
            Sha256::digest(
                serde_json::to_vec(&("gc", config.max_batches))
                    .map_err(|error| error.to_string())?
            )
        );
        let receipt = format!("gc:{key}");
        let intent = GcReplay {
            fingerprint: fingerprint.clone(),
            report: None,
        };
        if let Some(replay) = self.store.claim_receipt(&receipt, "gc", &intent)? {
            if replay.fingerprint != fingerprint {
                return Err(format!(
                    "GC_IDEMPOTENCY_CONFLICT: key \"{key}\" was already used for a different request"
                ));
            }
            if let Some(report) = replay.report {
                return Ok(report);
            }
            // Durable intent without a report means the earlier pass stopped
            // before recording it. Every step of a pass is idempotent, so the
            // pass runs again under the same key.
        }
        let report = self.collect_garbage(true, &config, controller).await;
        let report = match report {
            Ok(report) => report,
            Err(error) => {
                self.record_gc(Err(&error));
                return Err(error);
            }
        };
        self.store.put_receipt(
            &receipt,
            "gc",
            &GcReplay {
                fingerprint,
                report: Some(report.clone()),
            },
        )?;
        Ok(report)
    }

    /// Restarts the lifetime of an unowned background execution after a
    /// caller observed or drove it. Failing to record a touch never fails the
    /// caller's request.
    pub(super) fn touch_execution(&self, id: &str) {
        if let Err(error) = self.store.touch_execution(id, now_ms()) {
            tracing::warn!(id = %id, error = %error, "could not record an execution touch");
        }
    }

    /// Records the lifetime of a background execution that no execution or
    /// session owns.
    pub(super) fn register_unowned_lifetime(
        &self,
        execution: &crate::model::Execution,
        keep_alive: bool,
        lifetime_ms: Option<u64>,
    ) -> Result<(), String> {
        if execution.parent_id.is_some() || execution.session_id.is_some() {
            return Ok(());
        }
        let lifetime =
            (!keep_alive).then(|| lifetime_ms.unwrap_or(self.gc_config.unowned_lifetime_ms));
        self.store
            .register_execution_lifetime(&execution.id, lifetime, execution.created_at)
    }

    /// Runs the cleanup pass every configured interval until shutdown.
    pub(crate) fn spawn_gc(daemon: &Arc<Daemon>) -> Option<tokio::task::JoinHandle<()>> {
        let period = daemon.gc_config.interval_ms;
        if period == 0 {
            return None;
        }
        let daemon = Arc::clone(daemon);
        Some(tokio::spawn(async move {
            let period = Duration::from_millis(period);
            let mut ticks = tokio::time::interval_at(tokio::time::Instant::now() + period, period);
            ticks.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
            let controller = default_controller();
            loop {
                tokio::select! {
                    _ = daemon.shutdown.cancelled() => break,
                    _ = ticks.tick() => {
                        let config = daemon.gc_config.clone();
                        if let Err(error) = daemon.collect_garbage(true, &config, &controller).await {
                            tracing::warn!(error = %error, "cleanup pass failed");
                            daemon.record_gc(Err(&error));
                        }
                    }
                }
            }
        }))
    }

    /// Stops an isolated daemon once its state root is deleted, or once it
    /// has had no connected client and no nonterminal work for the idle
    /// period. The per-user default daemon never stops on its own.
    pub(crate) fn spawn_idle_exit(daemon: &Arc<Daemon>) -> Option<tokio::task::JoinHandle<()>> {
        if !daemon.isolated {
            return None;
        }
        let idle_ms = daemon.idle_exit_ms;
        let daemon = Arc::clone(daemon);
        let tick = Duration::from_millis(if idle_ms == 0 {
            500
        } else {
            (idle_ms / 4).clamp(50, 1_000)
        });
        Some(tokio::spawn(async move {
            loop {
                tokio::select! {
                    _ = daemon.shutdown.cancelled() => break,
                    _ = tokio::time::sleep(tick) => {}
                }
                if !daemon.state_dir.exists() {
                    eprintln!(
                        "[apoc] state directory {} was removed; exiting",
                        daemon.state_dir.display()
                    );
                    daemon.shutdown.cancel();
                    break;
                }
                if idle_ms == 0 {
                    continue;
                }
                let now = now_ms();
                if daemon.busy() {
                    daemon.activity.last_active_at.store(now, Ordering::Release);
                    continue;
                }
                let idle_for =
                    now.saturating_sub(daemon.activity.last_active_at.load(Ordering::Acquire));
                if idle_for >= idle_ms {
                    eprintln!("[apoc] isolated daemon idle for {idle_for} ms; exiting");
                    daemon.shutdown.cancel();
                    break;
                }
            }
        }))
    }

    /// Whether a client is connected or any work is nonterminal. A failed
    /// read counts as busy, so an error never causes an exit.
    fn busy(&self) -> bool {
        self.activity.connections.load(Ordering::Acquire) > 0
            || !matches!(self.store.active_execution_count(), Ok(0))
            || !matches!(self.store.running_code_execution_count(), Ok(0))
            || !matches!(self.store.running_hook_delivery_count(), Ok(0))
    }
}

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

    #[test]
    fn only_a_non_default_state_or_socket_is_isolated() {
        let default_state = dirs::data_dir().unwrap().join("apoc");
        let default_runtime =
            std::env::temp_dir().join(format!("apoc-{}", unsafe { libc::geteuid() }));
        let default = CoreConfig {
            state_dir: default_state.clone(),
            runtime_dir: default_runtime.clone(),
        };
        assert!(!is_isolated(&default));
        assert!(is_isolated(&CoreConfig {
            state_dir: default_state.join("elsewhere"),
            runtime_dir: default_runtime.clone(),
        }));
        assert!(is_isolated(&CoreConfig {
            state_dir: default_state,
            runtime_dir: default_runtime.join("elsewhere"),
        }));
    }
}