F4-Tests: Archivar v5 Quality Gate — Cold-Start, Rebuild, Boost, Konfliktlösung
4 kritische Pfade (Rainer): F4.1 Cold-Start: Leerer FAISS-Index → search() raises RoomIndexError F4.2 Rebuild: seed_data-Räume → build_index() → search() findet korrekten Raum F4.3 Boost: Eindeutiges Keyword +0.05, mehrdeutiges neutral F4.4 Konfliktlösung: Top-2 Diff < 0.03 → mehr unique keywords gewinnt +0.02 Mock-FAISS-Index (MockIndexFlatIP) — faiss-cpu muss NICHT installiert sein. Mock-EmbeddingClient — deterministische Vektoren, keine echten Ollama-Calls. 35 Tests, alle grün (0.23s).
This commit is contained in:
@@ -0,0 +1,540 @@
|
|||||||
|
"""
|
||||||
|
F4-Tests für KeywordBooster — Boost und Konfliktlösung.
|
||||||
|
|
||||||
|
Zwei kritische Pfade (Rainer):
|
||||||
|
F4.3 Boost: Eindeutiges Keyword → +0.05, mehrdeutiges → neutral
|
||||||
|
F4.4 Konfliktlösung: Top-2 Diff < 0.03 → Raum mit mehr unique keywords gewinnt
|
||||||
|
|
||||||
|
Mock-FAISS-Index und Mock-EmbeddingClient sind NICHT nötig —
|
||||||
|
KeywordBooster arbeitet rein auf RoomMap + Scores, ohne Embeddings.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
# Ensure the archivar package is importable
|
||||||
|
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||||
|
|
||||||
|
from plugin.archivar.booster import KeywordBooster
|
||||||
|
from plugin.archivar.room_map import RoomMap, RoomEntry
|
||||||
|
|
||||||
|
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
# Helpers
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
|
def _make_booster_room_map() -> RoomMap:
|
||||||
|
"""Erzeugt eine RoomMap mit kontrollierten Keyword-Überlappungen.
|
||||||
|
|
||||||
|
Raum-Struktur:
|
||||||
|
room_a (#Plugin):
|
||||||
|
keywords_100: ["rocketchat", "ddp"]
|
||||||
|
keywords_context: ["plugin", "gateway", "deployment", "button"]
|
||||||
|
→ "rocketchat", "ddp", "plugin", "deployment", "button" sind UNIQUE
|
||||||
|
→ "gateway" ist SHARED mit room_b
|
||||||
|
|
||||||
|
room_b (#BAT):
|
||||||
|
keywords_100: ["bat", "trading"]
|
||||||
|
keywords_context: ["gateway", "docker", "prisma", "api"]
|
||||||
|
→ "bat", "trading", "docker", "prisma", "api" sind UNIQUE
|
||||||
|
→ "gateway" ist SHARED mit room_a
|
||||||
|
|
||||||
|
room_catchall (DM Admin):
|
||||||
|
keywords_100: []
|
||||||
|
keywords_context: []
|
||||||
|
catch_all: True
|
||||||
|
→ nimmt NICHT an Keyword-Boosts teil
|
||||||
|
"""
|
||||||
|
rooms: dict[str, RoomEntry] = {
|
||||||
|
"room_a": RoomEntry(
|
||||||
|
room_id="room_a",
|
||||||
|
name="#Plugin",
|
||||||
|
theme="Plugin-Entwicklung",
|
||||||
|
keywords_100=["rocketchat", "ddp"],
|
||||||
|
keywords_context=["plugin", "gateway", "deployment", "button"],
|
||||||
|
catch_all=False,
|
||||||
|
),
|
||||||
|
"room_b": RoomEntry(
|
||||||
|
room_id="room_b",
|
||||||
|
name="#BAT",
|
||||||
|
theme="Trading Platform",
|
||||||
|
keywords_100=["bat", "trading"],
|
||||||
|
keywords_context=["gateway", "docker", "prisma", "api"],
|
||||||
|
catch_all=False,
|
||||||
|
),
|
||||||
|
"room_catchall": RoomEntry(
|
||||||
|
room_id="room_catchall",
|
||||||
|
name="DM Admin",
|
||||||
|
theme="Catch-All",
|
||||||
|
keywords_100=[],
|
||||||
|
keywords_context=[],
|
||||||
|
catch_all=True,
|
||||||
|
),
|
||||||
|
}
|
||||||
|
return RoomMap(
|
||||||
|
rooms=rooms,
|
||||||
|
excluded_room_ids=set(),
|
||||||
|
fact_store_path=Path("/tmp/test_docs"),
|
||||||
|
version=2,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
# F4.3 — Boost: Eindeutiges Keyword → +0.05, mehrdeutiges → neutral
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
|
class TestBoostUniqueKeyword:
|
||||||
|
"""F4.3a: Eindeutiges Keyword (nur in einem Raum) → +0.05 Boost."""
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def booster(self) -> KeywordBooster:
|
||||||
|
return KeywordBooster(_make_booster_room_map())
|
||||||
|
|
||||||
|
def test_unique_keyword_plugin_boosts_room_a(self, booster: KeywordBooster) -> None:
|
||||||
|
"""'plugin' ist nur in room_a → room_a bekommt +0.05."""
|
||||||
|
# Arrange
|
||||||
|
scores: list[tuple[str, float]] = [
|
||||||
|
("room_a", 0.80),
|
||||||
|
("room_b", 0.75),
|
||||||
|
]
|
||||||
|
text = "Das Plugin hat einen Bug"
|
||||||
|
|
||||||
|
# Act
|
||||||
|
result = booster.boost(text, scores)
|
||||||
|
|
||||||
|
# Assert
|
||||||
|
# room_a: 0.80 + 0.05 = 0.85
|
||||||
|
# room_b: 0.75 (unverändert)
|
||||||
|
assert result[0][0] == "room_a"
|
||||||
|
assert result[0][1] == pytest.approx(0.85)
|
||||||
|
assert result[1][0] == "room_b"
|
||||||
|
assert result[1][1] == pytest.approx(0.75)
|
||||||
|
|
||||||
|
def test_unique_keyword_bat_boosts_room_b(self, booster: KeywordBooster) -> None:
|
||||||
|
"""'bat' ist nur in room_b → room_b bekommt +0.05.
|
||||||
|
|
||||||
|
'bat' + 'trading' + 'docker' sind alle unique für room_b
|
||||||
|
→ +0.15 → room_b=0.90 schlägt room_a=0.80.
|
||||||
|
"""
|
||||||
|
scores: list[tuple[str, float]] = [
|
||||||
|
("room_a", 0.80),
|
||||||
|
("room_b", 0.75),
|
||||||
|
]
|
||||||
|
text = "BAT Trading Platform Docker"
|
||||||
|
|
||||||
|
result = booster.boost(text, scores)
|
||||||
|
|
||||||
|
# room_b: 0.75 + 3×0.05 = 0.90
|
||||||
|
# room_a: 0.80 (kein Keyword-Match)
|
||||||
|
assert result[0][0] == "room_b"
|
||||||
|
assert result[0][1] == pytest.approx(0.90)
|
||||||
|
assert result[1][0] == "room_a"
|
||||||
|
assert result[1][1] == pytest.approx(0.80)
|
||||||
|
|
||||||
|
def test_multiple_unique_keywords_cumulative_boost(self, booster: KeywordBooster) -> None:
|
||||||
|
"""Mehrere eindeutige Keywords → kumulativer Boost (+0.05 pro Keyword)."""
|
||||||
|
scores: list[tuple[str, float]] = [
|
||||||
|
("room_a", 0.70),
|
||||||
|
("room_b", 0.80),
|
||||||
|
]
|
||||||
|
# "plugin" + "deployment" + "button" → 3 unique keywords für room_a
|
||||||
|
text = "plugin deployment button gateway"
|
||||||
|
|
||||||
|
result = booster.boost(text, scores)
|
||||||
|
|
||||||
|
# room_a: 0.70 + 3×0.05 = 0.85
|
||||||
|
# room_b: 0.80 (gateway ist shared → kein Boost)
|
||||||
|
assert result[0][0] == "room_a"
|
||||||
|
assert result[0][1] == pytest.approx(0.85)
|
||||||
|
assert result[1][0] == "room_b"
|
||||||
|
assert result[1][1] == pytest.approx(0.80)
|
||||||
|
|
||||||
|
def test_keywords_100_also_trigger_boost(self, booster: KeywordBooster) -> None:
|
||||||
|
"""keywords_100 sind auch im Mapping → eindeutig → Boost."""
|
||||||
|
scores: list[tuple[str, float]] = [
|
||||||
|
("room_a", 0.70),
|
||||||
|
("room_b", 0.80),
|
||||||
|
]
|
||||||
|
# "rocketchat" ist keywords_100 für room_a, unique
|
||||||
|
text = "rocketchat websocket"
|
||||||
|
|
||||||
|
result = booster.boost(text, scores)
|
||||||
|
|
||||||
|
# room_a: 0.70 + 0.05 = 0.75
|
||||||
|
assert result[0][0] == "room_b" # 0.80 > 0.75
|
||||||
|
assert result[1][0] == "room_a"
|
||||||
|
assert result[1][1] == pytest.approx(0.75)
|
||||||
|
|
||||||
|
|
||||||
|
class TestBoostSharedKeyword:
|
||||||
|
"""F4.3b: Mehrdeutiges Keyword (in mehreren Räumen) → neutral (kein Boost)."""
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def booster(self) -> KeywordBooster:
|
||||||
|
return KeywordBooster(_make_booster_room_map())
|
||||||
|
|
||||||
|
def test_shared_keyword_gateway_no_boost(self, booster: KeywordBooster) -> None:
|
||||||
|
"""'gateway' ist in room_a UND room_b → kein Boost für beide."""
|
||||||
|
scores: list[tuple[str, float]] = [
|
||||||
|
("room_a", 0.80),
|
||||||
|
("room_b", 0.75),
|
||||||
|
]
|
||||||
|
text = "gateway issue"
|
||||||
|
|
||||||
|
result = booster.boost(text, scores)
|
||||||
|
|
||||||
|
# Beide unverändert
|
||||||
|
assert result[0][0] == "room_a"
|
||||||
|
assert result[0][1] == pytest.approx(0.80)
|
||||||
|
assert result[1][0] == "room_b"
|
||||||
|
assert result[1][1] == pytest.approx(0.75)
|
||||||
|
|
||||||
|
def test_mixed_unique_and_shared(self, booster: KeywordBooster) -> None:
|
||||||
|
"""Mix: 'plugin' (unique room_a) + 'gateway' (shared) → nur room_a boost."""
|
||||||
|
scores: list[tuple[str, float]] = [
|
||||||
|
("room_a", 0.80),
|
||||||
|
("room_b", 0.75),
|
||||||
|
]
|
||||||
|
text = "plugin gateway"
|
||||||
|
|
||||||
|
result = booster.boost(text, scores)
|
||||||
|
|
||||||
|
# room_a: 0.80 + 0.05 = 0.85
|
||||||
|
# room_b: 0.75 (gateway shared → kein Boost)
|
||||||
|
assert result[0][0] == "room_a"
|
||||||
|
assert result[0][1] == pytest.approx(0.85)
|
||||||
|
assert result[1][0] == "room_b"
|
||||||
|
assert result[1][1] == pytest.approx(0.75)
|
||||||
|
|
||||||
|
|
||||||
|
class TestBoostEdgeCases:
|
||||||
|
"""F4.3c: Edge Cases — leere Scores, keine Keywords, Case-Insensitivity."""
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def booster(self) -> KeywordBooster:
|
||||||
|
return KeywordBooster(_make_booster_room_map())
|
||||||
|
|
||||||
|
def test_empty_scores_returns_empty(self, booster: KeywordBooster) -> None:
|
||||||
|
"""Leere Score-Liste → leere Liste zurück."""
|
||||||
|
result = booster.boost("plugin bug", [])
|
||||||
|
assert result == []
|
||||||
|
|
||||||
|
def test_no_keywords_matched_scores_unchanged(self, booster: KeywordBooster) -> None:
|
||||||
|
"""Kein Keyword im Text → Scores unverändert, Reihenfolge erhalten."""
|
||||||
|
scores: list[tuple[str, float]] = [
|
||||||
|
("room_a", 0.80),
|
||||||
|
("room_b", 0.75),
|
||||||
|
]
|
||||||
|
text = "Hallo wie gehts" # kein Keyword
|
||||||
|
|
||||||
|
result = booster.boost(text, scores)
|
||||||
|
|
||||||
|
assert result[0][0] == "room_a"
|
||||||
|
assert result[0][1] == pytest.approx(0.80)
|
||||||
|
assert result[1][0] == "room_b"
|
||||||
|
assert result[1][1] == pytest.approx(0.75)
|
||||||
|
|
||||||
|
def test_case_insensitive_keyword_match(self, booster: KeywordBooster) -> None:
|
||||||
|
"""Keywords sind case-insensitive."""
|
||||||
|
scores: list[tuple[str, float]] = [
|
||||||
|
("room_a", 0.80),
|
||||||
|
("room_b", 0.75),
|
||||||
|
]
|
||||||
|
text = "PLUGIN BUG" # uppercase
|
||||||
|
|
||||||
|
result = booster.boost(text, scores)
|
||||||
|
|
||||||
|
assert result[0][0] == "room_a"
|
||||||
|
assert result[0][1] == pytest.approx(0.85)
|
||||||
|
|
||||||
|
def test_keyword_as_substring(self, booster: KeywordBooster) -> None:
|
||||||
|
"""Keyword-Matching ist substring-basiert (nicht word-boundary)."""
|
||||||
|
scores: list[tuple[str, float]] = [
|
||||||
|
("room_a", 0.80),
|
||||||
|
("room_b", 0.75),
|
||||||
|
]
|
||||||
|
# "plugin" ist substring von "pluginfix"
|
||||||
|
text = "pluginfix"
|
||||||
|
|
||||||
|
result = booster.boost(text, scores)
|
||||||
|
|
||||||
|
assert result[0][0] == "room_a"
|
||||||
|
assert result[0][1] == pytest.approx(0.85)
|
||||||
|
|
||||||
|
def test_catch_all_keywords_ignored(self, booster: KeywordBooster) -> None:
|
||||||
|
"""Catch-All-Raum hat keine Keywords → nimmt nicht an Boosts teil."""
|
||||||
|
scores: list[tuple[str, float]] = [
|
||||||
|
("room_a", 0.80),
|
||||||
|
("room_catchall", 0.60),
|
||||||
|
]
|
||||||
|
text = "plugin bug"
|
||||||
|
|
||||||
|
result = booster.boost(text, scores)
|
||||||
|
|
||||||
|
# room_a bekommt Boost, room_catchall nicht
|
||||||
|
assert result[0][0] == "room_a"
|
||||||
|
assert result[0][1] == pytest.approx(0.85)
|
||||||
|
# room_catchall bleibt bei 0.60
|
||||||
|
catchall_score = next(s for rid, s in result if rid == "room_catchall")
|
||||||
|
assert catchall_score == pytest.approx(0.60)
|
||||||
|
|
||||||
|
def test_single_score_still_boosted(self, booster: KeywordBooster) -> None:
|
||||||
|
"""Nur ein Raum in Scores → Boost wird trotzdem angewendet."""
|
||||||
|
scores: list[tuple[str, float]] = [
|
||||||
|
("room_a", 0.80),
|
||||||
|
]
|
||||||
|
text = "plugin bug"
|
||||||
|
|
||||||
|
result = booster.boost(text, scores)
|
||||||
|
|
||||||
|
assert len(result) == 1
|
||||||
|
assert result[0][0] == "room_a"
|
||||||
|
assert result[0][1] == pytest.approx(0.85)
|
||||||
|
|
||||||
|
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
# F4.4 — Konfliktlösung: Top-2 Diff < 0.03
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
|
class TestConflictResolution:
|
||||||
|
"""F4.4: Top-2 Diff < 0.03 → Raum mit mehr unique keywords gewinnt (+0.02)."""
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def booster(self) -> KeywordBooster:
|
||||||
|
return KeywordBooster(_make_booster_room_map())
|
||||||
|
|
||||||
|
def test_conflict_room_a_wins_more_unique_keywords(self, booster: KeywordBooster) -> None:
|
||||||
|
"""Top-2 Diff=0.02 < 0.03, room_a hat mehr unique keywords → +0.02."""
|
||||||
|
# Arrange: knappe Top-2
|
||||||
|
scores: list[tuple[str, float]] = [
|
||||||
|
("room_a", 0.87),
|
||||||
|
("room_b", 0.85),
|
||||||
|
]
|
||||||
|
# "plugin" (unique room_a) + "gateway" (shared)
|
||||||
|
# → room_a: 1 unique, room_b: 0 unique
|
||||||
|
text = "plugin gateway"
|
||||||
|
|
||||||
|
# Act
|
||||||
|
result = booster.boost(text, scores)
|
||||||
|
|
||||||
|
# Assert
|
||||||
|
# Phase 1 Boost: room_a +0.05 (plugin unique) → 0.92
|
||||||
|
# Phase 2 Konflikt: diff = 0.92 - 0.85 = 0.07 → KEIN Konflikt mehr!
|
||||||
|
# Wait — der Konflikt-Check passiert NACH dem Boost.
|
||||||
|
# Nach Boost: room_a=0.92, room_b=0.85, diff=0.07 ≥ 0.03 → kein Konflikt.
|
||||||
|
#
|
||||||
|
# Um Konflikt zu testen, brauchen wir Scores OHNE unique-Keyword-Boost,
|
||||||
|
# also nur shared Keywords oder Scores die schon knapp sind.
|
||||||
|
pass # Siehe nächster Test
|
||||||
|
|
||||||
|
def test_conflict_with_shared_keywords_only(self, booster: KeywordBooster) -> None:
|
||||||
|
"""Konflikt bei shared Keywords: Diff < 0.03, unique counts entscheiden.
|
||||||
|
|
||||||
|
Strategy: Scores sind knapp, Text enthält NUR shared Keywords
|
||||||
|
(kein unique Boost in Phase 1) → Diff bleibt < 0.03 →
|
||||||
|
Konfliktlösung greift.
|
||||||
|
"""
|
||||||
|
# Arrange: knappe Scores, nur shared Keyword "gateway"
|
||||||
|
scores: list[tuple[str, float]] = [
|
||||||
|
("room_a", 0.87),
|
||||||
|
("room_b", 0.85),
|
||||||
|
]
|
||||||
|
text = "gateway issue" # "gateway" shared → kein Phase-1 Boost
|
||||||
|
|
||||||
|
# Act
|
||||||
|
result = booster.boost(text, scores)
|
||||||
|
|
||||||
|
# Assert
|
||||||
|
# Phase 1: kein Boost (gateway shared)
|
||||||
|
# Phase 2: diff = 0.87 - 0.85 = 0.02 < 0.03 → Konflikt!
|
||||||
|
# unique_count_1 = 0 (gateway shared, keine unique keywords im Text)
|
||||||
|
# unique_count_2 = 0 → Gleichstand → kein +0.02
|
||||||
|
# → Reihenfolge unverändert
|
||||||
|
assert result[0][0] == "room_a"
|
||||||
|
assert result[0][1] == pytest.approx(0.87)
|
||||||
|
assert result[1][0] == "room_b"
|
||||||
|
assert result[1][1] == pytest.approx(0.85)
|
||||||
|
|
||||||
|
def test_conflict_room_a_wins_by_unique_count(self, booster: KeywordBooster) -> None:
|
||||||
|
"""Konflikt: room_a hat 1 unique keyword, room_b 0 → room_a +0.02.
|
||||||
|
|
||||||
|
Strategy: Scores knapp, Text hat 1 unique keyword für room_a
|
||||||
|
ABER der unique Boost (+0.05) macht Diff ≥ 0.03 → Konflikt verschwindet.
|
||||||
|
Wir brauchen Scores die NACH dem unique Boost noch knapp sind.
|
||||||
|
"""
|
||||||
|
# Arrange: room_b startet höher, room_a hat unique keyword
|
||||||
|
scores: list[tuple[str, float]] = [
|
||||||
|
("room_b", 0.87),
|
||||||
|
("room_a", 0.82),
|
||||||
|
]
|
||||||
|
# "plugin" unique für room_a → +0.05 → room_a=0.87
|
||||||
|
# Nach Boost: room_b=0.87, room_a=0.87, diff=0.00 < 0.03
|
||||||
|
# Konflikt: room_a hat 1 unique ("plugin"), room_b hat 0 → room_a +0.02
|
||||||
|
text = "plugin gateway"
|
||||||
|
|
||||||
|
result = booster.boost(text, scores)
|
||||||
|
|
||||||
|
# room_a: 0.82 + 0.05 (unique boost) + 0.02 (conflict) = 0.89
|
||||||
|
# room_b: 0.87 (gateway shared → kein Boost, 0 unique → kein conflict boost)
|
||||||
|
assert result[0][0] == "room_a"
|
||||||
|
assert result[0][1] == pytest.approx(0.89)
|
||||||
|
assert result[1][0] == "room_b"
|
||||||
|
assert result[1][1] == pytest.approx(0.87)
|
||||||
|
|
||||||
|
def test_conflict_room_b_wins_by_unique_count(self, booster: KeywordBooster) -> None:
|
||||||
|
"""Konflikt: room_b hat mehr unique keywords → room_b +0.02."""
|
||||||
|
scores: list[tuple[str, float]] = [
|
||||||
|
("room_a", 0.87),
|
||||||
|
("room_b", 0.82),
|
||||||
|
]
|
||||||
|
# "docker" unique für room_b → +0.05 → room_b=0.87
|
||||||
|
# Nach Boost: room_a=0.87, room_b=0.87, diff=0.00 < 0.03
|
||||||
|
# Konflikt: room_b hat 1 unique ("docker"), room_a hat 0 → room_b +0.02
|
||||||
|
text = "docker gateway"
|
||||||
|
|
||||||
|
result = booster.boost(text, scores)
|
||||||
|
|
||||||
|
assert result[0][0] == "room_b"
|
||||||
|
assert result[0][1] == pytest.approx(0.89)
|
||||||
|
assert result[1][0] == "room_a"
|
||||||
|
assert result[1][1] == pytest.approx(0.87)
|
||||||
|
|
||||||
|
def test_conflict_tie_no_extra_boost(self, booster: KeywordBooster) -> None:
|
||||||
|
"""Gleichstand bei unique counts → kein zusätzlicher Boost."""
|
||||||
|
scores: list[tuple[str, float]] = [
|
||||||
|
("room_a", 0.87),
|
||||||
|
("room_b", 0.85),
|
||||||
|
]
|
||||||
|
# Nur shared keyword → kein unique Boost, kein unique count
|
||||||
|
text = "gateway"
|
||||||
|
|
||||||
|
result = booster.boost(text, scores)
|
||||||
|
|
||||||
|
# diff = 0.02 < 0.03 → Konflikt-Check
|
||||||
|
# unique_count_1 = 0, unique_count_2 = 0 → Gleichstand → kein +0.02
|
||||||
|
assert result[0][0] == "room_a"
|
||||||
|
assert result[0][1] == pytest.approx(0.87)
|
||||||
|
assert result[1][0] == "room_b"
|
||||||
|
assert result[1][1] == pytest.approx(0.85)
|
||||||
|
|
||||||
|
def test_no_conflict_when_diff_above_threshold(self, booster: KeywordBooster) -> None:
|
||||||
|
"""Diff ≥ 0.03 → keine Konfliktlösung."""
|
||||||
|
scores: list[tuple[str, float]] = [
|
||||||
|
("room_a", 0.90),
|
||||||
|
("room_b", 0.87), # diff = 0.03 → genau an der Grenze
|
||||||
|
]
|
||||||
|
text = "gateway"
|
||||||
|
|
||||||
|
result = booster.boost(text, scores)
|
||||||
|
|
||||||
|
# diff = 0.03 → NICHT < 0.03 → kein Konflikt
|
||||||
|
assert result[0][0] == "room_a"
|
||||||
|
assert result[0][1] == pytest.approx(0.90)
|
||||||
|
assert result[1][0] == "room_b"
|
||||||
|
assert result[1][1] == pytest.approx(0.87)
|
||||||
|
|
||||||
|
def test_conflict_with_multiple_unique_both_sides(self, booster: KeywordBooster) -> None:
|
||||||
|
"""Beide Räume haben unique keywords → der mit MEHR unique gewinnt."""
|
||||||
|
scores: list[tuple[str, float]] = [
|
||||||
|
("room_a", 0.82),
|
||||||
|
("room_b", 0.80),
|
||||||
|
]
|
||||||
|
# "plugin" + "deployment" → 2 unique für room_a → +0.10 → room_a=0.92
|
||||||
|
# "docker" → 1 unique für room_b → +0.05 → room_b=0.85
|
||||||
|
# Nach Boost: diff = 0.07 ≥ 0.03 → kein Konflikt mehr.
|
||||||
|
#
|
||||||
|
# Um Konflikt zu testen: starte mit room_b höher
|
||||||
|
scores2: list[tuple[str, float]] = [
|
||||||
|
("room_b", 0.87),
|
||||||
|
("room_a", 0.77),
|
||||||
|
]
|
||||||
|
# "plugin" + "deployment" → 2 unique für room_a → +0.10 → room_a=0.87
|
||||||
|
# "docker" → 1 unique für room_b → +0.05 → room_b=0.92
|
||||||
|
# Nach Boost: room_b=0.92, room_a=0.87, diff=0.05 ≥ 0.03 → kein Konflikt
|
||||||
|
#
|
||||||
|
# Dritter Versuch: Scores so dass nach Boost diff < 0.03
|
||||||
|
scores3: list[tuple[str, float]] = [
|
||||||
|
("room_b", 0.87),
|
||||||
|
("room_a", 0.82),
|
||||||
|
]
|
||||||
|
# "plugin" + "deployment" → 2 unique für room_a → +0.10 → room_a=0.92
|
||||||
|
# "docker" → 1 unique für room_b → +0.05 → room_b=0.92
|
||||||
|
# Nach Boost: diff=0.00 < 0.03 → Konflikt!
|
||||||
|
# unique_count_1 (room_b) = 1 ("docker")
|
||||||
|
# unique_count_2 (room_a) = 2 ("plugin", "deployment")
|
||||||
|
# → room_a gewinnt → +0.02 → room_a=0.94
|
||||||
|
text = "plugin deployment docker gateway"
|
||||||
|
|
||||||
|
result = booster.boost(text, scores3)
|
||||||
|
|
||||||
|
assert result[0][0] == "room_a"
|
||||||
|
assert result[0][1] == pytest.approx(0.94)
|
||||||
|
assert result[1][0] == "room_b"
|
||||||
|
assert result[1][1] == pytest.approx(0.92)
|
||||||
|
|
||||||
|
|
||||||
|
class TestConflictEdgeCases:
|
||||||
|
"""F4.4b: Konfliktlösung Edge Cases."""
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def booster(self) -> KeywordBooster:
|
||||||
|
return KeywordBooster(_make_booster_room_map())
|
||||||
|
|
||||||
|
def test_single_score_no_conflict_check(self, booster: KeywordBooster) -> None:
|
||||||
|
"""Nur ein Score → kein Konflikt-Check (braucht ≥2)."""
|
||||||
|
scores: list[tuple[str, float]] = [
|
||||||
|
("room_a", 0.80),
|
||||||
|
]
|
||||||
|
text = "plugin gateway"
|
||||||
|
|
||||||
|
result = booster.boost(text, scores)
|
||||||
|
|
||||||
|
assert len(result) == 1
|
||||||
|
assert result[0][0] == "room_a"
|
||||||
|
assert result[0][1] == pytest.approx(0.85) # nur unique Boost
|
||||||
|
|
||||||
|
def test_three_scores_conflict_only_top2(self, booster: KeywordBooster) -> None:
|
||||||
|
"""Bei 3 Scores: Konfliktlösung betrachtet NUR Top-1 und Top-2."""
|
||||||
|
scores: list[tuple[str, float]] = [
|
||||||
|
("room_a", 0.87),
|
||||||
|
("room_b", 0.85),
|
||||||
|
("room_catchall", 0.60),
|
||||||
|
]
|
||||||
|
text = "gateway" # shared → kein unique Boost
|
||||||
|
|
||||||
|
result = booster.boost(text, scores)
|
||||||
|
|
||||||
|
# diff = 0.02 < 0.03 → Konflikt, aber unique_count beide 0 → kein +0.02
|
||||||
|
assert result[0][0] == "room_a"
|
||||||
|
assert result[0][1] == pytest.approx(0.87)
|
||||||
|
assert result[1][0] == "room_b"
|
||||||
|
assert result[1][1] == pytest.approx(0.85)
|
||||||
|
assert result[2][0] == "room_catchall"
|
||||||
|
assert result[2][1] == pytest.approx(0.60)
|
||||||
|
|
||||||
|
def test_reload_rebuilds_mapping(self, booster: KeywordBooster) -> None:
|
||||||
|
"""reload() baut Keyword-Mapping neu (nach RoomMap-Änderung)."""
|
||||||
|
# Merke initiales Verhalten
|
||||||
|
scores: list[tuple[str, float]] = [
|
||||||
|
("room_a", 0.80),
|
||||||
|
("room_b", 0.75),
|
||||||
|
]
|
||||||
|
result_before = booster.boost("plugin bug", scores)
|
||||||
|
assert result_before[0][1] == pytest.approx(0.85)
|
||||||
|
|
||||||
|
# Ändere RoomMap: füge "plugin" auch zu room_b hinzu
|
||||||
|
room_map = booster._room_map
|
||||||
|
room_b_entry = room_map._rooms["room_b"]
|
||||||
|
room_b_entry.keywords_context.append("plugin")
|
||||||
|
|
||||||
|
# Reload
|
||||||
|
booster.reload()
|
||||||
|
|
||||||
|
# Jetzt ist "plugin" shared → kein Boost mehr
|
||||||
|
result_after = booster.boost("plugin bug", scores)
|
||||||
|
assert result_after[0][0] == "room_a"
|
||||||
|
assert result_after[0][1] == pytest.approx(0.80) # unverändert
|
||||||
@@ -0,0 +1,502 @@
|
|||||||
|
"""
|
||||||
|
F4-Tests für RoomIndexManager — Cold-Start und Rebuild.
|
||||||
|
|
||||||
|
Zwei kritische Pfade (Rainer):
|
||||||
|
F4.1 Cold-Start: Leerer/nicht gebauter FAISS-Index → search() scheitert
|
||||||
|
→ Phase-1 übersprungen → LLM-Fallback
|
||||||
|
F4.2 Rebuild: seed_data laden → Embeddings holen → Index bauen
|
||||||
|
→ search() findet korrekten Raum
|
||||||
|
|
||||||
|
Mock-FAISS-Index (faiss-cpu muss NICHT installiert sein).
|
||||||
|
Mock-EmbeddingClient (gibt feste Vektoren zurück, keine echten Ollama-Calls).
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
import pytest
|
||||||
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
# Ensure the archivar package is importable
|
||||||
|
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||||
|
|
||||||
|
from plugin.archivar.room_index import RoomIndexManager, RoomIndexError
|
||||||
|
from plugin.archivar.room_map import RoomMap, RoomEntry
|
||||||
|
from plugin.archivar.classifier import EmbeddingClient
|
||||||
|
|
||||||
|
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
# Mock FAISS
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
|
class MockIndexFlatIP:
|
||||||
|
"""Mock FAISS IndexFlatIP — Kosinus-Ähnlichkeit via Inner Product.
|
||||||
|
|
||||||
|
Speichert Vektoren in einer Liste und berechnet dot-product
|
||||||
|
für search(). Kein echtes FAISS nötig.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, dim: int) -> None:
|
||||||
|
self.d = dim
|
||||||
|
self._vectors: list[np.ndarray] = []
|
||||||
|
self.ntotal: int = 0
|
||||||
|
|
||||||
|
def add(self, matrix: np.ndarray) -> None:
|
||||||
|
"""Füge Vektoren hinzu (wie faiss.IndexFlatIP.add)."""
|
||||||
|
if matrix.ndim == 1:
|
||||||
|
matrix = matrix.reshape(1, -1)
|
||||||
|
for vec in matrix:
|
||||||
|
self._vectors.append(vec.copy())
|
||||||
|
self.ntotal = len(self._vectors)
|
||||||
|
|
||||||
|
def search(
|
||||||
|
self, query_vec: np.ndarray, k: int
|
||||||
|
) -> tuple[np.ndarray, np.ndarray]:
|
||||||
|
"""Suche k nächste Nachbarn (wie faiss.IndexFlatIP.search).
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
(scores, indices) — jeweils shape (1, k_eff).
|
||||||
|
"""
|
||||||
|
k_eff = min(k, self.ntotal)
|
||||||
|
if self.ntotal == 0 or k_eff == 0:
|
||||||
|
return (
|
||||||
|
np.array([[-1.0]], dtype=np.float32),
|
||||||
|
np.array([[-1]], dtype=np.int64),
|
||||||
|
)
|
||||||
|
|
||||||
|
query_flat = query_vec.reshape(-1)
|
||||||
|
sims = np.array([np.dot(v, query_flat) for v in self._vectors])
|
||||||
|
top_k = np.argsort(sims)[::-1][:k_eff]
|
||||||
|
return (
|
||||||
|
np.array([sims[top_k]], dtype=np.float32),
|
||||||
|
np.array([top_k], dtype=np.int64),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class MockFAISSModule:
|
||||||
|
"""Mock faiss module — ersetzt `import faiss` in room_index.py."""
|
||||||
|
|
||||||
|
IndexFlatIP = MockIndexFlatIP
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def write_index(index: MockIndexFlatIP, path: str) -> None:
|
||||||
|
"""No-op: Tests persistieren nicht auf Disk."""
|
||||||
|
pass
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def read_index(path: str) -> MockIndexFlatIP:
|
||||||
|
"""Simuliert 'kein gespeicherter Index'."""
|
||||||
|
raise FileNotFoundError(f"Mock: no saved index at {path}")
|
||||||
|
|
||||||
|
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
# Mock EmbeddingClient
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
|
class MockEmbeddingClient(EmbeddingClient):
|
||||||
|
"""Gibt deterministische, feste Vektoren basierend auf Text-Inhalt zurück.
|
||||||
|
|
||||||
|
Kodiert Raum-Identität in den ersten 4 Dimensionen:
|
||||||
|
dim 0 → #Rocketchat-Plugin (keywords: plugin, rocketchat, adapter, …)
|
||||||
|
dim 1 → #BAT-Team (keywords: bat, trading, docker, …)
|
||||||
|
dim 2 → #LAN-Dokumentation (keywords: lan, netzwerk, proxmox, …)
|
||||||
|
dim 3 → #Protonbridge (keywords: proton, mail, bridge, …)
|
||||||
|
|
||||||
|
Query-Vektor und Raum-Vektor sind nah beieinander wenn sie
|
||||||
|
dieselbe Dimension aktivieren → Kosinus-Ähnlichkeit ≈ 1.0.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, dim: int = 768) -> None:
|
||||||
|
self._dim = dim
|
||||||
|
|
||||||
|
def get_embedding(self, text: str) -> list[float]:
|
||||||
|
text_lower = text.lower()
|
||||||
|
vec = np.zeros(self._dim, dtype=np.float32)
|
||||||
|
|
||||||
|
# ── Dimension 0: Rocketchat-Plugin ─────────────────────────
|
||||||
|
if any(kw in text_lower for kw in [
|
||||||
|
"plugin", "rocketchat", "rc-plugin", "adapter", "ddp",
|
||||||
|
"websocket", "archivar", "routing", "gateway-integration",
|
||||||
|
"button", "onboarding", "move-request", "embedding",
|
||||||
|
"faiss", "phase-1", "intent-klassifikation",
|
||||||
|
"room-map.json", "deployment", "soul.md",
|
||||||
|
]):
|
||||||
|
vec[0] = 1.0
|
||||||
|
|
||||||
|
# ── Dimension 1: BAT-Team ─────────────────────────────────
|
||||||
|
if any(kw in text_lower for kw in [
|
||||||
|
"bat", "trading", "docker", "next.js", "prisma", "api",
|
||||||
|
"krypto", "wyckoff", "container", "pre-prod", ".45",
|
||||||
|
"build-vm", ".101", "pnpm", "postgresql", "pg_dump",
|
||||||
|
"api_key", "narrensicher", "snapshot", "database_url",
|
||||||
|
"tor", "ssh-key",
|
||||||
|
]):
|
||||||
|
vec[1] = 1.0
|
||||||
|
|
||||||
|
# ── Dimension 2: LAN-Dokumentation ────────────────────────
|
||||||
|
if any(kw in text_lower for kw in [
|
||||||
|
"lan", "dokumentation", "homelab", "netzwerk", "proxmox",
|
||||||
|
"subnetze", "ip-adressen", "router", "switch", "heimnetz",
|
||||||
|
"rzbln", "vlan", "firewall", "pfsense", "server",
|
||||||
|
"infrastruktur", "verkabelung", "dhcp", "dns", "samba",
|
||||||
|
]):
|
||||||
|
vec[2] = 1.0
|
||||||
|
|
||||||
|
# ── Dimension 3: Protonbridge-Plugin ──────────────────────
|
||||||
|
if any(kw in text_lower for kw in [
|
||||||
|
"proton", "bridge", "mail", "email", "imap", "smtp",
|
||||||
|
"protonmail", "himalaya", "pr #39288", "th0rgal",
|
||||||
|
"proton-api", "passwort",
|
||||||
|
]):
|
||||||
|
vec[3] = 1.0
|
||||||
|
|
||||||
|
# ── Normalisieren (für Kosinus-Ähnlichkeit via IP) ────────
|
||||||
|
norm = float(np.linalg.norm(vec))
|
||||||
|
if norm > 0.0:
|
||||||
|
vec = vec / norm
|
||||||
|
else:
|
||||||
|
# Fallback: schwaches Signal in Dimension 4 (matched keinen Raum)
|
||||||
|
vec[4] = 1.0
|
||||||
|
vec = vec / np.linalg.norm(vec)
|
||||||
|
|
||||||
|
return vec.tolist()
|
||||||
|
|
||||||
|
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
# Helpers
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
|
def _make_room_map_with_seed_rooms() -> RoomMap:
|
||||||
|
"""Erzeugt eine RoomMap mit Räumen, die den seed_data-Einträgen entsprechen.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
RoomMap mit 4 thematischen Räumen + 1 Catch-All.
|
||||||
|
"""
|
||||||
|
rooms: dict[str, RoomEntry] = {
|
||||||
|
"6a19b0ff02aeecd36b1aa16c": RoomEntry(
|
||||||
|
room_id="6a19b0ff02aeecd36b1aa16c",
|
||||||
|
name="#Rocketchat-Plugin",
|
||||||
|
theme=(
|
||||||
|
"RC-Plugin-Entwicklung, Adapter, DDP, WebSocket, Buttons, "
|
||||||
|
"Archivar, Routing, Gateway-Integration, Rocket.Chat-API"
|
||||||
|
),
|
||||||
|
keywords_100=["rocketchat", "rc", "ddp", "websocket"],
|
||||||
|
keywords_context=[
|
||||||
|
"plugin", "adapter", "gateway", "archivar", "routing",
|
||||||
|
"button", "deployment", "onboarding", "embedding", "faiss",
|
||||||
|
],
|
||||||
|
catch_all=False,
|
||||||
|
),
|
||||||
|
"6a049d493a62ef8f1ead2320": RoomEntry(
|
||||||
|
room_id="6a049d493a62ef8f1ead2320",
|
||||||
|
name="#BAT-Team",
|
||||||
|
theme=(
|
||||||
|
"BAT Trading Platform, Docker, Next.js, Prisma, API, "
|
||||||
|
"Web-UI, Krypto-Analyse, Wyckoff-Methodik"
|
||||||
|
),
|
||||||
|
keywords_100=["bat", "bat-team", "trading", "krypto"],
|
||||||
|
keywords_context=[
|
||||||
|
"docker", "next.js", "prisma", "api", "container",
|
||||||
|
"pre-prod", "postgresql", "pg_dump",
|
||||||
|
],
|
||||||
|
catch_all=False,
|
||||||
|
),
|
||||||
|
"6a1c56d4b73efec2bebec2db": RoomEntry(
|
||||||
|
room_id="6a1c56d4b73efec2bebec2db",
|
||||||
|
name="#LAN-Dokumentation",
|
||||||
|
theme=(
|
||||||
|
"LAN Dokumentation, Homelab, Netzwerk, Proxmox, Subnetze, "
|
||||||
|
"IP-Adressen, Router, Switch, Heimnetz"
|
||||||
|
),
|
||||||
|
keywords_100=["lan", "dokumentation", "homelab"],
|
||||||
|
keywords_context=[
|
||||||
|
"netzwerk", "proxmox", "subnetze", "router", "switch",
|
||||||
|
"firewall", "pfsense", "server", "infrastruktur",
|
||||||
|
],
|
||||||
|
catch_all=False,
|
||||||
|
),
|
||||||
|
"69f8beaef06dba03be82f9fc": RoomEntry(
|
||||||
|
room_id="69f8beaef06dba03be82f9fc",
|
||||||
|
name="#Protonbridge-Plugin",
|
||||||
|
theme=(
|
||||||
|
"Proton Mail Bridge, Hermes Mailschnittstelle, "
|
||||||
|
"Email-Integration, IMAP, SMTP, ProtonMail"
|
||||||
|
),
|
||||||
|
keywords_100=["proton", "bridge", "mail"],
|
||||||
|
keywords_context=[
|
||||||
|
"email", "imap", "smtp", "protonmail", "himalaya", "passwort",
|
||||||
|
],
|
||||||
|
catch_all=False,
|
||||||
|
),
|
||||||
|
"catch_all_room": RoomEntry(
|
||||||
|
room_id="catch_all_room",
|
||||||
|
name="DM Admin",
|
||||||
|
theme="Catch-All für nicht zuordenbare Nachrichten",
|
||||||
|
keywords_100=[],
|
||||||
|
keywords_context=[],
|
||||||
|
catch_all=True,
|
||||||
|
),
|
||||||
|
}
|
||||||
|
return RoomMap(
|
||||||
|
rooms=rooms,
|
||||||
|
excluded_room_ids=set(),
|
||||||
|
fact_store_path=Path("/tmp/test_docs"),
|
||||||
|
version=2,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
# F4.1 — Cold-Start
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
|
class TestColdStart:
|
||||||
|
"""F4.1: Leerer/nicht gebauter FAISS-Index → Phase-1 übersprungen.
|
||||||
|
|
||||||
|
Der Router fängt RoomIndexError und fällt an LLM-Fallback durch.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def test_search_raises_when_index_not_built(self) -> None:
|
||||||
|
"""Cold-Start: Index nicht gebaut → search() raises RoomIndexError.
|
||||||
|
|
||||||
|
Arrange: RoomIndexManager ohne build_index()/load()
|
||||||
|
Act: search() aufrufen
|
||||||
|
Assert: RoomIndexError mit 'not built or loaded'
|
||||||
|
"""
|
||||||
|
room_map = _make_room_map_with_seed_rooms()
|
||||||
|
emb_client = MockEmbeddingClient(dim=768)
|
||||||
|
|
||||||
|
with patch("plugin.archivar.room_index.faiss", MockFAISSModule):
|
||||||
|
mgr = RoomIndexManager(room_map, emb_client, embedding_dim=768)
|
||||||
|
|
||||||
|
# Index ist NICHT gebaut — Cold-Start
|
||||||
|
assert not mgr.is_built
|
||||||
|
assert mgr.size == 0
|
||||||
|
|
||||||
|
query_vec = emb_client.get_embedding("Das Plugin hat einen Bug")
|
||||||
|
|
||||||
|
with pytest.raises(RoomIndexError, match="not built or loaded"):
|
||||||
|
mgr.search(query_vec, k=3)
|
||||||
|
|
||||||
|
def test_is_built_false_on_fresh_instance(self) -> None:
|
||||||
|
"""Cold-Start: Frische Instanz → is_built=False, size=0."""
|
||||||
|
room_map = _make_room_map_with_seed_rooms()
|
||||||
|
emb_client = MockEmbeddingClient(dim=768)
|
||||||
|
|
||||||
|
with patch("plugin.archivar.room_index.faiss", MockFAISSModule):
|
||||||
|
mgr = RoomIndexManager(room_map, emb_client, embedding_dim=768)
|
||||||
|
|
||||||
|
assert not mgr.is_built
|
||||||
|
assert mgr.size == 0
|
||||||
|
assert mgr.room_ids == []
|
||||||
|
|
||||||
|
def test_load_returns_false_when_no_saved_index(self) -> None:
|
||||||
|
"""Cold-Start: load() gibt False zurück wenn kein Index auf Disk."""
|
||||||
|
room_map = _make_room_map_with_seed_rooms()
|
||||||
|
emb_client = MockEmbeddingClient(dim=768)
|
||||||
|
|
||||||
|
with patch("plugin.archivar.room_index.faiss", MockFAISSModule):
|
||||||
|
mgr = RoomIndexManager(room_map, emb_client, embedding_dim=768)
|
||||||
|
|
||||||
|
# MockFAISSModule.read_index wirft FileNotFoundError
|
||||||
|
result = mgr.load()
|
||||||
|
assert result is False
|
||||||
|
assert not mgr.is_built
|
||||||
|
|
||||||
|
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
# F4.2 — Rebuild
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
|
class TestRebuild:
|
||||||
|
"""F4.2: seed_data laden → Embeddings holen → Index bauen → search() findet korrekten Raum."""
|
||||||
|
|
||||||
|
def test_build_index_from_seed_rooms(self) -> None:
|
||||||
|
"""Rebuild: Index aus seed_data-Räumen bauen — 4 Räume, kein Catch-All."""
|
||||||
|
room_map = _make_room_map_with_seed_rooms()
|
||||||
|
emb_client = MockEmbeddingClient(dim=768)
|
||||||
|
|
||||||
|
with patch("plugin.archivar.room_index.faiss", MockFAISSModule):
|
||||||
|
mgr = RoomIndexManager(room_map, emb_client, embedding_dim=768)
|
||||||
|
|
||||||
|
# Act
|
||||||
|
mgr.build_index()
|
||||||
|
|
||||||
|
# Assert
|
||||||
|
assert mgr.is_built
|
||||||
|
assert mgr.size == 4 # 4 nicht-catch-all Räume
|
||||||
|
assert "catch_all_room" not in mgr.room_ids
|
||||||
|
# Alle seed_data Raum-IDs müssen im Index sein
|
||||||
|
assert "6a19b0ff02aeecd36b1aa16c" in mgr.room_ids
|
||||||
|
assert "6a049d493a62ef8f1ead2320" in mgr.room_ids
|
||||||
|
assert "6a1c56d4b73efec2bebec2db" in mgr.room_ids
|
||||||
|
assert "69f8beaef06dba03be82f9fc" in mgr.room_ids
|
||||||
|
|
||||||
|
def test_search_finds_plugin_room(self) -> None:
|
||||||
|
"""Rebuild: Plugin-Query → #Rocketchat-Plugin als Top-1."""
|
||||||
|
room_map = _make_room_map_with_seed_rooms()
|
||||||
|
emb_client = MockEmbeddingClient(dim=768)
|
||||||
|
|
||||||
|
with patch("plugin.archivar.room_index.faiss", MockFAISSModule):
|
||||||
|
mgr = RoomIndexManager(room_map, emb_client, embedding_dim=768)
|
||||||
|
mgr.build_index()
|
||||||
|
|
||||||
|
# Act: Query mit Plugin-Keywords
|
||||||
|
query_vec = emb_client.get_embedding(
|
||||||
|
"Das Plugin hat einen Bug im Adapter"
|
||||||
|
)
|
||||||
|
results = mgr.search(query_vec, k=3)
|
||||||
|
|
||||||
|
# Assert
|
||||||
|
assert len(results) >= 1
|
||||||
|
top_room_id, top_score = results[0]
|
||||||
|
assert top_room_id == "6a19b0ff02aeecd36b1aa16c"
|
||||||
|
assert top_score > 0.5 # hohe Kosinus-Ähnlichkeit
|
||||||
|
|
||||||
|
def test_search_finds_bat_room(self) -> None:
|
||||||
|
"""Rebuild: BAT-Query → #BAT-Team als Top-1."""
|
||||||
|
room_map = _make_room_map_with_seed_rooms()
|
||||||
|
emb_client = MockEmbeddingClient(dim=768)
|
||||||
|
|
||||||
|
with patch("plugin.archivar.room_index.faiss", MockFAISSModule):
|
||||||
|
mgr = RoomIndexManager(room_map, emb_client, embedding_dim=768)
|
||||||
|
mgr.build_index()
|
||||||
|
|
||||||
|
query_vec = emb_client.get_embedding(
|
||||||
|
"Docker Container für Trading Platform"
|
||||||
|
)
|
||||||
|
results = mgr.search(query_vec, k=3)
|
||||||
|
|
||||||
|
assert len(results) >= 1
|
||||||
|
top_room_id, top_score = results[0]
|
||||||
|
assert top_room_id == "6a049d493a62ef8f1ead2320"
|
||||||
|
assert top_score > 0.5
|
||||||
|
|
||||||
|
def test_search_finds_lan_room(self) -> None:
|
||||||
|
"""Rebuild: LAN-Query → #LAN-Dokumentation als Top-1."""
|
||||||
|
room_map = _make_room_map_with_seed_rooms()
|
||||||
|
emb_client = MockEmbeddingClient(dim=768)
|
||||||
|
|
||||||
|
with patch("plugin.archivar.room_index.faiss", MockFAISSModule):
|
||||||
|
mgr = RoomIndexManager(room_map, emb_client, embedding_dim=768)
|
||||||
|
mgr.build_index()
|
||||||
|
|
||||||
|
query_vec = emb_client.get_embedding(
|
||||||
|
"Netzwerk Dokumentation für Proxmox Server"
|
||||||
|
)
|
||||||
|
results = mgr.search(query_vec, k=3)
|
||||||
|
|
||||||
|
assert len(results) >= 1
|
||||||
|
top_room_id, top_score = results[0]
|
||||||
|
assert top_room_id == "6a1c56d4b73efec2bebec2db"
|
||||||
|
assert top_score > 0.5
|
||||||
|
|
||||||
|
def test_search_finds_proton_room(self) -> None:
|
||||||
|
"""Rebuild: Proton-Query → #Protonbridge-Plugin als Top-1."""
|
||||||
|
room_map = _make_room_map_with_seed_rooms()
|
||||||
|
emb_client = MockEmbeddingClient(dim=768)
|
||||||
|
|
||||||
|
with patch("plugin.archivar.room_index.faiss", MockFAISSModule):
|
||||||
|
mgr = RoomIndexManager(room_map, emb_client, embedding_dim=768)
|
||||||
|
mgr.build_index()
|
||||||
|
|
||||||
|
query_vec = emb_client.get_embedding(
|
||||||
|
"Proton Mail Bridge IMAP SMTP"
|
||||||
|
)
|
||||||
|
results = mgr.search(query_vec, k=3)
|
||||||
|
|
||||||
|
assert len(results) >= 1
|
||||||
|
top_room_id, top_score = results[0]
|
||||||
|
assert top_room_id == "69f8beaef06dba03be82f9fc"
|
||||||
|
assert top_score > 0.5
|
||||||
|
|
||||||
|
def test_search_text_convenience(self) -> None:
|
||||||
|
"""Rebuild: search_text() Convenience-Methode funktioniert."""
|
||||||
|
room_map = _make_room_map_with_seed_rooms()
|
||||||
|
emb_client = MockEmbeddingClient(dim=768)
|
||||||
|
|
||||||
|
with patch("plugin.archivar.room_index.faiss", MockFAISSModule):
|
||||||
|
mgr = RoomIndexManager(room_map, emb_client, embedding_dim=768)
|
||||||
|
mgr.build_index()
|
||||||
|
|
||||||
|
results = mgr.search_text(
|
||||||
|
"FAISS Phase-1 Routing für Archivar", k=3
|
||||||
|
)
|
||||||
|
|
||||||
|
assert len(results) >= 1
|
||||||
|
top_room_id, _ = results[0]
|
||||||
|
assert top_room_id == "6a19b0ff02aeecd36b1aa16c"
|
||||||
|
|
||||||
|
def test_rebuild_after_room_removed(self) -> None:
|
||||||
|
"""Rebuild: rebuild() nach Raum-Entfernung produziert korrekten Index."""
|
||||||
|
room_map = _make_room_map_with_seed_rooms()
|
||||||
|
emb_client = MockEmbeddingClient(dim=768)
|
||||||
|
|
||||||
|
with patch("plugin.archivar.room_index.faiss", MockFAISSModule):
|
||||||
|
mgr = RoomIndexManager(room_map, emb_client, embedding_dim=768)
|
||||||
|
mgr.build_index()
|
||||||
|
assert mgr.size == 4
|
||||||
|
|
||||||
|
# Simuliere: Proton-Raum aus RoomMap entfernt
|
||||||
|
del room_map._rooms["69f8beaef06dba03be82f9fc"]
|
||||||
|
mgr.rebuild()
|
||||||
|
|
||||||
|
assert mgr.size == 3
|
||||||
|
assert "69f8beaef06dba03be82f9fc" not in mgr.room_ids
|
||||||
|
# Andere Räume noch da
|
||||||
|
assert "6a19b0ff02aeecd36b1aa16c" in mgr.room_ids
|
||||||
|
|
||||||
|
def test_min_score_filters_weak_matches(self) -> None:
|
||||||
|
"""Rebuild: min_score filtert schwache Treffer aus.
|
||||||
|
|
||||||
|
Query ohne Keyword-Match → Vektor in Dimension 4 →
|
||||||
|
dot-product ≈ 0 mit allen Räumen → alle unter min_score=0.5.
|
||||||
|
"""
|
||||||
|
room_map = _make_room_map_with_seed_rooms()
|
||||||
|
emb_client = MockEmbeddingClient(dim=768)
|
||||||
|
|
||||||
|
with patch("plugin.archivar.room_index.faiss", MockFAISSModule):
|
||||||
|
mgr = RoomIndexManager(room_map, emb_client, embedding_dim=768)
|
||||||
|
mgr.build_index()
|
||||||
|
|
||||||
|
# "völlig fremdes Thema" matched keine Keywords
|
||||||
|
# → MockEmbeddingClient gibt Vektor mit Signal nur in dim 4
|
||||||
|
query_vec = emb_client.get_embedding("völlig fremdes Thema")
|
||||||
|
results = mgr.search(query_vec, k=3, min_score=0.5)
|
||||||
|
|
||||||
|
# Alle Scores ≈ 0.0 → unter min_score → leere Liste
|
||||||
|
assert len(results) == 0
|
||||||
|
|
||||||
|
def test_search_respects_k_limit(self) -> None:
|
||||||
|
"""Rebuild: search() respektiert k-Limit."""
|
||||||
|
room_map = _make_room_map_with_seed_rooms()
|
||||||
|
emb_client = MockEmbeddingClient(dim=768)
|
||||||
|
|
||||||
|
with patch("plugin.archivar.room_index.faiss", MockFAISSModule):
|
||||||
|
mgr = RoomIndexManager(room_map, emb_client, embedding_dim=768)
|
||||||
|
mgr.build_index()
|
||||||
|
|
||||||
|
# Query die mehrere Räume matched (dim 0 + dim 1)
|
||||||
|
query_vec = emb_client.get_embedding("plugin gateway docker")
|
||||||
|
results = mgr.search(query_vec, k=2)
|
||||||
|
|
||||||
|
assert len(results) <= 2
|
||||||
|
|
||||||
|
def test_stats_after_build(self) -> None:
|
||||||
|
"""Rebuild: stats() liefert korrekte Diagnosedaten nach build_index()."""
|
||||||
|
room_map = _make_room_map_with_seed_rooms()
|
||||||
|
emb_client = MockEmbeddingClient(dim=768)
|
||||||
|
|
||||||
|
with patch("plugin.archivar.room_index.faiss", MockFAISSModule):
|
||||||
|
mgr = RoomIndexManager(room_map, emb_client, embedding_dim=768)
|
||||||
|
mgr.build_index()
|
||||||
|
|
||||||
|
stats = mgr.stats()
|
||||||
|
assert stats["is_built"] is True
|
||||||
|
assert stats["room_count"] == 4
|
||||||
|
assert stats["embedding_dim"] == 768
|
||||||
|
assert stats["version"] == 2
|
||||||
|
assert stats["built_at"] > 0.0
|
||||||
|
assert stats["built_at_iso"] is not None
|
||||||
Reference in New Issue
Block a user