P-028 Mitigation: split keyword matching — match_keyword_exact for kw100, match_keyword for kwctx
TEIL 1 — booster.py: - Split _keyword_to_rooms into _kw100_to_rooms + _kwctx_to_rooms - keywords_100 matched via match_keyword_exact (no fuzzy/stemming, hyphen-insensitive) - keywords_context matched via match_keyword (fuzzy/stemming preserved) - _build_mapping() builds both mappings separately - boost() uses separate matchers per keyword type - _count_unique_matches() checks both mappings with respective matchers - _record_matches() now takes only matched_kw100 (context keywords never tracked) - cleanup_orphaned_rooms() rebuilds both mappings TEIL 2 — room-map.json (data, not in git): - Removed 39 space-variant dual keywords (e.g. 'presence engine' removed, 'presence-engine' kept). No longer needed since match_keyword_exact is hyphen-insensitive. - Backup: .bak-pre-curation-20260805 Tests: 35/35 passed (pytest -k booster)
This commit is contained in:
+77
-35
@@ -7,6 +7,12 @@ Verfeinert FAISS-Suchergebnisse durch Keyword-Analyse:
|
||||
- Mehrdeutige Keywords sind neutral
|
||||
- Bei knappen Top-2 entscheidet die Anzahl eindeutiger Keywords (+0.05 Boost)
|
||||
|
||||
P-028 Mitigation (2026-08-05):
|
||||
- keywords_100 werden mit match_keyword_exact gematcht (kein Fuzzy/Stemming,
|
||||
nur hyphen-insensitiv) → verhindert False Positives wie 'homelab' ↔ 'homelabor'
|
||||
- keywords_context werden mit match_keyword gematcht (mit Fuzzy/Stemming,
|
||||
da Context-Keywords weniger präzise sein sollen)
|
||||
|
||||
Usage::
|
||||
|
||||
from .room_map import RoomMap
|
||||
@@ -27,7 +33,7 @@ import logging
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Dict, List, Set, Tuple
|
||||
|
||||
from .keyword_matcher import match_keyword
|
||||
from .keyword_matcher import match_keyword, match_keyword_exact
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -35,8 +41,12 @@ logger = logging.getLogger(__name__)
|
||||
class KeywordBooster:
|
||||
"""Keyword-basierter Score-Booster für RoomIndexManager.search()-Ergebnisse.
|
||||
|
||||
Baut aus einer geladenen RoomMap ein Mapping: keyword → set of room_ids.
|
||||
Wendet dann Boosts auf FAISS-Scores an basierend auf Keyword-Eindeutigkeit.
|
||||
Baut aus einer geladenen RoomMap zwei Mappings:
|
||||
- _kw100_to_rooms: keyword → set of room_ids (aus keywords_100)
|
||||
- _kwctx_to_rooms: keyword → set of room_ids (aus keywords_context)
|
||||
|
||||
keywords_100 werden mit match_keyword_exact gematcht (P-028),
|
||||
keywords_context mit match_keyword (Fuzzy/Stemming).
|
||||
"""
|
||||
|
||||
def __init__(self, room_map) -> None:
|
||||
@@ -46,34 +56,45 @@ class KeywordBooster:
|
||||
room_map: Eine ``RoomMap``-Instanz (aus ``room_map.py``).
|
||||
"""
|
||||
self._room_map = room_map
|
||||
self._keyword_to_rooms: Dict[str, Set[str]] = {}
|
||||
self._kw100_to_rooms: Dict[str, Set[str]] = {}
|
||||
self._kwctx_to_rooms: Dict[str, Set[str]] = {}
|
||||
self._build_mapping()
|
||||
|
||||
# ── Mapping ───────────────────────────────────────────────────────
|
||||
|
||||
def _build_mapping(self) -> None:
|
||||
"""Baut keyword → set(room_ids) aus allen keywords_100 + keywords_context."""
|
||||
self._keyword_to_rooms.clear()
|
||||
"""Baut kw100 → set(room_ids) und kwctx → set(room_ids) getrennt auf."""
|
||||
self._kw100_to_rooms.clear()
|
||||
self._kwctx_to_rooms.clear()
|
||||
|
||||
for room_id, entry in self._room_map.rooms.items():
|
||||
if entry.catch_all:
|
||||
continue # Catch-All nimmt nicht an Keyword-Boosts teil
|
||||
|
||||
all_keywords: List[str] = []
|
||||
all_keywords.extend(entry.keywords_100)
|
||||
all_keywords.extend(entry.keywords_context)
|
||||
|
||||
for kw in all_keywords:
|
||||
# keywords_100 → _kw100_to_rooms
|
||||
for kw in entry.keywords_100:
|
||||
kw_lower = kw.lower().strip()
|
||||
if not kw_lower:
|
||||
continue
|
||||
if kw_lower not in self._keyword_to_rooms:
|
||||
self._keyword_to_rooms[kw_lower] = set()
|
||||
self._keyword_to_rooms[kw_lower].add(room_id)
|
||||
if kw_lower not in self._kw100_to_rooms:
|
||||
self._kw100_to_rooms[kw_lower] = set()
|
||||
self._kw100_to_rooms[kw_lower].add(room_id)
|
||||
|
||||
# keywords_context → _kwctx_to_rooms
|
||||
for kw in entry.keywords_context:
|
||||
kw_lower = kw.lower().strip()
|
||||
if not kw_lower:
|
||||
continue
|
||||
if kw_lower not in self._kwctx_to_rooms:
|
||||
self._kwctx_to_rooms[kw_lower] = set()
|
||||
self._kwctx_to_rooms[kw_lower].add(room_id)
|
||||
|
||||
total_kw = len(self._kw100_to_rooms) + len(self._kwctx_to_rooms)
|
||||
logger.debug(
|
||||
"KeywordBooster mapping built: %d keywords across %d rooms",
|
||||
len(self._keyword_to_rooms),
|
||||
"KeywordBooster mapping built: %d kw100 + %d kwctx = %d total across %d rooms",
|
||||
len(self._kw100_to_rooms),
|
||||
len(self._kwctx_to_rooms),
|
||||
total_kw,
|
||||
len(self._room_map.rooms),
|
||||
)
|
||||
|
||||
@@ -101,21 +122,33 @@ class KeywordBooster:
|
||||
# ── Score-Dict aufbauen ──────────────────────────────────
|
||||
score_dict: Dict[str, float] = {room_id: score for room_id, score in scores}
|
||||
|
||||
# ── Keywords im Text finden ───────────────────────────────
|
||||
matched_keywords: List[str] = [
|
||||
kw for kw in self._keyword_to_rooms if match_keyword(kw, text)
|
||||
# ── Keywords im Text finden (P-028: getrennte Matcher) ────
|
||||
# keywords_100: match_keyword_exact (kein Fuzzy, hyphen-insensitiv)
|
||||
matched_kw100: List[str] = [
|
||||
kw for kw in self._kw100_to_rooms if match_keyword_exact(kw, text)
|
||||
]
|
||||
# keywords_context: match_keyword (mit Fuzzy/Stemming)
|
||||
matched_kwctx: List[str] = [
|
||||
kw for kw in self._kwctx_to_rooms if match_keyword(kw, text)
|
||||
]
|
||||
|
||||
matched_keywords = matched_kw100 + matched_kwctx
|
||||
|
||||
if not matched_keywords:
|
||||
# Keine Keywords → Scores unverändert zurück
|
||||
return sorted(scores, key=lambda x: x[1], reverse=True)
|
||||
|
||||
# ── V8.2 A3: Matches für Demotion-Tracking aufzeichnen ──────
|
||||
self._record_matches(text, matched_keywords)
|
||||
self._record_matches(text, matched_kw100)
|
||||
|
||||
# ── Boost-Phase: +0.10 für eindeutige Keywords ────────────
|
||||
# Vereinigtes Mapping für Boost-Lookup
|
||||
all_kw_to_rooms: Dict[str, Set[str]] = {}
|
||||
all_kw_to_rooms.update(self._kw100_to_rooms)
|
||||
all_kw_to_rooms.update(self._kwctx_to_rooms)
|
||||
|
||||
for kw in matched_keywords:
|
||||
rooms = self._keyword_to_rooms[kw]
|
||||
rooms = all_kw_to_rooms[kw]
|
||||
if len(rooms) == 1:
|
||||
unique_room = next(iter(rooms))
|
||||
if unique_room in score_dict:
|
||||
@@ -130,7 +163,7 @@ class KeywordBooster:
|
||||
# Zähle eindeutige Keywords pro Raum und gib Bonus für hohe Anzahl
|
||||
unique_counts_per_room: Dict[str, int] = {}
|
||||
for kw in matched_keywords:
|
||||
rooms = self._keyword_to_rooms[kw]
|
||||
rooms = all_kw_to_rooms[kw]
|
||||
if len(rooms) == 1:
|
||||
unique_room = next(iter(rooms))
|
||||
if unique_room in score_dict:
|
||||
@@ -151,7 +184,7 @@ class KeywordBooster:
|
||||
# ── Nach Boost sortieren ──────────────────────────────────
|
||||
boosted = sorted(score_dict.items(), key=lambda x: x[1], reverse=True)
|
||||
|
||||
# ── Konfliktlösung: Top-2 Diff < 0.03 ────────────────────
|
||||
# ── Konfliktlösung: Top-2 Diff < 0.05 ────────────────────
|
||||
if len(boosted) >= 2:
|
||||
top1_room, top1_score = boosted[0]
|
||||
top2_room, top2_score = boosted[1]
|
||||
@@ -188,6 +221,8 @@ class KeywordBooster:
|
||||
def _count_unique_matches(self, text: str, room_id: str) -> int:
|
||||
"""Zählt wie viele eindeutige Keywords (nur in diesem Raum) im Text vorkommen.
|
||||
|
||||
Prüft beide Mappings (kw100 + kwctx) mit den jeweiligen Matchern.
|
||||
|
||||
Args:
|
||||
text: Der Nachrichtentext (RAW, Normalisierung passiert intern).
|
||||
room_id: Die zu prüfende Raum-ID.
|
||||
@@ -196,15 +231,23 @@ class KeywordBooster:
|
||||
Anzahl der eindeutigen Keyword-Treffer für diesen Raum.
|
||||
"""
|
||||
count = 0
|
||||
for kw, rooms in self._keyword_to_rooms.items():
|
||||
|
||||
# keywords_100: match_keyword_exact
|
||||
for kw, rooms in self._kw100_to_rooms.items():
|
||||
if len(rooms) == 1 and room_id in rooms and match_keyword_exact(kw, text):
|
||||
count += 1
|
||||
|
||||
# keywords_context: match_keyword
|
||||
for kw, rooms in self._kwctx_to_rooms.items():
|
||||
if len(rooms) == 1 and room_id in rooms and match_keyword(kw, text):
|
||||
count += 1
|
||||
|
||||
return count
|
||||
|
||||
# ── V8.2 A3: 90-Tage-Demotion ─────────────────────────────────────
|
||||
|
||||
def _record_matches(self, text: str, matched_keywords: List[str]) -> None:
|
||||
"""Zeichnet last_matched-Timestamps für alle getroffenen Keywords.
|
||||
def _record_matches(self, text: str, matched_kw100: List[str]) -> None:
|
||||
"""Zeichnet last_matched-Timestamps für alle getroffenen kw100-Keywords.
|
||||
|
||||
Wird nach jedem boost()-Aufruf aufgerufen, um die RoomMap-Tracking-Felder
|
||||
aktuell zu halten. Nur Keywords in keywords_100 werden getrackt
|
||||
@@ -212,13 +255,12 @@ class KeywordBooster:
|
||||
|
||||
Args:
|
||||
text: Der Nachrichtentext (RAW, Normalisierung passiert intern).
|
||||
matched_keywords: Liste der im Text gefundenen Keywords.
|
||||
matched_kw100: Liste der via match_keyword_exact gefundenen kw100-Keywords.
|
||||
"""
|
||||
now = datetime.now().isoformat()
|
||||
for kw in matched_keywords:
|
||||
rooms = self._keyword_to_rooms.get(kw, set())
|
||||
for kw in matched_kw100:
|
||||
rooms = self._kw100_to_rooms.get(kw, set())
|
||||
for room_id in rooms:
|
||||
# Nur keywords_100 tracken (Demotion betrifft nur 100%-Keywords)
|
||||
entry = self._room_map.get_room_by_id(room_id)
|
||||
if entry is None:
|
||||
continue
|
||||
@@ -254,9 +296,9 @@ class KeywordBooster:
|
||||
def cleanup_orphaned_rooms(self, valid_room_ids: set) -> int:
|
||||
"""M13: Bereinigt das Keyword-Mapping für gelöschte Räume.
|
||||
|
||||
Baut das interne ``_keyword_to_rooms``-Mapping komplett neu aus
|
||||
der aktuellen RoomMap. Da die RoomMap bereits durch M13 bereinigt
|
||||
wurde, enthält das neue Mapping nur noch gültige Räume.
|
||||
Baut die internen ``_kw100_to_rooms``- und ``_kwctx_to_rooms``-Mappings
|
||||
komplett neu aus der aktuellen RoomMap. Da die RoomMap bereits durch M13
|
||||
bereinigt wurde, enthalten die neuen Mappings nur noch gültige Räume.
|
||||
|
||||
Args:
|
||||
valid_room_ids: Set von Raum-IDs, die behalten werden sollen
|
||||
@@ -266,9 +308,9 @@ class KeywordBooster:
|
||||
Returns:
|
||||
Anzahl der Keywords im neuen Mapping (0 wenn keine Räume übrig).
|
||||
"""
|
||||
before = len(self._keyword_to_rooms)
|
||||
before = len(self._kw100_to_rooms) + len(self._kwctx_to_rooms)
|
||||
self._build_mapping()
|
||||
after = len(self._keyword_to_rooms)
|
||||
after = len(self._kw100_to_rooms) + len(self._kwctx_to_rooms)
|
||||
if before != after:
|
||||
logger.info(
|
||||
"KeywordBooster GC: mapping rebuilt — %d → %d keywords "
|
||||
|
||||
@@ -30,7 +30,7 @@ def main() -> int:
|
||||
]
|
||||
|
||||
print(f"FAISS+Booster Smoke-Test: {idx.size} Raeume, Version {idx._version}")
|
||||
print(f"Booster: {len(booster._keyword_to_rooms)} Keywords, immer aktiv, +0.10/unique")
|
||||
print(f"Booster: {len(booster._kw100_to_rooms)} kw100 + {len(booster._kwctx_to_rooms)} kwctx Keywords, +0.10/unique")
|
||||
print()
|
||||
|
||||
ok = 0
|
||||
|
||||
+15
-13
@@ -553,7 +553,7 @@ class TestBoosterCleanup:
|
||||
|
||||
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)
|
||||
before = len(booster._kw100_to_rooms) + len(booster._kwctx_to_rooms)
|
||||
|
||||
# Entferne room_b aus der RoomMap (simuliert GC)
|
||||
del booster._room_map._rooms["room_b"]
|
||||
@@ -564,16 +564,17 @@ class TestBoosterCleanup:
|
||||
# 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
|
||||
# "bat" war unique für room_b (kw100) → sollte nicht mehr im Mapping sein
|
||||
assert "bat" not in booster._kw100_to_rooms
|
||||
assert "bat" not in booster._kwctx_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"}
|
||||
# "plugin" war unique für room_a (kwctx) → sollte noch da sein
|
||||
assert "plugin" in booster._kwctx_to_rooms
|
||||
assert booster._kwctx_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)
|
||||
before = len(booster._kw100_to_rooms) + len(booster._kwctx_to_rooms)
|
||||
after = booster.cleanup_orphaned_rooms({"room_a", "room_b", "room_catchall"})
|
||||
assert after == before
|
||||
|
||||
@@ -585,7 +586,8 @@ class TestBoosterCleanup:
|
||||
# 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
|
||||
assert len(booster._kw100_to_rooms) == 0
|
||||
assert len(booster._kwctx_to_rooms) == 0
|
||||
|
||||
def test_cleanup_then_boost_still_works(self, booster: KeywordBooster) -> None:
|
||||
"""Nach Cleanup: Boost funktioniert korrekt mit bereinigtem Mapping."""
|
||||
@@ -683,8 +685,8 @@ class TestV82A3BoosterDemotion:
|
||||
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
|
||||
# Vorher: "rocketchat" ist im kw100-Mapping
|
||||
assert "rocketchat" in booster._kw100_to_rooms
|
||||
|
||||
demoted = booster.demote_stale_keywords(max_age_days=90)
|
||||
assert demoted >= 1
|
||||
@@ -695,7 +697,7 @@ class TestV82A3BoosterDemotion:
|
||||
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
|
||||
assert "rocketchat" in booster._kwctx_to_rooms
|
||||
|
||||
def test_demote_no_stale_returns_zero(self, booster: KeywordBooster) -> None:
|
||||
"""Keine stale Keywords → demote_stale_keywords() gibt 0 zurück."""
|
||||
@@ -715,8 +717,8 @@ class TestV82A3BoosterDemotion:
|
||||
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
|
||||
assert "rocketchat" in booster._kwctx_to_rooms
|
||||
assert "ddp" in booster._kwctx_to_rooms
|
||||
|
||||
def test_demote_then_boost_still_works(self, booster: KeywordBooster) -> None:
|
||||
"""Nach Demotion: boost() funktioniert korrekt mit neuem Mapping."""
|
||||
|
||||
Reference in New Issue
Block a user