Files
Hermes_rocket.chat_Plugin/tests/test_booster.py
T

739 lines
30 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""
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.10 = 0.90
# room_b: 0.75 (unverändert)
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.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.10 + 2×0.05 = 1.15
# room_a: 0.80 (kein Keyword-Match)
assert result[0][0] == "room_b"
assert result[0][1] == pytest.approx(1.15)
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.10 + 2×0.05 = 1.10
# room_b: 0.80 (gateway ist shared → kein Boost)
assert result[0][0] == "room_a"
assert result[0][1] == pytest.approx(1.10)
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.10 = 0.80
assert result[0][0] == "room_a" # 0.80 == 0.80, room_a hat unique keyword
assert result[1][0] == "room_b"
assert result[1][1] == pytest.approx(0.80)
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.10 = 0.90
# room_b: 0.75 (gateway shared → kein Boost)
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.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.90)
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.90)
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.90)
# 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.90)
# ═══════════════════════════════════════════════════════════════════════════
# 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.10 (unique boost) + 0.05 (conflict) = 0.97
# 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.97)
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.97)
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(1.07)
assert result[1][0] == "room_b"
assert result[1][1] == pytest.approx(0.97)
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.90) # 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.90)
# Ä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
# ═══════════════════════════════════════════════════════════════════════════
# M13: cleanup_orphaned_rooms Tests
# ═══════════════════════════════════════════════════════════════════════════
class TestBoosterCleanup:
"""M13: Tests für KeywordBooster.cleanup_orphaned_rooms()."""
@pytest.fixture
def booster(self) -> KeywordBooster:
return KeywordBooster(_make_booster_room_map())
def test_cleanup_rebuilds_mapping(self, booster: KeywordBooster) -> None:
"""cleanup_orphaned_rooms() baut das Mapping aus der aktuellen RoomMap neu."""
before = len(booster._keyword_to_rooms)
# Entferne room_b aus der RoomMap (simuliert GC)
del booster._room_map._rooms["room_b"]
# Cleanup mit nur noch room_a + room_catchall als gültig
after = booster.cleanup_orphaned_rooms({"room_a", "room_catchall"})
# Mapping sollte kleiner sein (room_b's unique keywords sind weg)
assert after < before
# "bat" war unique für room_b → sollte nicht mehr im Mapping sein
assert "bat" not in booster._keyword_to_rooms
# "plugin" war unique für room_a → sollte noch da sein
assert "plugin" in booster._keyword_to_rooms
assert booster._keyword_to_rooms["plugin"] == {"room_a"}
def test_cleanup_no_orphans_returns_same_count(self, booster: KeywordBooster) -> None:
"""Keine orphaned Räume → Mapping bleibt gleich groß."""
before = len(booster._keyword_to_rooms)
after = booster.cleanup_orphaned_rooms({"room_a", "room_b", "room_catchall"})
assert after == before
def test_cleanup_all_rooms_removed_returns_zero(self, booster: KeywordBooster) -> None:
"""Alle nicht-catch-all Räume entfernt → leeres Mapping."""
# Entferne ALLE nicht-catch-all Räume
del booster._room_map._rooms["room_a"]
del booster._room_map._rooms["room_b"]
# room_catchall bleibt (catch_all=True, wird von _build_mapping ignoriert)
after = booster.cleanup_orphaned_rooms({"room_catchall"})
assert after == 0
assert len(booster._keyword_to_rooms) == 0
def test_cleanup_then_boost_still_works(self, booster: KeywordBooster) -> None:
"""Nach Cleanup: Boost funktioniert korrekt mit bereinigtem Mapping."""
# Entferne room_b
del booster._room_map._rooms["room_b"]
booster.cleanup_orphaned_rooms({"room_a", "room_catchall"})
scores: list[tuple[str, float]] = [
("room_a", 0.80),
("room_catchall", 0.60),
]
result = booster.boost("plugin bug", scores)
# "plugin" ist unique für room_a → +0.10 (tatsächlicher Boost-Wert)
assert result[0][0] == "room_a"
assert result[0][1] == pytest.approx(0.90)
# ═══════════════════════════════════════════════════════════════════════════
# V8.2 A3: 90-Tage-Keyword-Booster-Demotion
# ═══════════════════════════════════════════════════════════════════════════
class TestV82A3RecordMatches:
"""V8.2 A3: _record_matches() setzt last_matched-Timestamps."""
@pytest.fixture
def booster(self) -> KeywordBooster:
return KeywordBooster(_make_booster_room_map())
def test_record_matches_sets_timestamp_for_100_keywords(self, booster: KeywordBooster) -> None:
"""_record_matches setzt _keyword_last_matched für keywords_100."""
# "rocketchat" ist keywords_100 für room_a
booster._record_matches("rocketchat websocket", ["rocketchat"])
entry = booster._room_map.get_room_by_id("room_a")
assert entry is not None
assert "rocketchat" in entry._keyword_last_matched
# Timestamp sollte ISO-Format sein
from datetime import datetime
ts = entry._keyword_last_matched["rocketchat"]
datetime.fromisoformat(ts) # wirft ValueError wenn nicht ISO
def test_record_matches_skips_context_keywords(self, booster: KeywordBooster) -> None:
"""_record_matches tracked NUR keywords_100, nicht keywords_context."""
# "plugin" ist keywords_context für room_a (nicht keywords_100)
booster._record_matches("plugin bug", ["plugin"])
entry = booster._room_map.get_room_by_id("room_a")
assert entry is not None
# "plugin" ist context, nicht 100 → kein Timestamp
assert "plugin" not in entry._keyword_last_matched
def test_record_matches_handles_shared_keyword(self, booster: KeywordBooster) -> None:
"""_record_matches tracked shared keywords in allen betroffenen Räumen."""
# "gateway" ist keywords_context in room_a UND room_b
# → kein keywords_100 → keine Timestamps
booster._record_matches("gateway issue", ["gateway"])
entry_a = booster._room_map.get_room_by_id("room_a")
entry_b = booster._room_map.get_room_by_id("room_b")
assert "gateway" not in entry_a._keyword_last_matched
assert "gateway" not in entry_b._keyword_last_matched
def test_record_matches_handles_unknown_keyword(self, booster: KeywordBooster) -> None:
"""_record_matches mit unbekanntem Keyword → kein Fehler."""
# Sollte nicht crashen
booster._record_matches("xyz unknown", ["xyz"])
# Kein Assert nötig — kein Crash = bestanden
def test_boost_calls_record_matches(self, booster: KeywordBooster) -> None:
"""boost() ruft _record_matches() auf → Timestamps werden gesetzt."""
scores: list[tuple[str, float]] = [
("room_a", 0.80),
("room_b", 0.75),
]
# "rocketchat" ist keywords_100 für room_a
booster.boost("rocketchat plugin", scores)
entry = booster._room_map.get_room_by_id("room_a")
assert "rocketchat" in entry._keyword_last_matched
class TestV82A3BoosterDemotion:
"""V8.2 A3: KeywordBooster.demote_stale_keywords() delegiert an RoomMap."""
@pytest.fixture
def booster(self) -> KeywordBooster:
return KeywordBooster(_make_booster_room_map())
def test_demote_stale_delegates_to_room_map(self, booster: KeywordBooster) -> None:
"""demote_stale_keywords() delegiert an RoomMap und baut Mapping neu."""
from datetime import datetime, timedelta
# Setze "rocketchat" (keywords_100 für room_a) auf 91 Tage alt
old_date = (datetime.now() - timedelta(days=91)).isoformat()
booster._room_map.set_keyword_last_matched("room_a", "rocketchat", old_date)
# Vorher: "rocketchat" ist im Mapping
assert "rocketchat" in booster._keyword_to_rooms
demoted = booster.demote_stale_keywords(max_age_days=90)
assert demoted >= 1
# Nach Demotion: "rocketchat" ist nicht mehr keywords_100
entry = booster._room_map.get_room_by_id("room_a")
assert "rocketchat" not in entry.keywords_100
assert "rocketchat" in entry.keywords_context
# Mapping wurde neu gebaut → "rocketchat" ist jetzt als context-Keyword im Mapping
assert "rocketchat" in booster._keyword_to_rooms
def test_demote_no_stale_returns_zero(self, booster: KeywordBooster) -> None:
"""Keine stale Keywords → demote_stale_keywords() gibt 0 zurück."""
# Keine last_matched gesetzt → initial, nicht demoten
demoted = booster.demote_stale_keywords(max_age_days=90)
assert demoted == 0
def test_demote_rebuilds_mapping(self, booster: KeywordBooster) -> None:
"""Nach Demotion: Mapping enthält demoted Keywords als context-Keywords."""
from datetime import datetime, timedelta
old_date = (datetime.now() - timedelta(days=100)).isoformat()
booster._room_map.set_keyword_last_matched("room_a", "rocketchat", old_date)
booster._room_map.set_keyword_last_matched("room_a", "ddp", old_date)
demoted = booster.demote_stale_keywords(max_age_days=90)
assert demoted == 2
# Beide Keywords sind jetzt im Mapping (als context)
assert "rocketchat" in booster._keyword_to_rooms
assert "ddp" in booster._keyword_to_rooms
def test_demote_then_boost_still_works(self, booster: KeywordBooster) -> None:
"""Nach Demotion: boost() funktioniert korrekt mit neuem Mapping."""
from datetime import datetime, timedelta
old_date = (datetime.now() - timedelta(days=100)).isoformat()
booster._room_map.set_keyword_last_matched("room_a", "rocketchat", old_date)
booster.demote_stale_keywords(max_age_days=90)
# "rocketchat" ist jetzt context-Keyword → unique Boost funktioniert noch
scores: list[tuple[str, float]] = [
("room_a", 0.80),
("room_b", 0.75),
]
result = booster.boost("rocketchat issue", scores)
# room_a bekommt +0.10 (unique keyword, jetzt context)
assert result[0][0] == "room_a"
assert result[0][1] == pytest.approx(0.90)