Skip to content

Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors

Rust

fix(temporal): preserve retirement history in V62 backfill

enrelle30838c95823
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a596c9b4..0cd83598 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -12,7 +12,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
a second `as_of` stream: `memory_query(as_of=T)` now fuses the entity
timeline with version-filtered full-text search over the page versions
alive at T, using the default path's RRF (k=60) plus the same bounded
- authority adjustment — relevance at T over knowledge valid at T. This
+ authority adjustment — current-index relevance over knowledge valid at T. This
answers entity-less pages and paraphrased audit questions ("which
database were we on during the outage?") that the entity-only lookup
missed. `explain=true` reports both streams (`streams_active:
@@ -21,7 +21,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
the default (no `as_of`) path is unchanged. Every retire path
(supersede, decay, reorg graveyard, move-regenerate) closes both grains
in the same transaction, and the V62 backfill closes successor-less
- retirements at `COALESCE(superseded_at, updated_at)` (the V58 rule).
+ retirements at the decay marker, existing entity-link close, or
+ `updated_at` fallback, preserving recorded reorg/move history.
Phase B world-time stays deferred. (#656)
- `[retrieval]` section with two opt-in ranking signals, both off by default
so unconfigured stores rank exactly as before. `query_intent` routes
@@ -58,6 +59,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
(#675)
### Fixed
+- Preserved recorded entity-link retirement timestamps when backfilling
+ page ingestion windows for historical reorg/move-regenerate pages,
+ preventing empty page windows when `updated_at` still held creation
+ time. Clarified current-index ranking and snapshot-based rollback. (#682)
- Wiki auto-commits stage what the wiki wrote instead of walking the
whole tree, keep the repository open between commits, and no longer
drop the commit when another session is writing a file at the same
diff --git a/crates/ai-memory-store/migrations/V62__page_ingestion_windows.sql b/crates/ai-memory-store/migrations/V62__page_ingestion_windows.sql
index 7d43c31a..28917fb7 100644
--- a/crates/ai-memory-store/migrations/V62__page_ingestion_windows.sql
+++ b/crates/ai-memory-store/migrations/V62__page_ingestion_windows.sql
@@ -30,10 +30,15 @@ UPDATE pages SET valid_to = (
-- Successor-less retirements (decay tombstones, graveyard merges,
-- move-regenerate rows — the V58 class): close at the decay eviction
--- marker when present, else the row's own updated_at — the best
--- available retirement instant, the same rule V58 used for the link
--- grain. Latest versions keep valid_to NULL (still current).
-UPDATE pages SET valid_to = COALESCE(superseded_at, updated_at)
+-- marker when present, else the existing link-window close. Reorg and
+-- move-regenerate recorded their retirement there without updating the
+-- page's updated_at. Only fall back to updated_at when neither grain
+-- retained the retirement instant. Latest versions stay open.
+UPDATE pages SET valid_to = COALESCE(
+ superseded_at,
+ (SELECT MIN(l.superseded_at) FROM entity_page_links l WHERE l.page_id = pages.id),
+ updated_at
+)
WHERE is_latest = 0 AND valid_to IS NULL
AND NOT EXISTS (SELECT 1 FROM pages s WHERE s.supersedes = pages.id);
diff --git a/crates/ai-memory-store/src/lib.rs b/crates/ai-memory-store/src/lib.rs
index 15ff1e1c..c25621d5 100644
--- a/crates/ai-memory-store/src/lib.rs
+++ b/crates/ai-memory-store/src/lib.rs
@@ -6486,8 +6486,7 @@ mod tests {
/// path produces: `valid_from` from each version's `created_at`,
/// `valid_to` from the earliest superseding version, NULL for
/// latest; successor-less retirements close at
- /// `COALESCE(superseded_at, updated_at)` (the V58 rule at page
- /// grain). Mirrors `v56_backfill_reconstructs_the_windows`.
+ /// the decay marker, existing link close, or updated_at fallback.
#[tokio::test]
async fn v62_backfill_reconstructs_page_windows() {
let tmp = TempDir::new().unwrap();
@@ -6543,20 +6542,17 @@ mod tests {
assert!(live[2].2.is_none(), "latest stays open");
assert!(live[3].2.is_some(), "tombstone is closed");
- // Fabricate the pre-V62 state, then replay the migration's
- // backfill statements verbatim.
- db.execute("UPDATE pages SET valid_from = NULL, valid_to = NULL", [])
- .unwrap();
+ // Replay the actual migration against the pre-V62 schema.
db.execute_batch(
- "UPDATE pages SET valid_from = created_at; \
- UPDATE pages SET valid_to = ( \
- SELECT MIN(s.created_at) FROM pages s WHERE s.supersedes = pages.id \
- ) WHERE EXISTS (SELECT 1 FROM pages s WHERE s.supersedes = pages.id); \
- UPDATE pages SET valid_to = COALESCE(superseded_at, updated_at) \
- WHERE is_latest = 0 AND valid_to IS NULL \
- AND NOT EXISTS (SELECT 1 FROM pages s WHERE s.supersedes = pages.id);",
+ "DROP INDEX idx_pages_validity; \
+ ALTER TABLE pages DROP COLUMN valid_from; \
+ ALTER TABLE pages DROP COLUMN valid_to;",
)
.unwrap();
+ db.execute_batch(include_str!(
+ "../migrations/V62__page_ingestion_windows.sql"
+ ))
+ .unwrap();
let backfilled: Vec<(Vec<u8>, Option<i64>, Option<i64>)> = db
.prepare("SELECT id, valid_from, valid_to FROM pages ORDER BY created_at")
.unwrap()
@@ -6572,6 +6568,61 @@ mod tests {
}
}
+ /// Pre-V62 reorg/move retirements kept their instant only at link grain.
+ #[test]
+ fn v62_backfill_preserves_retired_link_windows() {
+ let db = rusqlite::Connection::open_in_memory().unwrap();
+ db.execute_batch(
+ "CREATE TABLE pages (
+ id INTEGER PRIMARY KEY, workspace_id INTEGER, project_id INTEGER,
+ created_at INTEGER, updated_at INTEGER, superseded_at INTEGER,
+ supersedes INTEGER, is_latest INTEGER);
+ CREATE TABLE entity_page_links (page_id INTEGER, superseded_at INTEGER);
+ INSERT INTO pages VALUES
+ (1,1,1,100,100,NULL,NULL,0),
+ (2,1,1,100,100,NULL,NULL,0),
+ (3,1,1,100,150,NULL,NULL,0),
+ (4,2,2,100,100,NULL,NULL,1),
+ (5,1,1,100,100,350,NULL,0);
+ INSERT INTO entity_page_links VALUES
+ (1,300),(1,300),(2,300),(4,300),(5,100);",
+ )
+ .unwrap();
+ db.execute_batch(include_str!(
+ "../migrations/V62__page_ingestion_windows.sql"
+ ))
+ .unwrap();
+ // Reorg and move keep [100,300); missing evidence falls back;
+ // a sibling scope's live page stays open; the decay marker wins.
+ for (id, expected) in [
+ (1, Some(300)),
+ (2, Some(300)),
+ (3, Some(150)),
+ (4, None),
+ (5, Some(350)),
+ ] {
+ let window: (i64, Option<i64>) = db
+ .query_row(
+ "SELECT valid_from, valid_to FROM pages WHERE id = ?1",
+ [id],
+ |r| Ok((r.get(0)?, r.get(1)?)),
+ )
+ .unwrap();
+ assert_eq!(window, (100, expected), "page {id}");
+ }
+ for (instant, expected) in [(99, 0), (100, 2), (200, 2), (299, 2), (300, 0)] {
+ let count: i64 = db
+ .query_row(
+ "SELECT COUNT(*) FROM pages WHERE id IN (1,2)
+ AND valid_from <= ?1 AND (valid_to IS NULL OR valid_to > ?1)",
+ [instant],
+ |r| r.get(0),
+ )
+ .unwrap();
+ assert_eq!(count, expected, "instant {instant}");
+ }
+ }
+
/// Issue #656 acceptance: `postgres → sqlite → postgres` (+ revert).
/// `as_of` inside the middle window returns that version via the
/// entity stream AND via version-filtered FTS — the middle version
diff --git a/crates/ai-memory-store/src/reader.rs b/crates/ai-memory-store/src/reader.rs
index 2ee9a351..adee4558 100644
--- a/crates/ai-memory-store/src/reader.rs
+++ b/crates/ai-memory-store/src/reader.rs
@@ -1854,8 +1854,9 @@ impl ReaderPool {
}
/// Authority-adjusted full-text candidates over the page versions
- /// whose ingestion windows contain `as_of_us` (issue #656): "what
- /// would search have said at T". Same candidate shape as
+ /// whose ingestion windows contain `as_of_us` (issue #656).
+ /// BM25 uses the current index's statistics, not a snapshot at T.
+ /// Same candidate shape as
/// [`Self::search_page_candidates_for_project`], but the corpus is
/// versions alive at `T` instead of latest versions. TTL expiry is
/// evaluated at `T`: a page already expired then was already hidden
@@ -1953,7 +1954,7 @@ impl ReaderPool {
/// unchanged, plus version-filtered FTS over the page ingestion
/// windows alive at `as_of_us`, fused with the same RRF (k=60) the
/// default path uses and the same bounded authority adjustment —
- /// relevance *at T* over knowledge *valid at T*. Vector, graph, and
+ /// current-index relevance over knowledge *valid at T*. Vector, graph, and
/// the raw-observation fallback stay out of audit mode: embeddings
/// and links are present-tense artifacts with no version scope, and
/// audit reads must not perturb access stats (no bump, no rerank).
diff --git a/docs/design-page-ingestion-windows.md b/docs/design-page-ingestion-windows.md
index 667b4658..aa7dc198 100644
--- a/docs/design-page-ingestion-windows.md
+++ b/docs/design-page-ingestion-windows.md
@@ -74,15 +74,15 @@ A version's window closes at exactly one of:
`is_latest` flip (mirrors the link-window close in `upsert_page_in_tx`).
2. **Retire without successor** — decay tombstone, purge-regenerate,
graveyard merge (the V58 class). `valid_to` = the retirement instant
- (`updated_at` at retire time, as V58 did for links), closed in the same
+ (recorded explicitly on both grains), closed in the same
transaction as the retire. New retire paths must close both grains;
V58's audit is the checklist.
3. **Open** — `valid_to IS NULL` while the version is the latest live one.
Deletion stays deletion: purged pages cascade away and the timeline does
not survive a purge, exactly as `docs/temporal.md` already states for
-links. Expiry/TTL is orthogonal: an expired page is hidden from both the
-default path and `as_of` (same `not_expired` predicate, evaluated at T).
+links. Expiry/TTL is orthogonal: the FTS leg applies `not_expired` at T;
+the entity leg preserves its existing ignore-expiry behavior.
## 4. Materialized columns vs. a view/join
@@ -131,7 +131,9 @@ renamed surface, no changed defaults) — but additive is not free:
- **Refinery migration**, one step: add the nullable columns, backfill
(`valid_from = created_at`; `valid_to` from the superseding version's
`created_at` via `pages.supersedes`, `NULL` for latest;
- successor-less retired rows closed at their `updated_at` per V58),
+ successor-less retired rows closed at the decay marker, else the
+ earliest existing entity-link close, else `updated_at` as an
+ approximation when no retirement timestamp survived),
create the `(valid_from, valid_to)` index. Idempotent re-run migrates
zero rows.
- **Backup gate.** The migration refuses to run without a verified
@@ -140,9 +142,10 @@ renamed surface, no changed defaults) — but additive is not free:
when the archive cannot be written or verified). This is the step the
issue understates, stated here so the implementation PR is sized
honestly.
-- **Rollback.** Nullable columns are ignored by older binaries, so a
- downgrade reads the migrated store; deletion of the columns is never
- required. Forward re-runs are no-ops.
+- **Rollback.** Restore the verified pre-migration snapshot from #633
+ before starting the older binary. Refinery rejects newer applied
+ schema versions; an older binary cannot read the migrated store.
+ Forward re-runs are no-ops.
## 6. `as_of` gains version-filtered FTS: the explicit reversal
@@ -157,9 +160,12 @@ silent scope slip:
- The original objection is about mixing **present-tense relevance** with
**past validity**. Constraining the FTS corpus to versions whose
- ingestion window contains T makes *both* signals past-tense: relevance
- *at T* over knowledge *valid at T*. That is "what would search have
- said in July", asked honestly.
+ ingestion window contains T makes the retrieved content historical.
+ Ranking is not a historical snapshot: FTS5 BM25 still uses the current
+ index's statistics, including later versions and other projects.
+ Later writes can change ordering and the limited result set at a
+ fixed T. Phase A retrieves historical versions with current-index
+ relevance; it does not reproduce what search would have ranked then.
- Concretely, `as_of` runs two streams at T and merges via the existing
RRF: the unchanged entity-window lookup plus FTS over page versions
with `valid_from <= T AND (valid_to IS NULL OR valid_to > T)` (and the
diff --git a/docs/temporal.md b/docs/temporal.md
index 1c1dc2c9..14917d15 100644
--- a/docs/temporal.md
+++ b/docs/temporal.md
@@ -51,7 +51,12 @@ a superseded version.
| column | meaning |
|---|---|
| `valid_from` | the version's own `created_at` |
-| `valid_to` | `created_at` of the superseding version; the retirement instant for successor-less retirements (decay tombstones, graveyard merges, move-regenerate rows — `COALESCE(superseded_at, updated_at)`, the V58 rule); `NULL` while the version is latest |
+| `valid_to` | `created_at` of the superseding version; the retirement instant for successor-less retirements; `NULL` while the version is latest |
+
+For existing successor-less retirements, V62 uses the decay marker first,
+then the earliest recorded entity-link close, then `updated_at` as an
+approximation when no retirement timestamp survived. Reorg and
+move-regenerate historically recorded the close only in entity links.
The end is named `valid_to`, not `superseded_at`, because
`pages.superseded_at` already exists with a different meaning: the V03
@@ -96,7 +101,7 @@ outage?"), still resolves through the text that was live at T.
## Query
`memory_query` accepts `as_of` (ISO-8601). When present the query is
-a **time-travel lookup over two streams, both past-tense at T**:
+a **lookup over historical versions using two streams**:
- the **entity timeline**: links whose window contains the instant
(`valid_from <= T AND (superseded_at IS NULL OR superseded_at > T)`),
@@ -104,16 +109,16 @@ a **time-travel lookup over two streams, both past-tense at T**:
- **version-filtered FTS**: page versions whose page-grain window
contains the instant
(`valid_from <= T AND (valid_to IS NULL OR valid_to > T)`),
- answering entity-less pages and paraphrased questions — "what would
- search have said in July".
+ answering questions through lexical matches even without entity metadata.
The two streams merge with the default path's RRF (k=60) plus the same
bounded authority adjustment, and `explain=true` reports both in
`streams_active` (`["entity", "fts"]`) with per-stream ranks and RRF
-contributions. Constraining the FTS corpus to versions alive at T is
-what answers the original objection to FTS in `as_of` (that mixing
-present-tense relevance with past validity answers neither honestly):
-both signals are past-tense here.
+contributions. The time filter selects historical versions, but FTS5
+BM25 uses statistics from the current index, including later versions
+and other projects. Later writes can therefore change ordering and the
+limited result set for the same T. This retrieves historical content;
+it does not reproduce the ranking a search would have returned at T.
Still out of `as_of`: vector (embeddings are present-tense artifacts
of the current text; version-scoped vectors are a separate project),