agent-sdk-store-sqlite 0.1.0-alpha.4

SQLite-backed durable store adapters for the Agent SDK.
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
use std::{
    collections::{BTreeMap, BTreeSet, VecDeque},
    path::{Path, PathBuf},
    sync::{Arc, Mutex},
};

use agent_sdk_core::{
    AgentError, AgentErrorKind, AgentPoolId, AgentPoolMember, AgentPoolSnapshot, AgentPoolStore,
    AgentPoolStoreConfig, AgentPoolStoreCursor, AgentPoolStoreRecord, AgentPoolStoreRecordPayload,
    AgentPoolStoreStream, AgentPoolStoredMessage, AgentPoolStoredWake, CompiledEventFilter,
    IdempotencyKey, MessageId, MessageReceipt, RetryClassification, RunId, RunMessage, TopicId,
    WakeCondition, WakeConditionId, WakeRegistration,
};
use rusqlite::{Connection, params};

/// SQLite-backed implementation of `AgentPoolStore`.
///
/// Two independent `SqliteAgentPoolStore` values opened against the same
/// database file share pool membership, messages, wake registrations, dedupe,
/// rehydration, and watch cursors. The adapter stores core pool records as JSON
/// and replays them into snapshots; it does not own workflow scheduling or a
/// second event bus.
#[derive(Clone)]
pub struct SqliteAgentPoolStore {
    path: PathBuf,
    connection: Arc<Mutex<Connection>>,
}

impl SqliteAgentPoolStore {
    /// Opens or creates a SQLite-backed agent-pool store.
    pub fn open(path: impl AsRef<Path>) -> Result<Self, AgentError> {
        let path = path.as_ref().to_path_buf();
        let connection = Connection::open(&path).map_err(sqlite_error)?;
        connection
            .execute_batch(
                "PRAGMA journal_mode = WAL;
                 CREATE TABLE IF NOT EXISTS agent_pool_records (
                     pool_id TEXT NOT NULL,
                     seq INTEGER NOT NULL,
                     kind TEXT NOT NULL,
                     payload_json TEXT NOT NULL,
                     PRIMARY KEY (pool_id, seq)
                 );
                 CREATE TABLE IF NOT EXISTS agent_pool_event_seq (
                     pool_id TEXT PRIMARY KEY,
                     seq INTEGER NOT NULL
                 );",
            )
            .map_err(sqlite_error)?;
        Ok(Self {
            path,
            connection: Arc::new(Mutex::new(connection)),
        })
    }

    /// Returns the backing database path.
    pub fn path(&self) -> &Path {
        &self.path
    }

    fn append_record(
        &self,
        pool_id: &AgentPoolId,
        payload: AgentPoolStoreRecordPayload,
    ) -> Result<AgentPoolStoreCursor, AgentError> {
        let mut connection = self.connection()?;
        let transaction = connection.transaction().map_err(sqlite_error)?;
        let next_seq = transaction
            .query_row(
                "SELECT COALESCE(MAX(seq), 0) + 1 FROM agent_pool_records WHERE pool_id = ?1",
                params![pool_id.as_str()],
                |row| row.get::<_, i64>(0),
            )
            .map_err(sqlite_error)?;
        let payload_json = serde_json::to_string(&payload).map_err(serde_error)?;
        transaction
            .execute(
                "INSERT INTO agent_pool_records (pool_id, seq, kind, payload_json)
                 VALUES (?1, ?2, ?3, ?4)",
                params![
                    pool_id.as_str(),
                    next_seq,
                    payload_kind(&payload),
                    payload_json
                ],
            )
            .map_err(sqlite_error)?;
        transaction.commit().map_err(sqlite_error)?;
        Ok(AgentPoolStoreCursor::new(next_seq as u64))
    }

