Knowledge Freshness and Temporal Updates › As-Of Retrieval: Reproducible Time-Aware RAG

Michael BrenndoerferDecember 1, 20266 min read
Language AI HandbookAll chapters
Part 45 of 67Knowledge, Memory, Editing, and Unlearning
Chapter 348Knowledge Freshness and Temporal Updates › As-Of Retrieval: Reproducible Time-Aware RAG
Reading section 6 of 12 · As-Of Retrieval: Reproducible Time-Aware RAG · 6 minSection 6 of 12 · 6 min

Section 6 of 12 · 6 min read

Reading settings

Definitions

Choose how many terms have tooltips.

Article links

Make inline references clickable

Notes & comments

As-of retrieval narrows the candidate pool before scoring. A world-date request uses the valid intervals applied to the evidence. A historical serving replay starts with what was available in a retained snapshot. A request can specify both dates.

Two flavors again

Mirroring the fact model, an as-of retrieval query has two modes:

  • Valid-time retrieval: admit evidence whose recorded validity interval covers the target date. Select the evidence snapshot separately if the question also specifies when the facts had to be known.
  • Transaction-time retrieval: admit evidence indexed by the target date in this insert-only toy. A history with removals needs a snapshot or a record of when each document stopped being visible.

A document indexed in September can describe a February fact. It can enter a February lookup over the latest snapshot and remain absent from a replay of the May snapshot.

Consider two queries about February 2023. One asks what the latest corrected record says about February. The other asks what the assistant could have retrieved in June about February. The first lookup can use a September correction. The second uses the June evidence snapshot and the validity intervals recorded in June. Applying the latest intervals to June's documents would change what was retrievable then. When two documents in an admissible set give conflicting dates, a deterministic sort key makes the ordering repeatable. Source authority or an adjudicated timeline is needed to resolve the disagreement.

Filtering, not just ranking

Filter before scoring here so an ineligible candidate cannot occupy a top-kk slot. Truncating to an unfiltered top kk first can leave too few results after exclusions.

This NumPy example ranks eligible documents by cosine similarity over deterministic hashed character trigrams. The lexical score does not judge source authority.

PythonIn [11]
CollapseExpand
from hashlib import blake2b

import numpy as np

DIM = 256


def embed(text: str) -> np.ndarray:
    weights = np.zeros(DIM)
    normalized = text.lower()
    for i in range(len(normalized) - 2):
        trigram = normalized[i : i + 3].encode("utf-8")
        bucket = (
            int.from_bytes(blake2b(trigram, digest_size=8).digest(), "big")
            % DIM
        )
        weights[bucket] += 1
    norm = np.linalg.norm(weights)
    return weights / norm if norm else weights


@dataclass(frozen=True)
class Doc:
    doc_id: str
    text: str
    published_at: datetime
    indexed_at: datetime
    valid_from: datetime
    valid_to: Optional[datetime] = None
    validity_source: Optional[str] = None
    validity_recorded_at: Optional[datetime] = None


def cosine(a, b) -> float:
    return float(np.dot(a, b))

The retrieval function applies the time predicate before scoring. Transaction mode checks the index date, so a published filing can still be ineligible. A lowercased query shorter than three characters has no trigram features. Its scores tie at zero, and document IDs determine the order among eligible candidates.

PythonIn [12]
CollapseExpand
def admissible_at(doc: Doc, target: datetime, mode: str) -> bool:
    if mode == "transaction":
        return doc.indexed_at <= target
    if mode == "valid":
        return doc.valid_from <= target and (
            doc.valid_to is None or target < doc.valid_to
        )
    raise ValueError(f"Unknown mode: {mode}")


def as_of_retrieve(
    query: str, docs, k: int, target: datetime, mode: str = "transaction"
) -> list[Doc]:
    if k < 0:
        raise ValueError("k must be nonnegative")
    if mode not in {"transaction", "valid"}:
        raise ValueError(f"Unknown mode: {mode}")
    candidates = [doc for doc in docs if admissible_at(doc, target, mode)]
    query_vector = embed(query)
    return sorted(
        candidates,
        key=lambda doc: (-cosine(query_vector, embed(doc.text)), doc.doc_id),
    )[:k]

