Skip to content

Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.

refactor(retrieval): 移除热度加权及其配置 (#5454)

Qin Haojie00490c93a9c9
diff --git a/docs/en/concepts/07-retrieval.md b/docs/en/concepts/07-retrieval.md
index 58b976341..e38a3af29 100644
--- a/docs/en/concepts/07-retrieval.md
+++ b/docs/en/concepts/07-retrieval.md
@@ -90,6 +90,7 @@ Image queries skip text reranking and recall `limit` candidates. They default to
Rerank processes only the candidates from the completed global search; it never starts another search. For example, with `limit=10`, reranking recalls the top 20 vector hits and returns at most 10 results after reranking. Without reranking, recall is limited to 10 hits.
- Candidate index records supply the `abstract` text for reranking.
+- Scores and ranking use rerank scores when available, otherwise vector scores; access frequency, update time, and parent-directory scores do not affect them.
- Score thresholds apply after reranking, or to vector scores when reranking is disabled.
- Failed requests or invalid rerank results retain the existing fallback to vector scores.
- Directory priority queues, parent-to-child score propagation, and convergence rounds are removed.
diff --git a/docs/en/configuration/01-server.md b/docs/en/configuration/01-server.md
index 01f4cdd03..c19b91a6f 100644
--- a/docs/en/configuration/01-server.md
+++ b/docs/en/configuration/01-server.md
@@ -157,7 +157,6 @@ Rerank has no separate `enabled` field. It becomes available when the required p
```json
{
"retrieval": {
- "hotness_alpha": 0,
"enable_intent": true
}
}
@@ -167,7 +166,6 @@ Rerank has no separate `enabled` field. It becomes available when the required p
| Field | Type / values | Default | Purpose |
|---|---|---|---|
-| `hotness_alpha` | number, `0`–`1` | `0` | Hotness score weight; `0` disables it |
| `enable_intent` | boolean | `true` | Run intent analysis/query planning when `session_id` is present |
Search and Find requests default to `limit: 10`; override the limit on each API or SDK request. `retrieval.enable_intent` controls LLM query planning for session-aware Search, while result reranking is enabled only when `rerank` has a usable provider configuration.
diff --git a/docs/en/faq/faq.md b/docs/en/faq/faq.md
index 3c632837e..9775c6174 100644
--- a/docs/en/faq/faq.md
+++ b/docs/en/faq/faq.md
@@ -293,25 +293,11 @@ overview = await client.overview(uri="viking://resources")
### How is the retrieval result score calculated?
-OpenViking uses a score propagation mechanism:
+Results use vector scores directly when reranking is disabled. When reranking is enabled, its scores determine the final ranking; failed requests or invalid rerank results fall back to vector scores. Access frequency, update time, and parent-directory scores do not add any weight.
-```
-Final Score = 0.5 × Embedding Similarity + 0.5 × Parent Directory Score
-```
-
-This design gives content under high-scoring directories a boost, reflecting the importance of "contextual environment".
-
-### What is directory recursive retrieval?
-
-Directory recursive retrieval is OpenViking's innovative retrieval strategy:
-
-1. **Intent Analysis**: Analyze query to generate multiple retrieval conditions
-2. **Initial Positioning**: Vector retrieval to locate high-scoring directories
-3. **Refined Exploration**: Secondary retrieval within high-scoring directories
-4. **Recursive Drill-down**: Layer-by-layer recursion until convergence
-5. **Result Aggregation**: Return the most relevant context
+### How does global retrieval work?
-This strategy finds semantically matching fragments while understanding the complete context of the information.
+Each query runs one global vector search within its directory scope, permission filters, and requested levels. THINKING with a usable reranker recalls at most `2 × limit` candidates, reranks them once, and returns at most `limit` results. Without reranking, it recalls `limit` hits directly. Retrieval does not navigate directories recursively or trigger further searches after reranking.
## Troubleshooting
diff --git a/docs/en/guides/01-configuration.md b/docs/en/guides/01-configuration.md
index f2633d783..983c94c9e 100644
--- a/docs/en/guides/01-configuration.md
+++ b/docs/en/guides/01-configuration.md
@@ -1099,12 +1099,12 @@ If rerank is not configured, search uses vector similarity only.
### retrieval
-Retrieval ranking configuration for final search scores.
+Configuration for session intent analysis and context assembly timeouts.
```json
{
"retrieval": {
- "hotness_alpha": 0.0,
+ "enable_intent": true,
"recall_intent_timeout_s": 5.0,
"recall_rewrite_timeout_s": 30.0
}
@@ -1113,9 +1113,7 @@ Retrieval ranking configuration for final search scores.
| Parameter | Type | Description | Default |
|-----------|------|-------------|---------|
-| `hotness_alpha` | float | Weight for blending hotness into final retrieval scores. `0.0` disables the hotness boost and keeps scores equal to semantic similarity; `1.0` uses only hotness. Valid range: `0.0` to `1.0`. | `0.0` |
-
-Keep `hotness_alpha` at `0.0` when you need scores to reflect pure vector similarity. Set it above `0.0` only when frequently accessed or recently updated contexts should receive a ranking boost.
+| `enable_intent` | bool | Run intent analysis and query planning when `search()` receives a `session_id`. | `true` |
The `mode="context"` assembly face on `/search` uses two timeout fuses:
@@ -2064,7 +2062,7 @@ For detailed encryption explanations, see [Data Encryption](../concepts/10-encry
"extra_headers": {}
},
"retrieval": {
- "hotness_alpha": 0.0
+ "enable_intent": true
},
"encryption": {
"enabled": false,
diff --git a/docs/zh/concepts/07-retrieval.md b/docs/zh/concepts/07-retrieval.md
index 575ca71c7..c5f9e7910 100644
--- a/docs/zh/concepts/07-retrieval.md
+++ b/docs/zh/concepts/07-retrieval.md
@@ -90,6 +90,7 @@ class TypedQuery:
Rerank 只处理本次全局召回的候选,不会触发下一轮检索。例如 `limit=10`,启用 Rerank 时先召回向量分数最高的 20 条,再按 Rerank 结果返回最多 10 条;未启用时直接召回 10 条。
- 使用候选索引记录的 `abstract` 字段作为 Rerank 文本。
+- 分数与排序使用 Rerank 分数,否则使用向量分数;访问频次、更新时间和父目录分数不参与加权。
- 分数阈值在 Rerank 后应用;未启用 Rerank 时使用向量分数。
- Rerank 请求失败或返回无效结果时,保留已有的向量分数回退行为。
- 不再使用目录优先队列、父子分数传播或多轮收敛判断。
diff --git a/docs/zh/configuration/01-server.md b/docs/zh/configuration/01-server.md
index d0631fe66..d9915f29d 100644
--- a/docs/zh/configuration/01-server.md
+++ b/docs/zh/configuration/01-server.md
@@ -157,7 +157,6 @@ Rerank 没有单独的 `enabled` 字段;配置了对应 provider 所需的凭
```json
{
"retrieval": {
- "hotness_alpha": 0,
"enable_intent": true
}
}
@@ -167,7 +166,6 @@ Rerank 没有单独的 `enabled` 字段;配置了对应 provider 所需的凭
| 字段 | 类型 / 可选值 | 默认值 | 作用 |
|---|---|---|---|
-| `hotness_alpha` | number,`0`–`1` | `0` | 热度分数权重;`0` 表示关闭热度加权 |
| `enable_intent` | boolean | `true` | 有 `session_id` 时是否进行意图分析和查询规划 |
Search 和 Find 请求的默认 `limit` 为 `10`,可以在每次 API 或 SDK 请求中覆盖。`retrieval.enable_intent` 控制带 Session 的 Search 是否执行 LLM 查询规划;只有配置了可用的 `rerank` provider 时才会执行结果重排。
diff --git a/docs/zh/faq/faq.md b/docs/zh/faq/faq.md
index c62fe8d99..c6af6719d 100644
--- a/docs/zh/faq/faq.md
+++ b/docs/zh/faq/faq.md
@@ -286,25 +286,11 @@ overview = await client.overview(uri="viking://resources")
### 检索结果的分数是如何计算的?
-OpenViking 使用分数传播机制:
+未启用 Rerank 时,结果直接使用向量分数。启用 Rerank 时,使用其分数排序;请求失败或返回无效结果时回退到向量分数。访问频次、更新时间和父目录分数均不参与加权。
-```
-最终分数 = 0.5 × Embedding 相似度 + 0.5 × 父目录分数
-```
-
-这种设计让高分目录下的内容获得加成,体现了"上下文语境"的重要性。
-
-### 什么是目录递归检索?
-
-目录递归检索是 OpenViking 的创新检索策略:
-
-1. **意图分析**:分析查询生成多个检索条件
-2. **初始定位**:向量检索定位高分目录
-3. **精细探索**:在高分目录下进行二次检索
-4. **递归下探**:逐层递归直到收敛
-5. **结果汇总**:返回最相关的上下文
+### 全局检索是如何执行的?
-这种策略能找到语义匹配的片段,同时理解信息的完整语境。
+每条查询在指定目录范围、权限过滤和 level 条件内执行一次全局向量检索。THINKING 模式且配置了可用 Rerank 时,召回最多 `2 × limit` 条候选,统一精排一次后返回最多 `limit` 条;不启用 Rerank 时直接召回 `limit` 条。检索不会逐层遍历目录,也不会在精排后触发下一轮召回。
## 故障排除
diff --git a/docs/zh/guides/01-configuration.md b/docs/zh/guides/01-configuration.md
index 5a292a595..875f1e724 100644
--- a/docs/zh/guides/01-configuration.md
+++ b/docs/zh/guides/01-configuration.md
@@ -1062,12 +1062,12 @@ Jev 适配器将 query 和候选文档作为结构化 System One `state`,并
### retrieval
-最终搜索分数的召回排序配置。
+会话意图分析和上下文组装的超时配置。
```json
{
"retrieval": {
- "hotness_alpha": 0.0,
+ "enable_intent": true,
"recall_intent_timeout_s": 5.0,
"recall_rewrite_timeout_s": 30.0
}
@@ -1076,9 +1076,7 @@ Jev 适配器将 query 和候选文档作为结构化 System One `state`,并
| 参数 | 类型 | 说明 | 默认值 |
|------|------|------|--------|
-| `hotness_alpha` | float | hotness 分数在最终召回分数中的混合权重。`0.0` 表示关闭 hotness boost,最终分数等于语义相似度;`1.0` 表示只使用 hotness。有效范围:`0.0` 到 `1.0`。 | `0.0` |
-
-如果需要分数严格反映向量相似度,保持 `hotness_alpha` 为 `0.0`。只有当希望高频访问或最近更新的上下文获得排序提升时,才将它设置为大于 `0.0`。
+| `enable_intent` | bool | `search()` 收到 `session_id` 时是否执行意图分析和查询规划。 | `true` |
`/search` 的 `mode="context"` 组装面用到两个超时熔断:
@@ -2030,7 +2028,7 @@ Task 记录文件位于所属账号的系统目录:
"extra_headers": {}
},
"retrieval": {
- "hotness_alpha": 0.0
+ "enable_intent": true
},
"encryption": {
"enabled": false,
diff --git a/examples/ov.conf.example b/examples/ov.conf.example
index 23402435a..5b81cb297 100644
--- a/examples/ov.conf.example
+++ b/examples/ov.conf.example
@@ -243,7 +243,6 @@
"threshold": 0.1,
},
"retrieval": {
- "hotness_alpha": 0.0,
"recall_intent_timeout_s": 5.0,
"recall_rewrite_timeout_s": 30.0,
},
diff --git a/openviking/retrieve/hierarchical_retriever.py b/openviking/retrieve/hierarchical_retriever.py
index 7085013b9..6e3dffb9f 100644
--- a/openviking/retrieve/hierarchical_retriever.py
+++ b/openviking/retrieve/hierarchical_retriever.py
@@ -7,14 +7,12 @@ Global vector retrieval with optional reranking of the recalled candidates.
import asyncio
import math
import time
-from datetime import datetime
from typing import Any, Dict, List, Optional
from openviking.core.context import ContextLevel
from openviking.core.retrieval_targets import default_target_directories
from openviking.models.embedder.base import EmbedResult, embed_compat
from openviking.models.rerank import RerankClient
-from openviking.retrieve.memory_lifecycle import hotness_score
from openviking.retrieve.retrieval_stats import get_stats_collector
from openviking.server.identity import RequestContext
from openviking.storage.abstract_overview import AbstractOverviewFormatError, body_for_preview
@@ -22,7 +20,6 @@ from openviking.storage.expr import FilterExpr
from openviking.storage.vikingdb_manager import VikingDBManager, VikingDBManagerProxy
from openviking.telemetry import get_current_telemetry
from openviking.utils.tags import normalize_search_tags
-from openviking.utils.time_utils import parse_iso_datetime
from openviking.utils.token_estimation import (
estimate_text_tokens,
truncate_text_to_token_budget,
@@ -34,7 +31,7 @@ from openviking_cli.retrieve.types import (
QueryResult,
TypedQuery,
)
-from openviking_cli.utils.config import RerankConfig, RetrievalConfig
+from openviking_cli.utils.config import RerankConfig
from openviking_cli.utils.logger import get_logger
logger = get_logger(__name__)
@@ -56,7 +53,6 @@ class HierarchicalRetriever:
storage: VikingDBManager,
embedder: Optional[Any],
rerank_config: Optional[RerankConfig] = None,
- retrieval_config: Optional[RetrievalConfig] = None,
):
"""Initialize retriever with rerank_config.
@@ -64,14 +60,11 @@ class HierarchicalRetriever:
storage: VikingVectorIndexBackend instance
embedder: Embedder instance (supports dense/sparse/hybrid)
rerank_config: Rerank configuration (optional, will fallback to vector search only)
- retrieval_config: Retrieval ranking configuration.
"""
self.vector_store = storage
self.embedder = embedder
self.rerank_config = rerank_config
self.rerank_max_input_tokens = rerank_config.max_input_tokens if rerank_config else 0
- self.retrieval_config = retrieval_config or RetrievalConfig()
- self.hotness_alpha = self.retrieval_config.hotness_alpha
# Use rerank threshold if available, otherwise use a default
self.threshold = rerank_config.threshold if rerank_config else 0
@@ -211,11 +204,7 @@ class HierarchicalRetriever:
if self._passes_threshold(score, effective_threshold, score_gte)
]
telemetry.count("vector.passed", len(candidates))
- matched = await self._convert_to_matched_contexts(
- candidates,
- ctx=ctx,
- apply_hotness=use_rerank,
- )
+ matched = await self._convert_to_matched_contexts(candidates, ctx=ctx)
final = matched[:limit]
elapsed_ms = (time.monotonic() - t0) * 1000
@@ -305,41 +294,11 @@ class HierarchicalRetriever:
self,
candidates: List[Dict[str, Any]],
ctx: RequestContext,
- apply_hotness: bool = True,
) -> List[MatchedContext]:
- """Convert candidate results to MatchedContext list.
-
- Blends semantic similarity with a hotness score derived from
- ``active_count`` and ``updated_at`` when configured. The blend weight
- is controlled by ``retrieval.hotness_alpha`` (0 disables the boost).
- """
+ """Convert candidates to contexts ordered by vector or rerank score."""
results = []
for c in candidates:
- # Fix: clamp inf/nan scores from vector search (#inf-score)
- semantic_score = self._finite_score(c.get("_final_score", c.get("_score", 0.0)))
-
- alpha = self.hotness_alpha
- if apply_hotness and alpha > 0:
- updated_at_raw = c.get("updated_at")
- if isinstance(updated_at_raw, str):
- try:
- updated_at_val = parse_iso_datetime(updated_at_raw)
- except (ValueError, TypeError):
- updated_at_val = None
- elif isinstance(updated_at_raw, datetime):
- updated_at_val = updated_at_raw
- else:
- updated_at_val = None
-
- h_score = hotness_score(
- active_count=c.get("active_count", 0),
- updated_at=updated_at_val,
- )
- final_score = (1 - alpha) * semantic_score + alpha * h_score
- else:
- final_score = semantic_score
- if not math.isfinite(final_score):
- final_score = 0.0
+ final_score = self._finite_score(c.get("_final_score", c.get("_score", 0.0)))
level = c.get("level", 2)
display_uri = self._append_level_suffix(c.get("uri", ""), level)
abstract = c.get("abstract", "")
@@ -369,7 +328,6 @@ class HierarchicalRetriever:
)
)
- # Re-sort by blended score so hotness boost can change ranking
results.sort(key=lambda x: x.score, reverse=True)
return results
diff --git a/openviking/retrieve/memory_lifecycle.py b/openviking/retrieve/memory_lifecycle.py
index 45d62da76..003a4c1b7 100644
--- a/openviking/retrieve/memory_lifecycle.py
+++ b/openviking/retrieve/memory_lifecycle.py
@@ -3,9 +3,8 @@
"""Hotness scoring for cold/hot memory lifecycle management (#296).
Provides a pure function to compute a 0.0–1.0 hotness score based on
-access frequency (active_count) and recency (updated_at). The score
-can be blended with semantic similarity to boost frequently-accessed,
-recently-updated contexts in search results.
+access frequency (active_count) and recency (updated_at). The memory
+health statistics API uses this score to classify cold, warm, and hot memories.
"""
import math
diff --git a/openviking/retrieve/skill_package_retriever.py b/openviking/retrieve/skill_package_retriever.py
index c90b0802c..9dd3d4cd9 100644
--- a/openviking/retrieve/skill_package_retriever.py
+++ b/openviking/retrieve/skill_package_retriever.py
@@ -83,9 +83,7 @@ class SkillPackageRetriever(HierarchicalRetriever):
previous = candidates.get(key)
if previous is None or score > previous["_final_score"]:
candidates[key] = {**item, "_score": score, "_final_score": score}
- converted = await self._convert_to_matched_contexts(
- list(candidates.values()), ctx=ctx, apply_hotness=False
- )
+ converted = await self._convert_to_matched_contexts(list(candidates.values()), ctx=ctx)
matches = await skill_resolver.resolve(converted)
if len(matches) >= limit or len(page) < page_size:
break
diff --git a/openviking/service/search_service.py b/openviking/service/search_service.py
index 536d2cbdf..cf8018d52 100644
--- a/openviking/service/search_service.py
+++ b/openviking/service/search_service.py
@@ -205,7 +205,6 @@ class SearchService:
storage=storage,
embedder=embedder,
rerank_config=fs.rerank_config,
- retrieval_config=fs.retrieval_config,
)
result = await retriever.retrieve_skills(
TypedQuery(query, ContextType.SKILL, "", target_directories=targets),
diff --git a/openviking/storage/viking_fs/_base.py b/openviking/storage/viking_fs/_base.py
index f8513da52..4607b6f02 100644
--- a/openviking/storage/viking_fs/_base.py
+++ b/openviking/storage/viking_fs/_base.py
@@ -215,7 +215,7 @@ def init_viking_fs(
agfs: Pre-initialized AGFS client (HTTP or Binding)
query_embedder: Embedder instance
rerank_config: Rerank configuration
- retrieval_config: Retrieval ranking configuration
+ retrieval_config: Retrieval behavior configuration
grep_config: Grep engine configuration
glob_config: Glob engine configuration
vector_store: Vector store instance
diff --git a/openviking/storage/viking_fs/_semantic.py b/openviking/storage/viking_fs/_semantic.py
index 5fa48d82d..535794b3a 100644
--- a/openviking/storage/viking_fs/_semantic.py
+++ b/openviking/storage/viking_fs/_semantic.py
@@ -264,7 +264,6 @@ class _SemanticMixin:
storage=storage,
embedder=embedder,
rerank_config=self.rerank_config,
- retrieval_config=self.retrieval_config,
)
typed_query = TypedQuery(
@@ -486,7 +485,6 @@ class _SemanticMixin:
storage=storage,
embedder=embedder,
rerank_config=self.rerank_config,
- retrieval_config=self.retrieval_config,
)
async def _execute(tq: TypedQuery):
diff --git a/openviking_cli/utils/config/open_viking_config.py b/openviking_cli/utils/config/open_viking_config.py
index 6e829ceed..74293e5ab 100644
--- a/openviking_cli/utils/config/open_viking_config.py
+++ b/openviking_cli/utils/config/open_viking_config.py
@@ -222,7 +222,7 @@ class OpenVikingConfig(BaseModel):
retrieval: RetrievalConfig = Field(
default_factory=RetrievalConfig,
- description="Retrieval ranking configuration",
+ description="Retrieval behavior configuration",
)
grep: GrepConfig = Field(
diff --git a/openviking_cli/utils/config/retrieval_config.py b/openviking_cli/utils/config/retrieval_config.py
index 2188a67a0..161771ccb 100644
--- a/openviking_cli/utils/config/retrieval_config.py
+++ b/openviking_cli/utils/config/retrieval_config.py
@@ -5,17 +5,8 @@ from pydantic import BaseModel, Field
class RetrievalConfig(BaseModel):
- """Configuration for retrieval ranking behavior."""
+ """Configuration for query planning and context assembly."""
- hotness_alpha: float = Field(
- default=0.0,
- ge=0.0,
- le=1.0,
- description=(
- "Weight for blending hotness into final retrieval scores. "
- "0 disables hotness boost; 1 uses only hotness."
- ),
- )
recall_intent_timeout_s: float = Field(
default=5.0,
gt=0.0,
diff --git a/tests/misc/test_retrieval_enable_intent.py b/tests/misc/test_retrieval_enable_intent.py
index bb1a03bf2..03317a878 100644
--- a/tests/misc/test_retrieval_enable_intent.py
+++ b/tests/misc/test_retrieval_enable_intent.py
@@ -54,7 +54,7 @@ async def test_search_skips_intent_and_uses_raw_query_when_disabled(monkeypatch)
raise AssertionError("intent analysis must not run when disabled")
class FakeRetriever:
- def __init__(self, storage, embedder, rerank_config, retrieval_config):
+ def __init__(self, storage, embedder, rerank_config):
pass
async def retrieve(self, typed_query, **kwargs):
diff --git a/tests/misc/test_vikingfs_find_without_rerank.py b/tests/misc/test_vikingfs_find_without_rerank.py
index fd873e297..2349098fb 100644
--- a/tests/misc/test_vikingfs_find_without_rerank.py
+++ b/tests/misc/test_vikingfs_find_without_rerank.py
@@ -41,11 +41,10 @@ async def test_find_works_without_rerank_config(monkeypatch) -> None:
captured = {}
class FakeRetriever:
- def __init__(self, storage, embedder, rerank_config, retrieval_config):
+ def __init__(self, storage, embedder, rerank_config):
captured["storage"] = storage
captured["embedder"] = embedder
captured["rerank_config"] = rerank_config
- captured["retrieval_config"] = retrieval_config
async def retrieve(
self,
@@ -95,7 +94,6 @@ async def test_find_works_without_rerank_config(monkeypatch) -> None:
assert captured["storage"] is fs.vector_store
assert captured["embedder"] is fs.query_embedder
assert captured["rerank_config"] is None
- assert captured["retrieval_config"] is None
assert captured["typed_query"].query == "guide"
assert captured["typed_query"].context_type is None
assert captured["typed_query"].target_directories == ["viking://resources/docs"]
@@ -114,7 +112,7 @@ async def test_find_accepts_image_url_without_text_query(monkeypatch) -> None:
captured = {}
class FakeRetriever:
- def __init__(self, storage, embedder, rerank_config, retrieval_config):
+ def __init__(self, storage, embedder, rerank_config):
pass
async def retrieve(
@@ -170,7 +168,7 @@ async def test_find_uses_quick_mode_with_rerank_config(monkeypatch) -> None:
captured = {}
class FakeRetriever:
- def __init__(self, storage, embedder, rerank_config, retrieval_config):
+ def __init__(self, storage, embedder, rerank_config):
captured["rerank_config"] = rerank_config
async def retrieve(self, typed_query, **kwargs):
diff --git a/tests/retrieve/test_hierarchical_retriever_rerank.py b/tests/retrieve/test_hierarchical_retriever_rerank.py
index 4a9f9806b..c09f02569 100644
--- a/tests/retrieve/test_hierarchical_retriever_rerank.py
+++ b/tests/retrieve/test_hierarchical_retriever_rerank.py
@@ -16,7 +16,7 @@ from openviking.storage.abstract_overview import render_abstract_overview
from openviking.utils.token_estimation import estimate_text_tokens
from openviking_cli.retrieve.types import ContextType, TypedQuery
from openviking_cli.session.user_id import UserIdentifier
-from openviking_cli.utils.config import RerankConfig, RetrievalConfig
+from openviking_cli.utils.config import RerankConfig
def _result(uri, score, level=2, abstract=None, **extra):
@@ -402,76 +402,6 @@ async def test_retrieve_without_rerank_filters_by_vector_score():
]
-async def test_retrieve_without_rerank_keeps_vector_scores_when_hotness_configured(monkeypatch):
- monkeypatch.setattr(
- "openviking.retrieve.hierarchical_retriever.hotness_score",
- lambda *args, **kwargs: pytest.fail("hotness_score should not be called without rerank"),
- )
- storage = DummyStorage(
- [
- _result(
- "viking://resources/file-a",
- 0.8,
- abstract="file A",
- active_count=100,
- updated_at="2026-01-01T00:00:00+00:00",
- )
- ]
- )
- retriever = HierarchicalRetriever(
- storage=storage,
- embedder=DummyEmbedder(),
- rerank_config=None,
- retrieval_config=RetrievalConfig(hotness_alpha=0.5),
- )
-
- result = await retriever.retrieve(_query(), ctx=_ctx(), limit=1)
-
- assert result.matched_contexts[0].score == pytest.approx(0.8)
-
-
-async def test_default_retrieval_config_uses_semantic_score_without_hotness(monkeypatch):
- monkeypatch.setattr(
- "openviking.retrieve.hierarchical_retriever.hotness_score",
- lambda *args, **kwargs: pytest.fail("hotness_score should not be called by default"),
- )
- retriever = HierarchicalRetriever(
- storage=DummyStorage(),
- embedder=None,
- rerank_config=None,
- )
-
- result = await retriever._convert_to_matched_contexts(
- [_result("viking://resources/file-a", 1.0, abstract="child A")],
- ctx=_ctx(),
- )
-
- assert result[0].score == pytest.approx(1.0)
-
-
-async def test_retrieval_hotness_alpha_blends_when_configured(monkeypatch):
- monkeypatch.setattr(
- "openviking.retrieve.hierarchical_retriever.hotness_score",
- lambda *args, **kwargs: 0.5,
- )
- retriever = HierarchicalRetriever(
- storage=DummyStorage(),
- embedder=None,
- rerank_config=None,
- retrieval_config=RetrievalConfig(hotness_alpha=0.2),
- )
-
- result = await retriever._convert_to_matched_contexts(
- [_result("viking://resources/file-a", 1.0, abstract="child A")],
- ctx=_ctx(),
- )
-
- assert result[0].score == pytest.approx(0.9)
-
-
@pytest.mark.asyncio
async def test_convert_to_matched_contexts_propagates_search_tags():
retriever = HierarchicalRetriever(
diff --git a/tests/test_config_loader.py b/tests/test_config_loader.py
index 0f73728f3..7e8484014 100644
--- a/tests/test_config_loader.py
+++ b/tests/test_config_loader.py
@@ -439,7 +439,7 @@ def test_openviking_config_ignores_deprecated_code_summary_mode(monkeypatch):
OpenVikingConfigSingleton.reset_instance()
-def test_openviking_config_retrieval_hotness_alpha_defaults_to_zero(monkeypatch):
+def test_openviking_config_transaction_redo_recovery_enabled_defaults_true(monkeypatch):
monkeypatch.setenv(OPENVIKING_CONFIG_ENV, "/tmp/codex-no-config.json")
from openviking_cli.utils.config.open_viking_config import (
@@ -449,7 +449,6 @@ def test_openviking_config_retrieval_hotness_alpha_defaults_to_zero(monkeypatch)
config = OpenVikingConfig.from_dict({})
- assert config.retrieval.hotness_alpha == 0.0
assert config.storage.transaction.redo_recovery_enabled is True
OpenVikingConfigSingleton.reset_instance()
@@ -472,30 +471,16 @@ def test_openviking_config_transaction_redo_recovery_enabled_can_be_disabled(mon
OpenVikingConfigSingleton.reset_instance()
-def test_openviking_config_retrieval_alpha_validates_range(monkeypatch):
- monkeypatch.setenv(OPENVIKING_CONFIG_ENV, "/tmp/codex-no-config.json")
-
- from openviking_cli.utils.config.open_viking_config import (
- OpenVikingConfig,
- OpenVikingConfigSingleton,
- )
-
- with pytest.raises(ValueError):
- OpenVikingConfig.from_dict({"retrieval": {"hotness_alpha": 1.5}})
-
- OpenVikingConfigSingleton.reset_instance()
-
-
def test_openviking_config_singleton_preserves_value_error_for_bad_config(tmp_path, monkeypatch):
monkeypatch.setenv(OPENVIKING_CONFIG_ENV, "/tmp/codex-no-config.json")
from openviking_cli.utils.config.open_viking_config import OpenVikingConfigSingleton
config_path = tmp_path / "ov.conf"
- config_path.write_text('{"retrieval": {"hotness_alpha": 1.5}}')
+ config_path.write_text('{"retrieval": {"recall_intent_timeout_s": 0}}')
OpenVikingConfigSingleton.reset_instance()
- with pytest.raises(ValueError, match="retrieval.hotness_alpha"):
+ with pytest.raises(ValueError, match="retrieval.recall_intent_timeout_s"):
OpenVikingConfigSingleton.initialize(config_path=str(config_path))
OpenVikingConfigSingleton.reset_instance()
diff --git a/tests/test_memory_lifecycle.py b/tests/test_memory_lifecycle.py
index af4a9eabd..1d1fd1281 100644
--- a/tests/test_memory_lifecycle.py
+++ b/tests/test_memory_lifecycle.py
@@ -4,8 +4,6 @@
from datetime import datetime, timedelta, timezone
-import pytest
-
from openviking.retrieve.memory_lifecycle import DEFAULT_HALF_LIFE_DAYS, hotness_score
NOW = datetime(2026, 2, 26, 12, 0, 0, tzinfo=timezone.utc)
@@ -76,49 +74,3 @@ class TestHotnessScore:
s_mid = hotness_score(5, NOW - timedelta(days=3), now=NOW)
s_new = hotness_score(5, NOW - timedelta(hours=1), now=NOW)
assert s_old < s_mid < s_new
-
-
-class TestHotnessBlending:
- """Tests for the blending logic (alpha weighting)."""
-
- def test_alpha_zero_preserves_semantic_order(self):
- """With alpha=0, final score equals semantic score exactly."""
- semantic = 0.85
- alpha = 0.0
- h = hotness_score(100, NOW, now=NOW)
- blended = (1 - alpha) * semantic + alpha * h
- assert blended == pytest.approx(semantic)
-
- def test_hotness_boost_can_rerank(self):
- """A hot memory with lower semantic score can overtake a cold one."""
- alpha = 0.4 # aggressive weight for demonstration
-
- # Memory A: high semantic, cold (old, low access)
- sem_a = 0.8
- h_a = hotness_score(1, NOW - timedelta(days=60), now=NOW)
- blended_a = (1 - alpha) * sem_a + alpha * h_a
-
- # Memory B: lower semantic, hot (recent, high access)
- sem_b = 0.6
- h_b = hotness_score(500, NOW, now=NOW)
- blended_b = (1 - alpha) * sem_b + alpha * h_b
-
- # B should overtake A due to hotness
- assert blended_b > blended_a
-
- def test_small_alpha_preserves_semantic_dominance(self):
- """With a small alpha, a large semantic gap is not overturned."""
- alpha = 0.2
-
- # Memory A: much higher semantic, cold
- sem_a = 0.9
- h_a = hotness_score(0, NOW - timedelta(days=30), now=NOW)
- blended_a = (1 - alpha) * sem_a + alpha * h_a
-
- # Memory B: much lower semantic, hot
- sem_b = 0.3
- h_b = hotness_score(1000, NOW, now=NOW)
- blended_b = (1 - alpha) * sem_b + alpha * h_b
-
- # A should still win — semantic dominance preserved
- assert blended_a > blended_b