    fn records_after(
        &self,
        pool_id: &AgentPoolId,
        cursor: Option<AgentPoolStoreCursor>,
    ) -> Result<Vec<AgentPoolStoreRecord>, AgentError> {
        let start_after = cursor.map(|cursor| cursor.sequence).unwrap_or(0);
        let connection = self.connection()?;
        let mut statement = connection
            .prepare(
                "SELECT seq, payload_json
                 FROM agent_pool_records
                 WHERE pool_id = ?1 AND seq > ?2
                 ORDER BY seq ASC",
            )
            .map_err(sqlite_error)?;
        let rows = statement
            .query_map(params![pool_id.as_str(), start_after as i64], |row| {
                let seq: i64 = row.get(0)?;
                let payload_json: String = row.get(1)?;
                Ok((seq, payload_json))
            })
            .map_err(sqlite_error)?;

        let mut records = Vec::new();
        for row in rows {
            let (seq, payload_json) = row.map_err(sqlite_error)?;
            let payload = serde_json::from_str::<AgentPoolStoreRecordPayload>(&payload_json)
                .map_err(serde_error)?;
            records.push(AgentPoolStoreRecord {
                pool_id: pool_id.clone(),
                cursor: AgentPoolStoreCursor::new(seq as u64),
                payload,
            });
        }
        Ok(records)
    }

    fn replay(&self, pool_id: &AgentPoolId) -> Result<PoolReplay, AgentError> {
        let mut replay = PoolReplay::default();
        for record in self.records_after(pool_id, Some(AgentPoolStoreCursor::start()))? {
            replay.cursor = Some(record.cursor.clone());
            replay.apply(record.payload)?;
        }
        Ok(replay)
    }

    fn connection(&self) -> Result<std::sync::MutexGuard<'_, Connection>, AgentError> {
        self.connection
            .lock()
            .map_err(|_| AgentError::contract_violation("sqlite agent pool store lock poisoned"))
    }
}

impl AgentPoolStore for SqliteAgentPoolStore {
    fn open_pool(
        &self,
        pool_id: AgentPoolId,
        config: AgentPoolStoreConfig,
    ) -> Result<AgentPoolSnapshot, AgentError> {
        let replay = self.replay(&pool_id)?;
        if let Some(existing) = replay.config.as_ref() {
            if existing != &config {
                return Err(AgentError::new(
                    AgentErrorKind::InvalidStateTransition,
                    RetryClassification::RepairNeeded,
                    "sqlite agent pool store config conflicts with existing pool",
                ));
            }
        } else {
            self.append_record(&pool_id, AgentPoolStoreRecordPayload::PoolOpened { config })?;
        }
        self.snapshot(&pool_id)
    }

    fn snapshot(&self, pool_id: &AgentPoolId) -> Result<AgentPoolSnapshot, AgentError> {
        self.replay(pool_id)?.snapshot(pool_id.clone())
    }

    fn record_pool_created(
        &self,
        pool_id: &AgentPoolId,
    ) -> Result<AgentPoolStoreCursor, AgentError> {
        self.append_record(pool_id, AgentPoolStoreRecordPayload::PoolCreated)
    }

    fn join_member(
        &self,
        pool_id: &AgentPoolId,
        member: AgentPoolMember,
    ) -> Result<AgentPoolStoreCursor, AgentError> {
        self.snapshot(pool_id)?;
        self.append_record(
            pool_id,
            AgentPoolStoreRecordPayload::MemberJoined { member },
        )
    }

    fn leave_member(
        &self,
        pool_id: &AgentPoolId,
        run_id: &RunId,
    ) -> Result<(AgentPoolMember, AgentPoolStoreCursor), AgentError> {
        let replay = self.replay(pool_id)?;
        let member = replay.members.get(run_id).cloned().ok_or_else(|| {
            AgentError::new(
                AgentErrorKind::InvalidStateTransition,
                RetryClassification::NotRetryable,
                "run is not a member of this agent pool",
            )
        })?;
        let cursor = self.append_record(
            pool_id,
            AgentPoolStoreRecordPayload::MemberLeft {
                member: member.clone(),
            },
        )?;
        Ok((member, cursor))
    }