The correction is published in August 2024, indexed in September, and applies from February 2023. This raw evidence pool uses the latest validity metadata and keeps both Bob filings. Both name Bob as CEO in May 2024, but they disagree about his start date. Use this pool to compare the two filters. The serving snapshots below use the adjudicated timeline recorded when each snapshot was sealed.

PythonIn [13]
CollapseExpand
docs = [
    Doc(
        "alice-2014",
        "Alice was the CEO of Acme.",
        published_at=utc(2014, 1, 1),
        indexed_at=utc(2024, 1, 1),
        valid_from=alice_start,
        valid_to=corrected_bob_start,
    ),
    Doc(
        "bob-2023",
        "Bob became CEO of Acme in March 2023.",
        published_at=utc(2023, 3, 1),
        indexed_at=utc(2024, 6, 15),
        valid_from=initial_bob_start,
    ),
    Doc(
        "bob-fix-2024",
        "Correction: Bob became CEO of Acme in February 2023.",
        published_at=utc(2024, 8, 20),
        indexed_at=utc(2024, 9, 1),
        valid_from=corrected_bob_start,
    ),
]
query = "Who is the CEO of Acme"
query_times = [utc(2024, 5, 1), utc(2024, 8, 1), utc(2024, 10, 1)]
retrieval_results = [
    (time, mode, as_of_retrieve(query, docs, len(docs), time, mode))
    for time in query_times
    for mode in ("transaction", "valid")
]
ConsoleOut [14]
CollapseExpand
2024-05-01 transaction ['alice-2014']
2024-05-01 valid ['bob-2023', 'bob-fix-2024']
2024-08-01 transaction ['alice-2014', 'bob-2023']
2024-08-01 valid ['bob-2023', 'bob-fix-2024']
2024-10-01 transaction ['alice-2014', 'bob-2023', 'bob-fix-2024']
2024-10-01 valid ['bob-2023', 'bob-fix-2024']

At the May transaction cutoff only Alice's document is eligible. August admits Alice's document and the first Bob filing. October admits all three. This test checks their index arrival dates. In valid mode, both Bob documents cover all three query dates in the latest raw pool. Source authority decides which start date to use.

Count admissible documents before scoring to isolate the filters. The date sweep uses one-day steps. The vertical gap is a difference in counts because either mode can include a document that the other excludes.

PythonIn [15]
CollapseExpand
import numpy as np

# Sweep target dates at daily resolution and record admissible counts.
sweep_start = utc(2024, 1, 1)
sweep_days = 320
sweep_dates = [sweep_start + timedelta(days=d) for d in range(sweep_days)]
trans_counts = np.zeros(sweep_days, dtype=int)
valid_counts = np.zeros(sweep_days, dtype=int)
for i, t in enumerate(sweep_dates):
    trans_counts[i] = sum(admissible_at(doc, t, "transaction") for doc in docs)
    valid_counts[i] = sum(admissible_at(doc, t, "valid") for doc in docs)
sweep_x = mdates.date2num(sweep_dates)
VisualizationOut [16]
CollapseExpand
Transaction-time counts rise in June and September. The dashed valid-time line stays at two.
Admissible documents by date in the synthetic corpus. Transaction-time counts rise from one to three as documents are indexed. Valid-time counts stay at two in this 2024 sweep, using the latest supplied evidence.

The transaction-time steps mark June 15 and September 1, the indexing dates of the two Bob documents. The valid-time count stays at two because both Bob documents cover the entire plotted period in the latest supplied evidence pool.

As-of retrieval is the foundation of reproducibility

Log the query, target, mode, and index version to identify a retrieval request. Keep the encoder, ranking configuration, and retrieved document IDs to investigate the replay. A past answer also depends on the prompt and model execution. Retain the original response when the audit requires it and your retention policy allows it.

Comments

Add to the conversation

A question, a correction, or an example from your own work.

No comments yet. Be the first to share your thoughts!

Newsletter

Stay up to date

Get new articles, book updates, and notes on AI and technology.

Unsubscribe at any time. Privacy policy