Feature: full bi-temporal memory and knowledge retrieval

Abierto
#25 2 comentarios 0 reacciones 0 asignados Ver en GitHub

Los mantenedores suelen responder en 1 día

Nadie ha tomado este issue todavía.

  • #30 de @zlareb1 — cerrado sin fusionar

Evaluación

Dificultad
5/5
Tiempo estimado
Más de una semana
Aptitud para principiantes
15/100
Tipo de issue
Nueva funcionalidad
Claridad
Bien especificado
Estado de actividad
Estancado
Stack tecnológico
clickhouse, python
Área
ai, backend, databases

Línea de trabajo

Start by reading the current temporal memory implementation at the referenced commit, especially memory_versions, memory.set, and the insert and projection paths described in the issue. The issue calls for an authoritative amendment journal, serialized namespace publication, and historical reads across multiple memory types, so this is a broad design and implementation effort. Done means the first strict release meets the stated mutation, retry, publication, projection, and exact-read contracts.

Escrito por el modelo de indexación a partir del texto del issue.

Descripción

enhancement hold

Goal

Answer: Which assertions applied at valid time V, according to the beliefs Loom had recorded at knowledge time K? Preserve earlier beliefs after corrections, deletion, and merges.

Temporal consistency does not establish truth. Source evidence, accepted beliefs, and context actually shown to an agent remain separate records.

Recommendation and scope

Decision Recommendation
Authority An immutable amendment journal; each committed row contains one complete change to a logical memory
Serving Revision-qualified assertion projections; retain existing current-state tables as compatibility projections
Ordering One serialized logical publisher per namespace; a namespace commit sequence defines publication order
First strict release Durable private memory, all enabled memory mutations, exact reads/history, interval correction, and basic search
Later coverage Shared memory, records, graphs/derived retrieval, documents/conversations, then code/tracker generations
Replay guarantees Historical content correctness first; repeatable retrieval and decision reconstruction are additional capabilities

Use amendment events with periodic checkpoints. A bounded correction copies only affected segments; full timeline copies on every edit can accumulate quadratic write volume. Reuse memory_versions as migration evidence and compatibility history; its present shape cannot atomically represent a multi-segment correction.

Benchmark checkpoint frequency, projection layout, and exact/ANN search thresholds. These tune the chosen model; they do not postpone the authority or consistency decision.

Current implementation: verified gaps

Assessed at b0f7d297ad7618a450f9e5e39009c9d33ef61825.

  • as_of/as_of_basis selects one axis. Search reads current embedding projections rather than reconstructing all prior beliefs.
  • memory.set preserves the memory's original created_at; that field cannot timestamp a revision. time.time_ns() orders current versions but is not a publication protocol.
  • memory_versions retains inserted versions because its sorting key includes version. Its materialized view does not capture in-place mutations; usage metadata and graph interval repairs need separate treatment.
  • Memory/embedding inserts run concurrently; graph, evidence, and other projections may finish later. Strict temporal reads cannot assume cross-table atomicity.
  • Conditional key locking falls back to a process lock when Keeper is unavailable. Namespace publication and crash recovery need a stronger, explicitly bounded contract.
  • Shared memory has no equivalent temporal mirror; record queries join current fields; graph repairs mutate intervals; derived lineage generally lacks exact assertion revisions.
  • Evidence already separates observed_at and created_at; deferred extraction introduces a later belief-publication event. Exposure records contain returned keys, not complete revision/context receipts.
  • Documents, compiler indexes, and live tracker sources need their own retained revision/generation histories before participating in historical answers.

Temporal and belief contracts

  • UTC DateTime64(6, 'UTC'); state validity uses [valid_at, valid_to). valid_to=NULL means an open end.
  • Unknown validity is distinct from an asserted unbounded past. Preserve precision, original date text, timezone, and whether an endpoint was stated, extracted, or inferred.
  • Observation time, evidence receipt time, and belief publication time are separate. Extraction/re-extraction never backdates a belief's publication to the source date.
  • Recording time is assigned by the publisher, increasing with its commit sequence. It is an application timestamp; the sequence/token provides the precise publication boundary, not an implied ClickHouse transaction timestamp.
  • Preserve the full physical identity (org, namespace, scope, agent, user_id, session_id, memory_key). Where available, subject/predicate/qualifiers identify a semantic claim; do not force triples onto arbitrary prose or merge tenant scopes.
  • State, event, snapshot, and rule memories have different temporal behavior. An event/snapshot must not become an indefinitely active state.
  • Attribution, modality, grounding, confidence, attestation, source class, and support links are versioned. Planned, hypothetical, quoted, and disputed content cannot silently become observed fact.
  • Arrival order is a recording order, not a universal conflict-resolution rule. Retain competing claims and explicit resolution decisions; enforce non-overlap only for resolved, single-valued claims within the same qualifiers/scope.
  • Repeated/copy-derived evidence shares source lineage; it is not independent corroboration. Source withdrawal or changed trust produces a new assessment of dependent beliefs.