    fn message_receipt(
        &self,
        pool_id: &AgentPoolId,
        idempotency_key: &IdempotencyKey,
    ) -> Result<Option<MessageReceipt>, AgentError> {
        Ok(self
            .replay(pool_id)?
            .message_dedupe
            .get(idempotency_key)
            .cloned())
    }

    fn record_message(
        &self,
        pool_id: &AgentPoolId,
        message: RunMessage,
        receipt: MessageReceipt,
    ) -> Result<AgentPoolStoreCursor, AgentError> {
        self.snapshot(pool_id)?;
        self.append_record(
            pool_id,
            AgentPoolStoreRecordPayload::RunMessage {
                stored: AgentPoolStoredMessage { message, receipt },
            },
        )
    }

    fn wake_registration(
        &self,
        pool_id: &AgentPoolId,
        idempotency_key: &IdempotencyKey,
    ) -> Result<Option<WakeRegistration>, AgentError> {
        Ok(self
            .replay(pool_id)?
            .wake_dedupe
            .get(idempotency_key)
            .cloned())
    }

    fn wake(
        &self,
        pool_id: &AgentPoolId,
        condition_id: &WakeConditionId,
    ) -> Result<Option<AgentPoolStoredWake>, AgentError> {
        Ok(self.replay(pool_id)?.wakes.get(condition_id).cloned())
    }

    fn record_wake(
        &self,
        pool_id: &AgentPoolId,
        condition: WakeCondition,
        compiled_filter: CompiledEventFilter,
        registration: WakeRegistration,
    ) -> Result<AgentPoolStoreCursor, AgentError> {
        self.snapshot(pool_id)?;
        self.append_record(
            pool_id,
            AgentPoolStoreRecordPayload::Wake {
                stored: AgentPoolStoredWake {
                    condition,
                    compiled_filter,
                    registration,
                },
            },
        )
    }

    fn watch(
        &self,
        pool_id: &AgentPoolId,
        cursor: Option<AgentPoolStoreCursor>,
    ) -> Result<AgentPoolStoreStream, AgentError> {
        Ok(AgentPoolStoreStream::new(VecDeque::from(
            self.records_after(pool_id, cursor)?,
        )))
    }

    fn next_event_sequence(&self, pool_id: &AgentPoolId) -> Result<u64, AgentError> {
        let mut connection = self.connection()?;
        let transaction = connection.transaction().map_err(sqlite_error)?;
        transaction
            .execute(
                "INSERT OR IGNORE INTO agent_pool_event_seq (pool_id, seq) VALUES (?1, 0)",
                params![pool_id.as_str()],
            )
            .map_err(sqlite_error)?;
        transaction
            .execute(
                "UPDATE agent_pool_event_seq SET seq = seq + 1 WHERE pool_id = ?1",
                params![pool_id.as_str()],
            )
            .map_err(sqlite_error)?;
        let seq = transaction
            .query_row(
                "SELECT seq FROM agent_pool_event_seq WHERE pool_id = ?1",
                params![pool_id.as_str()],
                |row| row.get::<_, i64>(0),
            )
            .map_err(sqlite_error)?;
        transaction.commit().map_err(sqlite_error)?;
        Ok(seq as u64)
    }
}

#[derive(Default)]
struct PoolReplay {
    config: Option<AgentPoolStoreConfig>,
    created: bool,
    members: BTreeMap<RunId, AgentPoolMember>,
    messages: BTreeMap<MessageId, AgentPoolStoredMessage>,
    message_dedupe: BTreeMap<IdempotencyKey, MessageReceipt>,
    wakes: BTreeMap<WakeConditionId, AgentPoolStoredWake>,
    wake_dedupe: BTreeMap<IdempotencyKey, WakeRegistration>,
    cursor: Option<AgentPoolStoreCursor>,
}

