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
//! Durable lifetime bookkeeping and bounded retention of stale history.
//!
//! Every query here is bounded by a caller limit and every deletion runs in one
//! short transaction that takes SQLite write intent before it reads, so a
//! cleanup pass never holds the shared connection for long and never upgrades
//! a deferred read under competing writers.
use super::*;

/// Label that exempts an execution, its children, and its invocations from
/// history retention. Its value must be exactly `true`.
pub const KEEP_LABEL: &str = "apoc.keep";

const TERMINAL_LISTING: &str = "('completed', 'failed', 'canceled')";
const ACTIVE_LISTING: &str = "('queued', 'running', 'stalled', 'interrupted')";

/// Rows removed by one retention batch.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct RetentionDeleted {
    pub executions: usize,
    pub events: usize,
    pub payloads: usize,
    pub process_events: usize,
    pub invocations: usize,
    pub observations: usize,
    pub leases: usize,
}

/// One unowned background execution whose lifetime elapsed.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ExpiredLifetime {
    pub id: String,
    pub touched_at: u64,
    pub lifetime_ms: u64,
}

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

pub(super) fn migrate(connection: &Connection) -> Result<(), String> {
    connection
        .execute_batch(
            "CREATE TABLE IF NOT EXISTS execution_lifetimes (
                id TEXT PRIMARY KEY,
                lifetime_ms INTEGER,
                touched_at INTEGER NOT NULL
            );",
        )
        .map_err(|error| error.to_string())
}

fn keep_check(alias: &str) -> String {
    // COALESCE keeps an absent label false rather than NULL, which `NOT`
    // would otherwise turn into a row silently excluded from retention.
    format!("COALESCE(json_extract({alias}.value, '$.spec.labels.\"{KEEP_LABEL}\"') = 'true', 0)")
}

fn retention_execution_sql() -> String {
    let kept_self = keep_check("e");
    let kept_parent = keep_check("p");
    let kept_child = keep_check("ce");
    format!(
        "SELECT l.id FROM execution_listing l
         JOIN execution_records e ON e.id = l.id
         WHERE l.updated_at < ?1 AND l.status IN {TERMINAL_LISTING}
           AND NOT ({kept_self})
           AND NOT EXISTS (
               SELECT 1 FROM execution_records p
               WHERE p.id = e.parent_id AND {kept_parent}
           )
           AND NOT EXISTS (
               SELECT 1 FROM execution_listing pl
               WHERE pl.id = e.parent_id
                 AND (pl.status NOT IN {TERMINAL_LISTING} OR pl.updated_at >= ?1)
           )
           AND NOT EXISTS (
               SELECT 1 FROM execution_listing c
               JOIN execution_records ce ON ce.id = c.id
               WHERE c.parent_id = l.id
                 AND (c.status NOT IN {TERMINAL_LISTING} OR c.updated_at >= ?1 OR {kept_child})
           )
         ORDER BY l.updated_at ASC, l.id ASC
         LIMIT ?2"
    )
}

const RETENTION_INVOCATION_SQL: &str = "SELECT id FROM invocations
     WHERE updated_at < ?1 AND status != 'running' AND recording_id IS NULL
       AND (execution_id IS NULL OR NOT EXISTS (
           SELECT 1 FROM execution_records r WHERE r.id = invocations.execution_id
       ))
     ORDER BY updated_at ASC, id ASC
     LIMIT ?2";

const RETENTION_PROCESS_EVENT_SQL: &str = "SELECT id FROM process_events
     WHERE at < ?1 AND execution_id IS NULL AND run_id IS NULL
     ORDER BY at ASC
     LIMIT ?2";

fn ids(
    connection: &Connection,
    sql: &str,
    cutoff: u64,
    limit: usize,
) -> Result<Vec<String>, String> {
    let mut statement = connection.prepare(sql).map_err(|error| error.to_string())?;
    statement
        .query_map(
            params![as_i64(cutoff), limit.min(i64::MAX as usize) as i64],
            |row| row.get::<_, String>(0),
        )
        .map_err(|error| error.to_string())?
        .collect::<Result<Vec<_>, _>>()
        .map_err(|error| error.to_string())
}

fn capped_count(
    connection: &Connection,
    sql: &str,
    cutoff: u64,
    cap: usize,
) -> Result<(usize, bool), String> {
    let count = connection
        .query_row(
            &format!("SELECT COUNT(*) FROM ({sql})"),
            params![
                as_i64(cutoff),
                cap.saturating_add(1).min(i64::MAX as usize) as i64
            ],
            |row| row.get::<_, i64>(0),
        )
        .map_err(|error| error.to_string())?
        .max(0) as usize;
    Ok((count.min(cap), count > cap))
}