Mutation semantics
Intent Valid-time effect Knowledge-time effect
Assert Add supported interval/event; disclose an inferred recording-time fallback if no effective date is known New assertion becomes recorded at this commit
Correct Replace specified assertion/interval; preserve unaffected supported segments Previous interpretation remains queryable at earlier K
Transition End old state at explicit effective V; start the new state Record the transition now, including future-effective transitions
Temporary override Replace only its declared interval; resume a prior value only under a supported continuity policy Retain prior expectations and later amendments/cancellation
Retract/delete Remove the assertion from the served belief set; do not imply the world changed at deletion time Earlier authorized beliefs remain in history
Verify/resolve/change confidence or expiry Revise assessment/serving metadata without inventing a world-state transition New assessment becomes visible at this commit
Restore/rollback/import Apply a compensating change with explicit source lineage New local publication time; never rewrite an earlier commit
Redact/erase Remove prohibited content from every retained slice Immediate read suppression, followed by verified physical cleanup

An ordinary value edit revises the recorded assertion; it does not assert a transition at write time. Add explicit correction/transition intent and expected revision to write APIs.

Data model

memory_temporal_commits — authoritative journal, MergeTree.

Field group Required fields
Tenant/key Full physical identity and stable logical memory_id
Order Namespace commit_seq, commit_id, key parent_commit_id, publisher generation, recorded_at
Retry/integrity Original request/idempotency identity, operation, payload schema version, canonical payload hash
Authorship Actor, source class, source-resource references, erasure generation
Amendment Retired assertion IDs and complete new assertion payloads, serialized in one row
  • Proposed sort key: (org, namespace, commit_seq, commit_id); recording-month partitioning. Add a logical-key skip index and benchmark namespace/time pruning.
  • Each new assertion contains its ID, parent/origin assertion references, value/content hash, temporal kind and validity basis, interval/occurrence, status, confidence, expiry, attestation, qualifiers, and exact evidence/derivation references.
  • A finite correction atomically retires its target and adds the supported before/corrected/after segments. New semantic versions receive new assertion IDs; immutable source evidence retains its identity.
  • A retry reuses the same commit ID, sequence, timestamp, and payload hash. Deduplicate equal retries explicitly; conflicting payloads for one commit/sequence are an integrity error, never last-write-wins.
  • Keep client idempotency identity in the journal beyond the transport cache's lifetime. A reused key with a different request is refused; without a client retry key, do not claim exactly-once behavior across separately submitted requests.

Projections and checkpoints.

  • memory_temporal_assertions: immutable assertion content plus born_seq and derived retired_seq. A projection may use ReplacingMergeTree(projected_seq); every re-emission carries every column. History remains in the journal.
  • Model-qualified vector/lexical projections refer to assertion identity. Reuse embeddings by actual embedding-input hash plus model/dimension/configuration, including key-axis inputs; content hash alone is insufficient.
  • Each projection publishes a durable contiguous applied sequence. A failed event blocks advancement; later successes cannot hide the gap.
  • Checkpoints hold the reduced assertion set at sequence C with original temporal/provenance metadata. They are storage artifacts, not new beliefs. Reconstruct from a checkpoint plus the subsequent journal tail.
  • Current memory/shared compatibility rows are projections. Their selected legacy value follows existing resolution policy; temporal APIs expose the assertion set and dispute state.

Publication protocol: first strict release

Choose a single logical publisher per namespace. API replicas and workers submit semantic changes to it; embedding and LLM preparation happen outside its serialized commit section.

  1. Authorize the original caller and prepare the proposed change against an expected key revision.
  2. Under the publisher, recheck current revision, current policy/locks, evidence availability, and erasure generation. Refuse or re-prepare stale proposals.
  3. Allocate the next namespace sequence and monotonic recording timestamp; construct the complete amendment and stable retry identity.
  4. Synchronously insert one journal row in one block/partition. This insert is the publication boundary; no serving-table insert can publish a belief independently.
  5. Return its receipt after confirmed persistence; apply serving projections idempotently. A projection failure cannot revoke the committed belief.
  6. A read-your-write token names the committed sequence. Exact reads may reduce the journal tail; search waits within budget or returns explicit projection-not-ready when required indexes lag.