impl PoolReplay {
    fn apply(&mut self, payload: AgentPoolStoreRecordPayload) -> Result<(), AgentError> {
        match payload {
            AgentPoolStoreRecordPayload::PoolOpened { config } => {
                if self
                    .config
                    .as_ref()
                    .is_some_and(|existing| existing != &config)
                {
                    return Err(AgentError::new(
                        AgentErrorKind::InvalidStateTransition,
                        RetryClassification::RepairNeeded,
                        "sqlite agent pool store contains conflicting pool open records",
                    ));
                }
                self.config = Some(config);
            }
            AgentPoolStoreRecordPayload::PoolCreated => {
                self.created = true;
            }
            AgentPoolStoreRecordPayload::MemberJoined { member } => {
                self.members.insert(member.run_id.clone(), member);
            }
            AgentPoolStoreRecordPayload::MemberLeft { member } => {
                self.members.remove(&member.run_id);
            }
            AgentPoolStoreRecordPayload::RunMessage { stored } => {
                self.message_dedupe.insert(
                    stored.message.idempotency_key.clone(),
                    stored.receipt.clone(),
                );
                self.messages
                    .insert(stored.message.message_id.clone(), stored);
            }
            AgentPoolStoreRecordPayload::Wake { stored } => {
                self.wake_dedupe.insert(
                    stored.condition.idempotency_key.clone(),
                    stored.registration.clone(),
                );
                self.wakes
                    .insert(stored.condition.condition_id.clone(), stored);
            }
        }
        Ok(())
    }

    fn snapshot(self, pool_id: AgentPoolId) -> Result<AgentPoolSnapshot, AgentError> {
        let config = self.config.ok_or_else(|| {
            AgentError::new(
                AgentErrorKind::HostConfigurationNeeded,
                RetryClassification::HostConfigurationNeeded,
                "sqlite agent pool store has not opened this pool",
            )
        })?;
        let topics = topics_from_members(self.members.values());
        Ok(AgentPoolSnapshot {
            pool_id,
            created: self.created,
            members: self.members.into_values().collect(),
            topics,
            message_policy: config.message_policy,
            wake_policy: config.wake_policy,
            policy_refs: config.policy_refs,
            messages: self.messages.into_values().collect(),
            wakes: self.wakes.into_values().collect(),
            cursor: self.cursor,
        })
    }
}

fn topics_from_members<'a>(members: impl IntoIterator<Item = &'a AgentPoolMember>) -> Vec<TopicId> {
    let mut topics = BTreeSet::new();
    for member in members {
        topics.extend(member.topics.iter().cloned());
    }
    topics.into_iter().collect()
}

fn payload_kind(payload: &AgentPoolStoreRecordPayload) -> &'static str {
    match payload {
        AgentPoolStoreRecordPayload::PoolOpened { .. } => "pool_opened",
        AgentPoolStoreRecordPayload::PoolCreated => "pool_created",
        AgentPoolStoreRecordPayload::MemberJoined { .. } => "member_joined",
        AgentPoolStoreRecordPayload::MemberLeft { .. } => "member_left",
        AgentPoolStoreRecordPayload::RunMessage { .. } => "run_message",
        AgentPoolStoreRecordPayload::Wake { .. } => "wake",
    }
}

fn sqlite_error(error: rusqlite::Error) -> AgentError {
    AgentError::new(
        AgentErrorKind::InvalidStateTransition,
        RetryClassification::RepairNeeded,
        format!("sqlite agent pool store failure: {error}"),
    )
}

fn serde_error(error: serde_json::Error) -> AgentError {
    AgentError::new(
        AgentErrorKind::InvalidStateTransition,
        RetryClassification::RepairNeeded,
        format!("sqlite agent pool store serialization failure: {error}"),
    )
}