fn delete_invocation(transaction: &rusqlite::Transaction<'_>, id: &str) -> Result<usize, String> {
    // The invocation delete trigger appends a tombstone version, which stays so
    // a resuming observer still learns the row is gone. Only the superseded
    // live versions are removed.
    transaction
        .execute("DELETE FROM invocations WHERE id = ?1", [id])
        .map_err(|error| error.to_string())?;
    transaction
        .execute(
            "DELETE FROM observation_versions WHERE id = ?1 AND deleted = 0",
            [format!("invocation:{id}")],
        )
        .map_err(|error| error.to_string())
}

impl Store {
    /// Records the lifetime of one unowned background execution. `None` keeps
    /// it alive until it ends or is canceled. A replayed start keeps the
    /// lifetime first recorded.
    pub fn register_execution_lifetime(
        &self,
        id: &str,
        lifetime_ms: Option<u64>,
        at: u64,
    ) -> Result<(), String> {
        self.connection
            .lock()
            .map_err(|error| error.to_string())?
            .execute(
                "INSERT OR IGNORE INTO execution_lifetimes(id, lifetime_ms, touched_at)
                 VALUES (?1, ?2, ?3)",
                params![id, lifetime_ms.map(as_i64), as_i64(at)],
            )
            .map_err(|error| error.to_string())?;
        Ok(())
    }

    /// Restarts the lifetime of an unowned background execution because a
    /// caller read, waited on, attached to, or wrote to it. Executions without
    /// a recorded lifetime are not written.
    pub fn touch_execution(&self, id: &str, at: u64) -> Result<bool, String> {
        let connection = self.connection.lock().map_err(|error| error.to_string())?;
        let tracked = connection
            .query_row(
                "SELECT EXISTS(SELECT 1 FROM execution_lifetimes WHERE id = ?1)",
                [id],
                |row| row.get::<_, bool>(0),
            )
            .map_err(|error| error.to_string())?;
        if !tracked {
            return Ok(false);
        }
        connection
            .execute(
                "UPDATE execution_lifetimes SET touched_at = MAX(touched_at, ?2) WHERE id = ?1",
                params![id, as_i64(at)],
            )
            .map_err(|error| error.to_string())?;
        Ok(true)
    }

    /// Reads the recorded lifetime and last touch of one execution.
    pub fn execution_lifetime(&self, id: &str) -> Result<Option<(Option<u64>, u64)>, String> {
        self.connection
            .lock()
            .map_err(|error| error.to_string())?
            .query_row(
                "SELECT lifetime_ms, touched_at FROM execution_lifetimes WHERE id = ?1",
                [id],
                |row| {
                    Ok((
                        row.get::<_, Option<i64>>(0)?
                            .map(|value| value.max(0) as u64),
                        row.get::<_, i64>(1)?.max(0) as u64,
                    ))
                },
            )
            .optional()
            .map_err(|error| error.to_string())
    }

    /// Counts Code Mode programs recorded as running, through the partial
    /// running index.
    pub fn running_code_execution_count(&self) -> Result<usize, String> {
        let count = self
            .connection
            .lock()
            .map_err(|error| error.to_string())?
            .query_row(
                "SELECT COUNT(*) FROM executions WHERE json_extract(value, '$.status') = 'running'",
                [],
                |row| row.get::<_, i64>(0),
            )
            .map_err(|error| error.to_string())?;
        Ok(count.max(0) as usize)
    }

    /// Lists nonterminal unowned executions whose lifetime elapsed by `now`,
    /// least recently touched first, with the total count capped at `cap`.
    pub fn expired_lifetimes(
        &self,
        now: u64,
        limit: usize,
        cap: usize,
    ) -> Result<(Vec<ExpiredLifetime>, usize, bool), String> {
        let sql = format!(
            "SELECT t.id, t.touched_at, t.lifetime_ms FROM execution_lifetimes t
             JOIN execution_listing l ON l.id = t.id
             WHERE t.lifetime_ms IS NOT NULL AND t.touched_at + t.lifetime_ms <= ?1
               AND l.status IN {ACTIVE_LISTING}
             ORDER BY t.touched_at ASC, t.id ASC
             LIMIT ?2"
        );
        let connection = self.connection.lock().map_err(|error| error.to_string())?;
        let expired = {
            let mut statement = connection
                .prepare(&sql)
                .map_err(|error| error.to_string())?;
            statement
                .query_map(params![as_i64(now), limit as i64], |row| {
                    Ok(ExpiredLifetime {
                        id: row.get(0)?,
                        touched_at: row.get::<_, i64>(1)?.max(0) as u64,
                        lifetime_ms: row.get::<_, i64>(2)?.max(0) as u64,
                    })
                })
                .map_err(|error| error.to_string())?
                .collect::<Result<Vec<_>, _>>()
                .map_err(|error| error.to_string())?
        };
        let (count, capped) = capped_count(&connection, &sql, now, cap)?;
        Ok((expired, count, capped))
    }