Failure Required behavior
Crash before journal insert No published change
Timeout/uncertain insert result Reconcile the same commit ID/hash; do not publish another successor until its outcome is known
Retry inserts the same row twice One logical commit after explicit deduplication
Same sequence/ID has different payloads Mark integrity failure and stop strict serving beyond the last valid prefix
Crash after publication, before projections/response Recover receipt from the journal and resume projection replay
Publisher unavailable Reads continue at retained watermarks; semantic writes fail closed
Publisher takeover Stop/fence the old process and quiesce its in-flight inserts before recovery; a lease timeout alone is insufficient
Read replica is behind a receipt/token Wait within budget, route to the authoritative reader, or return not-ready; never answer from an older cutoff as if it matched

The first release trades automatic write failover for a tractable correctness model. Do not rely on today's host-local supervisor/key locks to enforce this across hosts. Add explicit publisher routing, bounded queues, ownership checks, and deployment validation; reuse forwarding infrastructure where suitable while preserving caller identity.

Distributed publishers/automatic takeover require a separately proven fencing/acceptance protocol. They are not silently enabled by setting web_workers>1. Bulk and cross-namespace operations expose per-key/per-namespace partial completion; the MVP promises no cross-key transaction.

Journal inserts must reject missing temporal columns/schema drift. Disable permissive column projection for the authority; an omitted field must not silently weaken its guarantees.

Read cutoffs and write receipts use the same authoritative ClickHouse route. Validate acknowledgement durability and replica-read behavior for supported Cloud/OSS deployments; declare the covered failure model and required quorum/storage settings instead of assuming every replica has observed an insert.

Read contract

Request Meaning
No temporal arguments Current valid state using current recorded beliefs
valid_as_of=V Latest recorded interpretation at V
known_as_of=K Recorded interpretation at K of the world at K
Both Recorded interpretation at K of the world at V
  • Capture a canonical namespace cutoff C in one journal query: highest committed sequence with recording time ≤ K, or current sequence. Return V, K, C, history coverage, and completeness.
  • Proposed wire additions: valid_as_of, known_as_of, read_token, and validity_policy; writes add change_kind, target assertion, expected_revision, and durable idempotency identity. Register memory.amend for bounded corrections rather than overloading deletion or silently changing memory.set intent.
  • Temporal results include assertion/revision IDs, interval/occurrence, source/validity basis, dispute state, cutoff, and coverage. Compatibility validity admits disclosed fallbacks; strict validity excludes unknown/inferred bounds. The same policy must reach every retrieval leg and synthesis input.
  • Pinned tokens retain that cutoff per namespace/plane. Namespace sequences are not a cross-namespace atomic snapshot; expose the selected cutoff vector instead of claiming a global transaction.
  • Reconstruct accepted assertions through C, then filter validity and historical status/expiry. Never filter content/tags before resolving amendments; a removed assertion must not reappear because its replacement fails a filter.
  • Projection eligibility is born_seq <= C AND (retired_seq IS NULL OR C < retired_seq), followed by the valid-time predicate. Later retirement rows remain compatible with earlier C.
  • Use a projection only when its contiguous applied watermark covers C, or correctly overlay/reduce the missing tail. A completed historical answer cannot silently omit newly published assertions.
  • Current permissions, blacklist/disclosure controls, and erasure suppression apply regardless of K. Historical analysis does not authorize an action today.
  • Preserve legacy as_of/as_of_basis via an explicit adapter; legacy knowledge-time replay ignores validity. Reject ambiguous combinations and document its limits.
  • Add interval/history queries and separate diffs: world-state changes at fixed K versus belief changes at fixed V. Future V can describe recorded plans/rules; future K is invalid.
  • Distinguish absent evidence, unresolved dispute, unknown validity, pending processing, denied access, and unavailable retained history. Preserve existing non-disclosing authorization responses.
  • Bind pagination/cache/offloaded context to cutoff, permissions, model/configuration, and erasure generation. TTL limits the served set; physical retention independently limits recovery.

Cross-plane work

