fix(p1-2): E1 Lock-Scope erweitert + E2 Concurrency-Test

E1: Lock-Scope in increment_background_tasks und decrement_background_tasks
erweitert — _persist_plugin_state wird jetzt unter _background_tasks_lock
aufgerufen. Verhindert dass bei zwei konkurrierenden Threads ein veralteter
Count persistiert wird.

E2: Concurrency-Test für _write_plugin_state — zwei Threads schreiben
parallel, danach wird verifiziert dass die Datei gültiges JSON enthält
(keine halbe Datei, kein korruptes JSON, keine .tmp-Leichen).
This commit is contained in:
Bernd (Hermes)
2026-07-26 06:08:02 +02:00
parent 6d8aab83a0
commit 20da8a9aeb
2 changed files with 133 additions and 6 deletions
+14 -6
View File
@@ -459,14 +459,18 @@ class PresenceEngine:
P1-2: Persists to plugin state file for DetectionTimer. P1-2: Persists to plugin state file for DetectionTimer.
E1: Lock-Scope erweitert — _persist_plugin_state wird jetzt unter
_background_tasks_lock aufgerufen, sodass kein veralteter Count
persistiert werden kann (Race zwischen zwei konkurrierenden Threads).
Returns: Returns:
New counter value. New counter value.
""" """
with self._background_tasks_lock: with self._background_tasks_lock:
self._background_tasks += 1 self._background_tasks += 1
count = self._background_tasks count = self._background_tasks
self._pulse_controller.set_background_count(count) self._pulse_controller.set_background_count(count)
self._persist_plugin_state(count) self._persist_plugin_state(count)
return count return count
def decrement_background_tasks(self) -> int: def decrement_background_tasks(self) -> int:
@@ -474,6 +478,10 @@ class PresenceEngine:
P1-2: Persists to plugin state file for DetectionTimer. P1-2: Persists to plugin state file for DetectionTimer.
E1: Lock-Scope erweitert — _persist_plugin_state wird jetzt unter
_background_tasks_lock aufgerufen, sodass kein veralteter Count
persistiert werden kann (Race zwischen zwei konkurrierenden Threads).
Returns: Returns:
New counter value. New counter value.
""" """
@@ -481,10 +489,10 @@ class PresenceEngine:
if self._background_tasks > 0: if self._background_tasks > 0:
self._background_tasks -= 1 self._background_tasks -= 1
count = self._background_tasks count = self._background_tasks
self._pulse_controller.set_background_count(count) self._pulse_controller.set_background_count(count)
if count == 0: if count == 0:
self._pulse_controller.stop() self._pulse_controller.stop()
self._persist_plugin_state(count) self._persist_plugin_state(count)
return count return count
def _persist_plugin_state(self, background_tasks: int) -> None: def _persist_plugin_state(self, background_tasks: int) -> None:
@@ -1835,6 +1835,125 @@ class TestPluginStateFile:
assert not list(tmp_path.glob("*.tmp")) assert not list(tmp_path.glob("*.tmp"))
# ═══════════════════════════════════════════════════════════════════════════
# E2: Concurrency-Test für _write_plugin_state
# ═══════════════════════════════════════════════════════════════════════════
class TestWritePluginStateConcurrency:
"""E2: Zwei Threads parallel schreiben → kein korruptes JSON, keine halbe Datei."""
def test_concurrent_writes_produce_valid_json(self, tmp_path):
"""Zwei Threads schreiben parallel — finale Datei ist gültiges JSON."""
from plugin.archivar.presence_engine import _write_plugin_state, _read_plugin_state
import json
state_path = str(tmp_path / "hermes_rocket_plugin.json")
os.makedirs(os.path.dirname(state_path), exist_ok=True)
# Seed the file so both threads have something to overwrite
_write_plugin_state(state_path, {
"background_tasks": 0,
"last_update_iso": "2026-01-01T00:00:00",
"source": "plugin_internal",
"schema_version": 1,
})
errors = []
last_written: list = [None] # mutable container for the last-written data
def writer(thread_id: int, n: int):
try:
for i in range(n):
data = {
"background_tasks": thread_id * 1000 + i,
"last_update_iso": f"2026-07-26T{thread_id:02d}:{i:02d}:00",
"source": f"thread_{thread_id}",
"schema_version": 1,
}
_write_plugin_state(state_path, data)
last_written[0] = data
except Exception as e:
errors.append(f"thread_{thread_id}: {e}")
N = 50
t1 = threading.Thread(target=writer, args=(1, N))
t2 = threading.Thread(target=writer, args=(2, N))
t1.start()
t2.start()
t1.join()
t2.join()
assert len(errors) == 0, f"Thread errors: {errors}"
# Read back — must be valid JSON, no JSONDecodeError
result = _read_plugin_state(state_path)
assert isinstance(result, dict), f"Expected dict, got {type(result)}"
assert "background_tasks" in result
assert "source" in result
assert "schema_version" in result
# The file must contain complete, valid JSON — _read_plugin_state
# already verified that (returns {} on corrupt JSON). If we got a
# dict with keys, the file is intact.
assert result["schema_version"] == 1
# Verify no .tmp leftovers (atomic rename worked)
assert not list(tmp_path.glob("*.tmp")), "Temp files left behind"
def test_concurrent_writes_no_truncated_file(self, tmp_path):
"""Parallele writes erzeugen keine trunkierte Datei (kein halbes JSON)."""
from plugin.archivar.presence_engine import _write_plugin_state
import json
state_path = str(tmp_path / "hermes_rocket_plugin.json")
os.makedirs(os.path.dirname(state_path), exist_ok=True)
_write_plugin_state(state_path, {
"background_tasks": 0,
"last_update_iso": "2026-01-01T00:00:00",
"source": "plugin_internal",
"schema_version": 1,
})
def writer(thread_id: int, n: int):
for i in range(n):
data = {
"background_tasks": thread_id * 1000 + i,
"last_update_iso": f"2026-07-26T{thread_id:02d}:{i:02d}:00",
"source": f"thread_{thread_id}",
"schema_version": 1,
}
_write_plugin_state(state_path, data)
N = 100
t1 = threading.Thread(target=writer, args=(1, N))
t2 = threading.Thread(target=writer, args=(2, N))
t1.start()
t2.start()
t1.join()
t2.join()
# Read raw bytes — must be parseable JSON
with open(state_path, "rb") as f:
raw = f.read()
# Must not be empty
assert len(raw) > 0, "File is empty after concurrent writes"
# Must parse as JSON (no JSONDecodeError)
try:
parsed = json.loads(raw)
except json.JSONDecodeError as e:
pytest.fail(f"Corrupt JSON after concurrent writes: {e}")
assert isinstance(parsed, dict)
assert "background_tasks" in parsed
assert "source" in parsed
# ═══════════════════════════════════════════════════════════════════════════ # ═══════════════════════════════════════════════════════════════════════════
# P1-2: Plugin-State Persistenz in increment/decrement_background_tasks # P1-2: Plugin-State Persistenz in increment/decrement_background_tasks
# ═══════════════════════════════════════════════════════════════════════════ # ═══════════════════════════════════════════════════════════════════════════