    /// Lists terminal executions last updated before `cutoff` that retention
    /// may delete: not kept, not under a kept or still-retained parent, and
    /// with no active, young, or kept child.
    pub fn retention_execution_candidates(
        &self,
        cutoff: u64,
        limit: usize,
    ) -> Result<Vec<String>, String> {
        let connection = self.connection.lock().map_err(|error| error.to_string())?;
        ids(&connection, &retention_execution_sql(), cutoff, limit)
    }

    /// Counts retention-eligible executions, capped at `cap`.
    pub fn count_retention_executions(
        &self,
        cutoff: u64,
        cap: usize,
    ) -> Result<(usize, bool), String> {
        let connection = self.connection.lock().map_err(|error| error.to_string())?;
        capped_count(&connection, &retention_execution_sql(), cutoff, cap)
    }

    /// Lists terminal invocation records older than `cutoff` that no retained
    /// execution or recording references.
    pub fn retention_invocation_candidates(
        &self,
        cutoff: u64,
        limit: usize,
    ) -> Result<Vec<String>, String> {
        let connection = self.connection.lock().map_err(|error| error.to_string())?;
        ids(&connection, RETENTION_INVOCATION_SQL, cutoff, limit)
    }

    /// Counts retention-eligible invocation records, capped at `cap`.
    pub fn count_retention_invocations(
        &self,
        cutoff: u64,
        cap: usize,
    ) -> Result<(usize, bool), String> {
        let connection = self.connection.lock().map_err(|error| error.to_string())?;
        capped_count(&connection, RETENTION_INVOCATION_SQL, cutoff, cap)
    }

    /// Lists process events older than `cutoff` that belong to no execution.
    pub fn retention_process_event_candidates(
        &self,
        cutoff: u64,
        limit: usize,
    ) -> Result<Vec<String>, String> {
        let connection = self.connection.lock().map_err(|error| error.to_string())?;
        ids(&connection, RETENTION_PROCESS_EVENT_SQL, cutoff, limit)
    }

    /// Counts retention-eligible unowned process events, capped at `cap`.
    pub fn count_retention_process_events(
        &self,
        cutoff: u64,
        cap: usize,
    ) -> Result<(usize, bool), String> {
        let connection = self.connection.lock().map_err(|error| error.to_string())?;
        capped_count(&connection, RETENTION_PROCESS_EVENT_SQL, cutoff, cap)
    }

