Repository navigation
feat(kr-activation): bitemporal as-of route + durable tool-observation memory #98
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -167,6 +167,7 @@ pub struct KnowledgeRuntime { | |
| config: RuntimeConfig, | ||
| entity_registry: EntityRegistry, | ||
| projection_tracker: ProjectionTracker, | ||
| bitemporal_records: Vec<bitemporal_runtime::BitemporalRecord<String>>, | ||
| } | ||
|
|
||
| impl KnowledgeRuntime { | ||
|
|
@@ -189,9 +190,20 @@ impl KnowledgeRuntime { | |
| config, | ||
| entity_registry, | ||
| projection_tracker, | ||
| bitemporal_records: Vec::new(), | ||
| }) | ||
| } | ||
|
|
||
| /// Wire a bitemporal record source so the temporal route answers as-of | ||
| /// version selection from `bitemporal-runtime` (empty = existing behavior). | ||
| pub fn with_bitemporal_records( | ||
| mut self, | ||
| records: Vec<bitemporal_runtime::BitemporalRecord<String>>, | ||
| ) -> Self { | ||
| self.bitemporal_records = records; | ||
| self | ||
| } | ||
|
|
||
| pub(crate) fn adapter_ref(&self) -> &SemanticMemoryAdapter { | ||
| &self.adapter | ||
| } | ||
|
|
@@ -447,7 +459,35 @@ impl KnowledgeRuntime { | |
| trace.recorded_as_of = Some(recorded_at_or_before.to_string()); | ||
| trace.temporal_mode = Some(temporal_mode.to_string()); | ||
|
|
||
| let results = merged.results.into_iter().map(|m| m.result).collect(); | ||
| let mut results: Vec<SearchResult> = merged.results.into_iter().map(|m| m.result).collect(); | ||
| if !self.bitemporal_records.is_empty() { | ||
| if let (Ok(v), Ok(r)) = ( | ||
| chrono::DateTime::parse_from_rfc3339(valid_at), | ||
| chrono::DateTime::parse_from_rfc3339(recorded_at_or_before), | ||
| ) { | ||
| let asof = crate::temporal::bitemporal_bridge::as_of( | ||
| &self.bitemporal_records, | ||
| v.with_timezone(&chrono::Utc), | ||
| r.with_timezone(&chrono::Utc), | ||
| ); | ||
| if !asof.is_empty() { | ||
| results = asof | ||
| .into_iter() | ||
| .map(|rec| SearchResult { | ||
|
Comment on lines
+473
to
+476
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Whenever any injected records are visible at the requested timestamps, this replaces the query pipeline's results with every visible record, regardless of the query text, resolved entity, or configured result limit. For example, a targeted temporal query with AGENTS.md reference: knowledge-runtime/AGENTS.md:L23-L24 Useful? React with 👍 / 👎. |
||
| content: rec.value, | ||
| source: semantic_memory::SearchSource::Fact { | ||
| fact_id: rec.id, | ||
| namespace: scope.namespace.clone(), | ||
|
Comment on lines
+476
to
+480
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
When a runtime has injected records, querying another namespace or a narrower workspace/repository scope returns the same records: AGENTS.md reference: knowledge-runtime/AGENTS.md:L23-L25 Useful? React with 👍 / 👎. |
||
| }, | ||
| score: 1.0, | ||
| bm25_rank: None, | ||
| vector_rank: None, | ||
| cosine_similarity: None, | ||
| }) | ||
| .collect(); | ||
| } | ||
| } | ||
| } | ||
| Ok((results, trace)) | ||
| } | ||
|
|
||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,91 @@ | ||
| //! As-of temporal bridge over `bitemporal-runtime`. | ||
| //! | ||
| //! Scope: process-lifetime store injection only. Durable persistence is | ||
| //! evidence debt; callers must inject a store. | ||
| //! | ||
| //! Signatures mirror `bitemporal-runtime/src/queries.rs`: | ||
| //! - `as_of_query` -> `Vec<BitemporalRecord<T>>` | ||
| //! - `append_supersede` -> `Result<Vec<SupersessionReceipt>, BitemporalError>` | ||
| //! - `temporal_snapshot(records, as_of_time)` -> `Vec<BitemporalRecord<T>>` | ||
|
|
||
| use bitemporal_runtime::{ | ||
| append_supersede, as_of_query, temporal_snapshot, BitemporalError, BitemporalRecord, | ||
| SupersessionReceipt, | ||
| }; | ||
| use chrono::{DateTime, Utc}; | ||
|
|
||
| /// Records visible as of `valid_time` and `recorded_time`. | ||
| pub fn as_of( | ||
| records: &[BitemporalRecord<String>], | ||
| valid_time: DateTime<Utc>, | ||
| recorded_time: DateTime<Utc>, | ||
| ) -> Vec<BitemporalRecord<String>> { | ||
| as_of_query(records, valid_time, recorded_time) | ||
| } | ||
|
|
||
| /// Append a supersession; returns receipts for each superseded prior version. | ||
| pub fn supersede( | ||
| records: &mut Vec<BitemporalRecord<String>>, | ||
| new_record: BitemporalRecord<String>, | ||
| ) -> Result<Vec<SupersessionReceipt>, BitemporalError> { | ||
| append_supersede(records, new_record) | ||
| } | ||
|
|
||
| /// Full snapshot at a recorded time. | ||
| pub fn snapshot( | ||
| records: &[BitemporalRecord<String>], | ||
| recorded_time: DateTime<Utc>, | ||
| ) -> Vec<BitemporalRecord<String>> { | ||
| temporal_snapshot(records, recorded_time) | ||
| } | ||
|
|
||
| #[cfg(test)] | ||
| mod tests { | ||
| use super::*; | ||
| use chrono::TimeZone; | ||
|
|
||
| fn rec(id: &str, valid: i64, recorded: i64, value: &str) -> BitemporalRecord<String> { | ||
| BitemporalRecord { | ||
| id: id.to_string(), | ||
| valid_time: Utc.timestamp_opt(valid, 0).unwrap(), | ||
| recorded_time: Utc.timestamp_opt(recorded, 0).unwrap(), | ||
| value: value.to_string(), | ||
| } | ||
| } | ||
|
|
||
| #[test] | ||
| fn as_of_returns_version_valid_at_that_time() { | ||
| let r1 = rec("x", 100, 100, "old"); | ||
| let r2 = rec("x", 200, 200, "new"); | ||
| let records = vec![r1, r2]; | ||
| let at_150 = as_of( | ||
| &records, | ||
| Utc.timestamp_opt(150, 0).unwrap(), | ||
| Utc.timestamp_opt(250, 0).unwrap(), | ||
| ); | ||
| assert_eq!(at_150.len(), 1); | ||
| assert_eq!(at_150[0].value, "old"); | ||
| let at_250 = as_of( | ||
| &records, | ||
| Utc.timestamp_opt(250, 0).unwrap(), | ||
| Utc.timestamp_opt(250, 0).unwrap(), | ||
| ); | ||
| assert_eq!(at_250.len(), 1); | ||
| assert_eq!(at_250[0].value, "new"); | ||
| } | ||
|
|
||
| #[test] | ||
| fn supersede_emits_receipt() { | ||
| let mut records = vec![rec("y", 100, 100, "v1")]; | ||
| let receipts = supersede(&mut records, rec("y", 200, 200, "v2")).unwrap(); | ||
| assert_eq!(receipts.len(), 1); | ||
| } | ||
|
|
||
| #[test] | ||
| fn snapshot_reflects_latest_recorded() { | ||
| let records = vec![rec("z", 100, 100, "a"), rec("z", 150, 150, "b")]; | ||
| let snap = snapshot(&records, Utc.timestamp_opt(160, 0).unwrap()); | ||
| assert_eq!(snap.len(), 1); | ||
| assert_eq!(snap[0].value, "b"); | ||
| } | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1 +1,2 @@ | ||
| pub mod bitemporal_bridge; | ||
| pub mod claims; |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,83 @@ | ||
| #![allow( | ||
| clippy::unwrap_used, | ||
| clippy::expect_used, | ||
| clippy::field_reassign_with_default | ||
| )] | ||
| use bitemporal_runtime::BitemporalRecord; | ||
| use chrono::TimeZone; | ||
| use knowledge_runtime::adapters::semantic_memory::SemanticMemoryAdapter; | ||
| use knowledge_runtime::{KnowledgeRuntime, RuntimeConfig, Scope}; | ||
| use semantic_memory::{MemoryConfig, MemoryStore, MockEmbedder}; | ||
|
|
||
| fn rec(id: &str, valid: i64, recorded: i64, v: &str) -> BitemporalRecord<String> { | ||
| BitemporalRecord { | ||
| id: id.to_string(), | ||
| valid_time: chrono::Utc.timestamp_opt(valid, 0).unwrap(), | ||
| recorded_time: chrono::Utc.timestamp_opt(recorded, 0).unwrap(), | ||
| value: v.to_string(), | ||
| } | ||
| } | ||
|
|
||
| fn runtime(dir: &std::path::Path, records: Vec<BitemporalRecord<String>>) -> KnowledgeRuntime { | ||
| let cfg = MemoryConfig { | ||
| base_dir: dir.join("mem"), | ||
| ..Default::default() | ||
| }; | ||
| let dims = cfg.embedding.dimensions; | ||
| let store = MemoryStore::open_with_embedder(cfg, Box::new(MockEmbedder::new(dims))).unwrap(); | ||
| let adapter = SemanticMemoryAdapter::new(store); | ||
| let config = RuntimeConfig { | ||
| default_scope: Scope::new("ns"), | ||
| query: Default::default(), | ||
| entity: Default::default(), | ||
| projection: Default::default(), | ||
| strict_temporal: false, | ||
| strict_scope: false, | ||
| }; | ||
| KnowledgeRuntime::new(config, adapter) | ||
| .unwrap() | ||
| .with_bitemporal_records(records) | ||
| } | ||
|
|
||
| #[tokio::test] | ||
| async fn temporal_route_consumes_bitemporal_records() { | ||
| let dir = tempfile::tempdir().unwrap(); | ||
| let rt = runtime( | ||
| dir.path(), | ||
| vec![rec("x", 100, 100, "old"), rec("x", 200, 200, "new")], | ||
| ); | ||
|
|
||
| // As of valid=150, recorded=250 -> only "old" was valid. | ||
| let (early, trace) = rt | ||
| .query_temporal_with_trace( | ||
| "what changed", | ||
| None, | ||
| None, | ||
| "1970-01-01T00:02:30Z", // 150s | ||
| "1970-01-01T00:04:10Z", // 250s | ||
| ) | ||
| .await | ||
| .expect("temporal query should succeed"); | ||
| assert!(!early.is_empty(), "expected a bitemporal result"); | ||
| assert_eq!( | ||
| early[0].content, "old", | ||
| "as-of must select the older version" | ||
| ); | ||
| assert!(trace.temporal_mode.as_deref().is_some()); | ||
|
|
||
| // As of valid=250 -> "new". | ||
| let (late, _) = rt | ||
| .query_temporal_with_trace( | ||
| "what changed", | ||
| None, | ||
| None, | ||
| "1970-01-01T00:04:10Z", | ||
| "1970-01-01T00:04:10Z", | ||
| ) | ||
| .await | ||
| .expect("temporal query should succeed"); | ||
| assert_eq!( | ||
| late[0].content, "new", | ||
| "as-of must select the newer version" | ||
| ); | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,91 @@ | ||
| //! Durable `ToolObservationMemory` implementation backed by `semantic-memory`. | ||
| //! | ||
| //! `llm-tool-runtime` previously defined the trait but shipped only | ||
| //! `InMemoryToolObservationMemory` (and the trait module was not even wired | ||
| //! into the crate root). This module provides the durable store-backed impl. | ||
|
|
||
| use crate::semantic_memory::{ | ||
| ToolObservationDerivedCandidateTraceV1, ToolObservationMemory, ToolObservationMemoryRecordV1, | ||
| ToolObservationMemorySearchV1, | ||
| }; | ||
| use crate::{ToolError, ToolErrorClass}; | ||
| use async_trait::async_trait; | ||
| use semantic_memory::MemoryStore; | ||
|
|
||
| /// Fixed source label stamped onto stored tool observations. | ||
| const OBSERVATION_SOURCE: &str = "llm-tool-runtime"; | ||
|
|
||
| #[async_trait] | ||
| impl ToolObservationMemory for MemoryStore { | ||
| async fn store_tool_observation( | ||
| &self, | ||
| record: ToolObservationMemoryRecordV1, | ||
| ) -> Result<(), ToolError> { | ||
| let metadata = serde_json::json!({ | ||
| "kind": "tool_observation_v1", | ||
| "tool_name": record.tool_name, | ||
| "invocation_id": record.invocation_id, | ||
| "session_id": record.session_id, | ||
| "status": record.status, | ||
| "started_at": record.started_at, | ||
| "completed_at": record.completed_at, | ||
| "receipt_id": record.receipt_id, | ||
| }); | ||
| self.add_fact( | ||
| &record.scope, | ||
| &record.summary, | ||
| Some(OBSERVATION_SOURCE), | ||
| Some(metadata), | ||
|
Comment on lines
+34
to
+38
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
When two invocations in the same scope produce the same summary, the second observation is silently discarded. Useful? React with 👍 / 👎. |
||
| ) | ||
| .await | ||
| .map(|_| ()) | ||
| .map_err(|e| { | ||
| ToolError::new( | ||
| ToolErrorClass::ProviderContract, | ||
| format!("semantic-memory store failed: {e}"), | ||
| ) | ||
| }) | ||
| } | ||
|
|
||
| async fn find_similar_tool_observations( | ||
| &self, | ||
| query: &str, | ||
| scope: &str, | ||
| limit: usize, | ||
| ) -> Result<ToolObservationMemorySearchV1, ToolError> { | ||
| if limit == 0 { | ||
| return Err(ToolError::new( | ||
| ToolErrorClass::ProviderContract, | ||
| "limit must be greater than zero for tool observation search", | ||
| )); | ||
| } | ||
| let namespaces = [scope]; | ||
| let results = self | ||
| .search(query, Some(limit), Some(&namespaces), None) | ||
| .await | ||
|
Comment on lines
+62
to
+65
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
If the supplied Useful? React with 👍 / 👎. |
||
| .map_err(|e| { | ||
| ToolError::new( | ||
| ToolErrorClass::ProviderContract, | ||
| format!("semantic-memory search failed: {e}"), | ||
| ) | ||
| })?; | ||
| let observations = results | ||
| .into_iter() | ||
| .map(|r| ToolObservationMemoryRecordV1 { | ||
| tool_name: String::new(), | ||
| invocation_id: String::new(), | ||
| session_id: None, | ||
| scope: scope.to_string(), | ||
|
Comment on lines
+74
to
+78
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Searching for a stored observation always replaces its tool name, invocation ID, status, session, timestamps, and receipt ID with empty values, despite persisting those fields in metadata. Consequently, even a successful store/search round trip cannot identify the invocation or dereference its receipt, unlike the existing in-memory implementation, which returns the original record. Resolve each matching fact and deserialize its stored observation metadata instead of constructing a summary-only placeholder. Useful? React with 👍 / 👎. |
||
| summary: r.content, | ||
| status: String::new(), | ||
| started_at: None, | ||
| completed_at: None, | ||
| receipt_id: None, | ||
| }) | ||
| .collect(); | ||
| Ok(ToolObservationMemorySearchV1 { | ||
| observations, | ||
| derived_candidate_receipts: Vec::<ToolObservationDerivedCandidateTraceV1>::new(), | ||
| }) | ||
| } | ||
| } | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
When injected records exist but none are visible at the requested valid/recorded coordinates, this condition discards the empty as-of answer and retains the earlier pipeline results. With no projection imports and non-strict temporal mode, that pipeline performs ordinary hybrid search, so querying before the first injected version can return current facts instead of the empty historical state. Distinguish an unconfigured source from a configured source with no visible records, and preserve the latter's empty answer rather than treating it as a reason to fall back. The scoped guidance specifically forbids substituting hybrid fact search for temporal behavior.
AGENTS.md reference: knowledge-runtime/AGENTS.md:L38-L39
Useful? React with 👍 / 👎.