Surface Required extension
All memory writers API, bulk/extraction, CLI, workers, conflict decisions, pin/lock/verify, expiry, restore/rollback, copy/move, consolidation and promotion must journal semantic changes
In-place mutations Inventory dynamic/lightweight updates as well as static ALTER; counters may remain operational, but trust/status/validity changes need temporal records
Shared/records Promotion lineage and shared history; historical record fields and schemas must match the selected record revision
Graphs Revision-qualified assertions, contribution/support lineage, historical entity aliases/categories; derive aggregates from eligible evidence
Summaries/observations Exact source revisions, own derivation publication time, versioned dependency reassessment; no invented common interval for mixed-period summaries
Search/ask Eligible assertions before ranking/ANN limits; measure selective-filter recall, use exact/bounded fallback, include revision-qualified citations
Profile/procedures/context Resolve historical scope precedence; exclude current working memory/advisories from historical packs unless snapshotted
Documents/conversations Source/effective dates separate from ingestion/edit time; retain document/chunk membership and required blobs
Code Commit, compiler/extractor generation, publication time, and complete generation manifest across symbols/edges/chunks
Tracker Retained source observations with fetch/effective times; historical queries cannot consult today's source state
Unified search Declare per-plane capabilities; unsupported historical legs return coverage gaps

Repeatable scoring additionally requires historical corpus statistics, graph degrees, trust/recall signals, and ranking configuration. The content-correctness MVP may use current ranking with explicit disclosure.

Decision reconstruction requires receipts for the exact revisions/excerpts, packing order, query/rewrite, cutoff, prompt/ranking/model versions, and run/request identity actually supplied to an agent. Available memory is not proof of exposure; reconstruction does not guarantee regenerating an LLM's answer.

Agent-memory scenario matrix

Each scenario needs an executable fixture and expected result; this is explicit initial coverage, not a claim that every future use case is known.

ID Scenario Required result
U01 Employer changes versus correcting a mistaken employer Explicit transition versus corrected belief
U02 Old conversation arrives after a newer update Fill older period without reverting newer state
U03 Future policy is amended/cancelled Preserve current state and earlier future expectations
U04 Preference A → B → A Separate episodes despite repeated content
U05 Temporary override ends Supported fallback or unknown; no invented resumption
U06 Sources disagree about the same period Dispute or explicit justified resolution
U07 Evidence is copied/repeated by agents Shared lineage; no manufactured corroboration
U08 Quotation, speculation, hypothetical, plan Preserve speaker/subject/modality
U09 Unknown/approximate/relative/date-only time Preserve uncertainty, precision, reference timezone
U10 What changed/when/how long Correct interval/diff reasoning with visible gaps
U11 Evidence received before extraction finishes Different receipt and belief-publication boundaries
U12 Re-extraction after source/model correction New publication time; previous extraction retained
U13 Source retracts evidence or loses trust New dependent assessment; earlier beliefs preserved
U14 Human verifies/resolves/rejects Version decision, actor, rationale, attested hash
U15 Subject/key rename or merge Historical identity/aliases; tenant isolation
U16 Multiple roles/contextual preferences Cardinality and qualifiers prevent false supersession
U17 Session/project/user overrides Historical scope precedence with source attribution
U18 Event, balance snapshot, rule, state Appropriate temporal shape; no false continuity
U19 Summary spans mixed validity periods Exact dependencies and claim-level attribution
U20 Investigate a past agent decision Actual exposure distinct from available memory
U21 Act today using historical facts Current authorization/locks/action constraints
U22 TTL, deletion, redaction, erasure Explicit archive policy; prohibited content cannot return
U23 Parallel agents retry/conflict Stable receipts, expected-revision checks, visible conflicts
U24 Simulation/counterfactual No pollution of main beliefs; branches outside MVP
U25 Incomplete history/projections/no evidence Gap/dispute/pending/abstention; no confident invented answer
Minimal temporal oracle
  • January 10: record A, supported from January 1 onward.
  • January 20: correct January 5–15 to B, preserving supported A outside that interval.
V K Answer
January 7 January 9 No recorded assertion
January 7 January 12 A
January 7 January 21 B
January 3 January 21 A
January 17 January 21 A

This oracle tests a supported baseline correction. It must not imply automatic resumption after an unrelated temporary override.