    /// Deletes terminal executions and every durable row that depends on them,
    /// in one transaction. Active executions are refused. Pinned payload
    /// bodies are kept; a payload shared with a surviving event reads as
    /// pruned, exactly as an expired body does.
    pub fn delete_execution_history(&self, ids: &[String]) -> Result<RetentionDeleted, String> {
        let mut deleted = RetentionDeleted::default();
        if ids.is_empty() {
            return Ok(deleted);
        }
        let mut connection = self.connection.lock().map_err(|error| error.to_string())?;
        let transaction = connection
            .transaction_with_behavior(TransactionBehavior::Immediate)
            .map_err(|error| error.to_string())?;
        for id in ids {
            let status = transaction
                .query_row(
                    "SELECT status FROM execution_listing WHERE id = ?1",
                    [id],
                    |row| row.get::<_, Option<String>>(0),
                )
                .optional()
                .map_err(|error| error.to_string())?
                .flatten();
            if !matches!(status.as_deref(), Some("completed" | "failed" | "canceled")) {
                continue;
            }
            let lease = format!("execution/{id}");
            let payloads = {
                let mut statement = transaction
                    .prepare(
                        "SELECT DISTINCT payload_id FROM causal_events
                         WHERE execution_id = ?1 AND payload_id IS NOT NULL",
                    )
                    .map_err(|error| error.to_string())?;
                statement
                    .query_map([id], |row| row.get::<_, String>(0))
                    .map_err(|error| error.to_string())?
                    .collect::<Result<Vec<_>, _>>()
                    .map_err(|error| error.to_string())?
            };
            for payload in &payloads {
                deleted.payloads += transaction
                    .execute(
                        "DELETE FROM causal_payloads WHERE id = ?1 AND pinned = 0",
                        [payload],
                    )
                    .map_err(|error| error.to_string())?;
            }
            deleted.events += transaction
                .execute("DELETE FROM causal_events WHERE execution_id = ?1", [id])
                .map_err(|error| error.to_string())?;
            deleted.process_events += transaction
                .execute(
                    "DELETE FROM process_events WHERE execution_id = ?1 OR run_id = ?1",
                    [id],
                )
                .map_err(|error| error.to_string())?;
            let invocations = {
                let mut statement = transaction
                    .prepare(
                        "SELECT id FROM invocations
                         WHERE execution_id = ?1 AND recording_id IS NULL",
                    )
                    .map_err(|error| error.to_string())?;
                statement
                    .query_map([id], |row| row.get::<_, String>(0))
                    .map_err(|error| error.to_string())?
                    .collect::<Result<Vec<_>, _>>()
                    .map_err(|error| error.to_string())?
            };
            for invocation in &invocations {
                deleted.observations += delete_invocation(&transaction, invocation)?;
            }
            deleted.invocations += invocations.len();
            transaction
                .execute("DELETE FROM reservations WHERE lease_id = ?1", [&lease])
                .map_err(|error| error.to_string())?;
            deleted.leases += transaction
                .execute("DELETE FROM leases WHERE id = ?1", [&lease])
                .map_err(|error| error.to_string())?;
            for sql in [
                "DELETE FROM execution_lifetimes WHERE id = ?1",
                "DELETE FROM artifacts WHERE execution_id = ?1",
                "DELETE FROM executions WHERE id = ?1",
                "DELETE FROM runs WHERE id = ?1",
                "DELETE FROM execution_idempotency WHERE execution_id = ?1",
                "DELETE FROM poll_iterations WHERE poll_id = ?1",
                "DELETE FROM telemetry_samples WHERE capture_id IN (
                    SELECT id FROM telemetry_captures WHERE execution_id = ?1
                 )",
                "DELETE FROM telemetry_captures WHERE execution_id = ?1",
            ] {
                transaction
                    .execute(sql, [id])
                    .map_err(|error| error.to_string())?;
            }
            deleted.executions += transaction
                .execute("DELETE FROM execution_records WHERE id = ?1", [id])
                .map_err(|error| error.to_string())?;
        }
        transaction.commit().map_err(|error| error.to_string())?;
        Ok(deleted)
    }

    /// Deletes terminal invocation records and their search and observation
    /// rows in one transaction. Running invocations are refused.
    pub fn delete_invocations(&self, ids: &[String]) -> Result<usize, String> {
        let mut connection = self.connection.lock().map_err(|error| error.to_string())?;
        let transaction = connection
            .transaction_with_behavior(TransactionBehavior::Immediate)
            .map_err(|error| error.to_string())?;
        let mut deleted = 0;
        for id in ids {
            let terminal = transaction
                .query_row(
                    "SELECT status != 'running' FROM invocations WHERE id = ?1",
                    [id],
                    |row| row.get::<_, bool>(0),
                )
                .optional()
                .map_err(|error| error.to_string())?
                .unwrap_or(false);
            if terminal {
                delete_invocation(&transaction, id)?;
                deleted += 1;
            }
        }
        transaction.commit().map_err(|error| error.to_string())?;
        Ok(deleted)
    }

    /// Deletes process events by identifier in one transaction.
    pub fn delete_process_events(&self, ids: &[String]) -> Result<usize, String> {
        let mut connection = self.connection.lock().map_err(|error| error.to_string())?;
        let transaction = connection
            .transaction_with_behavior(TransactionBehavior::Immediate)
            .map_err(|error| error.to_string())?;
        let mut deleted = 0;
        for id in ids {
            deleted += transaction
                .execute("DELETE FROM process_events WHERE id = ?1", [id])
                .map_err(|error| error.to_string())?;
        }
        transaction.commit().map_err(|error| error.to_string())?;
        Ok(deleted)
    }

    /// Returns up to `max_pages` free pages to the operating system when the
    /// database uses incremental auto-vacuum, and reports what remains free.
    ///
    /// A database created before auto-vacuum was enabled keeps its free pages
    /// for reuse; converting it needs a full `VACUUM`, which apoc never runs
    /// on its own.
    pub fn reclaim_space(&self, max_pages: u64) -> Result<SpaceReclaim, String> {
        let connection = self.connection.lock().map_err(|error| error.to_string())?;
        let pragma = |name: &str| {
            connection
                .pragma_query_value(None, name, |row| row.get::<_, i64>(0))
                .map(|value| value.max(0) as u64)
                .map_err(|error| error.to_string())
        };
        let mode = pragma("auto_vacuum")?;
        let before = pragma("freelist_count")?;
        if mode == 2 && before > 0 && max_pages > 0 {
            connection
                .execute_batch(&format!("PRAGMA incremental_vacuum({max_pages});"))
                .map_err(|error| error.to_string())?;
        }
        let after = pragma("freelist_count")?;
        Ok(SpaceReclaim {
            auto_vacuum: match mode {
                1 => "full",
                2 => "incremental",
                _ => "none",
            }
            .to_string(),
            freelist_pages: after,
            reclaimed_pages: before.saturating_sub(after),
        })
    }
}