Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.
Python agent-contextagent-memoryagent-pluginsagentic-ragcontext-databasedsh-pluginknowledge-basememorymemory-managementself-evolvingvector-database
feat(retrieval): add event time-decay ranking (#5214)
Lusen Dong42d9a7f1f4f9
diff --git a/crates/ov_cli/src/client.rs b/crates/ov_cli/src/client.rsindex 177880d6e..b6b3ca9ae 100644--- a/crates/ov_cli/src/client.rs+++ b/crates/ov_cli/src/client.rs@@ -749,6 +749,7 @@ impl HttpClient {context_type: Option<Vec<String>>,tags: Option<Vec<String>>,read_content: bool,+ events_time_decay_protection: Option<String>,) -> Result<serde_json::Value> {let image_url = normalize_image_input(image)?;let mut body = serde_json::json!({@@ -764,6 +765,7 @@ impl HttpClient {"context_type": context_type,"tags": tags,"read_content": read_content.then_some(true),+ "events_time_decay_protection": events_time_decay_protection,});compact_request_body(&mut body);self.post("/api/v1/search/find", &body).await@@ -784,6 +786,7 @@ impl HttpClient {context_type: Option<Vec<String>>,tags: Option<Vec<String>>,read_content: bool,+ events_time_decay_protection: Option<String>,) -> Result<serde_json::Value> {let image_url = normalize_image_input(image)?;let mut body = serde_json::json!({@@ -800,6 +803,7 @@ impl HttpClient {"context_type": context_type,"tags": tags,"read_content": read_content.then_some(true),+ "events_time_decay_protection": events_time_decay_protection,});compact_request_body(&mut body);self.post("/api/v1/search/search", &body).awaitdiff --git a/crates/ov_cli/src/commands/search.rs b/crates/ov_cli/src/commands/search.rsindex 92ef83a96..5037172d8 100644--- a/crates/ov_cli/src/commands/search.rs+++ b/crates/ov_cli/src/commands/search.rs@@ -130,6 +130,7 @@ pub async fn find(context_type: Option<Vec<String>>,tags: Option<Vec<String>>,read_content: bool,+ events_time_decay_protection: Option<String>,output_format: OutputFormat,compact: bool,) -> Result<()> {@@ -147,6 +148,7 @@ pub async fn find(context_type,tags,read_content,+ events_time_decay_protection,).await?;output_search_results(@@ -173,6 +175,7 @@ pub async fn search(context_type: Option<Vec<String>>,tags: Option<Vec<String>>,read_content: bool,+ events_time_decay_protection: Option<String>,output_format: OutputFormat,compact: bool,) -> Result<()> {@@ -191,6 +194,7 @@ pub async fn search(context_type,tags,read_content,+ events_time_decay_protection,).await?;output_search_results(@@ -425,7 +429,7 @@ fn render_search_result_card(metadata.push(theme::value(level).bold().to_string());}- if let Some(score) = search_result_score(object) {+ for score in search_result_scores(object) {metadata.push(theme::warning(score).bold().to_string());}}@@ -598,13 +602,40 @@ fn normalize_level_value(level: &str) -> &str {}fn search_result_score(object: Option<&serde_json::Map<String, Value>>) -> Option<String> {- let value = object?.get("score")?;+ parse_score(object?.get("score")?).map(|score| format!("score {score:.3}"))+}++fn search_result_scores(object: Option<&serde_json::Map<String, Value>>) -> Vec<String> {+ let Some(object) = object else {+ return Vec::new();+ };+ if !object.contains_key("origin_score") && !object.contains_key("time_score") {+ return search_result_score(Some(object)).into_iter().collect();+ }++ [+ ("semantic", object.get("origin_score")),+ ("time", object.get("time_score")),+ ("final", object.get("score")),+ ]+ .into_iter()+ .map(|(label, value)| {+ let value = value+ .and_then(parse_score)+ .map(|score| format!("{score:.3}"))+ .unwrap_or_else(|| "not provided".to_string());+ format!("{label} {value}")+ })+ .collect()+}++fn parse_score(value: &Value) -> Option<f64> {let score = value.as_f64().or_else(|| {value.as_str().and_then(|value| value.trim().parse::<f64>().ok())})?;- Some(format!("score {score:.3}"))+ Some(score)}fn search_result_uri(object: Option<&serde_json::Map<String, Value>>) -> Option<&str> {@@ -907,6 +938,8 @@ mod tests {"uri": "viking://user/default/memories/entities/.overview.md","level": 1,"score": 0.3805481195449829,+ "origin_score": 0.8,+ "time_score": 0.5,"abstract": "Entity memories from user's world. Each entity has its own subdirectory including projects, people, concepts, etc."}]);@@ -914,7 +947,7 @@ mod tests {let rendered = strip_ansi(&render_search_results_for_table(&results).expect("cards"));assert!(rendered.starts_with("1 result\nRanked by relevance\n\n"));- assert!(rendered.contains("1. memory · Level 1 · score 0.381"));+ assert!(rendered.contains("1. memory · Level 1 · semantic 0.800 · time 0.500 · final 0.381"));assert!(rendered.contains("viking://user/default/memories/entities/.overview.md"));assert!(rendered.contains("Entity memories from user's world."));assert!(!rendered.contains("peop\n le"));diff --git a/crates/ov_cli/src/handlers.rs b/crates/ov_cli/src/handlers.rsindex 228088959..718cc18f8 100644--- a/crates/ov_cli/src/handlers.rs+++ b/crates/ov_cli/src/handlers.rs@@ -1494,6 +1494,7 @@ pub async fn handle_find(context_type: Option<Vec<String>>,tags: Option<Vec<String>>,read_content: bool,+ events_time_decay_protection: Option<String>,ctx: CliContext,) -> Result<()> {let query = query.unwrap_or_default();@@ -1528,6 +1529,9 @@ pub async fn handle_find(if read_content {params.push("--read-content".to_string());}+ if let Some(ref protection) = events_time_decay_protection {+ params.push(format!("--events-time-decay-protection {}", protection));+ }params.push(format!("\"{}\"", query));print_command_echo("ov find", ¶ms.join(" "), ctx.config.echo_command);let client = ctx.get_client();@@ -1545,6 +1549,7 @@ pub async fn handle_find(context_type,tags,read_content,+ events_time_decay_protection,ctx.output_format,ctx.compact,)@@ -1564,6 +1569,7 @@ pub async fn handle_search(context_type: Option<Vec<String>>,tags: Option<Vec<String>>,read_content: bool,+ events_time_decay_protection: Option<String>,ctx: CliContext,) -> Result<()> {let query = query.unwrap_or_default();@@ -1601,6 +1607,9 @@ pub async fn handle_search(if read_content {params.push("--read-content".to_string());}+ if let Some(ref protection) = events_time_decay_protection {+ params.push(format!("--events-time-decay-protection {}", protection));+ }params.push(format!("\"{}\"", query));print_command_echo("ov search", ¶ms.join(" "), ctx.config.echo_command);let client = ctx.get_client();@@ -1619,6 +1628,7 @@ pub async fn handle_search(context_type,tags,read_content,+ events_time_decay_protection,ctx.output_format,ctx.compact,)diff --git a/crates/ov_cli/src/main.rs b/crates/ov_cli/src/main.rsindex f1d0a5196..de44518d1 100644--- a/crates/ov_cli/src/main.rs+++ b/crates/ov_cli/src/main.rs@@ -30,6 +30,35 @@ use std::{io::{self, IsTerminal},};+const MAX_TIME_DECAY_DURATION_DAYS: u128 = 3000 * 365;++fn parse_event_time_decay_protection(value: &str) -> std::result::Result<String, String> {+ if value == "0" {+ return Ok(value.to_string());+ }+ let Some((amount, unit)) = value.split_at_checked(value.len().saturating_sub(1)) else {+ return Err("must be '0' or a non-negative integer followed by m, h, or d".to_string());+ };+ if amount.is_empty() || !amount.bytes().all(|byte| byte.is_ascii_digit()) {+ return Err("must be '0' or a non-negative integer followed by m, h, or d".to_string());+ }+ let amount = amount+ .parse::<u128>()+ .map_err(|_| "exceeds the maximum duration of 1095000d".to_string())?;+ let duration_minutes = match unit {+ "m" => amount,+ "h" => amount.saturating_mul(60),+ "d" => amount.saturating_mul(24 * 60),+ _ => {+ return Err("must be '0' or a non-negative integer followed by m, h, or d".to_string());+ }+ };+ if duration_minutes > MAX_TIME_DECAY_DURATION_DAYS * 24 * 60 {+ return Err("exceeds the maximum duration of 1095000d".to_string());+ }+ Ok(value.to_string())+}+/// CLI context shared across commands#[derive(Debug, Clone)]pub struct CliContext {@@ -922,6 +951,14 @@ enum Commands {/// Include the full visible content for every matched URI#[arg(long, help_heading = "Advanced options")]read_content: bool,+ /// Enable event decay with protection duration: 0 (immediate) or Xm/Xh/Xd+ #[arg(+ long,+ alias = "events_time_decay_protection",+ value_parser = parse_event_time_decay_protection,+ help_heading = "Advanced options"+ )]+ events_time_decay_protection: Option<String>,},/// [Experimental][Data] Run context-aware retrievalSearch {@@ -994,6 +1031,14 @@ enum Commands {/// Include the full visible content for every matched URI#[arg(long, help_heading = "Advanced options")]read_content: bool,+ /// Enable event decay with protection duration: 0 (immediate) or Xm/Xh/Xd+ #[arg(+ long,+ alias = "events_time_decay_protection",+ value_parser = parse_event_time_decay_protection,+ help_heading = "Advanced options"+ )]+ events_time_decay_protection: Option<String>,},/// [Data] Run content pattern searchGrep {@@ -3852,6 +3897,7 @@ async fn main() {context_type,tags,read_content,+ events_time_decay_protection,} => {handlers::handle_find(query,@@ -3865,6 +3911,7 @@ async fn main() {context_type,tags,read_content,+ events_time_decay_protection,ctx,).await@@ -3882,6 +3929,7 @@ async fn main() {context_type,tags,read_content,+ events_time_decay_protection,} => {handlers::handle_search(query,@@ -3896,6 +3944,7 @@ async fn main() {context_type,tags,read_content,+ events_time_decay_protection,ctx,).awaitdiff --git a/docs/en/api/06-retrieval.md b/docs/en/api/06-retrieval.mdindex 8f67428aa..8625137a4 100644--- a/docs/en/api/06-retrieval.md+++ b/docs/en/api/06-retrieval.md@@ -55,6 +55,7 @@ The `find()` method runs one global vector similarity search in QUICK mode for s| query | str | No | "" | Search query string. Required unless `image_url` is provided || image_url | str | No | None | Image query as a `data:image/...;base64,...`, `http(s)://`, or `viking://` URI. Requires a multimodal embedding model || target_uri | str \| List[str] | No | "" | Limit search to specific URI prefix |+| events_time_decay_protection | str \| null | No | null | Omit or pass `null` to disable decay. Pass `"0"` to decay immediately, or a duration such as `"7d"` to preserve the original score during that period and decay afterward. Supports non-negative integer `Xm`/`Xh`/`Xd` || context_type | str \| List[str] | No | None | Limit results to one or more `ContextType` values: `memory`, `resource`, or `skill` || tags | List[str] | No | None | Explicit retrieval tags in strict `k=v` form. Multiple tags are combined with AND; a result must contain every requested tag || node_limit | int | No | None | Optional HTTP alias; overrides `limit` when provided |@@ -392,6 +393,7 @@ The `search()` method adds session context understanding and intent analysis cap| target_uri | str \| List[str] | No | "" | Limit search to specific URI prefix || session | Session | No | None | Session for context-aware search (SDK) || session_id | str | No | None | Session ID for context-aware search (HTTP) |+| events_time_decay_protection | str \| null | No | null | Omit or pass `null` to disable decay. Pass `"0"` to decay immediately, or a duration such as `"7d"` to preserve the original score during that period and decay afterward. Supports non-negative integer `Xm`/`Xh`/`Xd` || context_type | str \| List[str] | No | None | Limit results to one or more `ContextType` values: `memory`, `resource`, or `skill` || tags | List[str] | No | None | Explicit retrieval tags in strict `k=v` form. Multiple tags are combined with AND; a result must contain every requested tag || node_limit | int | No | None | Optional HTTP alias; overrides `limit` when provided |@@ -407,6 +409,16 @@ The `search()` method adds session context understanding and intent analysis cap`search()` uses the same target resolution and explicit tag filtering rules as `find()`, including the peer collection filter selected by `X-OpenViking-Actor-Peer` or SDK `actor_peer_id`. When `image_url` is provided, `search()` uses direct image retrieval and skips session query planning.+Event time decay applies to results tagged `memory_type=events` in semantic `find()` and both `search(mode="list")` and `search(mode="context")`. Memory extraction writes this tag on user/peer event L2 records; retrieval identifies events by the tag rather than inferring the type from a URI or level. Untagged/non-event results, query-less filter-only `find()`, `recall`, `grep`, and `glob` are unaffected. During event recall, the vector engine multiplies the original vector score by `time_score`. List responses expose this recall-stage vector score as `origin_score` and the factor as `time_score`; `score` is the final retrieval score, which may come from model rerank. Context mode uses that final score while assembling its candidates. The CLI labels list-result scores as semantic, time, and final scores. Inside the protection period `time_score` is 1, so the original score is unchanged. Time distance follows the VikingDB exponential decay operator, using the absolute difference from the request time. Time is read from the existing indexed `updated_at` field; no reindex or timestamp rewrite is required. Local fusion preserves the original score for missing or invalid timestamps; cloud fusion uses the indexed date-time field and the backend operator. The curve is owned by the server; callers only provide the per-request protection period. No `ov.conf` or `ovcli.conf` change is required.++New and updated memories produced by memory extraction automatically receive a `memory_type=<type>` search tag. With decay enabled, both local and cloud backends recall records tagged `memory_type=events` separately and merge them with the complementary untagged/non-event branch; both branches preserve the original scope, permission and level filters, without requiring a peer ID. Existing data is not backfilled; untagged memories keep their original scores. Direct content refreshes and ordinary tag updates preserve the existing memory type without inferring it from the URI.++The local vector engine expands the requested event window by at most 3x internally (capped at 100,000), computes decay and sorts in C++, then returns top-k before any abstract or payload fields are fetched. This is a bounded candidate approximation, so events outside that semantic window are not guaranteed to be promoted. The HTTP vector service forwards the same native rule. Cloud adapters use VikingDB score fusion and request only the required limit plus offset, without a fixed 100,000-input override. cuVS collections use their native scalar/vector index for decay requests. openGauss accepts the forwarded parameters but does not apply time decay; it retains ordinary vector scoring.++When model rerank is enabled, each recall branch requests `2 × limit` results. Event decay is already applied inside VikingDB for cloud backends, or inside the local C++ engine, before the two branches merge. The best `2 × limit` merged candidates go through one model rerank; model scores determine the final ranking and score threshold. There is no additional decay after the model. If rerank fails, retrieval keeps the already-decayed recall scores. `origin_score` and `time_score` remain recall-stage details, so their product need not equal a successful model rerank score. Parent-directory scores and hotness are not mixed into the result.++The local engine's 3x expansion applies to the requested event window independently of the model's 2x window. For a final `limit=10`, each branch returns at most 20 results, the local event engine considers at most 60 vector candidates internally, and at most 20 merged results reach the model.+#### 3. Usage Examples**HTTP API**@@ -422,9 +434,10 @@ curl -X POST http://localhost:1933/api/v1/search/search \-d '{"query": "best practices","session_id": "abc123",- "context_type": "skill",+ "context_type": "memory","since": "2h","time_field": "updated_at",+ "events_time_decay_protection": "1d","limit": 10}'```@@ -542,6 +555,10 @@ openviking search "best practices" --context-type skill# Search with time filteropenviking search "watch vs scheduled" --after 2026-03-15 --before 2026-03-20+# Rank user and peer event memories with time decay+openviking search "recent decisions" --context-type memory --level 2 \+ --events-time-decay-protection 1d+# Search without session (still performs intent analysis)openviking search "how to implement OAuth 2.0 authorization code flow"@@ -621,7 +638,7 @@ Injecting context every turn used to mean searching per type, reading each hit b#### 2. Parameters-**L0 retrieval domain**: `query`, `image_url`, `context_type`, `limit`, `score_threshold`, `filter`, `tags`, `since`/`until` behave as in list mode. `limit` applies only to quota-free retrieval. Once `purpose` or explicit `quotas` enables bucketed retrieval, the per-category quotas are the only candidate ceilings. `target_uri` is not supported in context mode yet (returns 400); `level` is ignored because `detail` governs tiers.+**L0 retrieval domain**: `query`, `image_url`, `context_type`, `limit`, `score_threshold`, `filter`, `tags`, `since`/`until`, and the optional `events_time_decay_protection` behave as in list mode. `limit` applies only to quota-free retrieval. Once `purpose` or explicit `quotas` enables bucketed retrieval, the per-category quotas are the only candidate ceilings. `target_uri` is not supported in context mode yet (returns 400); `level` is ignored because `detail` governs tiers.**L1 query understanding**diff --git a/docs/en/guides/06-mcp-integration.md b/docs/en/guides/06-mcp-integration.mdindex a5f3b14d8..467294894 100644--- a/docs/en/guides/06-mcp-integration.md+++ b/docs/en/guides/06-mcp-integration.md@@ -133,8 +133,8 @@ Once connected, OpenViking exposes 16 tools:| Tool | Description | Key Parameters ||------|-------------|----------------|-| `find` | Fast semantic retrieval without session context. `context_type="skill"` on its own switches to package-level skill retrieval: one hit per skill package, its URI pointing at that package's `SKILL.md` and its summary taken from the skill itself, even when an auxiliary file inside the package is what matched. Without `target_uri` it searches both your own skills and the account-shared `viking://agent/skills`. Mixing `skill` with another context type keeps the generic retrieval path | `query`, `target_uri` (optional), `limit`, `min_score`, `level` (optional), `context_type` (optional), `read_content` (optional — inline each hit's content) |-| `search` | Deep semantic retrieval; `mode="context"` assembles injection-ready context and replaces the former `recall` tool. `list` mode also returns one hit per skill package, its URI pointing at `SKILL.md` and its summary taken from the package itself, but `limit` applies before that merge, so a package matching in several files takes several slots and fewer than `limit` results come back | `query`, `mode` (`list` or `context`), `target_uri` (list mode only), `session_id` (optional), `limit`, `min_score`, `level` (list mode), `context_type` (optional), plus context-mode `quotas`, `purpose`, `max_tokens`, `detail` or `detail_by_category`, `dedup_turns`, `exclude_uris`, `peer_scope`, scalar `other_peer_penalty` or `other_peer_penalties` by category, and `rewrite` (`off` or `auto`) |+| `find` | Fast semantic retrieval without session context. `context_type="skill"` on its own switches to package-level skill retrieval: one hit per skill package, its URI pointing at that package's `SKILL.md` and its summary taken from the skill itself, even when an auxiliary file inside the package is what matched. Without `target_uri` it searches both your own skills and the account-shared `viking://agent/skills`. Mixing `skill` with another context type keeps the generic retrieval path | `query`, `target_uri` (optional), `limit`, `min_score`, `level` (optional), `context_type` (optional), `read_content` (optional — inline each hit's content), `events_time_decay_protection` (optional) |+| `search` | Deep semantic retrieval; `mode="context"` assembles injection-ready context and replaces the former `recall` tool. `list` mode also returns one hit per skill package, its URI pointing at `SKILL.md` and its summary taken from the package itself, but `limit` applies before that merge, so a package matching in several files takes several slots and fewer than `limit` results come back | `query`, `mode` (`list` or `context`), `target_uri` (list mode only), `session_id` (optional), `limit`, `min_score`, `level` (list mode), `context_type` (optional), `events_time_decay_protection` (optional in both modes), plus context-mode `quotas`, `purpose`, `max_tokens`, `detail` or `detail_by_category`, `dedup_turns`, `exclude_uris`, `peer_scope`, scalar `other_peer_penalty` or `other_peer_penalties` by category, and `rewrite` (`off` or `auto`) || `read` | Read one or more `viking://` URIs. PNG, JPEG, GIF, and WebP return native MCP image content; WAV, MP3, FLAC, OGG, and M4A return native audio content. Video is not supported because MCP has no standard video content block | `uris` (single string or array) || `list` | List entries under a `viking://` directory | `uri`, `recursive`, `offset`, `limit`, `sort_by`, `sort_order` (optional) || `tree` | Show the recursive directory tree under a `viking://` URI, indented by depth — use when you need a full picture of the file tree (prefer `list` for a single level, `glob` for filename patterns) | `uri` (optional), `level_limit` (default 3), `node_limit` (default 1000), `offset`, `limit`, `include_abstract` (optional — also show each directory's summary; for a skill directory that is its name and description) |diff --git a/docs/zh/api/06-retrieval.md b/docs/zh/api/06-retrieval.mdindex 89fa70a9c..30b46c1e8 100644--- a/docs/zh/api/06-retrieval.md+++ b/docs/zh/api/06-retrieval.md@@ -55,6 +55,7 @@ OpenViking 提供多种检索方法,包括简单的向量相似度搜索、带| query | str | 否 | "" | 搜索查询字符串;未提供 `image_url` 时必填 || image_url | str | 否 | None | 图片查询,支持 `data:image/...;base64,...`、`http(s)://` 或 `viking://` URI;需要 multimodal embedding 模型 || target_uri | str \| List[str] | 否 | "" | 限制搜索范围到指定的 URI 前缀 |+| events_time_decay_protection | str \| null | 否 | null | 不传或传 `null` 关闭衰减;传 `"0"` 立即衰减;传 `"7d"` 等时长则在保护期内保持原分,之后衰减。支持非负整数 `Xm`/`Xh`/`Xd` || context_type | str \| List[str] | 否 | None | 限定一个或多个 `ContextType` 取值:`memory`、`resource` 或 `skill` || tags | List[str] | 否 | None | 显式检索标签,必须是严格的 `k=v` 格式。多个 tags 之间是 AND 关系,结果必须同时包含所有请求的标签 || limit | int | 否 | 10 | 最大返回结果数 |@@ -393,6 +394,7 @@ openviking find "红色海报风格" --image ./poster.png --uri "viking://resour| target_uri | str \| List[str] | 否 | "" | 限制搜索范围到指定的 URI 前缀 || session | Session | 否 | None | 用于上下文感知搜索的会话(SDK)|| session_id | str | 否 | None | 用于上下文感知搜索的会话 ID(HTTP)|+| events_time_decay_protection | str \| null | 否 | null | 不传或传 `null` 关闭衰减;传 `"0"` 立即衰减;传 `"7d"` 等时长则在保护期内保持原分,之后衰减。支持非负整数 `Xm`/`Xh`/`Xd` || context_type | str \| List[str] | 否 | None | 限定一个或多个 `ContextType` 取值:`memory`、`resource` 或 `skill` || tags | List[str] | 否 | None | 显式检索标签,必须是严格的 `k=v` 格式。多个 tags 之间是 AND 关系,结果必须同时包含所有请求的标签 || limit | int | 否 | 10 | 最大返回结果数 |@@ -409,6 +411,16 @@ openviking find "红色海报风格" --image ./poster.png --uri "viking://resour`search()` 使用和 `find()` 相同的目标解析和显式标签过滤规则,包括由 `X-OpenViking-Actor-Peer` 或 SDK `actor_peer_id` 选择的 peer 集合过滤。提供 `image_url` 时,`search()` 会直接执行图片检索并跳过会话 query planning。+事件时间衰减作用于语义 `find()`、`search(mode="list")` 和 `search(mode="context")` 中带 `memory_type=events` 标签的结果。记忆提取流程将该标签写入 user / peer 事件的 L2 记录;检索按标签判断,不从 URI 或层级推断事件类型。无事件标签的结果、无 query 的纯过滤 `find()`、`recall`、`grep` 和 `glob` 不受影响。事件召回阶段由向量引擎将原向量分乘以 `time_score`;响应中的 `score` 是最终检索分数,开启模型 rerank 时使用模型分。context 模式按最终分组装候选。保护期内 `time_score` 为 1,原分不变;时间距离与 VikingDB 指数衰减算子一致,取时间戳与请求时间的绝对差。list 响应中的 event 结果额外返回 `origin_score` 和 `time_score`,CLI 分别展示为 semantic、time 和 final 分。时间取自已有索引的 `updated_at` 字段,无需重新索引或改写时间戳;本地计算遇到缺失或非法时间时保持原分;云端使用索引中的日期时间字段和后处理算子。衰减曲线由服务端内部维护,调用方只需按请求传入保护期,无需修改 `ov.conf` 或 `ovcli.conf`。++由记忆提取流程新生成或更新的记忆会自动写入 `memory_type=<类型>` 检索标签。启用衰减时,本地和云端均将按是否带 `memory_type=events` 标签拆成互斥且完整覆盖原范围的两路,再合并排序;两路均保留原 scope 的权限、目录和 level 限制,无需指定 peer id。存量数据不补标签,无标签记忆保持原分。直接内容刷新和普通标签更新保留已有类型,不从 URI 推断或重设类型。++本地向量引擎按所需 event 条数在内部最多放大 3 倍候选(上限 100,000),在 C++ 中计算衰减并排序,截取 top-k 后才读取摘要等字段。这是有界候选近似,不能保证将语义候选窗口以外的事件提升进结果。HTTP 向量服务透传同一规则;云端 Adapter 使用 VikingDB 分数融合,仅请求 limit + offset,不设置固定 100,000 条输入预算。cuVS 集合的衰减请求使用其原生标量/向量索引。openGauss 接收透传参数但不执行时间衰减,保留普通向量分数。++启用模型 rerank 时,两路各请求 `2 × limit` 条结果。事件分支在召回时已完成衰减:云端由 VikingDB 计算,开源本地由 C++ 引擎计算。两路按召回分合并,取前 `2 × limit` 条统一执行一次模型 rerank,再按模型分排序、过滤阈值并取最终结果,模型后不再衰减。模型失败时使用已经衰减过的召回分。`origin_score` 和 `time_score` 始终描述召回阶段的原向量分与时间因子,因此二者乘积不一定等于成功 rerank 后的模型分。最终分数不混入父目录分数或热度分。++本地引擎的 3 倍扩召作用于事件分支请求窗口,模型的 2 倍候选窗口是另一层限制。例如最终 `limit=10` 时,两路各返回最多 20 条;本地事件引擎内部最多考虑 60 条向量候选,合并后最多 20 条进入模型。+#### 3. 使用示例**HTTP API**@@ -424,9 +436,10 @@ curl -X POST http://localhost:1933/api/v1/search/search \-d '{"query": "best practices","session_id": "abc123",- "context_type": "skill",+ "context_type": "memory","since": "2h","time_field": "updated_at",+ "events_time_decay_protection": "1d","limit": 10}'```@@ -544,6 +557,10 @@ openviking search "best practices" --context-type skill# 带时间过滤的搜索openviking search "watch vs scheduled" --after 2026-03-15 --before 2026-03-20+# 对 user 和 peer 的事件记忆启用时间衰减排序+openviking search "recent decisions" --context-type memory --level 2 \+ --events-time-decay-protection 1d+# 不带会话的搜索(仍进行意图分析)openviking search "how to implement OAuth 2.0 authorization code flow"@@ -623,7 +640,7 @@ Agent 插件每轮注入上下文时,过去需要按类型逐个检索、再#### 2. 接口和参数说明-**L0 检索域**:`query`、`image_url`、`context_type`、`limit`、`score_threshold`、`filter`、`tags`、`since`/`until` 与 list 模式一致。`limit` 只约束 quota-free 检索;一旦 `purpose` 或显式 `quotas` 启用分桶检索,各分类配额就是唯一候选上限。`target_uri` 在 context 模式下暂不支持(返回 400);`level` 被忽略,档位由 `detail` 决定。+**L0 检索域**:`query`、`image_url`、`context_type`、`limit`、`score_threshold`、`filter`、`tags`、`since`/`until` 以及可选的 `events_time_decay_protection` 与 list 模式一致。`limit` 只约束 quota-free 检索;一旦 `purpose` 或显式 `quotas` 启用分桶检索,各分类配额就是唯一候选上限。`target_uri` 在 context 模式下暂不支持(返回 400);`level` 被忽略,档位由 `detail` 决定。**L1 查询理解**diff --git a/docs/zh/guides/06-mcp-integration.md b/docs/zh/guides/06-mcp-integration.mdindex c15ec3dec..fd411ece4 100644--- a/docs/zh/guides/06-mcp-integration.md+++ b/docs/zh/guides/06-mcp-integration.md@@ -125,8 +125,8 @@ claude mcp add --transport http openviking \| 工具 | 说明 | 主要参数 ||------|------|----------|-| `find` | 无 session 上下文的快速语义检索。只传 `context_type="skill"` 时改走包级 skill 检索:每个 skill 包只返回一条命中,URI 指向该包的 `SKILL.md`,摘要取自 skill 本身,即使命中的是包内辅助文件也是如此;不传 `target_uri` 时同时检索自己的 skill 和账户共享的 `viking://agent/skills`。`skill` 与其它 context_type 混用时仍走通用检索路径 | `query`, `target_uri`(可选), `limit`, `min_score`, `level`(可选), `context_type`(可选), `read_content`(可选——直接内联每条命中的内容) |-| `search` | 深度语义检索;`mode="context"` 组装可直接注入的上下文,并替代原 `recall` 工具。`list` 模式下每个 skill 包也只出一条命中,URI 指向 `SKILL.md`、摘要取自包本身,但 `limit` 在合并之前生效,所以一个包在多个文件上命中时会占掉多个名额,返回条数少于 `limit` | `query`, `mode`(`list` 或 `context`), `target_uri`(仅 list 模式), `session_id`(可选), `limit`, `min_score`, `level`(list 模式), `context_type`(可选),以及 context 模式的 `quotas`, `purpose`, `max_tokens`, `detail` 或 `detail_by_category`, `dedup_turns`, `exclude_uris`, `peer_scope`, 标量 `other_peer_penalty` 或按类别设置的 `other_peer_penalties`, `rewrite`(`off` 或 `auto`) |+| `find` | 无 session 上下文的快速语义检索。只传 `context_type="skill"` 时改走包级 skill 检索:每个 skill 包只返回一条命中,URI 指向该包的 `SKILL.md`,摘要取自 skill 本身,即使命中的是包内辅助文件也是如此;不传 `target_uri` 时同时检索自己的 skill 和账户共享的 `viking://agent/skills`。`skill` 与其它 context_type 混用时仍走通用检索路径 | `query`, `target_uri`(可选), `limit`, `min_score`, `level`(可选), `context_type`(可选), `read_content`(可选——直接内联每条命中的内容), `events_time_decay_protection`(可选) |+| `search` | 深度语义检索;`mode="context"` 组装可直接注入的上下文,并替代原 `recall` 工具。`list` 模式下每个 skill 包也只出一条命中,URI 指向 `SKILL.md`、摘要取自包本身,但 `limit` 在合并之前生效,所以一个包在多个文件上命中时会占掉多个名额,返回条数少于 `limit` | `query`, `mode`(`list` 或 `context`), `target_uri`(仅 list 模式), `session_id`(可选), `limit`, `min_score`, `level`(list 模式), `context_type`(可选), `events_time_decay_protection`(两种模式均可选),以及 context 模式的 `quotas`, `purpose`, `max_tokens`, `detail` 或 `detail_by_category`, `dedup_turns`, `exclude_uris`, `peer_scope`, 标量 `other_peer_penalty` 或按类别设置的 `other_peer_penalties`, `rewrite`(`off` 或 `auto`) || `read` | 读取一个或多个 `viking://` URI 的内容。PNG、JPEG、GIF、WebP 返回 MCP 原生图片内容;WAV、MP3、FLAC、OGG、M4A 返回原生音频内容。MCP 没有标准视频内容块,因此暂不支持视频 | `uris`(单个字符串或数组) || `list` | 列出 `viking://` 目录下的条目 | `uri`, `recursive`(可选) || `tree` | 以缩进形式展示 `viking://` URI 下的递归目录树——当需要全面了解文件树结构时使用(单层列表用 `list`,按文件名查找用 `glob`) | `uri`(可选), `level_limit`(默认 3), `node_limit`(默认 1000), `include_abstract`(可选——同时展示每个目录的摘要;skill 目录的摘要就是它的名字和描述) |diff --git a/openviking/retrieve/context_assembler/gather.py b/openviking/retrieve/context_assembler/gather.pyindex ece42605a..dd4ae12e7 100644--- a/openviking/retrieve/context_assembler/gather.py+++ b/openviking/retrieve/context_assembler/gather.py@@ -210,6 +210,7 @@ async def gather_candidates(score_threshold: Optional[float],filter: Optional[Dict[str, Any]] = None,image_url: Optional[str] = None,+ events_time_decay_protection: Optional[str] = None,peer_scope: str = "all",penalties: Optional[Mapping[str, float]] = None,excluded: Optional[Set[str]] = None,@@ -301,6 +302,7 @@ async def gather_candidates(filter=find_filter if find_filter is not None else filter,image_url=image_url,level=None,+ events_time_decay_protection=events_time_decay_protection,)async def gather_bucket(bucket: str, quota: int) -> List[Candidate]:diff --git a/openviking/retrieve/context_assembler/params.py b/openviking/retrieve/context_assembler/params.pyindex 4bf1f7242..686db2149 100644--- a/openviking/retrieve/context_assembler/params.py+++ b/openviking/retrieve/context_assembler/params.py@@ -124,6 +124,7 @@ class AssembleParams:limit: int = DEFAULT_LIMITscore_threshold: Optional[float] = Nonefilter: Optional[Dict[str, Any]] = None+ events_time_decay_protection: Optional[str] = Nonesession_id: Optional[str] = Nonequery_expansion: Literal["off", "auto"] = "auto"diff --git a/openviking/retrieve/context_assembler/pipeline.py b/openviking/retrieve/context_assembler/pipeline.pyindex 1c98bc180..5a669af0e 100644--- a/openviking/retrieve/context_assembler/pipeline.py+++ b/openviking/retrieve/context_assembler/pipeline.py@@ -32,6 +32,7 @@ from openviking.retrieve.context_assembler.render import render_contextfrom openviking.retrieve.context_assembler.rewrite import rewrite_context, server_rewrite_enabledfrom openviking.retrieve.context_assembler.tiers import needs_content, prefetch_contentsfrom openviking.server.identity import RequestContext+from openviking.utils.time_decay import validate_event_time_decay_requestfrom openviking_cli.utils.logger import get_loggerlogger = get_logger(__name__)@@ -57,6 +58,7 @@ async def assemble_context(params: AssembleParams,) -> AssembleResult:"""Run the full assembly pipeline for one request."""+ validate_event_time_decay_request(params.events_time_decay_protection)quotas = normalize_quotas(params.quotas, params.purpose)penalties = normalize_penalties(params.other_peer_penalty)@@ -113,6 +115,7 @@ async def assemble_context(score_threshold=params.score_threshold,filter=params.filter,image_url=params.image_url,+ events_time_decay_protection=params.events_time_decay_protection,peer_scope=params.peer_scope,penalties=penalties,excluded=excluded,diff --git a/openviking/retrieve/hierarchical_retriever.py b/openviking/retrieve/hierarchical_retriever.pyindex 6e3dffb9f..a69c2ddba 100644--- a/openviking/retrieve/hierarchical_retriever.py+++ b/openviking/retrieve/hierarchical_retriever.py@@ -7,6 +7,7 @@ Global vector retrieval with optional reranking of the recalled candidates.import asyncioimport mathimport time+from datetime import datetime, timezonefrom typing import Any, Dict, List, Optionalfrom openviking.core.context import ContextLevel@@ -20,6 +21,7 @@ from openviking.storage.expr import FilterExprfrom openviking.storage.vikingdb_manager import VikingDBManager, VikingDBManagerProxyfrom openviking.telemetry import get_current_telemetryfrom openviking.utils.tags import normalize_search_tags+from openviking.utils.time_decay import parse_duration_msfrom openviking.utils.token_estimation import (estimate_text_tokens,truncate_text_to_token_budget,@@ -92,6 +94,8 @@ class HierarchicalRetriever:score_gte: bool = False,scope_dsl: Optional[FilterExpr | Dict[str, Any]] = None,level: Optional[List[int]] = None,+ events_time_decay_protection: Optional[str] = None,+ request_now: Optional[datetime] = None,) -> QueryResult:"""Run one global vector search, then optionally rerank its candidates.@@ -114,6 +118,15 @@ class HierarchicalRetriever:use_rerank = (mode == RetrieverMode.THINKING and self._rerank_client is not None and not image_query)+ decay_kwargs = {}+ if events_time_decay_protection is not None:+ parse_duration_ms(+ events_time_decay_protection, parameter_name="events_time_decay_protection"+ )+ decay_kwargs = {+ "events_time_decay_protection": events_time_decay_protection,+ "request_now": request_now or datetime.now(timezone.utc),+ }if image_query and level is None:level = [2]@@ -169,12 +182,14 @@ class HierarchicalRetriever:extra_filter=scope_dsl,level=level,limit=search_limit,+ **decay_kwargs,)telemetry.count("vector.searches", 1)telemetry.count("vector.scored", len(vector_results))telemetry.count("vector.scanned", len(vector_results))- # Keep the highest vector-scored hit for each URI before reranking.+ # Recall scores already include event decay from the vector engine.+ # Keep the highest-scored hit for each URI before model reranking.collected_by_uri: Dict[str, Dict[str, Any]] = {}for result in vector_results:uri = result.get("uri", "")@@ -325,6 +340,8 @@ class HierarchicalRetriever:category=c.get("category", ""),score=final_score,search_tags=normalize_search_tags(c.get("search_tags"), discard_invalid=True),+ origin_score=c.get("_origin_score"),+ time_score=c.get("_time_score"),))diff --git a/openviking/server/mcp_endpoint.py b/openviking/server/mcp_endpoint.pyindex 5d08a2d2b..25ee1c0b8 100644--- a/openviking/server/mcp_endpoint.py+++ b/openviking/server/mcp_endpoint.py@@ -82,6 +82,7 @@ from openviking.utils.search_filters import (resolve_context_types,)from openviking.utils.skill_processor import SkillProcessor+from openviking.utils.time_decay import validate_event_time_decay_requestfrom openviking_cli.exceptions import (InvalidArgumentError,NotFoundError,@@ -345,8 +346,13 @@ async def find(level: Optional[List[int]] = None,context_type: Optional[Union[str, List[str]]] = None,read_content: bool = False,+ events_time_decay_protection: Optional[str] = None,) -> str:"""Fast semantic retrieval without session context. Returns ranked memories, resources, and skills with URI, abstract, and score. context_type="skill" returns one hit per skill package, pointing at its SKILL.md, and without target_uri searches both the user's own and the account-shared skills."""+ try:+ validate_event_time_decay_request(events_time_decay_protection)+ except ValueError as exc:+ raise InvalidArgumentError(str(exc)) from excservice = get_service()ctx = _get_ctx()context_filter = _resolve_context_type_filter(context_type)@@ -377,6 +383,7 @@ async def find(score_threshold=min_score,filter=context_filter,level=level,+ events_time_decay_protection=events_time_decay_protection,)return await _format_search_result(result, service=service, ctx=ctx, read_content=read_content)@@ -413,6 +420,7 @@ async def search(rewrite: Literal["off", "auto"] = "off",rewrite_max_bullets: Annotated[int, Field(ge=1, le=20)] = 6,read_content: bool = False,+ events_time_decay_protection: Optional[str] = None,) -> str:"""Deep semantic retrieval with optional session context and intent analysis.@@ -422,6 +430,10 @@ async def search(detail tiers, cross-turn deduplication, peer scoping, and optional rewriting.``target_uri`` is only supported in list mode."""+ try:+ validate_event_time_decay_request(events_time_decay_protection)+ except ValueError as exc:+ raise InvalidArgumentError(str(exc)) from excservice = get_service()ctx = _get_ctx()context_filter = _resolve_context_type_filter(context_type)@@ -451,6 +463,7 @@ async def search(limit=limit,score_threshold=min_score,filter=context_filter,+ events_time_decay_protection=events_time_decay_protection,session_id=session_id,query_expansion=query_expansion,max_tokens=max_tokens,@@ -522,6 +535,7 @@ async def search(score_threshold=0.35 if min_score is None else min_score,filter=context_filter,level=level,+ events_time_decay_protection=events_time_decay_protection,)return await _format_search_result(result, service=service, ctx=ctx, read_content=read_content)@@ -589,6 +603,8 @@ async def _format_search_result(result, *, service, ctx, read_content: bool = Fa"hit_uri": m.uri,"score": getattr(m, "score", 0.0),"abstract": getattr(m, "abstract", "") or getattr(m, "overview", ""),+ "origin_score": getattr(m, "origin_score", None),+ "time_score": getattr(m, "time_score", None),}# Several files of one skill package can match; keep the best-scored hit.previous = seen.get(uri)@@ -624,6 +640,10 @@ async def _format_search_result(result, *, service, ctx, read_content: bool = Faabstract = (item["abstract"] or "(no abstract)").strip()uri = item["uri"]line = f"- [{item['type']} {item['score'] * 100:.0f}%] {uri}\n {abstract}"+ origin_score = item["origin_score"]+ time_score = item["time_score"]+ if origin_score is not None or time_score is not None:+ line += f"\n origin_score={origin_score}, time_score={time_score}"if uri in contents:line += f"\n\n {contents[uri]}"lines.append(line)diff --git a/openviking/server/routers/search.py b/openviking/server/routers/search.pyindex 660740a7d..8f4a8a4bc 100644--- a/openviking/server/routers/search.py+++ b/openviking/server/routers/search.py@@ -43,6 +43,7 @@ from openviking.utils.search_filters import (merge_search_filter,)from openviking.utils.tags import build_search_tags_filter+from openviking.utils.time_decay import validate_event_time_decay_requestfrom openviking_cli.exceptions import InvalidArgumentError, NotFoundError@@ -138,6 +139,15 @@ class FindRequest(BaseModel):level: Optional[Union[int, str, List[int]]] = Noneread_content: bool = Falsetelemetry: TelemetryRequest = False+ events_time_decay_protection: Optional[str] = None++ @model_validator(mode="after")+ def _validate_time_decay(self) -> "FindRequest":+ validate_event_time_decay_request(self.events_time_decay_protection)+ if self.events_time_decay_protection is not None:+ if not self.query.strip() and not self.image_url:+ raise ValueError("events_time_decay_protection requires a semantic query or image")+ return selfdef _reject_unknown_categories(value: Any, label: str, allowed: Sequence[str]) -> None:@@ -189,9 +199,10 @@ def context_only_fields_error(supplied_fields, as_named_by_caller=None) -> Optioused = sorted(set(CONTEXT_ONLY_FIELDS) & set(supplied_fields))if not used:return None- names = sorted({name for field in used for name in ((as_named_by_caller or {}).get(field) or {field})})- return (f"{', '.join(names)} require mode='context'; "- "set mode='context' or drop these fields")+ names = sorted(+ {name for field in used for name in ((as_named_by_caller or {}).get(field) or {field})}+ )+ return f"{', '.join(names)} require mode='context'; set mode='context' or drop these fields"class SearchRequest(BaseModel):@@ -222,6 +233,7 @@ class SearchRequest(BaseModel):level: Optional[Union[int, str, List[int]]] = Noneread_content: bool = Falsetelemetry: TelemetryRequest = False+ events_time_decay_protection: Optional[str] = Nonemode: Literal["list", "context"] = "list"@@ -239,6 +251,7 @@ class SearchRequest(BaseModel):@model_validator(mode="after")def _validate_mode(self) -> "SearchRequest":+ validate_event_time_decay_request(self.events_time_decay_protection)if self.mode == "list":error = context_only_fields_error(self.model_fields_set)if error:@@ -375,6 +388,7 @@ async def find(filter=effective_filter,level=_resolve_levels(request.level) or None,image_url=resolved_image_url,+ events_time_decay_protection=request.events_time_decay_protection,),)result = execution.result@@ -419,6 +433,7 @@ async def _search_context(limit=actual_limit,score_threshold=request.score_threshold,filter=effective_filter,+ events_time_decay_protection=request.events_time_decay_protection,session_id=request.session_id,query_expansion=request.query_expansion,max_tokens=request.max_tokens,@@ -494,6 +509,7 @@ async def search(filter=effective_filter,level=_resolve_levels(request.level) or None,image_url=resolved_image_url,+ events_time_decay_protection=request.events_time_decay_protection,)execution = await run_operation(diff --git a/openviking/service/search_service.py b/openviking/service/search_service.pyindex cf8018d52..5bdd30039 100644--- a/openviking/service/search_service.py+++ b/openviking/service/search_service.py@@ -99,6 +99,7 @@ class SearchService:filter: Optional[Dict] = None,level: Optional[List[int]] = None,image_url: Optional[str] = None,+ events_time_decay_protection: Optional[str] = None,) -> Any:"""Complex search with session context.@@ -133,6 +134,7 @@ class SearchService:filter=filter,level=level,image_url=resolved_image_url,+ events_time_decay_protection=events_time_decay_protection,)return result@@ -146,6 +148,7 @@ class SearchService:filter: Optional[Dict] = None,level: Optional[List[int]] = None,image_url: Optional[str] = None,+ events_time_decay_protection: Optional[str] = None,) -> Any:"""Semantic search without session context.@@ -172,6 +175,7 @@ class SearchService:filter=filter,level=level,image_url=resolved_image_url,+ events_time_decay_protection=events_time_decay_protection,)return resultdiff --git a/openviking/session/memory/memory_updater.py b/openviking/session/memory/memory_updater.pyindex 27927a829..01bba2f7e 100644--- a/openviking/session/memory/memory_updater.py+++ b/openviking/session/memory/memory_updater.py@@ -48,6 +48,7 @@ from openviking.telemetry import tracerfrom openviking.telemetry.request_wait_tracker import get_request_wait_trackerfrom openviking.telemetry.tracer import get_trace_idfrom openviking.utils.ingest_options import IngestOptions+from openviking.utils.tags import merge_search_tagsfrom openviking.utils.time_utils import parse_iso_datetimefrom openviking_cli.exceptions import ConflictError, NotFoundErrorfrom openviking_cli.utils import VikingURI, get_logger@@ -945,6 +946,7 @@ class MemoryUpdater:self._distribute_links_to_operations(operations)# Apply unified operations - _apply_edit returns True if edited, False if written+ uri_memory_type_map = {}for resolved_op in applicable_upserts:try:await self._apply_upsert(@@ -955,15 +957,14 @@ class MemoryUpdater:uri_remap=uri_remap,)# Add all uris to result (uris is List[str])- if self._is_uri_migration(resolved_op):- for uri in resolved_op.uris:- result.add_written(uri)- elif resolved_op.is_edit():- for uri in resolved_op.uris:- result.add_edited(uri)- else:- for uri in resolved_op.uris:- result.add_written(uri)+ add_result = (+ result.add_edited+ if resolved_op.is_edit() and not self._is_uri_migration(resolved_op)+ else result.add_written+ )+ for uri in resolved_op.uris:+ add_result(uri)+ uri_memory_type_map[uri] = resolved_op.memory_typeexcept Exception as e:tracer.error(f"Failed to apply operation: op_type={type(resolved_op).__name__}, uris={resolved_op.uris}",@@ -1058,13 +1059,15 @@ class MemoryUpdater:await self._sync_resource_refs_for_result(result, ctx, lease_ref=self._transaction_handle)# Vectorize written and edited memories- uri_memory_type_map = {}- for op in operations.upsert_operations:- for uri in op.uris:- uri_memory_type_map[uri] = op.memory_type# Merge caller-supplied transient tags with per-operation search_tags# (e.g. event-memory custom scalars) so both reach vectorization.effective_search_tags_by_uri = _collect_search_tags_by_uri(operations, search_tags_by_uri)+ for uri in result.written_uris + result.edited_uris:+ memory_type = uri_memory_type_map.get(uri)+ if memory_type:+ effective_search_tags_by_uri[uri] = merge_search_tags(+ effective_search_tags_by_uri.get(uri), [f"memory_type={memory_type}"]+ )await self._vectorize_memories(result,ctx,@@ -1858,6 +1861,10 @@ class MemoryUpdater:embedding_msg.context_data["_upsert_options"] = {"search_tag_mode": "append"}+ if memory_type:+ embedding_msg.context_data["_upsert_options"][+ "extracted_memory_type"+ ] = memory_typeif embedding_msg.telemetry_id:request_wait_tracker.register_embedding_root(embedding_msg.telemetry_id, embedding_msg.iddiff --git a/openviking/storage/collection_schemas.py b/openviking/storage/collection_schemas.pyindex 647d8375a..2df4d0855 100644--- a/openviking/storage/collection_schemas.py+++ b/openviking/storage/collection_schemas.py@@ -53,6 +53,7 @@ from openviking.utils.model_retry import (ERROR_CLASS_INPUT_TOO_LARGE,ERROR_CLASS_PERMANENT,)+from openviking.utils.tags import merge_search_tagsfrom openviking.utils.time_utils import get_current_timestampfrom openviking_cli.session.user_id import UserIdentifierfrom openviking_cli.utils import get_logger@@ -880,6 +881,9 @@ class TextEmbeddingHandler(DequeueHandlerBase):# Write to vector databasetry:raw_upsert_options = inserted_data.pop("_upsert_options", {})+ extracted_memory_type = raw_upsert_options.pop(+ "extracted_memory_type", None+ )# Reuse the actual vector-store ID when a semantic plan# rebuilds an existing same-level record. Only genuinely new# records derive an ID locally from (account, uri, level).@@ -926,6 +930,11 @@ class TextEmbeddingHandler(DequeueHandlerBase):inserted_data = FieldPatch(merge_fields, merge_modes).apply({**base, **inserted_data})+ if extracted_memory_type:+ inserted_data["search_tags"] = merge_search_tags(+ inserted_data.get("search_tags"),+ [f"memory_type={extracted_memory_type}"],+ )if not existing_records:missing_fields = missing_initial_record_fields(inserted_data)if missing_fields:diff --git a/openviking/storage/index_action.py b/openviking/storage/index_action.pyindex e47d59251..4a5c0660c 100644--- a/openviking/storage/index_action.py+++ b/openviking/storage/index_action.py@@ -8,7 +8,11 @@ from dataclasses import dataclass, fieldfrom enum import Enumfrom typing import Any, Mapping-from openviking.utils.tags import merge_search_tags, normalize_search_tags+from openviking.utils.tags import (+ merge_search_tags,+ normalize_search_tags,+ preserve_memory_type_tag,+)PATCHABLE_INDEX_FIELDS = frozenset({"md5", "content", "abstract", "updated_at", "active_count", "tags", "search_tags"}@@ -73,6 +77,11 @@ class FieldPatch:if self.modes.get(name, "replace") == "append"else incoming)+ if existing.get("context_type") == "memory":+ resolved[name] = preserve_memory_type_tag(+ existing.get(name),+ resolved[name],+ )else:resolved[name] = valuereturn resolveddiff --git a/openviking/storage/vectordb/collection/collection.py b/openviking/storage/vectordb/collection/collection.pyindex 93fc66677..177648fd5 100644--- a/openviking/storage/vectordb/collection/collection.py+++ b/openviking/storage/vectordb/collection/collection.py@@ -66,6 +66,8 @@ class ICollection(ABC):filters: Optional[Dict[str, Any]] = None,sparse_vector: Optional[Dict[str, float]] = None,output_fields: Optional[List[str]] = None,+ advance: Optional[Dict[str, Any]] = None,+ return_detail_info: bool = False,) -> SearchResult:raise NotImplementedError@@ -343,6 +345,8 @@ class Collection:filters: Optional[Dict[str, Any]] = None,sparse_vector: Optional[Dict[str, float]] = None,output_fields: Optional[List[str]] = None,+ advance: Optional[Dict[str, Any]] = None,+ return_detail_info: bool = False,):"""Perform vector similarity search on the specified index.@@ -362,8 +366,20 @@ class Collection:"""if self.__collection is None:raise RuntimeError("Collection is closed")+ detail_options: Dict[str, Any] = {}+ if advance is not None:+ detail_options["advance"] = advance+ if return_detail_info:+ detail_options["return_detail_info"] = Truereturn self.__collection.search_by_vector(- index_name, dense_vector, limit, offset, filters, sparse_vector, output_fields+ index_name,+ dense_vector,+ limit,+ offset,+ filters,+ sparse_vector,+ output_fields,+ **detail_options,)def search_by_keywords(diff --git a/openviking/storage/vectordb/collection/http_collection.py b/openviking/storage/vectordb/collection/http_collection.pyindex ed0270aca..f99983380 100644--- a/openviking/storage/vectordb/collection/http_collection.py+++ b/openviking/storage/vectordb/collection/http_collection.py@@ -14,6 +14,7 @@ from openviking.storage.vectordb.collection.result import (FetchDataInCollectionResult,SearchItemResult,SearchResult,+ parse_remote_search_result,)# Default request timeout (seconds)@@ -393,6 +394,8 @@ class HttpCollection(ICollection):filters: Optional[Dict[str, Any]] = None,sparse_vector: Optional[Dict[str, float]] = None,output_fields: Optional[List[str]] = None,+ advance: Optional[Dict[str, Any]] = None,+ return_detail_info: bool = False,) -> SearchResult:url = self.url_prefix + "api/vikingdb/data/search/vector"response = requests.post(@@ -408,6 +411,8 @@ class HttpCollection(ICollection):"output_fields": json.dumps(output_fields) if output_fields else None,"limit": limit,"offset": offset,+ **({"advance": advance} if advance is not None else {}),+ **({"return_detail_info": True} if return_detail_info else {}),},timeout=DEFAULT_TIMEOUT,)@@ -416,17 +421,7 @@ class HttpCollection(ICollection):return SearchResult()data = json.loads(response.text).get("data", {})- result = SearchResult()- if isinstance(data, dict) and "data" in data:- result.data = [- SearchItemResult(- id=item.get("id"),- fields=item.get("fields"),- score=item.get("score"),- )- for item in data.get("data", [])- ]- return result+ return parse_remote_search_result(data)def search_by_id(self,diff --git a/openviking/storage/vectordb/collection/local_collection.py b/openviking/storage/vectordb/collection/local_collection.pyindex 5f5cceb92..4854303c1 100644--- a/openviking/storage/vectordb/collection/local_collection.py+++ b/openviking/storage/vectordb/collection/local_collection.py@@ -507,7 +507,14 @@ class LocalCollection(ICollection):filters: Optional[Dict[str, Any]] = None,sparse_vector: Optional[Dict[str, float]] = None,output_fields: Optional[List[str]] = None,+ advance: Optional[Dict[str, Any]] = None,+ return_detail_info: bool = False,) -> SearchResult:+ time_decay = (advance or {}).get("time_decay")+ if advance is not None and (+ set(advance) != {"time_decay"} or not isinstance(time_decay, dict)+ ):+ raise NotImplementedError("Local advanced ranking supports time_decay only")search_result = SearchResult()index = self.indexes.get(index_name)if not index:@@ -521,9 +528,20 @@ class LocalCollection(ICollection):# Request more results to handle offsetactual_limit = limit + offset- label_list, scores_list = index.search(- dense_vector or [], actual_limit, filters, sparse_raw_terms, sparse_values- )+ details = {}+ if time_decay is not None:+ label_list, scores_list, details = index.search_with_time_decay(+ dense_vector or [],+ actual_limit,+ filters,+ sparse_raw_terms,+ sparse_values,+ time_decay,+ )+ else:+ label_list, scores_list = index.search(+ dense_vector or [], actual_limit, filters, sparse_raw_terms, sparse_values+ )# Apply offset by slicing the resultsif offset > 0:@@ -535,6 +553,7 @@ class LocalCollection(ICollection):label_list = label_list[:limit]scores_list = scores_list[:limit]+ score_details = [details.get(str(label), {}) for label in label_list]pk_list = label_listfields_list = []projected_fields = (@@ -570,6 +589,7 @@ class LocalCollection(ICollection):cands_vectors = [cands_vectors[i] for i in valid_indices]pk_list = [pk_list[i] for i in valid_indices]scores_list = [scores_list[i] for i in valid_indices]+ score_details = [score_details[i] for i in valid_indices]# Parse each candidate's fields defensively: a single corrupted JSON# string (e.g. truncated by the storage layer's uint16 length prefix)@@ -597,6 +617,7 @@ class LocalCollection(ICollection):cands_vectors = [cands_vectors[i] for i in json_valid_indices]pk_list = [pk_list[i] for i in json_valid_indices]scores_list = [scores_list[i] for i in json_valid_indices]+ score_details = [score_details[i] for i in json_valid_indices]if self.meta.primary_key:pk_list = [@@ -611,8 +632,16 @@ class LocalCollection(ICollection):fields_list[i][self.meta.vector_key] = vectorsearch_result.data = [- SearchItemResult(id=pk, fields=fields, score=score)- for pk, score, fields in zip_longest(pk_list, scores_list, fields_list)+ SearchItemResult(+ id=pk,+ fields=fields,+ score=score,+ origin_score=(detail or {}).get("origin_score"),+ addition_score=(detail or {}).get("addition_score"),+ )+ for pk, score, fields, detail in zip_longest(+ pk_list, scores_list, fields_list, score_details+ )]return search_resultdiff --git a/openviking/storage/vectordb/collection/result.py b/openviking/storage/vectordb/collection/result.pyindex 7078fb6c1..606e26795 100644--- a/openviking/storage/vectordb/collection/result.py+++ b/openviking/storage/vectordb/collection/result.py@@ -35,6 +35,8 @@ class SearchItemResult:id: Any = Nonefields: Optional[Dict[str, Any]] = Nonescore: Optional[float] = None+ origin_score: Optional[float] = None+ addition_score: Optional[float] = None@dataclass@@ -42,6 +44,24 @@ class SearchResult:data: List[SearchItemResult] = field(default_factory=list)+def parse_remote_search_result(payload: Dict[str, Any]) -> SearchResult:+ """Parse the common VikingDB search response, including score details."""+ result = SearchResult()+ if not isinstance(payload, dict) or "data" not in payload:+ return result+ result.data = [+ SearchItemResult(+ id=item.get("id"),+ fields=item.get("fields"),+ score=item.get("score"),+ origin_score=item.get("origin_score"),+ addition_score=item.get("addition_score"),+ )+ for item in payload.get("data", [])+ ]+ return result++@dataclassclass AggregateResult:"""Result of aggregation operation.diff --git a/openviking/storage/vectordb/collection/vikingdb_collection.py b/openviking/storage/vectordb/collection/vikingdb_collection.pyindex 098261029..9f7091c7a 100644--- a/openviking/storage/vectordb/collection/vikingdb_collection.py+++ b/openviking/storage/vectordb/collection/vikingdb_collection.py@@ -9,8 +9,8 @@ from openviking.storage.vectordb.collection.result import (AggregateResult,DataItem,FetchDataInCollectionResult,- SearchItemResult,SearchResult,+ parse_remote_search_result,)from openviking.storage.vectordb.collection.vikingdb_clients import (VIKINGDB_APIS,@@ -252,18 +252,7 @@ class VikingDBCollection(ICollection):return resultdef _parse_search_result(self, data: Dict[str, Any]) -> SearchResult:- result = SearchResult()- if isinstance(data, dict) and "data" in data:- data_list = data.get("data", [])- result.data = [- SearchItemResult(- id=item.get("id"),- fields=item.get("fields"),- score=item.get("score"),- )- for item in data_list- ]- return result+ return parse_remote_search_result(data)def search_by_vector(self,@@ -274,6 +263,8 @@ class VikingDBCollection(ICollection):filters: Optional[Dict[str, Any]] = None,sparse_vector: Optional[Dict[str, float]] = None,output_fields: Optional[List[str]] = None,+ advance: Optional[Dict[str, Any]] = None,+ return_detail_info: bool = False,) -> SearchResult:path = "/api/vikingdb/data/search/vector"data = {@@ -289,6 +280,10 @@ class VikingDBCollection(ICollection):}if sparse_vector:data["sparse_vector"] = sparse_vector+ if advance is not None:+ data["advance"] = advance+ if return_detail_info:+ data["return_detail_info"] = Trueresp_data = self._data_post(path, data)return self._parse_search_result(resp_data)diff --git a/openviking/storage/vectordb/collection/volcengine_api_key_collection.py b/openviking/storage/vectordb/collection/volcengine_api_key_collection.pyindex 077369ddc..66491c3ec 100644--- a/openviking/storage/vectordb/collection/volcengine_api_key_collection.py+++ b/openviking/storage/vectordb/collection/volcengine_api_key_collection.py@@ -12,8 +12,8 @@ from openviking.storage.vectordb.collection.result import (AggregateResult,DataItem,FetchDataInCollectionResult,- SearchItemResult,SearchResult,+ parse_remote_search_result,)from openviking.storage.vectordb.collection.volcengine_clients import (ClientForDataApi,@@ -211,18 +211,7 @@ class VolcengineApiKeyCollection(ICollection):return resultdef _parse_search_result(self, data: Dict[str, Any]) -> SearchResult:- result = SearchResult()- if isinstance(data, dict) and "data" in data:- data_list = data.get("data", [])- result.data = [- SearchItemResult(- id=item.get("id"),- fields=item.get("fields"),- score=item.get("score"),- )- for item in data_list- ]- return result+ return parse_remote_search_result(data)def _parse_aggregate_result(self,@@ -372,6 +361,8 @@ class VolcengineApiKeyCollection(ICollection):filters: Optional[Dict[str, Any]] = None,sparse_vector: Optional[Dict[str, float]] = None,output_fields: Optional[List[str]] = None,+ advance: Optional[Dict[str, Any]] = None,+ return_detail_info: bool = False,) -> SearchResult:if dense_vector is None and sparse_vector is None:raise ValueError("At least one of dense_vector or sparse_vector is required")@@ -388,6 +379,10 @@ class VolcengineApiKeyCollection(ICollection):}if sparse_vector:data["sparse_vector"] = sparse_vector+ if advance is not None:+ data["advance"] = advance+ if return_detail_info:+ data["return_detail_info"] = Trueresp_data = self._data_post(path, data)return self._parse_search_result(resp_data)diff --git a/openviking/storage/vectordb/collection/volcengine_collection.py b/openviking/storage/vectordb/collection/volcengine_collection.pyindex 8bf20beeb..32f2d24c2 100644--- a/openviking/storage/vectordb/collection/volcengine_collection.py+++ b/openviking/storage/vectordb/collection/volcengine_collection.py@@ -10,8 +10,8 @@ from openviking.storage.vectordb.collection.result import (AggregateResult,DataItem,FetchDataInCollectionResult,- SearchItemResult,SearchResult,+ parse_remote_search_result,)from openviking.storage.vectordb.collection.volcengine_clients import (VIKING_DB_VERSION,@@ -467,18 +467,7 @@ class VolcengineCollection(ICollection):return resultdef _parse_search_result(self, data: Dict[str, Any]) -> SearchResult:- result = SearchResult()- if isinstance(data, dict) and "data" in data:- data_list = data.get("data", [])- result.data = [- SearchItemResult(- id=item.get("id"),- fields=item.get("fields"),- score=item.get("score"),- )- for item in data_list- ]- return result+ return parse_remote_search_result(data)def search_by_vector(self,@@ -489,6 +478,8 @@ class VolcengineCollection(ICollection):filters: Optional[Dict[str, Any]] = None,sparse_vector: Optional[Dict[str, float]] = None,output_fields: Optional[List[str]] = None,+ advance: Optional[Dict[str, Any]] = None,+ return_detail_info: bool = False,) -> SearchResult:path = "/api/vikingdb/data/search/vector"data = {@@ -504,6 +495,10 @@ class VolcengineCollection(ICollection):}if sparse_vector:data["sparse_vector"] = sparse_vector+ if advance is not None:+ data["advance"] = advance+ if return_detail_info:+ data["return_detail_info"] = Trueresp_data = self._data_post(path, data)return self._parse_search_result(resp_data)diff --git a/openviking/storage/vectordb/engine/_python_api.py b/openviking/storage/vectordb/engine/_python_api.pyindex 6fc6a654c..04f0999bd 100644--- a/openviking/storage/vectordb/engine/_python_api.py+++ b/openviking/storage/vectordb/engine/_python_api.py@@ -316,7 +316,7 @@ class DeleteDataRequest(_RequestBase):class SearchRequest(_RequestBase):- __slots__ = ("query", "sparse_raw_terms", "sparse_values", "topk", "dsl")+ __slots__ = ("query", "sparse_raw_terms", "sparse_values", "topk", "dsl", "time_decay")def __init__(self):self.query = []@@ -324,6 +324,7 @@ class SearchRequest(_RequestBase):self.sparse_values = []self.topk = 0self.dsl = ""+ self.time_decay = ""class SearchResult:diff --git a/openviking/storage/vectordb/index/local_index.py b/openviking/storage/vectordb/index/local_index.pyindex 77d9e378a..b3104e338 100644--- a/openviking/storage/vectordb/index/local_index.py+++ b/openviking/storage/vectordb/index/local_index.py@@ -141,7 +141,12 @@ class IndexEngineProxy:filters: Optional[Dict[str, Any]] = None,sparse_raw_terms: Optional[List[str]] = None,sparse_values: Optional[List[float]] = None,- ) -> Tuple[List[int], List[float]]:+ *,+ time_decay: Optional[Dict[str, Any]] = None,+ ) -> Union[+ Tuple[List[int], List[float]],+ Tuple[List[int], List[float], Dict[str, Any]],+ ]:if not self.index_engine:raise RuntimeError("Index engine not initialized")@@ -152,6 +157,8 @@ class IndexEngineProxy:query_vector = normalize_vector(query_vector)req.query = query_vectorreq.topk = limit+ if time_decay is not None:+ req.time_decay = json.dumps(time_decay)if filters is None:filters = {}@@ -164,6 +171,8 @@ class IndexEngineProxy:search_result = self.index_engine.search(req)labels = search_result.labelsscores = search_result.scores+ if time_decay is not None:+ return labels, scores, json.loads(search_result.extra_json or "{}")return labels, scoresdef search_with_filter_token(@@ -842,6 +851,18 @@ class LocalIndex(IIndex):self._raise_dense_rebuild_failure()return self.dense_search is not None+ def search_with_time_decay(+ self, query_vector, limit, filters, sparse_raw_terms, sparse_values, time_decay+ ):+ """Use the native scalar/vector index, including for cuVS-backed collections."""+ if not self.engine_proxy:+ raise RuntimeError("Index engine not initialized")+ if self.field_type_converter and filters is not None:+ filters = self.field_type_converter.convert_filter_for_index(filters)+ return self.engine_proxy.search(+ query_vector, limit, filters, sparse_raw_terms, sparse_values, time_decay=time_decay+ )+def search(self,query_vector: Optional[List[float]],diff --git a/openviking/storage/vectordb/service/api_fastapi.py b/openviking/storage/vectordb/service/api_fastapi.pyindex 95bddf9db..30f36d519 100644--- a/openviking/storage/vectordb/service/api_fastapi.py+++ b/openviking/storage/vectordb/service/api_fastapi.py@@ -431,6 +431,8 @@ async def search_by_vector(request: SearchByVectorRequest, req: Request):filters=filters,sparse_vector=sparse_vector,output_fields=output_fields,+ advance=request.advance,+ return_detail_info=request.return_detail_info,)return success_response("search success", asdict(result), request=req)except VikingDBException as e:diff --git a/openviking/storage/vectordb/service/app_models.py b/openviking/storage/vectordb/service/app_models.pyindex 169eb58a9..18b240920 100644--- a/openviking/storage/vectordb/service/app_models.py+++ b/openviking/storage/vectordb/service/app_models.py@@ -99,6 +99,8 @@ class IndexDropRequest(BaseModel):class SearchByVectorRequest(BaseModel):+ advance: Optional[dict[str, Any]] = None+ return_detail_info: bool = Falsecollection_name: str = Field(..., description="Collection name")index_name: str = Field(..., description="Index name")project: Optional[str] = Field("default", description="Project name")diff --git a/openviking/storage/vectordb_adapters/base.py b/openviking/storage/vectordb_adapters/base.pyindex d305ba4e2..c45f00354 100644--- a/openviking/storage/vectordb_adapters/base.py+++ b/openviking/storage/vectordb_adapters/base.py@@ -484,7 +484,37 @@ class CollectionAdapter(ABC):output_fields: Optional[list[str]] = None,order_by: Optional[str] = None,order_desc: bool = False,+ advance: Optional[Dict[str, Any]] = None,) -> list[Dict[str, Any]]:+ decay_request = (advance or {}).get("time_decay")+ if decay_request is not None and self.mode != "opengauss":+ from openviking.utils.time_decay import (+ build_time_decay_fusion_spec,+ build_time_decay_post_process_ops,+ )+ from openviking.utils.time_utils import parse_iso_datetime++ protection = decay_request["protection"]+ origin = parse_iso_datetime(decay_request["origin"])+ if self.mode in {"local", "cuvs", "http"}:+ spec = build_time_decay_fusion_spec(protection=protection, origin=origin)+ advance = {+ "time_decay": {+ "field": spec.field,+ "origin_ms": spec.origin_ms,+ "offset_ms": spec.offset_ms,+ "scale_ms": spec.scale_ms,+ "decay": spec.decay,+ }+ }+ elif self.mode in {"vikingdb", "volcengine"}:+ advance = {+ "post_process_ops": build_time_decay_post_process_ops(+ protection=protection, origin=origin+ )+ }+ else:+ raise NotImplementedError(f"Time decay is not supported by {self.mode}")coll = self.get_collection()vectordb_filter = self._compile_filter(filter)@@ -497,6 +527,8 @@ class CollectionAdapter(ABC):offset=offset,filters=vectordb_filter,output_fields=output_fields,+ advance=advance,+ return_detail_info=decay_request is not None,)elif order_by:result = coll.search_by_scalar(@@ -538,6 +570,10 @@ class CollectionAdapter(ABC):record = dict(item.fields) if item.fields else {}record["id"] = item.idrecord["_score"] = _normalize_result_score(item.score)+ if item.origin_score is not None:+ record["_origin_score"] = _normalize_result_score(item.origin_score)+ if item.addition_score is not None:+ record["_time_score"] = _normalize_result_score(item.addition_score)record = self._normalize_record_for_read(record)records.append(record)return recordsdiff --git a/openviking/storage/vectordb_adapters/opengauss/collection.py b/openviking/storage/vectordb_adapters/opengauss/collection.pyindex ba1bb64c7..a093563aa 100644--- a/openviking/storage/vectordb_adapters/opengauss/collection.py+++ b/openviking/storage/vectordb_adapters/opengauss/collection.py@@ -1061,7 +1061,10 @@ class OpenGaussCollection(ICollection):filters: Optional[Dict[str, Any]] = None,sparse_vector: Optional[Dict[str, float]] = None,output_fields: Optional[List[str]] = None,+ advance: Optional[Dict[str, Any]] = None,+ return_detail_info: bool = False,) -> SearchResult:+ # Accept shared search options; openGauss does not apply time decay.# Sparse support is checked before the dense emptiness short-circuit:# a pure sparse query must fail loudly instead of returning an empty# result set that looks like "no recall".diff --git a/openviking/storage/viking_fs/_semantic.py b/openviking/storage/viking_fs/_semantic.pyindex 535794b3a..6a65e80e6 100644--- a/openviking/storage/viking_fs/_semantic.py+++ b/openviking/storage/viking_fs/_semantic.py@@ -3,6 +3,7 @@"""Semantic retrieval mixin for VikingFS."""import asyncio+from datetime import datetime, timezonefrom typing import Any, Dict, List, Optional, Unionfrom openviking.core.context import ContextLevel@@ -24,7 +25,8 @@ from openviking.storage.viking_fs._base import ()from openviking.telemetry import get_current_telemetryfrom openviking.utils.image_search import build_multimodal_embedding_input-from openviking_cli.exceptions import NotFoundError+from openviking.utils.time_decay import parse_duration_ms+from openviking_cli.exceptions import InvalidArgumentError, NotFoundErrorclass _SemanticMixin:@@ -199,6 +201,7 @@ class _SemanticMixin:ctx: Optional[RequestContext] = None,level: Optional[List[int]] = None,image_url: Optional[str] = None,+ events_time_decay_protection: Optional[str] = None,):"""Semantic search.@@ -223,8 +226,19 @@ class _SemanticMixin:filter_only = is_filter_only_query(query, image_url)if filter_only:_ensure_filter_present(filter)+ if events_time_decay_protection is not None:+ raise InvalidArgumentError(+ "events_time_decay_protection requires a semantic query or image"+ )else:_ensure_non_empty_search_query(query, image_url)+ if events_time_decay_protection is not None:+ parse_duration_ms(+ events_time_decay_protection, parameter_name="events_time_decay_protection"+ )+ request_now = (+ datetime.now(timezone.utc) if events_time_decay_protection is not None else None+ )telemetry = get_current_telemetry()from openviking.retrieve.hierarchical_retriever import (@@ -290,6 +304,8 @@ class _SemanticMixin:score_threshold=score_threshold,scope_dsl=filter,level=level,+ events_time_decay_protection=events_time_decay_protection,+ request_now=request_now,)# Convert QueryResult to FindResult@@ -381,6 +397,7 @@ class _SemanticMixin:ctx: Optional[RequestContext] = None,level: Optional[List[int]] = None,image_url: Optional[str] = None,+ events_time_decay_protection: Optional[str] = None,):"""Complex search with session context.@@ -395,6 +412,13 @@ class _SemanticMixin:FindResult"""_ensure_non_empty_search_query(query, image_url)+ if events_time_decay_protection is not None:+ parse_duration_ms(+ events_time_decay_protection, parameter_name="events_time_decay_protection"+ )+ request_now = (+ datetime.now(timezone.utc) if events_time_decay_protection is not None else None+ )telemetry = get_current_telemetry()from openviking.retrieve.hierarchical_retriever import HierarchicalRetrieverfrom openviking.retrieve.intent_analyzer import IntentAnalyzer@@ -499,6 +523,8 @@ class _SemanticMixin:score_threshold=score_threshold,scope_dsl=filter,level=level,+ events_time_decay_protection=events_time_decay_protection,+ request_now=request_now,)query_results = await asyncio.gather(*[_execute(tq) for tq in typed_queries])diff --git a/openviking/storage/viking_vector_index_backend.py b/openviking/storage/viking_vector_index_backend.pyindex b977ce506..330cf6d08 100644--- a/openviking/storage/viking_vector_index_backend.py+++ b/openviking/storage/viking_vector_index_backend.py@@ -9,6 +9,7 @@ import threadingimport uuidfrom contextlib import asynccontextmanagerfrom dataclasses import dataclass+from datetime import datetime, timezonefrom functools import wrapsfrom typing import Any, AsyncIterator, Awaitable, Callable, Container, Dict, List, Mapping, Optional@@ -41,7 +42,8 @@ from openviking.storage.vectordb.collection.collection import Collectionfrom openviking.storage.vectordb.collection.result import UpdateResultfrom openviking.storage.vectordb.utils.logging_init import init_cpp_loggingfrom openviking.storage.vectordb_adapters import create_collection_adapter-from openviking.utils.tags import merge_search_tags+from openviking.utils.tags import merge_search_tags, preserve_memory_type_tag+from openviking.utils.time_decay import parse_duration_msfrom openviking.utils.time_utils import get_current_timestampfrom openviking_cli.exceptions import InvalidArgumentErrorfrom openviking_cli.utils import get_logger@@ -805,6 +807,7 @@ class _SingleAccountBackend:output_fields: Optional[List[str]] = None,order_by: Optional[str] = None,order_desc: bool = False,+ advance: Optional[Dict[str, Any]] = None,) -> List[Dict[str, Any]]:self._validate_vector_dimension(query_vector)try:@@ -833,6 +836,7 @@ class _SingleAccountBackend:output_fields=output_fields,order_by=order_by,order_desc=order_desc,+ advance=advance,)except Exception as e:logger.error("Error querying collection: %s", e, exc_info=True)@@ -869,6 +873,7 @@ class _SingleAccountBackend:limit: int = 10,offset: int = 0,output_fields: Optional[List[str]] = None,+ advance: Optional[Dict[str, Any]] = None,) -> List[Dict[str, Any]]:return await self.query(query_vector=query_vector,@@ -877,6 +882,7 @@ class _SingleAccountBackend:limit=limit,offset=offset,output_fields=output_fields,+ advance=advance,)@_backend_operation@@ -1096,7 +1102,6 @@ class VikingVectorIndexBackend:self._collection_name = config.name or "context"self._index_name = config.index_name or DEFAULT_INDEX_NAMEself.acl_manager: Optional[AclManager] = None-self._account_backends: Dict[str, _SingleAccountBackend] = {}self._vector_config_resolver = Noneself._account_backend_locks = KeyedAsyncLockPool[str]()@@ -1478,6 +1483,11 @@ class VikingVectorIndexBackend:)else:updated_record["search_tags"] = list(tags)+ if updated_record.get("context_type") == "memory":+ updated_record["search_tags"] = preserve_memory_type_tag(+ full_records[0].get("search_tags"),+ updated_record["search_tags"],+ )except Exception as exc:logger.warning("update_search_tags failed to merge exact record tags uri=%s "@@ -1533,6 +1543,11 @@ class VikingVectorIndexBackend:)else:updated_record["search_tags"] = list(tags)+ if updated_record.get("context_type") == "memory":+ updated_record["search_tags"] = preserve_memory_type_tag(+ full_record.get("search_tags"),+ updated_record["search_tags"],+ )except Exception as exc:logger.warning("update_search_tags failed to merge leveled record tags uri=%s "@@ -1559,6 +1574,7 @@ class VikingVectorIndexBackend:output_fields: Optional[List[str]] = None,order_by: Optional[str] = None,order_desc: bool = False,+ advance: Optional[Dict[str, Any]] = None,*,ctx: RequestContext,) -> List[Dict[str, Any]]:@@ -1572,6 +1588,7 @@ class VikingVectorIndexBackend:output_fields=output_fields,order_by=order_by,order_desc=order_desc,+ advance=advance,)async def search_by_random(@@ -1606,6 +1623,7 @@ class VikingVectorIndexBackend:limit: int = 10,offset: int = 0,output_fields: Optional[List[str]] = None,+ advance: Optional[Dict[str, Any]] = None,*,ctx: RequestContext,) -> List[Dict[str, Any]]:@@ -1616,6 +1634,7 @@ class VikingVectorIndexBackend:limit=limit,offset=offset,output_fields=output_fields,+ advance=advance,ctx=ctx,)@@ -1869,6 +1888,8 @@ class VikingVectorIndexBackend:level: Optional[List[int]] = None,limit: int = 10,offset: int = 0,+ events_time_decay_protection: Optional[str] = None,+ request_now: Optional[datetime] = None,) -> List[Dict[str, Any]]:acl_enabled = await self._acl_enabled(ctx)scope_filter = self._build_scope_filter(@@ -1879,14 +1900,29 @@ class VikingVectorIndexBackend:level=level,acl_enabled=acl_enabled,)- return await self.search(+ if events_time_decay_protection is None:+ return await self.search(+ query_vector=query_vector,+ sparse_query_vector=sparse_query_vector,+ filter=scope_filter,+ limit=limit,+ offset=offset,+ output_fields=RETRIEVAL_OUTPUT_FIELDS,+ ctx=ctx,+ )++ parse_duration_ms(+ events_time_decay_protection, parameter_name="events_time_decay_protection"+ )+ return await self._search_with_event_time_decay(+ ctx=ctx,query_vector=query_vector,sparse_query_vector=sparse_query_vector,- filter=scope_filter,+ scope_filter=scope_filter,limit=limit,offset=offset,- output_fields=RETRIEVAL_OUTPUT_FIELDS,- ctx=ctx,+ events_time_decay_protection=events_time_decay_protection,+ request_now=request_now,)async def filter_in_tenant(@@ -1928,6 +1964,49 @@ class VikingVectorIndexBackend:ctx=ctx,)+ async def _search_with_event_time_decay(+ self,+ *,+ ctx: RequestContext,+ query_vector: Optional[List[float]],+ sparse_query_vector: Optional[Dict[str, float]],+ scope_filter: Optional[FilterExpr],+ limit: int,+ offset: int,+ events_time_decay_protection: str,+ request_now: Optional[datetime],+ ) -> List[Dict[str, Any]]:+ request_now = request_now or datetime.now(timezone.utc)+ final_window = limit + offset+ event_filter = self._merge_filters(scope_filter, Eq("search_tags", "memory_type=events"))+ non_event_filter = self._merge_filters(+ scope_filter,+ RawDSL({"op": "must_not", "field": "search_tags", "conds": ["memory_type=events"]}),+ )+ # The adapter owns backend parameters and the engine owns amplification.+ advance = {+ "time_decay": {+ "protection": events_time_decay_protection,+ "origin": request_now.isoformat(),+ }+ }+ search_kwargs: Dict[str, Any] = {+ "ctx": ctx,+ "query_vector": query_vector,+ "sparse_query_vector": sparse_query_vector,+ "limit": final_window,+ "offset": 0,+ "output_fields": RETRIEVAL_OUTPUT_FIELDS,+ }+ remaining_results, event_results = await asyncio.gather(+ self.search(filter=non_event_filter, **search_kwargs),+ self.search(filter=event_filter, advance=advance, **search_kwargs),+ )++ results = remaining_results + event_results+ results.sort(key=lambda item: item.get("_score", 0.0), reverse=True)+ return results[offset : offset + limit]+async def get_context_by_uri(self,uri: str,@@ -2808,7 +2887,9 @@ class VikingVectorIndexBackend:filters.append(tenant_filter)if targets:- uri_conds = [PathScope("uri", target_dir, depth=-1) for target_dir in targets]+ uri_conds: List[FilterExpr] = [+ PathScope("uri", target_dir, depth=-1) for target_dir in targets+ ]if uri_conds:filters.append(Or(uri_conds))@@ -2907,7 +2988,7 @@ class VikingVectorIndexBackend:return self.acl_manager is not None and await self.acl_manager.is_enabled(ctx.account_id)@staticmethod- def _merge_filters(*filters: Optional[FilterExpr]) -> Optional[FilterExpr]:+ def _merge_filters(*filters: Optional[FilterExpr | Dict[str, Any]]) -> Optional[FilterExpr]:non_empty: List[FilterExpr] = []for item in filters:if not item:diff --git a/openviking/storage/vikingdb_manager.py b/openviking/storage/vikingdb_manager.pyindex 8e601fbf4..6a3ffbd1a 100644--- a/openviking/storage/vikingdb_manager.py+++ b/openviking/storage/vikingdb_manager.py@@ -5,6 +5,7 @@ VikingDB Manager class that extends VikingVectorIndexBackend with queue manageme"""from contextlib import asynccontextmanager+from datetime import datetimefrom typing import Any, AsyncIterator, Dict, List, Mapping, Optional, Tuplefrom openviking.server.identity import RequestContext@@ -51,9 +52,7 @@ class VikingDBManager(VikingVectorIndexBackend):queue_manager: QueueManager instance."""# Initialize the base VikingVectorIndexBackend without queue management- super().__init__(- config=vectordb_config,- )+ super().__init__(config=vectordb_config)# Queue management specific attributesself._queue_manager = queue_manager@@ -158,6 +157,7 @@ class VikingDBManager(VikingVectorIndexBackend):logger.error(f"Error getting embedding queue size: {e}")return 0+class VikingDBManagerProxy:"""租户绑定的 VikingDBManager 代理。@@ -433,18 +433,25 @@ class VikingDBManagerProxy:level: Optional[List[int]] = None,limit: int = 10,offset: int = 0,+ events_time_decay_protection: Optional[str] = None,+ request_now: Optional[datetime] = None,) -> List[Dict[str, Any]]:- return await self._manager.search_in_tenant(- self._ctx,- query_vector=query_vector,- sparse_query_vector=sparse_query_vector,- context_type=context_type,- target_directories=target_directories,- extra_filter=extra_filter,- level=level,- limit=limit,- offset=offset,- )+ kwargs: Dict[str, Any] = {+ "query_vector": query_vector,+ "sparse_query_vector": sparse_query_vector,+ "context_type": context_type,+ "target_directories": target_directories,+ "extra_filter": extra_filter,+ "level": level,+ "limit": limit,+ "offset": offset,+ }+ if events_time_decay_protection is not None:+ kwargs.update(+ events_time_decay_protection=events_time_decay_protection,+ request_now=request_now,+ )+ return await self._manager.search_in_tenant(self._ctx, **kwargs)async def filter_in_tenant(self,diff --git a/openviking/utils/tags.py b/openviking/utils/tags.pyindex c9c581ae6..c447e213b 100644--- a/openviking/utils/tags.py+++ b/openviking/utils/tags.py@@ -96,3 +96,29 @@ def merge_search_tags(existing: Iterable[str] | None, incoming: Iterable[str] |ordered[key] = valuereturn [f"{key}={value}" for key, value in ordered.items()]+++def preserve_memory_type_tag(+ existing: Iterable[str] | None,+ incoming: Iterable[str] | None,+) -> list[str]:+ """Preserve the extracted memory type while updating ordinary search tags."""+ existing_memory_type = next(+ (+ tag+ for tag in normalize_search_tags(existing, discard_invalid=True)+ if tag.startswith("memory_type=")+ ),+ None,+ )+ # Only memory extraction creates or changes this tag. Ordinary writes+ # preserve it, including its absence on legacy memories.+ user_tags = [+ tag+ for tag in normalize_search_tags(incoming, discard_invalid=True)+ if not tag.startswith("memory_type=")+ ]+ return merge_search_tags(+ [existing_memory_type] if existing_memory_type is not None else [],+ user_tags,+ )diff --git a/openviking/utils/time_decay.py b/openviking/utils/time_decay.pynew file mode 100644index 000000000..d17690e59--- /dev/null+++ b/openviking/utils/time_decay.py@@ -0,0 +1,134 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0+"""Event time-decay validation and engine parameter translation."""++from __future__ import annotations++import math+import re+from dataclasses import dataclass+from datetime import datetime, timezone+from numbers import Real+from typing import Any, Optional++from openviking.utils.time_utils import format_iso8601, parse_iso_datetime++# This curve is an internal ranking contract; it is intentionally not part of+# ov.conf or ovcli.conf.+EVENT_TIME_DECAY_SCALE = "7d"+EVENT_TIME_DECAY_DECAY = 0.5+# Match VikingDB's date_time duration limit: 3000 years of 365 days.+MAX_DURATION_MS = 3000 * 365 * 24 * 60 * 60 * 1000++_DURATION_RE = re.compile(r"^(0|[0-9]+[mhd])$")+_DURATION_MULTIPLIERS_MS = {+ "m": 60 * 1000,+ "h": 60 * 60 * 1000,+ "d": 24 * 60 * 60 * 1000,+}+++def parse_duration_ms(value: Any, *, parameter_name: str = "duration") -> int:+ """Parse ``0`` or a non-negative integer duration with m/h/d units."""+ if not isinstance(value, str) or not _DURATION_RE.fullmatch(value):+ raise ValueError(+ f"{parameter_name} must be '0' or a non-negative integer followed by m, h, or d"+ )+ if value == "0":+ return 0+ duration_ms = int(value[:-1]) * _DURATION_MULTIPLIERS_MS[value[-1]]+ if duration_ms > MAX_DURATION_MS:+ raise ValueError(f"{parameter_name} exceeds the maximum duration of 1095000d")+ return duration_ms+++def validate_event_time_decay_request(protection: Any) -> None:+ """Validate the optional protection period without changing score thresholds."""+ if protection is None:+ return+ parse_duration_ms(protection, parameter_name="events_time_decay_protection")+++def _datetime_to_epoch_ms(value: Any) -> float:+ if isinstance(value, bool):+ raise ValueError("time value must not be boolean")+ if isinstance(value, Real):+ result = float(value)+ if not math.isfinite(result):+ raise ValueError("time value must be finite")+ return result+ if isinstance(value, str):+ value = parse_iso_datetime(value)+ if isinstance(value, datetime):+ if value.tzinfo is None:+ value = value.replace(tzinfo=timezone.utc)+ return value.timestamp() * 1000.0+ raise ValueError("time value must be an epoch millisecond number or ISO 8601 string")+++@dataclass(frozen=True)+class TimeDecayFusionSpec:+ """Compiled score-fusion parameters for event time decay."""++ field: str+ origin_ms: float+ offset_ms: int+ scale_ms: int+ decay: float++ def __post_init__(self) -> None:+ # Validate request constants before translating them for each backend.+ if self.scale_ms <= 0:+ raise ValueError("time-decay scale must be greater than zero")+ if not 0.0 < self.decay < 1.0:+ raise ValueError("time-decay decay must be in (0, 1)")+ object.__setattr__(self, "origin_ms", _datetime_to_epoch_ms(self.origin_ms))+++def build_time_decay_fusion_spec(+ *,+ protection: str,+ origin: Optional[datetime] = None,+ field: str = "updated_at",+) -> TimeDecayFusionSpec:+ """Compile the fixed event time-decay curve for one retrieval request."""+ return TimeDecayFusionSpec(+ field=field,+ origin_ms=origin or datetime.now(timezone.utc),+ offset_ms=parse_duration_ms(protection, parameter_name="events_time_decay_protection"),+ scale_ms=parse_duration_ms(EVENT_TIME_DECAY_SCALE, parameter_name="time-decay scale"),+ decay=EVENT_TIME_DECAY_DECAY,+ )+++def build_time_decay_post_process_ops(+ *,+ protection: str,+ origin: Optional[datetime] = None,+ field: str = "updated_at",+) -> list[dict[str, Any]]:+ """Build the fixed VikingDB score-fusion operator for event results."""+ protection_ms = parse_duration_ms(protection, parameter_name="events_time_decay_protection")+ addition = {+ "factor": 1,+ "base_value_from": "decay_func",+ "field": field,+ "func": "exp",+ "origin": format_iso8601(origin or datetime.now(timezone.utc)),+ "scale": EVENT_TIME_DECAY_SCALE,+ "decay": EVENT_TIME_DECAY_DECAY,+ }+ # VikingDB defaults an omitted offset to zero but rejects explicit zero+ # durations (including "0m", "0h", and "0d").+ if protection_ms > 0:+ addition["offset"] = protection++ return [+ {+ "op": "score_fusion",+ "fusion_by": "multiply",+ "normalize_for_origin_score": {"enable": False},+ "normalize_for_addition_score": {"enable": False},+ "addition_score": [addition],+ }+ ]diff --git a/openviking_cli/retrieve/types.py b/openviking_cli/retrieve/types.pyindex 260f7e2b2..45b4f6aaa 100644--- a/openviking_cli/retrieve/types.py+++ b/openviking_cli/retrieve/types.py@@ -66,7 +66,7 @@ class TraceEvent:def to_dict(self) -> Dict[str, Any]:"""Convert to dictionary for serialization."""- result = {+ result: Dict[str, Any] = {"event_type": self.event_type.value,"timestamp": round(self.timestamp, 4),"message": self.message,@@ -285,8 +285,10 @@ class MatchedContext:category: str = ""score: float = 0.0match_reason: str = ""-search_tags: List[str] = field(default_factory=list)+ # Recall-stage vector score and time factor, retained after model rerank.+ origin_score: Optional[float] = None+ time_score: Optional[float] = None@dataclass@@ -348,7 +350,7 @@ class FindResult:include_provenance: If True, include query_results with thinkingtrace and searched_directories for retrieval observability."""- result = {+ result: Dict[str, Any] = {"memories": [self._context_to_dict(m) for m in self.memories],"resources": [self._context_to_dict(r) for r in self.resources],"skills": [self._context_to_dict(s) for s in self.skills],@@ -373,7 +375,7 @@ class FindResult:``search_tags`` is surfaced under the ``tags`` key to match the``tags`` filter parameter accepted by find/search."""- return {+ result: Dict[str, Any] = {"context_type": ctx.context_type.value,"uri": ctx.uri,"level": ctx.level,@@ -381,12 +383,16 @@ class FindResult:"abstract": ctx.abstract,"tags": normalize_search_tags(ctx.search_tags, discard_invalid=True),}+ if ctx.origin_score is not None:+ result["origin_score"] = ctx.origin_score+ result["time_score"] = ctx.time_score+ return resultdef _query_to_dict(self, q: TypedQuery) -> Dict[str, Any]:"""Convert TypedQuery to dict."""return {"query": q.query,- "context_type": q.context_type.value,+ "context_type": q.context_type.value if q.context_type is not None else None,"intent": q.intent,"priority": q.priority,}@@ -402,6 +408,14 @@ class FindResult:"tier": f"L{ctx.level}","context_type": ctx.context_type.value,"score": ctx.score,+ **(+ {+ "origin_score": ctx.origin_score,+ "time_score": ctx.time_score,+ }+ if ctx.origin_score is not None+ else {}+ ),"match_reason": ctx.match_reason,}for ctx in qr.matched_contexts@@ -422,6 +436,8 @@ class FindResult:overview=d.get("overview"),category=d.get("category", ""),score=d.get("score", 0.0),+ origin_score=d.get("origin_score"),+ time_score=d.get("time_score"),match_reason=d.get("match_reason", ""),search_tags=list(d.get("tags") or d.get("search_tags") or []),)diff --git a/sdk/go/client_test.go b/sdk/go/client_test.goindex e033c2cf1..037347127 100644--- a/sdk/go/client_test.go+++ b/sdk/go/client_test.go@@ -130,6 +130,9 @@ func TestFindSendsHeadersQueryAndBody(t *testing.T) {if got := body["time_field"]; got != "created_at" {t.Fatalf("time_field = %#v", got)}+ if got := body["events_time_decay_protection"]; got != "2d" {+ t.Fatalf("events_time_decay_protection = %#v", got)+ }levels, ok := body["level"].([]any)if !ok || len(levels) != 2 || levels[0] != float64(0) || levels[1] != float64(2) {t.Fatalf("level = %#v", body["level"])@@ -147,14 +150,15 @@ func TestFindSendsHeadersQueryAndBody(t *testing.T) {defer closeServer()result, err := client.Find(context.Background(), "auth", &FindOptions{- TargetURI: "resources/docs",- Limit: 5,- ContextType: []string{"resource"},- Since: "2026-06-01",- Until: "2026-06-18",- TimeField: "created_at",- Level: []int{0, 2},- Tags: []string{"topic=docs", "kind=api"},+ TargetURI: "resources/docs",+ Limit: 5,+ ContextType: []string{"resource"},+ Since: "2026-06-01",+ Until: "2026-06-18",+ TimeField: "created_at",+ Level: []int{0, 2},+ Tags: []string{"topic=docs", "kind=api"},+ EventsTimeDecayProtection: "2d",})if err != nil {t.Fatal(err)@@ -726,6 +730,9 @@ func TestSearchContextSendsContextOptionsAndRejectsModeOverride(t *testing.T) {if body["max_tokens"] != float64(3000) || body["dedup_turns"] != float64(5) {t.Fatalf("budget fields = %#v", body)}+ if body["events_time_decay_protection"] != "2d" {+ t.Fatalf("events_time_decay_protection = %#v", body["events_time_decay_protection"])+ }writeOK(t, w, map[string]any{"rendered": "<memory />","entries": []any{},@@ -735,10 +742,11 @@ func TestSearchContextSendsContextOptionsAndRejectsModeOverride(t *testing.T) {defer closeServer()result, err := client.SearchContext(context.Background(), "continue refactor", &SearchContextOptions{- SessionID: "session-1",- Purpose: "coding",- MaxTokens: Int(3000),- DedupTurns: Int(5),+ SessionID: "session-1",+ Purpose: "coding",+ MaxTokens: Int(3000),+ DedupTurns: Int(5),+ EventsTimeDecayProtection: "2d",})if err != nil {t.Fatal(err)diff --git a/sdk/go/retrieval.go b/sdk/go/retrieval.goindex 62b7f38ca..d6ef3fe6e 100644--- a/sdk/go/retrieval.go+++ b/sdk/go/retrieval.go@@ -30,6 +30,7 @@ func (c *Client) Find(ctx context.Context, queryText string, opts *FindOptions)}payload["limit"] = limitsetString(payload, "image_url", imageURL)+ setString(payload, "events_time_decay_protection", opts.EventsTimeDecayProtection)setAny(payload, "score_threshold", opts.ScoreThreshold)setAny(payload, "filter", opts.Filter)setAny(payload, "context_type", opts.ContextType)@@ -76,6 +77,7 @@ func (c *Client) Search(ctx context.Context, queryText string, opts *SearchOptiopayload["limit"] = limitsetString(payload, "image_url", imageURL)setString(payload, "session_id", opts.SessionID)+ setString(payload, "events_time_decay_protection", opts.EventsTimeDecayProtection)setAny(payload, "score_threshold", opts.ScoreThreshold)setAny(payload, "filter", opts.Filter)setAny(payload, "context_type", opts.ContextType)@@ -126,6 +128,7 @@ func (c *Client) SearchContext(ctx context.Context, query string, opts *SearchCosetString(payload, "since", opts.Since)setString(payload, "until", opts.Until)setString(payload, "time_field", opts.TimeField)+ setString(payload, "events_time_decay_protection", opts.EventsTimeDecayProtection)setString(payload, "query_expansion", opts.QueryExpansion)setAny(payload, "max_tokens", opts.MaxTokens)if opts.Quotas != nil {diff --git a/sdk/go/types.go b/sdk/go/types.goindex 139e15217..4552c4cdd 100644--- a/sdk/go/types.go+++ b/sdk/go/types.go@@ -294,72 +294,75 @@ type ReindexOptions struct {// FindOptions controls Find.type FindOptions struct {- TargetURI any- Image string- Limit int- NodeLimit *int- ScoreThreshold *float64- Filter map[string]any- ContextType any- IncludeProvenance *bool- ReadContent *bool- Telemetry any- Since string- Until string- TimeField string- Level []int- Tags []string- Extra map[string]any+ EventsTimeDecayProtection string+ TargetURI any+ Image string+ Limit int+ NodeLimit *int+ ScoreThreshold *float64+ Filter map[string]any+ ContextType any+ IncludeProvenance *bool+ ReadContent *bool+ Telemetry any+ Since string+ Until string+ TimeField string+ Level []int+ Tags []string+ Extra map[string]any}// SearchOptions controls Search.type SearchOptions struct {- TargetURI any- Image string- SessionID string- Limit int- NodeLimit *int- ScoreThreshold *float64- Filter map[string]any- ContextType any- IncludeProvenance *bool- ReadContent *bool- Telemetry any- Since string- Until string- TimeField string- Level []int- Tags []string- Extra map[string]any+ EventsTimeDecayProtection string+ TargetURI any+ Image string+ SessionID string+ Limit int+ NodeLimit *int+ ScoreThreshold *float64+ Filter map[string]any+ ContextType any+ IncludeProvenance *bool+ ReadContent *bool+ Telemetry any+ Since string+ Until string+ TimeField string+ Level []int+ Tags []string+ Extra map[string]any}// SearchContextOptions controls server-side context assembly.type SearchContextOptions struct {- Image string- SessionID string- Limit *int- NodeLimit *int- ScoreThreshold *float64- Filter map[string]any- ContextType any- IncludeProvenance *bool- Tags []string- Since string- Until string- TimeField string- QueryExpansion string- MaxTokens *int- Quotas map[string]int- Purpose string- Detail any- DedupTurns *int- ExcludeURIs []string- PeerScope string- OtherPeerPenalty any- Rewrite any- RewriteMaxBullets *int- Telemetry any- Extra map[string]any+ Image string+ SessionID string+ Limit *int+ NodeLimit *int+ ScoreThreshold *float64+ Filter map[string]any+ ContextType any+ IncludeProvenance *bool+ Tags []string+ Since string+ Until string+ TimeField string+ EventsTimeDecayProtection string+ QueryExpansion string+ MaxTokens *int+ Quotas map[string]int+ Purpose string+ Detail any+ DedupTurns *int+ ExcludeURIs []string+ PeerScope string+ OtherPeerPenalty any+ Rewrite any+ RewriteMaxBullets *int+ Telemetry any+ Extra map[string]any}// GrepOptions controls Grep.@@ -546,6 +549,8 @@ type MatchedContext struct {Content string `json:"content,omitempty"`Overview string `json:"overview,omitempty"`Category string `json:"category,omitempty"`+ OriginScore *float64 `json:"origin_score,omitempty"`+ TimeScore *float64 `json:"time_score,omitempty"`Score float64 `json:"score,omitempty"`MatchReason string `json:"match_reason,omitempty"`Tags []string `json:"tags,omitempty"`diff --git a/sdk/python/openviking_sdk/options.py b/sdk/python/openviking_sdk/options.pyindex 2f3539938..3c0c12106 100644--- a/sdk/python/openviking_sdk/options.py+++ b/sdk/python/openviking_sdk/options.py@@ -30,6 +30,7 @@ class FindOptions(_ExtraOptions, total=False):level: Levelread_content: booltelemetry: Any+ events_time_decay_protection: Optional[str]class SearchOptions(FindOptions, total=False):@@ -47,6 +48,7 @@ class SearchContextOptions(_ExtraOptions, total=False):since: struntil: strtime_field: TimeField+ events_time_decay_protection: Optional[str]query_expansion: Literal["off", "auto"]max_tokens: intquotas: Dict[str, int]diff --git a/sdk/python/tests/test_async_client_behaviors.py b/sdk/python/tests/test_async_client_behaviors.pyindex e75ff48d8..791f99af2 100644--- a/sdk/python/tests/test_async_client_behaviors.py+++ b/sdk/python/tests/test_async_client_behaviors.py@@ -902,11 +902,14 @@ async def test_search_forwards_level_zero_and_omits_unset_time_filters():client._handle_response_data = lambda _response: {"result": {}}# level=0 is a valid level and must survive compaction (is-None check, not falsy).- await client.search("hello", session_id="s1", options={"level": 0})+ await client.search(+ "hello", session_id="s1", options={"level": 0, "events_time_decay_protection": "0"}+ )payload = client._request.await_args.kwargs["json"]assert payload["level"] == 0assert payload["session_id"] == "s1"+ assert payload["events_time_decay_protection"] == "0"for key in ("since", "until", "time_field"):assert key not in payloaddiff --git a/sdk/typescript/src/client.ts b/sdk/typescript/src/client.tsindex 503de970c..d114cde5d 100644--- a/sdk/typescript/src/client.ts+++ b/sdk/typescript/src/client.ts@@ -393,6 +393,7 @@ export class OpenVikingClient {image_url: imageUrl,session_id:kind === "search" ? (options as SearchOptions).sessionId : undefined,+ events_time_decay_protection: options.eventsTimeDecayProtection,limit: options.limit,node_limit: options.nodeLimit,score_threshold: options.scoreThreshold,@@ -434,6 +435,7 @@ export class OpenVikingClient {since: options.since,until: options.until,time_field: options.timeField,+ events_time_decay_protection: options.eventsTimeDecayProtection,query_expansion: options.queryExpansion,max_tokens: options.maxTokens,quotas: options.quotas,diff --git a/sdk/typescript/src/types.ts b/sdk/typescript/src/types.tsindex 0f0e092db..3d65b8162 100644--- a/sdk/typescript/src/types.ts+++ b/sdk/typescript/src/types.ts@@ -163,6 +163,7 @@ export interface FindOptions {tags?: string[];includeProvenance?: boolean;readContent?: boolean;+ eventsTimeDecayProtection?: string | null;extra?: JsonObject;}/** Session-aware semantic retrieval options. */@@ -183,6 +184,7 @@ export interface SearchContextOptions {since?: string;until?: string;timeField?: string;+ eventsTimeDecayProtection?: string | null;queryExpansion?: "off" | "auto";maxTokens?: number;quotas?: Record<string, number>;@@ -370,6 +372,8 @@ export interface MatchedContext {level?: number;abstract?: string;score?: number;+ origin_score?: number | null;+ time_score?: number | null;tags?: string[];[key: string]: unknown;}diff --git a/sdk/typescript/tests/client.test.ts b/sdk/typescript/tests/client.test.tsindex 29d8f16aa..b4ef2abeb 100644--- a/sdk/typescript/tests/client.test.ts+++ b/sdk/typescript/tests/client.test.ts@@ -48,7 +48,11 @@ describe("OpenVikingClient", () => {actorPeerId: "peer",fetch: fetcher,});- await client.find("hello", { targetUri: "viking://resources", limit: 5 });+ await client.find("hello", {+ targetUri: "viking://resources",+ limit: 5,+ eventsTimeDecayProtection: "2d",+ });const [url, init] = fetcher.mock.calls[0]!;expect(String(url)).toBe("https://example.com/api/v1/search/find");expect(new Headers(init?.headers).get("X-OpenViking-Actor-Peer")).toBe(@@ -58,6 +62,7 @@ describe("OpenVikingClient", () => {query: "hello",target_uri: "viking://resources",limit: 5,+ events_time_decay_protection: "2d",});});@@ -107,6 +112,7 @@ describe("OpenVikingClient", () => {purpose: "coding",maxTokens: 3000,dedupTurns: 5,+ eventsTimeDecayProtection: "2d",}),).resolves.toMatchObject({ rendered: "<memory />" });@@ -117,6 +123,7 @@ describe("OpenVikingClient", () => {purpose: "coding",max_tokens: 3000,dedup_turns: 5,+ events_time_decay_protection: "2d",});await expect(client.searchContext("query", { extra: { mode: "list" } }),diff --git a/src/abi3_engine_backend.cpp b/src/abi3_engine_backend.cppindex 7ed708ad2..32d0885c2 100644--- a/src/abi3_engine_backend.cpp+++ b/src/abi3_engine_backend.cpp@@ -799,6 +799,14 @@ bool parse_search_request(PyObject* obj, vdb::SearchRequest* request) {}Py_XDECREF(value);+ if (!get_named_value(obj, "time_decay", &value, &found)) {+ return false;+ }+ if (found && !py_to_string(value, &request->time_decay, false)) {+ Py_DECREF(value);+ return false;+ }+ Py_XDECREF(value);return true;}diff --git a/src/index/common_structs.h b/src/index/common_structs.hindex c32578456..449fa0989 100644--- a/src/index/common_structs.h+++ b/src/index/common_structs.h@@ -29,6 +29,7 @@ struct SearchRequest {std::vector<float> sparse_values;uint32_t topk = 0;std::string dsl;+ std::string time_decay;};struct SearchResult {diff --git a/src/index/detail/index_manager_impl.cpp b/src/index/detail/index_manager_impl.cppindex 001e94464..36d05a8b5 100644--- a/src/index/detail/index_manager_impl.cpp+++ b/src/index/detail/index_manager_impl.cpp@@ -2,6 +2,8 @@// SPDX-License-Identifier: AGPL-3.0#include "index/detail/index_manager_impl.h"#include <algorithm>+#include <cmath>+#include <numeric>#include <stdexcept>#include <memory>#include <chrono>@@ -507,9 +509,32 @@ int IndexManagerImpl::perform_vector_recall(const SearchRequest& req,SearchContext& ctx,const BitmapPtr& bitmap,SearchResult& result) {+ JsonDoc decay;+ const bool apply_decay = !req.time_decay.empty();+ if (apply_decay) {+ decay.Parse(req.time_decay.c_str());+ if (decay.HasParseError() || !decay.IsObject() ||+ !decay.HasMember("field") || !decay["field"].IsString()) {+ throw std::invalid_argument("invalid time-decay field");+ }+ for (const auto* key : {"origin_ms", "offset_ms", "scale_ms", "decay"}) {+ if (!decay.HasMember(key) || !decay[key].IsNumber() ||+ !std::isfinite(decay[key].GetDouble())) {+ throw std::invalid_argument("invalid time-decay numeric parameter");+ }+ }+ if (decay["offset_ms"].GetDouble() < 0 ||+ decay["scale_ms"].GetDouble() <= 0 ||+ decay["decay"].GetDouble() <= 0 || decay["decay"].GetDouble() >= 1 ||+ req.topk > 100000) {+ throw std::invalid_argument("invalid time-decay range or topk");+ }+ }+ // The native recall owns candidate amplification; callers receive only topk.+ const uint32_t recall_topk = apply_decay ? std::min(req.topk * 3u, 100000u) : req.topk;VectorRecallRequest recall_request{.dense_vector = req.query.data(),- .topk = req.topk,+ .topk = recall_topk,.bitmap = bitmap.get(),.sparse_terms =req.sparse_raw_terms.empty() ? nullptr : &req.sparse_raw_terms,@@ -523,8 +548,46 @@ int IndexManagerImpl::perform_vector_recall(const SearchRequest& req,return ret;}- std::swap(result.labels, recall_result.labels);- std::swap(result.scores, recall_result.scores);+ if (!apply_decay) {+ std::swap(result.labels, recall_result.labels);+ std::swap(result.scores, recall_result.scores);+ return 0;+ }+ const auto time_values = scalar_index_->get_field_sets()->get_rangedmap_ptr(+ decay["field"].GetString());+ const double origin = decay["origin_ms"].GetDouble();+ const double protection = decay["offset_ms"].GetDouble();+ const double rate = std::log(decay["decay"].GetDouble()) / decay["scale_ms"].GetDouble();+ std::vector<float> fused = recall_result.scores;+ std::vector<double> time_scores(fused.size(), std::numeric_limits<double>::quiet_NaN());+ for (size_t i = 0; i < fused.size(); ++i) {+ const int offset = vector_index_->get_offset_by_label(recall_result.labels[i]);+ if (!time_values || offset < 0 || static_cast<uint32_t>(offset) >= time_values->size()) continue;+ const double updated = time_values->get_score_by_offset(offset);+ if (!std::isfinite(updated)) continue;+ time_scores[i] = std::exp(rate * std::max(0.0, std::abs(origin - updated) - protection));+ fused[i] *= time_scores[i];+ }+ std::vector<size_t> order(fused.size());+ std::iota(order.begin(), order.end(), 0);+ std::stable_sort(order.begin(), order.end(), [&](size_t a, size_t b) {+ return fused[a] > fused[b];+ });+ order.resize(std::min(order.size(), static_cast<size_t>(req.topk)));+ JsonDoc details;+ details.SetObject();+ auto& allocator = details.GetAllocator();+ for (const size_t i : order) {+ result.labels.push_back(recall_result.labels[i]);+ result.scores.push_back(fused[i]);+ rapidjson::Value detail(rapidjson::kObjectType);+ detail.AddMember("origin_score", recall_result.scores[i], allocator);+ if (std::isfinite(time_scores[i])) detail.AddMember("addition_score", time_scores[i], allocator);+ const auto label = std::to_string(recall_result.labels[i]);+ rapidjson::Value key(label.c_str(), allocator);+ details.AddMember(key, detail, allocator);+ }+ result.extra_json = json_stringify(details);return 0;}diff --git a/tests/client/test_http_client_compact.py b/tests/client/test_http_client_compact.pyindex f0d41d3c6..9b449a47d 100644--- a/tests/client/test_http_client_compact.py+++ b/tests/client/test_http_client_compact.py@@ -89,7 +89,14 @@ async def test_search_omits_unset_optional_fields():payload = fake.calls[-1]["json"]assert payload["query"] == "hello"- for dropped in ("session_id", "score_threshold", "filter", "context_type", "tags"):+ for dropped in (+ "session_id",+ "score_threshold",+ "filter",+ "context_type",+ "tags",+ "events_time_decay_protection",+ ):assert dropped not in payloaddiff --git a/tests/misc/test_vikingfs_find_without_rerank.py b/tests/misc/test_vikingfs_find_without_rerank.pyindex 2349098fb..711b4d484 100644--- a/tests/misc/test_vikingfs_find_without_rerank.py+++ b/tests/misc/test_vikingfs_find_without_rerank.py@@ -55,6 +55,8 @@ async def test_find_works_without_rerank_config(monkeypatch) -> None:score_threshold,scope_dsl,level,+ events_time_decay_protection=None,+ request_now=None,):captured["typed_query"] = typed_querycaptured["ctx"] = ctx@@ -124,6 +126,8 @@ async def test_find_accepts_image_url_without_text_query(monkeypatch) -> None:score_threshold,scope_dsl,level,+ events_time_decay_protection=None,+ request_now=None,):captured["typed_query"] = typed_querycaptured["mode"] = modediff --git a/tests/retrieve/test_context_assembler_pipeline.py b/tests/retrieve/test_context_assembler_pipeline.pyindex 5f7ac0262..9aeaf1e87 100644--- a/tests/retrieve/test_context_assembler_pipeline.py+++ b/tests/retrieve/test_context_assembler_pipeline.py@@ -178,6 +178,7 @@ async def test_query_expansion_fans_out_planned_queries(monkeypatch):async def fake_find(**kwargs):queries_seen.append(kwargs["query"])+ assert kwargs["events_time_decay_protection"] == "2d"return _FakeFindResult()async def fake_get(session_id, ctx, *, auto_create=False):@@ -200,6 +201,7 @@ async def test_query_expansion_fans_out_planned_queries(monkeypatch):ctx=_ctx(),params=AssembleParams(query="short",+ events_time_decay_protection="2d",session_id="s1",query_expansion="auto",peer_scope="actor",diff --git a/tests/retrieve/test_hierarchical_retriever_rerank.py b/tests/retrieve/test_hierarchical_retriever_rerank.pyindex c09f02569..561bc9028 100644--- a/tests/retrieve/test_hierarchical_retriever_rerank.py+++ b/tests/retrieve/test_hierarchical_retriever_rerank.py@@ -119,7 +119,13 @@ async def test_retrieve_reranks_global_candidates_once(monkeypatch, mode):_result("viking://resources/root", 0.95, level=0, abstract="root abstract"),_result("viking://resources/dir", 0.85, level=1, abstract="dir overview"),_result("viking://resources/file-c", 0.2, abstract="file C"),- _result("viking://resources/file-d", 0.05, abstract="file D"),+ _result(+ "viking://resources/file-d",+ 0.05,+ abstract="file D",+ _origin_score=0.5,+ _time_score=0.1,+ ),_result("viking://resources/outside-pool", 0.01, abstract="outside pool"),])@@ -128,13 +134,24 @@ async def test_retrieve_reranks_global_candidates_once(monkeypatch, mode):query.target_directories = ["viking://resources"]scope = {"op": "must", "field": "category", "conds": ["doc"]}- result = await retriever.retrieve(query, ctx=_ctx(), limit=2, mode=mode, scope_dsl=scope)+ result = await retriever.retrieve(+ query,+ ctx=_ctx(),+ limit=2,+ mode=mode,+ scope_dsl=scope,+ score_threshold=0.9,+ events_time_decay_protection="0",+ )assert [ctx.uri for ctx in result.matched_contexts] == ["viking://resources/file-d","viking://resources/file-c",]assert [ctx.score for ctx in result.matched_contexts] == [0.99, 0.95]+ # Thresholding and final ranking use model scores, without repeating recall decay.+ assert result.matched_contexts[0].origin_score == 0.5+ assert result.matched_contexts[0].time_score == 0.1assert fake_client.calls == [("hello", ["root abstract", "dir overview", "file C", "file D"])]assert len(storage.search_calls) == 1assert storage.search_calls[0]["limit"] == 4@@ -242,20 +259,30 @@ async def test_retrieve_falls_back_to_vector_scores_when_rerank_fails(monkeypatc)storage = DummyStorage([- _result("viking://resources/a/deep-a.md", 0.2, abstract="deep A"),+ _result(+ "viking://resources/a/deep-a.md",+ 0.2,+ abstract="deep A",+ _origin_score=0.8,+ _time_score=0.25,+ ),_result("viking://resources/b/deep-b.md", 0.8, abstract="deep B"),_result("viking://resources/b/deep-c.md", 0.05, abstract="deep C"),])retriever = HierarchicalRetriever(storage, DummyEmbedder(), rerank_config=_config())- result = await retriever.retrieve(_query(), ctx=_ctx(), limit=2)+ result = await retriever.retrieve(+ _query(), ctx=_ctx(), limit=2, events_time_decay_protection="0"+ )assert [ctx.uri for ctx in result.matched_contexts] == ["viking://resources/b/deep-b.md","viking://resources/a/deep-a.md",]assert [ctx.score for ctx in result.matched_contexts] == [0.8, 0.2]+ assert result.matched_contexts[1].origin_score == 0.8+ assert result.matched_contexts[1].time_score == 0.25assert len(storage.search_calls) == 1assert storage.search_calls[0]["limit"] == 4assert fake_client.calls == [("hello", ["deep B", "deep A", "deep C"])]@@ -372,7 +399,13 @@ async def test_retrieve_without_rerank_filters_by_vector_score():storage = DummyStorage([_result("viking://resources/high", 0.91, abstract="high"),- _result("viking://resources/exact", 0.9, abstract="exact"),+ _result(+ "viking://resources/exact",+ 0.9,+ abstract="exact",+ _origin_score=1.0,+ _time_score=0.9,+ ),])retriever = HierarchicalRetriever(@@ -386,6 +419,7 @@ async def test_retrieve_without_rerank_filters_by_vector_score():ctx=_ctx(),limit=2,score_threshold=0.9,+ events_time_decay_protection="0",)inclusive_result = await retriever.retrieve(_query(),@@ -393,6 +427,7 @@ async def test_retrieve_without_rerank_filters_by_vector_score():limit=2,score_threshold=0.9,score_gte=True,+ events_time_decay_protection="0",)assert [ctx.uri for ctx in strict_result.matched_contexts] == ["viking://resources/high"]diff --git a/tests/server/test_mcp_endpoint.py b/tests/server/test_mcp_endpoint.pyindex 3c810aa52..05696567d 100644--- a/tests/server/test_mcp_endpoint.py+++ b/tests/server/test_mcp_endpoint.py@@ -722,6 +722,7 @@ async def test_search_context_mode_returns_assembled_context(service, monkeypatcresult = await search(query="what happened",mode="context",+ events_time_decay_protection="2d",quotas={"events": 1, "entities": 0},purpose="coding",min_score=0.1,@@ -743,6 +744,7 @@ async def test_search_context_mode_returns_assembled_context(service, monkeypatcassert params.quotas == {"events": 1, "entities": 0}assert params.purpose == "coding"assert params.score_threshold == 0.1+ assert params.events_time_decay_protection == "2d"assert params.max_tokens == 800assert params.detail == {"events": "overview"}assert params.dedup_turns == 5diff --git a/tests/server/test_mcp_search_bounds.py b/tests/server/test_mcp_search_bounds.pyindex 0379bded4..2b16bcaee 100644--- a/tests/server/test_mcp_search_bounds.py+++ b/tests/server/test_mcp_search_bounds.py@@ -21,7 +21,7 @@ from pydantic import ValidationErrorimport openviking.server.mcp_endpoint as mcp_endpointfrom openviking.retrieve.context_assembler import MAX_EXCLUDE_URIS-from openviking.server.routers.search import SearchRequest+from openviking.server.routers.search import FindRequest, SearchRequest# name -> (REST field bound as it appears in the JSON schema, out-of-range value)BOUNDED = {@@ -75,7 +75,7 @@ async def test_call_tool_rejects_more_exclusions_than_it_can_apply():assert "exclude_uris" in str(excinfo.value)-def test_rest_rejects_the_same_values():+async def test_rest_and_mcp_reject_invalid_search_requests():# The point of this file is parity, so pin the side being matched too: if a bound is# relaxed over REST, this fails next to the tool test that would then be wrong.for name, (_, value) in BOUNDED.items():@@ -88,3 +88,14 @@ def test_rest_rejects_the_same_values():mode="context",exclude_uris=[f"viking://user/u/m{i}.md" for i in range(MAX_EXCLUDE_URIS + 1)],)++ with pytest.raises(ValidationError, match="events_time_decay_protection"):+ SearchRequest(query="q", events_time_decay_protection="-1d")+ with pytest.raises(Exception, match="events_time_decay_protection"):+ await mcp_endpoint.mcp.call_tool(+ "search", {"query": "q", "events_time_decay_protection": "-1d"}+ )+ with pytest.raises(ValidationError, match="semantic query or image"):+ FindRequest(+ filter={"op": "must", "field": "level", "conds": [2]}, events_time_decay_protection="0"+ )diff --git a/tests/session/memory/test_memory_updater.py b/tests/session/memory/test_memory_updater.pyindex 2138ff121..2e543de16 100644--- a/tests/session/memory/test_memory_updater.py+++ b/tests/session/memory/test_memory_updater.py@@ -546,6 +546,10 @@ class TestMemoryUpdater:assert set(operation.uris) == {alice_uri, bob_uri}assert set(result.written_uris) == {alice_uri, bob_uri}+ assert updater._vectorize_memories.await_args.kwargs["search_tags_by_uri"] == {+ alice_uri: ["memory_type=entities"],+ bob_uri: ["memory_type=entities"],+ }isolation_handler.calculate_memory_uris.assert_not_called()@pytest.mark.asynciodiff --git a/tests/storage/test_collection_schemas.py b/tests/storage/test_collection_schemas.pyindex 19c8f8f35..78ef455fb 100644--- a/tests/storage/test_collection_schemas.py+++ b/tests/storage/test_collection_schemas.py@@ -524,7 +524,14 @@ async def test_embedding_handler_merge_action_reads_and_merges_before_full_upserasync def get_strict(self, ids, *, ctx):captured["read"] = (list(ids), ctx.account_id)- return [{"id": ids[0], "search_tags": ["env=old"], "created_at": "old"}]+ return [+ {+ "id": ids[0],+ "context_type": "memory",+ "search_tags": ["env=old", "memory_type=preferences"],+ "created_at": "old",+ }+ ]async def upsert(self, data, *, ctx, options=UpsertOptions()):captured["data"] = dict(data)@@ -538,8 +545,10 @@ async def test_embedding_handler_merge_action_reads_and_merges_before_full_upsercontext_data={"id": "generated-id","_upsert_record_id": "generated-id",- "uri": "viking://resources/repo/a.py",+ "_upsert_options": {"extracted_memory_type": "events"},+ "uri": "viking://user/alice/peers/memories/memories/events/event.md","account_id": "acct",+ "context_type": "memory","abstract": "summary",},update_fields={"search_tags": ["scope=new"]},@@ -550,7 +559,7 @@ async def test_embedding_handler_merge_action_reads_and_merges_before_full_upserassert result.outcome is ProcessOutcome.SUCCESSassert captured["read"] == (["generated-id"], "acct")- assert captured["data"]["search_tags"] == ["env=old", "scope=new"]+ assert set(captured["data"]["search_tags"]) == {"env=old", "memory_type=events", "scope=new"}assert captured["data"]["created_at"] == "old"assert captured["options"].partial_update is Falsediff --git a/tests/storage/test_embedding_msg.py b/tests/storage/test_embedding_msg.pyindex bb5a1865f..d5d3a0537 100644--- a/tests/storage/test_embedding_msg.py+++ b/tests/storage/test_embedding_msg.py@@ -138,7 +138,7 @@ def test_embedding_update_fields_rejects_vector_fields():def test_field_patch_roundtrip_and_resolution():patch = FieldPatch(- values={"search_tags": ["scope=new"], "md5": "new-md5"},+ values={"search_tags": ["scope=new", "memory_type=preferences"], "md5": "new-md5"},modes={"search_tags": "append"},seed_fields={"uri": "viking://resources/demo/a.py",@@ -150,11 +150,21 @@ def test_field_patch_roundtrip_and_resolution():restored = FieldPatch.from_dict(patch.to_dict())- assert restored.resolve({"search_tags": ["env=old"], "md5": "old-md5"}) == {- "search_tags": ["env=old", "scope=new"],+ existing = {+ "context_type": "memory",+ "search_tags": ["env=old", "memory_type=events"],+ "md5": "old-md5",+ }+ assert restored.resolve(existing) == {+ "search_tags": ["memory_type=events", "env=old", "scope=new"],"md5": "new-md5",}assert restored.seed_fields["vector"] == [0.1, 0.2]+ # Ordinary replacement can clear user tags, but cannot create or overwrite a type.+ restored.modes["search_tags"] = "replace"+ restored.values["search_tags"] = ["memory_type=preferences"]+ assert restored.resolve(existing)["search_tags"] == ["memory_type=events"]+ assert restored.resolve({"context_type": "memory", "search_tags": []})["search_tags"] == []@pytest.mark.parametrize(diff --git a/tests/storage/test_viking_vector_scope_filter.py b/tests/storage/test_viking_vector_scope_filter.pyindex 6d08ee2da..aa551e4f5 100644--- a/tests/storage/test_viking_vector_scope_filter.py+++ b/tests/storage/test_viking_vector_scope_filter.py@@ -2,6 +2,7 @@# SPDX-License-Identifier: Apache-2.0import threading+from datetime import datetime, timezonefrom types import SimpleNamespacefrom unittest.mock import AsyncMock@@ -191,12 +192,14 @@ async def test_tenant_search_enforces_visible_roots_and_shared_acl("uri": own_uri,"account_id": "acct","context_type": "resource",+ "search_tags": ["memory_type=events"],},{"id": "cross-user","uri": cross_user_uri,"account_id": "acct","context_type": "resource",+ "search_tags": ["memory_type=events"],},{**legacy_mode,@@ -218,6 +221,7 @@ async def test_tenant_search_enforces_visible_roots_and_shared_acl("account_id": "acct","context_type": "resource","acl_mode": "inherit",+ "search_tags": ["memory_type=events"],"acl_direct_grants": ["1:user:alice"],},{@@ -242,6 +246,7 @@ async def test_tenant_search_enforces_visible_roots_and_shared_acl("account_id": "acct","context_type": "resource","acl_mode": "restricted",+ "search_tags": ["memory_type=events"],"acl_direct_grants": ["1:user:alice"],"acl_inherited_grants": ["7:user:bob"],},@@ -251,6 +256,7 @@ async def test_tenant_search_enforces_visible_roots_and_shared_acl("account_id": "acct","context_type": "resource","acl_mode": "inherit",+ "search_tags": ["memory_type=events"],"acl_direct_grants": [],"acl_inherited_grants": ["3:group:finance"],},@@ -281,18 +287,32 @@ async def test_tenant_search_enforces_visible_roots_and_shared_acl(user=UserIdentifier(record["account_id"], ctx.user.user_id), role=Role.ADMIN)await backend._upsert_many_raw(- [{**record, "level": 2, "vector": [1.0, 0.0, 0.0, 0.0]}], ctx=record_ctx+ [+ {+ **record,+ "level": 2,+ "updated_at": "2026-01-01T00:00:00Z",+ "vector": [1.0, 0.0, 0.0, 0.0],+ }+ ],+ ctx=record_ctx,)+ decay = {+ "events_time_decay_protection": "0",+ "request_now": datetime(2026, 1, 8, tzinfo=timezone.utc),+ }visible = await backend.search_in_tenant(ctx=ctx,query_vector=[1.0, 0.0, 0.0, 0.0],context_type="resource",+ **decay,)cross_user_only = await backend.search_in_tenant(ctx=ctx,query_vector=[1.0, 0.0, 0.0, 0.0],context_type="resource",+ **decay,target_directories=[cross_user_uri],)internal = await backend.search_in_tenant(@@ -303,11 +323,13 @@ async def test_tenant_search_enforces_visible_roots_and_shared_acl(),query_vector=[1.0, 0.0, 0.0, 0.0],context_type="resource",+ **decay,)finance = await backend.search_in_tenant(ctx=RequestContext(user=ctx.user, role=ctx.role, group_ids=("finance",)),query_vector=[1.0, 0.0, 0.0, 0.0],context_type="resource",+ **decay,target_directories=["viking://resources/finance"],)assert [record["id"] for record in finance] == ["denied-shared"]@@ -322,6 +344,11 @@ async def test_tenant_search_enforces_visible_roots_and_shared_acl("restricted-direct-shared",])+ by_id = {record["id"]: record for record in visible}+ assert by_id["own"]["_score"] == pytest.approx(0.5)+ assert by_id["own"]["_origin_score"] == pytest.approx(1.0)+ assert by_id["legacy-shared"]["_score"] == pytest.approx(1.0)+ assert "_time_score" not in by_id["legacy-shared"]assert cross_user_only == []assert sorted(record["id"] for record in internal) == sorted([@@ -342,6 +369,7 @@ async def test_tenant_search_enforces_visible_roots_and_shared_acl(ctx=ctx,query_vector=[1.0, 0.0, 0.0, 0.0],context_type="resource",+ **decay,)assert sorted(record["id"] for record in shared) == sorted([@@ -393,20 +421,57 @@ def test_no_target_keeps_original_tenant_filter():)-def test_merge_filters_wraps_raw_dict_filter():+async def test_tenant_search_preserves_raw_scope_across_decay_routes():backend = object.__new__(VikingVectorIndexBackend)-- result = backend._merge_filters(- {"op": "must", "field": "uri", "conds": ["viking://resources"]},- Eq("account_id", "acct"),- )-- assert result == And(+ backend.acl_manager = None+ backend.search = AsyncMock(return_value=[])+ ctx = _ctx()+ raw_filter = {"op": "must", "field": "search_tags", "conds": ["team=search"]}+ options = {+ "ctx": ctx,+ "query_vector": [1.0],+ "context_type": "resource",+ "level": [0, 1],+ "target_directories": ["viking://resources/wiki"],+ "extra_filter": raw_filter,+ "limit": 1,+ "offset": 1,+ }+ scope = And([- RawDSL({"op": "must", "field": "uri", "conds": ["viking://resources"]}),+ Eq("context_type", "resource"),Eq("account_id", "acct"),+ Or([PathScope("uri", "viking://resources/wiki", depth=-1)]),+ RawDSL(raw_filter),+ In("level", [0, 1]),])+ await backend.search_in_tenant(**options)+ call = backend.search.await_args.kwargs+ assert backend.search.await_count == 1+ assert call["filter"] == scope+ assert (call["limit"], call["offset"]) == (1, 1)+ assert "advance" not in call++ backend.search.reset_mock()+ event = {"id": "event", "_score": 0.4, "_origin_score": 0.8, "_time_score": 0.5}++ async def recall(**kwargs):+ return [event] if kwargs.get("advance") else [{"id": "ordinary", "_score": 0.7}]++ backend.search.side_effect = recall+ result = await backend.search_in_tenant(**options, events_time_decay_protection="0")+ calls = [call.kwargs for call in backend.search.await_args_list]+ assert len(calls) == 2+ other = next(call for call in calls if "advance" not in call)+ events = next(call for call in calls if "advance" in call)+ assert other["filter"] == And(+ [scope, RawDSL({"op": "must_not", "field": "search_tags", "conds": ["memory_type=events"]})]+ )+ assert events["filter"] == And([scope, Eq("search_tags", "memory_type=events")])+ assert (other["limit"], events["limit"], other["offset"], events["offset"]) == (2, 2, 0, 0)+ assert result == [event]def test_root_role_keeps_existing_target_only_behavior():diff --git a/tests/storage/test_volcengine_clients.py b/tests/storage/test_volcengine_clients.pyindex 39d2f7b39..c67446115 100644--- a/tests/storage/test_volcengine_clients.py+++ b/tests/storage/test_volcengine_clients.py@@ -2,6 +2,7 @@ import pytestimport requestsfrom volcengine.base.Request import Request+from openviking.storage.vectordb.collection.collection import Collectionfrom openviking.storage.vectordb.collection.volcengine_clients import (ClientForConsoleApi,ClientForDataApi,@@ -339,7 +340,7 @@ def test_volcengine_collection_update_data_sanitizes_uri_fields(monkeypatch):}-def test_volcengine_collection_uses_date_time_filter_operator(monkeypatch):+def test_volcengine_query_preserves_time_filters_and_applies_decay(monkeypatch):captured = {}class _Response:@@ -347,7 +348,13 @@ def test_volcengine_collection_uses_date_time_filter_operator(monkeypatch):@staticmethoddef json():- return {"result": {"agg": {"_total": 1}}}+ return {+ "result": {+ "data": [+ {"id": "event", "score": 0.4, "origin_score": 0.8, "addition_score": 0.5}+ ]+ }+ }collection = VolcengineCollection(ak="test-ak",@@ -363,11 +370,22 @@ def test_volcengine_collection_uses_date_time_filter_operator(monkeypatch):monkeypatch.setattr(collection.data_client, "do_req", _fake_do_req)+ adapter = VolcengineCollectionAdapter.from_config(+ VectorDBBackendConfig(+ backend="volcengine",+ name="context",+ volcengine=VolcengineConfig(ak="test-ak", sk="test-sk", region="cn-beijing"),+ )+ )+ adapter._collection = Collection(collection)# Both date_time fields (created_at, updated_at) must be normalized to# time_range, while numeric range nodes are left untouched.- collection.aggregate_data(- index_name="default",- filters={+ result = adapter.query(+ query_vector=[1.0],+ limit=10,+ offset=2,+ advance={"time_decay": {"protection": "0", "origin": "2026-08-17T00:00:00Z"}},+ filter={"op": "and","conds": [{@@ -386,7 +404,32 @@ def test_volcengine_collection_uses_date_time_filter_operator(monkeypatch):},)- assert captured["path"] == "/api/vikingdb/data/agg"+ assert captured["path"] == "/api/vikingdb/data/search/vector"+ assert result == [{"id": "event", "_score": 0.4, "_origin_score": 0.8, "_time_score": 0.5}]+ body = captured["req_body"]+ assert (body["limit"], body["offset"]) == (10, 2)+ assert body["return_detail_info"] is True+ assert body["advance"] == {+ "post_process_ops": [+ {+ "op": "score_fusion",+ "fusion_by": "multiply",+ "normalize_for_origin_score": {"enable": False},+ "normalize_for_addition_score": {"enable": False},+ "addition_score": [+ {+ "factor": 1,+ "base_value_from": "decay_func",+ "field": "updated_at",+ "func": "exp",+ "origin": "2026-08-17T00:00:00.000Z",+ "scale": "7d",+ "decay": 0.5,+ }+ ],+ }+ ]+ }assert captured["req_body"]["filter"] == {"op": "and","conds": [diff --git a/tests/unit/session/memory/test_embedding_template.py b/tests/unit/session/memory/test_embedding_template.pyindex 881e5f9a6..5009cf863 100644--- a/tests/unit/session/memory/test_embedding_template.py+++ b/tests/unit/session/memory/test_embedding_template.py@@ -151,9 +151,7 @@ class TestEmbeddingTextConstruction:embedding_msg = updater._vikingdb.enqueue_embedding_msg.await_args.args[0]assert embedding_msg.context_data["search_tags"] == tags- assert embedding_msg.context_data["_upsert_options"] == {- "search_tag_mode": expected_mode- }+ assert embedding_msg.context_data["_upsert_options"] == {"search_tag_mode": expected_mode}@pytest.mark.asyncioasync def test_trajectory_vectorization_adds_source_experience_search_tags(self):@@ -200,60 +198,32 @@ class TestEmbeddingTextConstruction:embedding_msg = updater._vikingdb.enqueue_embedding_msg.await_args.args[0]assert embedding_msg.context_data["search_tags"] == [experience_source_tag(experience_uri)]- assert embedding_msg.context_data["_upsert_options"] == {"search_tag_mode": "append"}+ assert embedding_msg.context_data["_upsert_options"] == {+ "search_tag_mode": "append",+ "extracted_memory_type": "trajectories",+ }@pytest.mark.asyncio- async def test_logs_final_embedding_text_before_vectorization(self):- registry = MemoryTypeRegistry(load_schemas=False)- registry._types["entities"] = registry._parse_memory_type(- {- "memory_type": "entities",- "directory": "viking://user/{{ user_space }}/memories/entities",- "filename_template": "{{ name }}.md",- "embedding_template": "{{ category }} -> {{ name }} -> {{ content }}",- "fields": [- {"name": "category", "type": "string"},- {"name": "name", "type": "string"},- {"name": "content", "type": "string"},- ],- }- )-- updater = MemoryUpdater(registry=registry, vikingdb=Mock())- updater._viking_fs = Mock()- updater._viking_fs.read_file = AsyncMock(- return_value=MemoryFileUtils.write(- MemoryFile(- uri="viking://user/alice/memories/entities/person/alice.md",- memory_type="entities",- content="Plain body",- extra_fields={"category": "person", "name": "alice"},- )- )- )- updater._vikingdb.enqueue_embedding_msg = AsyncMock(return_value=True)-- result = MemoryUpdateResult()- result.add_written("viking://user/alice/memories/entities/person/alice.md")- ctx = SimpleNamespace(user=None, account_id="default")-- with (- patch.object(EmbeddingMsgConverter, "from_context") as mock_from_context,- patch("openviking.session.memory.memory_updater.logger.error") as mock_logger_error,+ async def test_direct_refresh_does_not_infer_the_memory_type_from_a_peer_path(self):+ uri = "viking://user/alice/peers/memories/memories/events/event.md"+ viking_fs = Mock(read_file=AsyncMock(return_value="# Event body"))+ vikingdb = Mock(has_queue_manager=True)+ vikingdb.enqueue_embedding_msg = AsyncMock(return_value=True)+ with patch(+ "openviking.session.memory.memory_type_registry.get_default_registry",+ return_value=MemoryTypeRegistry(load_schemas=False),):- mock_from_context.side_effect = lambda context: SimpleNamespace(- telemetry_id=None, id="msg-1", message=context.get_vectorization_text()- )- await updater._vectorize_memories(- result,- ctx,- extract_context=None,- uri_memory_type_map={- "viking://user/alice/memories/entities/person/alice.md": "entities"- },+ refreshed = await MemoryUpdater.refresh_file_embedding(+ viking_fs=viking_fs,+ vikingdb=vikingdb,+ uri=uri,+ memory_type="memories",+ ctx=SimpleNamespace(user=None, account_id="default"),)-- mock_logger_error.assert_not_called()+ assert refreshed+ message = vikingdb.enqueue_embedding_msg.await_args.args[0]+ assert "search_tags" not in message.context_data+ assert "_upsert_options" not in message.context_data@pytest.mark.asyncioasync def test_embedding_template_overrides_plain_content(self):@@ -292,7 +262,10 @@ class TestEmbeddingTextConstruction:with patch.object(EmbeddingMsgConverter, "from_context") as mock_from_context:mock_from_context.side_effect = lambda context: SimpleNamespace(- telemetry_id=None, id="msg-1", message=context.get_vectorization_text()+ telemetry_id=None,+ id="msg-1",+ message=context.get_vectorization_text(),+ context_data={},)await updater._vectorize_memories(result,@@ -341,7 +314,10 @@ class TestEmbeddingTextConstruction:with patch.object(EmbeddingMsgConverter, "from_context") as mock_from_context:mock_from_context.side_effect = lambda context: SimpleNamespace(- telemetry_id=None, id="msg-1", message=context.get_vectorization_text()+ telemetry_id=None,+ id="msg-1",+ message=context.get_vectorization_text(),+ context_data={},)await updater._vectorize_memories(result,@@ -391,7 +367,10 @@ class TestEmbeddingTextConstruction:with patch.object(EmbeddingMsgConverter, "from_context") as mock_from_context:mock_from_context.side_effect = lambda context: SimpleNamespace(- telemetry_id=None, id="msg-1", message=context.get_vectorization_text()+ telemetry_id=None,+ id="msg-1",+ message=context.get_vectorization_text(),+ context_data={},)await updater._vectorize_memories(result,@@ -440,7 +419,10 @@ class TestEmbeddingTextConstruction:with patch.object(EmbeddingMsgConverter, "from_context") as mock_from_context:mock_from_context.side_effect = lambda context: SimpleNamespace(- telemetry_id=None, id="msg-1", message=context.get_vectorization_text()+ telemetry_id=None,+ id="msg-1",+ message=context.get_vectorization_text(),+ context_data={},)await updater._vectorize_memories(result,@@ -488,7 +470,10 @@ class TestEmbeddingTextConstruction:with patch.object(EmbeddingMsgConverter, "from_context") as mock_from_context:mock_from_context.side_effect = lambda context: SimpleNamespace(- telemetry_id=None, id="msg-1", message=context.get_vectorization_text()+ telemetry_id=None,+ id="msg-1",+ message=context.get_vectorization_text(),+ context_data={},)await updater._vectorize_memories(result,@@ -536,7 +521,10 @@ class TestEmbeddingTextConstruction:with patch.object(EmbeddingMsgConverter, "from_context") as mock_from_context:mock_from_context.side_effect = lambda context: SimpleNamespace(- telemetry_id=None, id="msg-1", message=context.get_vectorization_text()+ telemetry_id=None,+ id="msg-1",+ message=context.get_vectorization_text(),+ context_data={},)await updater._vectorize_memories(result,diff --git a/tests/vectordb/test_local_collection_projection.py b/tests/vectordb/test_local_collection_projection.pyindex 0852ba5f9..55ba9a1d6 100644--- a/tests/vectordb/test_local_collection_projection.py+++ b/tests/vectordb/test_local_collection_projection.py@@ -3,12 +3,15 @@import jsonfrom types import SimpleNamespace+from unittest.mock import Mockimport pytest+from openviking.storage.collection_schemas import CollectionSchemasfrom openviking.storage.vectordb.collection.local_collection import LocalCollectionfrom openviking.storage.vectordb.store.data import CandidateDatafrom openviking.storage.vectordb.store.store_manager import StoreManager+from openviking.storage.vectordb_adapters.local_adapter import LocalCollectionAdapterclass _FakeIndex:@@ -67,23 +70,78 @@ def _collection(store, labels=(11, 12), scores=(0.9, 0.8)):return collection-def test_search_by_vector_projects_fields_without_decoding_vectors():- store = _FakeStoreManager(- [- _candidate(11, "first", "/docs/one", [1.0, 0.0]),- _candidate(12, "second", "/docs/two", [0.0, 1.0]),- ]- )-- result = _collection(store).search_by_vector(- "default", dense_vector=[1.0, 0.0], output_fields=["uri"]- )-- assert store.calls == [("fields", [11, 12])]- assert [(item.id, item.fields, item.score) for item in result.data] == [- ("first", {"uri": "/docs/one"}, 0.9),- ("second", {"uri": "/docs/two"}, 0.8),- ]+def test_search_by_vector_projects_only_final_decayed_results(tmp_path, monkeypatch):+ adapter = LocalCollectionAdapter("context", str(tmp_path), "default")+ try:+ adapter.create_collection(+ "context",+ CollectionSchemas.context_collection("context", 4),+ distance="cosine",+ sparse_weight=0,+ index_name="default",+ )+ adapter.upsert(+ [+ {+ "id": str(index),+ "uri": f"viking://resources/{index}",+ "vector": [similarity, (1 - similarity**2) ** 0.5, 0, 0],+ **(+ {+ "updated_at": "2026-01-01T00:00:00Z"+ if index < 3+ else "2026-01-09T00:00:00Z"+ }+ if index < 5+ else {}+ ),+ }+ for index, similarity in enumerate([1.0, 0.9, 0.8, 0.7, 0.6, 0.5])+ ]+ )+ adapter.close()+ # Reloading must retain the timestamp index used for scoring.+ original_scores = {+ item["id"]: item["_score"] for item in adapter.query(query_vector=[1, 0, 0, 0], limit=6)+ }+ local = adapter.get_collection()._Collection__collection+ fetch = Mock(wraps=local.store_mgr.fetch_cands_fields)+ monkeypatch.setattr(local.store_mgr, "fetch_cands_fields", fetch)+ original_full_fetch = local.store_mgr.fetch_cands_data+ full_decode = Mock(side_effect=AssertionError("projected results must not decode vectors"))+ monkeypatch.setattr(local.store_mgr, "fetch_cands_data", full_decode)+ options = {+ "query_vector": [1, 0, 0, 0],+ "output_fields": ["uri"],+ "advance": {"time_decay": {"protection": "2d", "origin": "2026-01-10T00:00:00Z"}},+ }+ result = adapter.query(**options, limit=2)+ assert [item["id"] for item in result] == ["3", "4"]+ assert [item["_score"] for item in result] == pytest.approx(+ [original_scores["3"], original_scores["4"]]+ )+ assert [item["_time_score"] for item in result] == [1.0, 1.0]+ assert [item["uri"] for item in result] == ["viking://resources/3", "viking://resources/4"]+ assert all("vector" not in item and "updated_at" not in item for item in result)+ assert sum(len(call.args[0]) for call in fetch.call_args_list) == 2++ # Top-1 considers only three vector candidates, not the whole collection.+ one = adapter.query(**options, limit=1)+ assert one[0]["id"] == "0"+ assert one[0]["_origin_score"] == pytest.approx(original_scores["0"])+ assert one[0]["_score"] == pytest.approx(original_scores["0"] * 0.5)+ page = adapter.query(**options, limit=2, offset=1)+ assert [item["id"] for item in page] == ["4", "5"]+ assert page[1]["_score"] == pytest.approx(original_scores["5"])+ assert "_time_score" not in page[1]++ monkeypatch.setattr(local.store_mgr, "fetch_cands_data", original_full_fetch)+ adapter.update_data([{"id": "0", "updated_at": "2026-01-10T00:00:00Z"}])+ refreshed = adapter.query(**options, limit=2)+ assert refreshed[0]["id"] == "0"+ assert refreshed[0]["_score"] == pytest.approx(original_scores["0"])+ finally:+ adapter.close()@pytest.mark.parametrize("output_fields", [None, [], ["uri", "embedding"]])diff --git a/tests/vectordb/test_opengauss_adapter_complete.py b/tests/vectordb/test_opengauss_adapter_complete.pyindex 0eddfb9a7..6f1bb5016 100644--- a/tests/vectordb/test_opengauss_adapter_complete.py+++ b/tests/vectordb/test_opengauss_adapter_complete.py@@ -1438,6 +1438,19 @@ def test_search_sql_uses_stable_id_tiebreaker():collection.search_by_vector("default", dense_vector=[1.0, 0.0])assert "ORDER BY _distance, id" in cursor.execute.call_args.args[0]+ # Shared decay options pass through without changing openGauss scoring or pagination.+ cursor.fetchall.return_value = [("event", [1.0, 0.0], 0.2)]+ adapter = _adapter_without_connect()+ adapter.get_collection = Mock(return_value=collection)+ advance = {"time_decay": {"protection": "0", "origin": "2026-01-08T00:00:00Z"}}+ with patch.object(collection, "search_by_vector", wraps=collection.search_by_vector) as search:+ result = adapter.query(query_vector=[1.0, 0.0], limit=10, offset=2, advance=advance)+ assert search.call_args.kwargs["advance"] is advance+ sql, params = cursor.execute.call_args.args+ assert "ORDER BY _distance, id" in sql+ assert params[-2:] == [10, 2]+ assert result == [{"id": "event", "vector": [1.0, 0.0], "_score": pytest.approx(0.8)}]+cursor.description = [("id",), ("level",), ("_scalar_val",)]cursor.fetchall.return_value = []collection.search_by_scalar("default", field="level", order="desc")