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
//! Episodic Memory - Event timeline storage (US-003)
//!
//! Records events with timestamps and contextual information.
//! Supports temporal queries and similarity-based retrieval.
//! Uses a B-tree temporal index for efficient O(log N) time-based queries.
use crate::{Database, Point};
use serde_json::json;
use std::sync::Arc;
use super::error::AgentMemoryError;
use super::memory_helpers;
use super::temporal_index::TemporalIndex;
use super::ttl::{MemoryKind, MemoryTtl};
/// Episodic memory for storing event timelines with temporal context.
///
/// Records events with timestamps, descriptions, and embeddings.
/// Supports similarity-based retrieval and time-range queries.
pub struct EpisodicMemory {
collection_name: String,
db: Arc<Database>,
dimension: usize,
ttl: Arc<MemoryTtl>,
temporal_index: Arc<TemporalIndex>,
/// Edge-id allocator for [`Self::relate`] (seeded past existing edges).
next_edge_id: std::sync::atomic::AtomicU64,
}
impl EpisodicMemory {
const COLLECTION_NAME: &'static str = "_episodic_memory";
/// Returns the embedding dimension for this collection.
#[must_use]
pub fn dimension(&self) -> usize {
self.dimension
}
/// Creates or opens the episodic memory collection.
///
/// # Errors
///
/// Returns an error when collection creation/opening fails or dimensions mismatch.
pub fn new_from_db(db: Arc<Database>, dimension: usize) -> Result<Self, AgentMemoryError> {
Self::new(
db,
dimension,
Arc::new(MemoryTtl::new()),
Arc::new(TemporalIndex::new()),
)
}
pub(crate) fn new(
db: Arc<Database>,
dimension: usize,
ttl: Arc<MemoryTtl>,
temporal_index: Arc<TemporalIndex>,
) -> Result<Self, AgentMemoryError> {
let collection_name = Self::COLLECTION_NAME.to_string();
let actual_dimension =
memory_helpers::open_or_create_collection(&db, &collection_name, dimension)?;
if temporal_index.is_empty() {
if let Some(collection) = db.get_vector_collection(&collection_name) {
Self::rebuild_temporal_index(&collection.inner, &temporal_index);
}
}
memory_helpers::rebuild_ttl_from_payloads(
&db,
&collection_name,
&ttl,
MemoryKind::Episodic,
)?;
let next_edge_id = memory_helpers::seed_edge_counter(&memory_helpers::get_collection(
&db,
&collection_name,
)?);
Ok(Self {
collection_name,
db,
dimension: actual_dimension,
ttl,
temporal_index,
next_edge_id,
})
}
fn rebuild_temporal_index(
collection: &crate::collection::Collection,
temporal_index: &TemporalIndex,
) {
let all_ids = collection.all_ids();
let points = collection.get(&all_ids);
for point in points.into_iter().flatten() {
if let Some(payload) = &point.payload {
if let Some(ts) = payload.get("timestamp").and_then(serde_json::Value::as_i64) {
temporal_index.insert(point.id, ts);
}
}
}
}
/// Returns the name of the underlying `VelesDB` collection.
#[must_use]
pub fn collection_name(&self) -> &str {
&self.collection_name
}
/// Stores an event in episodic memory.
///
/// # Errors
///
/// Returns an error when the embedding dimension is invalid, when the collection
/// is unavailable, or when storage upsert fails.
pub fn record(
&self,
event_id: u64,
description: &str,
timestamp: i64,
embedding: Option<&[f32]>,
) -> Result<(), AgentMemoryError> {
self.record_internal(event_id, description, timestamp, embedding, None)
}
/// Shared store path: persists the event, optionally with a durable
/// `_veles_expires_at` payload field (epoch seconds) for TTL'd records.
fn record_internal(
&self,
event_id: u64,
description: &str,
timestamp: i64,
embedding: Option<&[f32]>,
expires_at: Option<u64>,
) -> Result<(), AgentMemoryError> {
let vector = memory_helpers::resolve_embedding(self.dimension, embedding)?;
let collection = memory_helpers::get_collection(&self.db, &self.collection_name)?;
let mut payload = json!({
"description": description,
"timestamp": timestamp
});
memory_helpers::attach_expiry(&mut payload, expires_at);
let point = Point::new(event_id, vector, Some(payload));
memory_helpers::upsert_points(&collection, vec![point])?;
self.temporal_index.insert(event_id, timestamp);
Ok(())
}
/// Stores an event and assigns a TTL for automatic expiration.
///
/// A `ttl_seconds` of `0` means "expire immediately": rather than persisting
/// a live point that lingers until the next `auto_expire`, the event is
/// eagerly removed (and any pre-existing point for `event_id` deleted),
/// harmonising the behaviour with `SemanticMemory::store_with_ttl`. The
/// embedding is still dimension-validated so callers get the same error
/// contract as a real record.
///
/// The expiry is persisted as a reserved `_veles_expires_at` (epoch
/// seconds) payload field, so the TTL survives a process restart: the
/// in-memory map is rebuilt from payloads when the collection is reopened.
///
/// # Errors
///
/// Returns the same errors as [`Self::record`].
pub fn record_with_ttl(
&self,
event_id: u64,
description: &str,
timestamp: i64,
embedding: Option<&[f32]>,
ttl_seconds: u64,
) -> Result<(), AgentMemoryError> {
if ttl_seconds == 0 {
if let Some(emb) = embedding {
memory_helpers::validate_dimension(self.dimension, emb.len())?;
}
return self.delete(event_id);
}
let expires_at = MemoryTtl::now().saturating_add(ttl_seconds);
self.record_internal(
event_id,
description,
timestamp,
embedding,
Some(expires_at),
)?;
self.ttl
.set_expiry(MemoryKind::Episodic, event_id, expires_at);
Ok(())
}
/// Durably sets (or refreshes) the TTL of an existing event.
///
/// Unlike `AgentMemory::set_episodic_ttl` (in-memory map only, lost on
/// restart), this persists the expiry to the reserved `_veles_expires_at`
/// payload field, so it survives a restart. A `ttl_seconds` of 0 expires
/// the event immediately.
///
/// # Errors
///
/// Returns `NotFound` when no event with `event_id` exists, or
/// `CollectionError` when persistence fails.
pub fn set_ttl_durable(&self, event_id: u64, ttl_seconds: u64) -> Result<(), AgentMemoryError> {
memory_helpers::set_ttl_durable(
&self.db,
&self.collection_name,
&self.ttl,
MemoryKind::Episodic,
event_id,
ttl_seconds,
)
}
/// Relates two live events with a typed, durable graph edge (e.g.
/// `CAUSED`, `FOLLOWED`); see `SemanticMemory::relate` for semantics.
///
/// # Errors
///
/// Returns `NotFound` when either endpoint is missing or expired, or
/// `CollectionError` when the edge write fails.
pub fn relate(
&self,
from_id: u64,
to_id: u64,
rel_type: &str,
properties: Option<&serde_json::Map<String, serde_json::Value>>,
) -> Result<u64, AgentMemoryError> {
let collection = memory_helpers::get_collection(&self.db, &self.collection_name)?;
for id in [from_id, to_id] {
memory_helpers::ensure_live(
&collection,
&self.collection_name,
&self.ttl,
MemoryKind::Episodic,
id,
)?;
}
let edge_id = memory_helpers::add_relation_edge(
&collection,
&self.next_edge_id,
(from_id, to_id),
rel_type,
properties,
)?;
// Close the check-then-add window: an endpoint deleted concurrently
// (its cascade may have run before our edge landed) must not leave a
// dangling, WAL-durable edge behind.
memory_helpers::verify_relation_endpoints(&collection, edge_id, (from_id, to_id))?;
Ok(edge_id)
}
/// Returns the outgoing relations of an event.
///
/// # Errors
///
/// Returns `CollectionError` when the collection cannot be resolved.
pub fn relations(
&self,
id: u64,
) -> Result<Vec<crate::collection::graph::GraphEdge>, AgentMemoryError> {
let collection = memory_helpers::get_collection(&self.db, &self.collection_name)?;
// Expired entries are invisible on every read surface — edges whose
// target has expired (but is not yet swept) are hidden too.
Ok(collection
.get_outgoing_edges(id)
.into_iter()
.filter(|edge| !self.ttl.is_expired(MemoryKind::Episodic, edge.target()))
.collect())
}
/// Removes a relation edge created by [`Self::relate`].
///
/// # Errors
///
/// Returns `CollectionError` when the collection cannot be resolved.
pub fn unrelate(&self, edge_id: u64) -> Result<bool, AgentMemoryError> {
let collection = memory_helpers::get_collection(&self.db, &self.collection_name)?;
Ok(collection.remove_edge(edge_id))
}
/// Returns recent events, optionally filtered by a lower timestamp bound.
///
/// # Errors
///
/// Returns an error when the collection is unavailable.
pub fn recent(
&self,
limit: usize,
since_timestamp: Option<i64>,
) -> Result<Vec<(u64, String, i64)>, AgentMemoryError> {
let collection = memory_helpers::get_collection(&self.db, &self.collection_name)?;
Ok(self.fetch_temporal_events(
limit,
|fetch_limit| {
let entries = self.temporal_index.recent(fetch_limit, since_timestamp);
entries.iter().map(|e| e.id).collect()
},
&collection,
))
}
/// Returns events older than `timestamp`.
///
/// # Errors
///
/// Returns an error when the collection is unavailable.
pub fn older_than(
&self,
timestamp: i64,
limit: usize,
) -> Result<Vec<(u64, String, i64)>, AgentMemoryError> {
let collection = memory_helpers::get_collection(&self.db, &self.collection_name)?;
Ok(self.fetch_temporal_events(
limit,
|fetch_limit| {
let entries = self.temporal_index.older_than(timestamp, fetch_limit);
entries.iter().map(|e| e.id).collect()
},
&collection,
))
}
/// Retrieves the `k` most similar episodic events to a query embedding.
///
/// # Errors
///
/// Returns an error when the embedding dimension is invalid, when the collection
/// is unavailable, or when vector search fails.
pub fn recall_similar(
&self,
query_embedding: &[f32],
k: usize,
) -> Result<Vec<(u64, String, i64, f32)>, AgentMemoryError> {
let results = memory_helpers::search_filtered(
&self.db,
&self.collection_name,
self.dimension,
query_embedding,
k,
&self.ttl,
MemoryKind::Episodic,
)?;
Ok(results
.into_iter()
.filter_map(|r| {
let (desc, ts) = extract_event_fields(&r.point)?;
Some((r.point.id, desc, ts, r.score))
})
.collect())
}
/// Retrieves an event with its embedding payload.
///
/// # Errors
///
/// Returns an error when the collection is unavailable.
pub fn get_with_embedding(
&self,
id: u64,
) -> Result<Option<(String, i64, Vec<f32>)>, AgentMemoryError> {
let collection = memory_helpers::get_collection(&self.db, &self.collection_name)?;
let points = collection.get(&[id]);
let Some(point) = points.into_iter().flatten().next() else {
return Ok(None);
};
if self.ttl.is_expired(MemoryKind::Episodic, point.id) {
return Ok(None);
}
let Some(payload) = point.payload.as_ref() else {
return Ok(None);
};
let desc = payload
.get("description")
.and_then(serde_json::Value::as_str)
.unwrap_or("")
.to_string();
let ts = payload
.get("timestamp")
.and_then(serde_json::Value::as_i64)
.unwrap_or(0);
Ok(Some((desc, ts, point.vector.clone())))
}
/// Deletes an episodic event by id.
///
/// # Errors
///
/// Returns an error when the collection is unavailable or delete fails.
pub fn delete(&self, id: u64) -> Result<(), AgentMemoryError> {
let collection = memory_helpers::get_collection(&self.db, &self.collection_name)?;
memory_helpers::delete_from_collection(&collection, &[id])?;
self.temporal_index.remove(id);
self.ttl.remove(MemoryKind::Episodic, id);
Ok(())
}
/// Serializes episodic points in temporal-order id set.
///
/// # Errors
///
/// Returns an error when the collection is unavailable or JSON encoding fails.
pub fn serialize(&self) -> Result<Vec<u8>, AgentMemoryError> {
let collection = memory_helpers::get_collection(&self.db, &self.collection_name)?;
let all_ids = self.temporal_index.all_ids();
memory_helpers::serialize_points(&collection, &all_ids)
}
/// Replaces episodic storage with previously serialized points.
///
/// # Errors
///
/// Returns an error when JSON decoding fails, collection access fails, or
/// persistence operations fail.
pub fn deserialize(&self, data: &[u8]) -> Result<(), AgentMemoryError> {
let collection = memory_helpers::get_collection(&self.db, &self.collection_name)?;
if let Some(points) = memory_helpers::deserialize_into_collection(data, &collection)? {
self.rebuild_temporal_from_points(&points);
}
Ok(())
}
/// Fetches temporal events with progressive widening, filtering expired entries.
fn fetch_temporal_events(
&self,
limit: usize,
id_fetcher: impl Fn(usize) -> Vec<u64>,
collection: &crate::collection::Collection,
) -> Vec<(u64, String, i64)> {
// Clamp the pre-allocation: the number of events can never exceed the
// total indexed entries, so a huge caller-supplied `limit` must not
// pre-allocate beyond available data.
let indexed = self.temporal_index.len();
let mut events = Vec::with_capacity(limit.min(indexed));
let mut fetch_limit = limit.saturating_mul(2);
// Saturating to keep an attacker-supplied `limit` near `usize::MAX` from
// overflowing the loop ceiling (panic under `panic=abort`, silent wrap in
// release). The `id_count < fetch_limit` break still terminates the loop.
let max_fetch = indexed.max(limit).saturating_mul(2);
while events.len() < limit && fetch_limit <= max_fetch {
let ids = id_fetcher(fetch_limit);
if ids.is_empty() {
break;
}
let id_count = ids.len();
events = Self::filter_live_events(&self.ttl, collection, &ids, limit);
if events.len() >= limit || id_count < fetch_limit {
break;
}
fetch_limit = fetch_limit.saturating_mul(2);
}
events
}
/// Fetches points by IDs, filters expired ones, and extracts event fields.
fn filter_live_events(
ttl: &MemoryTtl,
collection: &crate::collection::Collection,
ids: &[u64],
limit: usize,
) -> Vec<(u64, String, i64)> {
collection
.get(ids)
.into_iter()
.flatten()
.filter(|p| !ttl.is_expired(MemoryKind::Episodic, p.id))
.filter_map(|p| {
let (desc, ts) = extract_event_fields(&p)?;
Some((p.id, desc, ts))
})
.take(limit)
.collect()
}
/// Clears and rebuilds the temporal index from a set of points.
fn rebuild_temporal_from_points(&self, points: &[Point]) {
self.temporal_index.clear();
for point in points {
if let Some(payload) = &point.payload {
if let Some(ts) = payload.get("timestamp").and_then(serde_json::Value::as_i64) {
self.temporal_index.insert(point.id, ts);
}
}
}
}
}
/// Extracts `(description, timestamp)` from a point's payload.
fn extract_event_fields(point: &Point) -> Option<(String, i64)> {
let payload = point.payload.as_ref()?;
let desc = payload.get("description")?.as_str()?.to_string();
let ts = payload.get("timestamp")?.as_i64()?;
Some((desc, ts))
}