3179ce8b7b
Erweitert _sync_room_map_with_membership() um die von Andreas geforderten Bereinigungsschritte nach room-map.json-GC: 1. FAISS-Index: rebuild + save (war bereits in M13, jetzt robuster) 2. KeywordBooster: cleanup_orphaned_rooms() — baut _keyword_to_rooms Mapping aus bereinigter RoomMap neu 3. ArchivarState: cleanup_orphaned_rooms() — entfernt stay_decision, keyword_weights, sticky_keywords, manual_overrides, promotion_candidates für gelöschte Räume 4. Onboarding _stay_tracker: entfernt Einträge für gelöschte Räume Reihenfolge im Gateway-Start (adapter.py connect()): DDP connect → _sync_room_map_with_membership() → DDP subscribe → Archivar init → Auto-Onboarding Alle neuen Methoden sind idempotent und mit Tests abgedeckt: - test_archivar_state.py: +8 Tests (cleanup_orphaned_rooms) - test_booster.py: +4 Tests (cleanup_orphaned_rooms)
499 lines
19 KiB
Python
499 lines
19 KiB
Python
"""
|
|
Tests für das selbstlernende Keyword-Gewicht-System.
|
|
"""
|
|
|
|
import json
|
|
import os
|
|
import tempfile
|
|
import unittest
|
|
from datetime import datetime, timedelta
|
|
from pathlib import Path
|
|
import sys
|
|
|
|
# Add the parent directory to the path
|
|
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))
|
|
|
|
from archivar_state import ArchivarState, KeywordWeightEntry, ManualOverride
|
|
|
|
|
|
class TestArchivarStateKeywordWeights(unittest.TestCase):
|
|
"""Tests für das selbstlernende Keyword-Gewicht-System."""
|
|
|
|
def setUp(self):
|
|
"""Set up test fixtures."""
|
|
# Create a temporary file for the state
|
|
self.temp_file = tempfile.NamedTemporaryFile(delete=False, suffix='.json')
|
|
self.temp_file.close()
|
|
self.state_file_path = self.temp_file.name
|
|
self.state = ArchivarState(self.state_file_path)
|
|
|
|
def tearDown(self):
|
|
"""Clean up test fixtures."""
|
|
# Remove the temporary file
|
|
if os.path.exists(self.state_file_path):
|
|
os.unlink(self.state_file_path)
|
|
|
|
def test_keyword_weight_entry_serialization(self):
|
|
"""Test serialization of KeywordWeightEntry."""
|
|
# Create a KeywordWeightEntry
|
|
now = datetime.now().isoformat()
|
|
entry = KeywordWeightEntry(
|
|
weight=0.75,
|
|
last_updated=now,
|
|
confirmation_count=3,
|
|
rejection_count=1,
|
|
last_confirmation=now
|
|
)
|
|
|
|
# Create an ArchivarState and add the entry
|
|
self.state._keyword_weights = {
|
|
"test_keyword": {
|
|
"room1": entry
|
|
}
|
|
}
|
|
|
|
# Save and reload
|
|
self.assertTrue(self.state.save())
|
|
new_state = ArchivarState(self.state_file_path)
|
|
self.assertTrue(new_state.load())
|
|
|
|
# Check that the entry was loaded correctly
|
|
self.assertIn("test_keyword", new_state._keyword_weights)
|
|
self.assertIn("room1", new_state._keyword_weights["test_keyword"])
|
|
loaded_entry = new_state._keyword_weights["test_keyword"]["room1"]
|
|
self.assertEqual(loaded_entry.weight, 0.75)
|
|
self.assertEqual(loaded_entry.confirmation_count, 3)
|
|
self.assertEqual(loaded_entry.rejection_count, 1)
|
|
self.assertEqual(loaded_entry.last_updated, now)
|
|
self.assertEqual(loaded_entry.last_confirmation, now)
|
|
|
|
def test_manual_override_serialization(self):
|
|
"""Test serialization of ManualOverride."""
|
|
# Create a ManualOverride
|
|
now = datetime.now().isoformat()
|
|
override = ManualOverride(
|
|
override_weight=0.9,
|
|
override_reason="Manual adjustment by admin",
|
|
override_date=now,
|
|
override_by="admin_user"
|
|
)
|
|
|
|
# Create an ArchivarState and add the override
|
|
self.state._manual_overrides = {
|
|
"test_keyword": {
|
|
"room1": override
|
|
}
|
|
}
|
|
|
|
# Save and reload
|
|
self.assertTrue(self.state.save())
|
|
new_state = ArchivarState(self.state_file_path)
|
|
self.assertTrue(new_state.load())
|
|
|
|
# Check that the override was loaded correctly
|
|
self.assertIn("test_keyword", new_state._manual_overrides)
|
|
self.assertIn("room1", new_state._manual_overrides["test_keyword"])
|
|
loaded_override = new_state._manual_overrides["test_keyword"]["room1"]
|
|
self.assertEqual(loaded_override.override_weight, 0.9)
|
|
self.assertEqual(loaded_override.override_reason, "Manual adjustment by admin")
|
|
self.assertEqual(loaded_override.override_date, now)
|
|
self.assertEqual(loaded_override.override_by, "admin_user")
|
|
|
|
def test_update_keyword_weight_confirm(self):
|
|
"""Test updating keyword weight with confirm feedback."""
|
|
# Initialize with a keyword weight
|
|
self.state._keyword_weights = {
|
|
"plugin": {
|
|
"room1": KeywordWeightEntry(
|
|
weight=0.5,
|
|
last_updated=datetime.now().isoformat(),
|
|
confirmation_count=1,
|
|
rejection_count=0,
|
|
last_confirmation=None
|
|
),
|
|
"room2": KeywordWeightEntry(
|
|
weight=0.3,
|
|
last_updated=datetime.now().isoformat(),
|
|
confirmation_count=0,
|
|
rejection_count=0,
|
|
last_confirmation=None
|
|
)
|
|
}
|
|
}
|
|
|
|
# Apply confirm feedback
|
|
result = self.state.update_keyword_weight("plugin", "room1", "confirm")
|
|
self.assertTrue(result)
|
|
|
|
# Check that the weight was updated correctly
|
|
entry = self.state._keyword_weights["plugin"]["room1"]
|
|
# With learning rate 0.2: new_weight = 0.5 + (1 - 0.5) * 0.2 = 0.6
|
|
self.assertAlmostEqual(entry.weight, 0.6, places=2)
|
|
self.assertEqual(entry.confirmation_count, 2)
|
|
|
|
# Check that other room weights were reduced
|
|
other_entry = self.state._keyword_weights["plugin"]["room2"]
|
|
# With learning rate 0.2: reduced_weight = 0.3 - (0.3 * 0.2 / 1) = 0.24
|
|
self.assertAlmostEqual(other_entry.weight, 0.24, places=2)
|
|
|
|
def test_update_keyword_weight_stay(self):
|
|
"""Test updating keyword weight with stay feedback."""
|
|
# Initialize with a keyword weight
|
|
self.state._keyword_weights = {
|
|
"plugin": {
|
|
"room1": KeywordWeightEntry(
|
|
weight=0.5,
|
|
last_updated=datetime.now().isoformat(),
|
|
confirmation_count=1,
|
|
rejection_count=0,
|
|
last_confirmation=None
|
|
),
|
|
"room2": KeywordWeightEntry(
|
|
weight=0.3,
|
|
last_updated=datetime.now().isoformat(),
|
|
confirmation_count=0,
|
|
rejection_count=0,
|
|
last_confirmation=None
|
|
)
|
|
}
|
|
}
|
|
|
|
# Apply stay feedback
|
|
result = self.state.update_keyword_weight("plugin", "room1", "stay")
|
|
self.assertTrue(result)
|
|
|
|
# Check that the weight was updated correctly
|
|
entry = self.state._keyword_weights["plugin"]["room1"]
|
|
# With learning rate 0.2: new_weight = 0.5 - 0.5 * 0.2 * 0.5 = 0.45
|
|
self.assertAlmostEqual(entry.weight, 0.45, places=2)
|
|
self.assertEqual(entry.rejection_count, 1)
|
|
|
|
# Check that other room weights were increased
|
|
other_entry = self.state._keyword_weights["plugin"]["room2"]
|
|
# With learning rate 0.2: increased_weight = 0.3 + ((1 - 0.3) * 0.2 * 0.5 / 1) = 0.37
|
|
self.assertAlmostEqual(other_entry.weight, 0.37, places=2)
|
|
|
|
def test_update_keyword_weight_never(self):
|
|
"""Test updating keyword weight with never feedback."""
|
|
# Initialize with a keyword weight
|
|
self.state._keyword_weights = {
|
|
"plugin": {
|
|
"room1": KeywordWeightEntry(
|
|
weight=0.5,
|
|
last_updated=datetime.now().isoformat(),
|
|
confirmation_count=1,
|
|
rejection_count=0,
|
|
last_confirmation=None
|
|
)
|
|
}
|
|
}
|
|
|
|
# Apply never feedback
|
|
result = self.state.update_keyword_weight("plugin", "room1", "never")
|
|
self.assertTrue(result)
|
|
|
|
# Check that the weight was set to 0.0
|
|
entry = self.state._keyword_weights["plugin"]["room1"]
|
|
self.assertEqual(entry.weight, 0.0)
|
|
self.assertEqual(entry.rejection_count, 2) # Counts as 2 negative confirmations
|
|
|
|
# Check that the keyword was added to sticky_keywords
|
|
self.assertIn("plugin", self.state._sticky_keywords)
|
|
self.assertIn("room1", self.state._sticky_keywords["plugin"])
|
|
|
|
def test_calculate_room_score_with_override(self):
|
|
"""Test calculating room score with manual override."""
|
|
# Set up a manual override
|
|
now = datetime.now().isoformat()
|
|
self.state._manual_overrides = {
|
|
"plugin": {
|
|
"room1": ManualOverride(
|
|
override_weight=0.9,
|
|
override_reason="Manual adjustment",
|
|
override_date=now,
|
|
override_by="admin"
|
|
)
|
|
}
|
|
}
|
|
|
|
# Calculate score - should use override
|
|
score = self.state.calculate_room_score("plugin", "room1")
|
|
self.assertEqual(score, 0.9)
|
|
|
|
def test_calculate_room_score_with_sticky(self):
|
|
"""Test calculating room score with sticky keyword."""
|
|
# Set up a sticky keyword
|
|
self.state._sticky_keywords = {
|
|
"plugin": ["room1"]
|
|
}
|
|
|
|
# Calculate score - should be 0.0
|
|
score = self.state.calculate_room_score("plugin", "room1")
|
|
self.assertEqual(score, 0.0)
|
|
|
|
def test_calculate_room_score_with_learned_weight(self):
|
|
"""Test calculating room score with learned weight."""
|
|
# Set up a learned weight
|
|
now = datetime.now().isoformat()
|
|
self.state._keyword_weights = {
|
|
"plugin": {
|
|
"room1": KeywordWeightEntry(
|
|
weight=0.7,
|
|
last_updated=now,
|
|
confirmation_count=2,
|
|
rejection_count=0,
|
|
last_confirmation=now
|
|
)
|
|
}
|
|
}
|
|
|
|
# Calculate score - should use learned weight
|
|
score = self.state.calculate_room_score("plugin", "room1")
|
|
self.assertEqual(score, 0.7)
|
|
|
|
def test_check_promotion_eligibility(self):
|
|
"""Test checking promotion eligibility."""
|
|
# Set up a promotable keyword
|
|
now = datetime.now().isoformat()
|
|
self.state._keyword_weights = {
|
|
"plugin": {
|
|
"room1": KeywordWeightEntry(
|
|
weight=0.9,
|
|
last_updated=now,
|
|
confirmation_count=3,
|
|
rejection_count=0,
|
|
last_confirmation=now
|
|
)
|
|
}
|
|
}
|
|
|
|
# Check promotion eligibility
|
|
result = self.state.check_promotion_eligibility("plugin", "room1")
|
|
self.assertTrue(result)
|
|
|
|
# Check that it was added to promotion candidates
|
|
self.assertIn("plugin", self.state._promotion_candidates)
|
|
self.assertIn("room1", self.state._promotion_candidates["plugin"])
|
|
|
|
def test_apply_decay(self):
|
|
"""Test applying time-based decay."""
|
|
# Set up a keyword weight with old last_updated date (45 days ago)
|
|
old_date = (datetime.now() - timedelta(days=45)).isoformat()
|
|
self.state._keyword_weights = {
|
|
"plugin": {
|
|
"room1": KeywordWeightEntry(
|
|
weight=0.8,
|
|
last_updated=old_date,
|
|
confirmation_count=2,
|
|
rejection_count=0,
|
|
last_confirmation=old_date
|
|
)
|
|
}
|
|
}
|
|
|
|
# Apply decay
|
|
result = self.state.apply_decay()
|
|
self.assertTrue(result)
|
|
|
|
# Check that the weight was reduced (45 days is between 30 and 90 days,
|
|
# so it should be reduced by 10%)
|
|
entry = self.state._keyword_weights["plugin"]["room1"]
|
|
self.assertAlmostEqual(entry.weight, 0.8 * 0.9, places=2) # 0.72
|
|
|
|
# Test 90-day decay
|
|
very_old_date = (datetime.now() - timedelta(days=95)).isoformat()
|
|
self.state._keyword_weights = {
|
|
"plugin": {
|
|
"room1": KeywordWeightEntry(
|
|
weight=0.8,
|
|
last_updated=very_old_date,
|
|
confirmation_count=2,
|
|
rejection_count=0,
|
|
last_confirmation=very_old_date
|
|
)
|
|
}
|
|
}
|
|
|
|
# Apply decay
|
|
result = self.state.apply_decay()
|
|
self.assertTrue(result)
|
|
|
|
# Check that the weight was reduced by 30% (90 days = 30% reduction)
|
|
entry = self.state._keyword_weights["plugin"]["room1"]
|
|
self.assertAlmostEqual(entry.weight, 0.8 * 0.7, places=2) # 0.56
|
|
|
|
|
|
if __name__ == '__main__':
|
|
unittest.main()
|
|
|
|
|
|
# ═══════════════════════════════════════════════════════════════════════════
|
|
# M13: cleanup_orphaned_rooms Tests
|
|
# ═══════════════════════════════════════════════════════════════════════════
|
|
|
|
class TestArchivarStateCleanup(unittest.TestCase):
|
|
"""M13: Tests für cleanup_orphaned_rooms()."""
|
|
|
|
def setUp(self):
|
|
self.temp_file = tempfile.NamedTemporaryFile(delete=False, suffix='.json')
|
|
self.temp_file.close()
|
|
self.state_file_path = self.temp_file.name
|
|
self.state = ArchivarState(self.state_file_path)
|
|
|
|
def tearDown(self):
|
|
if os.path.exists(self.state_file_path):
|
|
os.unlink(self.state_file_path)
|
|
|
|
def _seed_state(self):
|
|
"""Befüllt den State mit Testdaten für 3 Räume."""
|
|
now = datetime.now().isoformat()
|
|
|
|
# Room states
|
|
self.state._rooms = {
|
|
"room_keep": type('RoomState', (), {
|
|
'stay_decision': 'always',
|
|
'decided_at': now,
|
|
'decided_by': 'andreas',
|
|
})(),
|
|
"room_orphan": type('RoomState', (), {
|
|
'stay_decision': 'never_route',
|
|
'decided_at': now,
|
|
'decided_by': 'andreas',
|
|
})(),
|
|
}
|
|
|
|
# Keyword weights
|
|
self.state._keyword_weights = {
|
|
"plugin": {
|
|
"room_keep": KeywordWeightEntry(
|
|
weight=0.8, last_updated=now,
|
|
confirmation_count=3, rejection_count=0,
|
|
last_confirmation=now,
|
|
),
|
|
"room_orphan": KeywordWeightEntry(
|
|
weight=0.5, last_updated=now,
|
|
confirmation_count=1, rejection_count=0,
|
|
last_confirmation=None,
|
|
),
|
|
},
|
|
"docker": {
|
|
"room_orphan": KeywordWeightEntry(
|
|
weight=0.7, last_updated=now,
|
|
confirmation_count=2, rejection_count=0,
|
|
last_confirmation=now,
|
|
),
|
|
},
|
|
}
|
|
|
|
# Sticky keywords
|
|
self.state._sticky_keywords = {
|
|
"plugin": ["room_orphan", "room_keep"],
|
|
"docker": ["room_orphan"],
|
|
}
|
|
|
|
# Manual overrides
|
|
self.state._manual_overrides = {
|
|
"plugin": {
|
|
"room_orphan": ManualOverride(
|
|
override_weight=0.9,
|
|
override_reason="test",
|
|
override_date=now,
|
|
override_by="admin",
|
|
),
|
|
},
|
|
}
|
|
|
|
# Promotion candidates
|
|
self.state._promotion_candidates = {
|
|
"plugin": {
|
|
"room_orphan": {"score": 3.8, "last_updated": now},
|
|
"room_keep": {"score": 4.2, "last_updated": now},
|
|
},
|
|
}
|
|
|
|
def test_cleanup_removes_orphaned_room_state(self):
|
|
"""Room state für orphaned Raum wird entfernt."""
|
|
self._seed_state()
|
|
self.assertIn("room_orphan", self.state._rooms)
|
|
self.assertIn("room_keep", self.state._rooms)
|
|
|
|
removed = self.state.cleanup_orphaned_rooms({"room_keep"})
|
|
|
|
self.assertGreater(removed, 0)
|
|
self.assertNotIn("room_orphan", self.state._rooms)
|
|
self.assertIn("room_keep", self.state._rooms)
|
|
|
|
def test_cleanup_removes_orphaned_keyword_weights(self):
|
|
"""Keyword weights für orphaned Raum werden entfernt."""
|
|
self._seed_state()
|
|
|
|
self.state.cleanup_orphaned_rooms({"room_keep"})
|
|
|
|
# "plugin" hat nur noch room_keep
|
|
self.assertIn("plugin", self.state._keyword_weights)
|
|
self.assertIn("room_keep", self.state._keyword_weights["plugin"])
|
|
self.assertNotIn("room_orphan", self.state._keyword_weights["plugin"])
|
|
|
|
# "docker" hatte NUR room_orphan → ganzes Keyword gelöscht
|
|
self.assertNotIn("docker", self.state._keyword_weights)
|
|
|
|
def test_cleanup_removes_orphaned_sticky_keywords(self):
|
|
"""Sticky keywords für orphaned Raum werden entfernt."""
|
|
self._seed_state()
|
|
|
|
self.state.cleanup_orphaned_rooms({"room_keep"})
|
|
|
|
# "plugin" sticky: room_orphan entfernt, room_keep bleibt
|
|
self.assertIn("plugin", self.state._sticky_keywords)
|
|
self.assertEqual(self.state._sticky_keywords["plugin"], ["room_keep"])
|
|
|
|
# "docker" sticky: nur room_orphan → ganzes Keyword gelöscht
|
|
self.assertNotIn("docker", self.state._sticky_keywords)
|
|
|
|
def test_cleanup_removes_orphaned_manual_overrides(self):
|
|
"""Manual overrides für orphaned Raum werden entfernt."""
|
|
self._seed_state()
|
|
|
|
self.state.cleanup_orphaned_rooms({"room_keep"})
|
|
|
|
# "plugin" override: nur room_orphan → ganzes Keyword gelöscht
|
|
self.assertNotIn("plugin", self.state._manual_overrides)
|
|
|
|
def test_cleanup_removes_orphaned_promotion_candidates(self):
|
|
"""Promotion candidates für orphaned Raum werden entfernt."""
|
|
self._seed_state()
|
|
|
|
self.state.cleanup_orphaned_rooms({"room_keep"})
|
|
|
|
# "plugin" promotion: room_orphan entfernt, room_keep bleibt
|
|
self.assertIn("plugin", self.state._promotion_candidates)
|
|
self.assertIn("room_keep", self.state._promotion_candidates["plugin"])
|
|
self.assertNotIn("room_orphan", self.state._promotion_candidates["plugin"])
|
|
|
|
def test_cleanup_no_orphans_returns_zero(self):
|
|
"""Keine verwaisten Räume → removed=0, State unverändert."""
|
|
self._seed_state()
|
|
|
|
removed = self.state.cleanup_orphaned_rooms({"room_keep", "room_orphan"})
|
|
|
|
self.assertEqual(removed, 0)
|
|
self.assertIn("room_orphan", self.state._rooms)
|
|
self.assertIn("room_keep", self.state._rooms)
|
|
|
|
def test_cleanup_empty_state_no_error(self):
|
|
"""Leerer State → cleanup_orphaned_rooms() wirft keinen Fehler."""
|
|
removed = self.state.cleanup_orphaned_rooms({"room_keep"})
|
|
self.assertEqual(removed, 0)
|
|
|
|
def test_cleanup_persists_to_disk(self):
|
|
"""Nach cleanup_orphaned_rooms() ist der bereinigte State auf Disk."""
|
|
self._seed_state()
|
|
self.state.cleanup_orphaned_rooms({"room_keep"})
|
|
|
|
# Reload von Disk
|
|
new_state = ArchivarState(self.state_file_path)
|
|
new_state.load()
|
|
|
|
self.assertNotIn("room_orphan", new_state._rooms)
|
|
self.assertIn("room_keep", new_state._rooms)
|
|
self.assertNotIn("docker", new_state._keyword_weights) |