Migration, retention, erasure

  • Add numbered migrations; regenerate schemas/schema.sql. Update typed builders/projections, registry/wire models, generated SDKs, MCP, CLI, dashboard, docs, and settings comments together.
  • Namespace rollout states: legacy, shadow capture, strict serving. Shadow capture reports gaps; it is not a correctness guarantee.
  • Before strict cutover, pause namespace semantic writes, drain in-flight work, build a baseline from retained history/current rows, reconcile capture, validate parity, and reopen through the sole publisher.
  • In strict namespaces, unsupported mutations must be refused explicitly rather than bypass the journal. Inventory imports, maintenance paths, and dynamically assembled SQL before enabling them.
  • Legacy nanosecond versions provide ordering evidence, not certified publication times. Mark precision/coverage and gaps; do not infer unrecorded mutation history or fabricate missing plane history.
  • The first strict guarantee begins at cutover. Pre-cutover reconstruction remains explicitly best effort unless its recording/coverage evidence meets the same contract.
  • Physical retention preserves the boundary checkpoint, active assertions/values, and required dependencies. Recording-month partition deletion alone can remove still-needed state.
  • Restore/import publishes new local commits while preserving source provenance; rollback publishes compensation. Never restore original publication order into the destination namespace.
  • Erasure first suppresses reads and advances a scoped erasure fence; stale commit/projection work touching erased identities is rejected. Unaffected history remains usable. Register all new tables/blobs/cache/receipts in saga steps and the residue census; verify cleanup across historical tokens and projections.
  • Preserve hash-only audit. Retain raw context receipts only under explicit content/disclosure/retention policy; erasure can make decision reconstruction unavailable.
  • Feature rollback disables strict serving and rebuilds current compatibility rows from the last valid journal prefix; preserve committed history and do not resume unjournaled writes unnoticed.

Delivery and release gates

  1. Contract/reference model: mutation semantics, use-case fixtures, authority schema, API/output examples, publisher deployment contract, and ADR.
  2. Journal/publication: stable retry receipts, recovery, all admitted semantic writer paths, ownership/admission controls, schema guards, and erasure-generation checks.
  3. Memory MVP: reducer/checkpoints, assertion/current projections, exact reads/history, bounded corrections, basic search, and shadow-to-strict cutover.
  4. Complete memory surface: shared memory, records, graphs/derived lineage, profile/procedures/context, ask/citations, caches/pages, UI/SDKs, and decision receipts.
  5. Cross-plane completion: document/conversation revisions, code manifests, retained tracker observations, unified capability reporting.
  6. Operations: retention/rebuild/rollback drills, capacity benchmarks, runbooks; a separate proven protocol before automatic distributed publisher failover.
  • The temporal oracle and U01–U25 pass applicable exact/search/ask/record/graph paths, including permuted source arrival and bounded context budgets.
  • Property tests compare interval amendment/retraction/reduction against a simple reference model; test endpoints, uncertainty, identical content, and no unsupported continuity.
  • Fault injection covers every publication failure above, partial projection replay, duplicate payloads, restart/takeover, and stale erasure generations.
  • No reader silently mixes cutoffs; future summaries/current profiles/live tracker/code generations cannot leak into historical content.
  • Erasure/redaction, revoked grants, cross-tenant/agent/session reads, and token invalidation pass actual ClickHouse integration tests.
  • Merge/re-embed/rebuild/retention/cutover/rollback preserves answers or explicitly reports lost coverage.
  • Establish budgets before implementation; report current/historical p50/p95/p99 latency, scanned bytes, temporal recall, queue pressure, checkpoint/rebuild time, and write/storage amplification against the current baseline.
  • Evaluate extraction, multi-session reasoning, temporal reasoning, updates, provenance/disagreement, and abstention using fixed models and dataset hashes; report per-category failures.
  • Required format/lint/typecheck/unit, schema/codegen, analyzer/integration, and retrieval benchmark gates pass. Advertise capabilities only after their corresponding gates pass.

Design sanity check: a reference reducer passed the temporal oracle, half-open endpoints, retry/conflicting-row checks, and randomized comparison with independent pointwise states. This checks interval semantics only; ClickHouse SQL, publication ownership, erasure, and performance still require the gates above.

Source anchors

Lenguaje dominante
Python
Estrellas
221
Forks
35
Merge medio
14 h 21 min
PR fusionados (30 d)
873

Preparar el entorno

Abrir en Codespaces

Inicia el contenedor de desarrollo del proyecto en tu navegador, con tu propia cuenta de GitHub.

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Más de ClickHouse/loom

Todos los issues de ClickHouse/loom

Issues similares

Más issues de Python

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.