335 lines
15 KiB
Python
335 lines
15 KiB
Python
import os
|
|
import sqlite3
|
|
import time
|
|
import logging
|
|
from pathlib import Path
|
|
|
|
logger = logging.getLogger("pmdb-connector.queue")
|
|
|
|
|
|
class TaskQueue:
|
|
"""Connector-lokale SQLite-Queue (F-XXX S1: Queue-Hygiene, F-XXX S2a: R-T1).
|
|
|
|
Status-Vokabular (pending_tasks.status, lokal, KEINE PMDB-Kopie):
|
|
pending, dispatched, acked,
|
|
verworfen (attempt-limit / backpressure / stale / nachlade-gescheitert),
|
|
ungueltig (pitch fehlt).
|
|
"""
|
|
|
|
def __init__(self, db_path: str, max_attempts: int = 3, grace_period_s: int = 10):
|
|
self.db_path = db_path
|
|
self.max_attempts = max_attempts
|
|
self.grace_period_s = grace_period_s
|
|
self._init_db()
|
|
|
|
def _init_db(self):
|
|
with sqlite3.connect(self.db_path) as conn:
|
|
conn.execute("""
|
|
CREATE TABLE IF NOT EXISTS pending_tasks (
|
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
event_id TEXT,
|
|
task_id INTEGER,
|
|
agent_name TEXT,
|
|
feature_id INTEGER,
|
|
target_bit INTEGER,
|
|
pitch TEXT,
|
|
received_at INTEGER,
|
|
dispatched_at INTEGER,
|
|
dispatched_pid INTEGER,
|
|
status TEXT,
|
|
attempt_count INTEGER DEFAULT 0,
|
|
last_error TEXT
|
|
)
|
|
""")
|
|
conn.execute("CREATE INDEX IF NOT EXISTS idx_pending_status ON pending_tasks (status, agent_name)")
|
|
conn.execute("CREATE INDEX IF NOT EXISTS idx_pending_event ON pending_tasks (event_id)")
|
|
conn.execute("CREATE INDEX IF NOT EXISTS idx_pending_task ON pending_tasks (task_id)")
|
|
|
|
@staticmethod
|
|
def _pid_alive(pid):
|
|
"""Prozess-Pruefung via os.kill(pid, 0) (stdlib, D.5.3)."""
|
|
if not pid:
|
|
return False
|
|
try:
|
|
os.kill(pid, 0)
|
|
return True
|
|
except OSError:
|
|
return False
|
|
|
|
def push(self, event_data: dict):
|
|
"""Inserts a task event into the queue. Implements Dedupe and Backpressure.
|
|
|
|
R-T1 (S2a, C.4): Dedupe-Key ist task_id (nicht event_id). Der Produzent
|
|
sendet KEIN event_id (P-NEW-F-XXX-CURSOR-OHNE-QUELLE) — ein zweites
|
|
SSE-Event zur selben task_id (Verteiler-Replay) ist damit ein idempotentes
|
|
No-Op statt eines Doppel-Rows. Liefert True wenn inseriert, False wenn deduped.
|
|
"""
|
|
with sqlite3.connect(self.db_path) as conn:
|
|
count = conn.execute("SELECT count(*) FROM pending_tasks WHERE status='pending'").fetchone()[0]
|
|
if count > 1000:
|
|
# Backpressure-Protokoll (D.5.4): statt stillem DELETE -> aelteste
|
|
# pending-Row auf verworfen setzen (Beleg bleibt erhalten, sichtbar
|
|
# statt verlustlos-still).
|
|
logger.warning("Queue backpressure: oldest pending task -> verworfen (last_error=backpressure).")
|
|
conn.execute(
|
|
"UPDATE pending_tasks SET status='verworfen', last_error='backpressure' "
|
|
"WHERE id = (SELECT id FROM pending_tasks WHERE status='pending' ORDER BY received_at ASC LIMIT 1)"
|
|
)
|
|
|
|
task_id = event_data.get("task_id")
|
|
# R-T1 (C.4): Dedupe auf task_id — ein Replay derselben task_id ist
|
|
# ein idempotentes Update, kein Doppel-Row.
|
|
if task_id is not None:
|
|
exists = conn.execute(
|
|
"SELECT 1 FROM pending_tasks WHERE task_id = ?", (task_id,)
|
|
).fetchone()
|
|
if exists:
|
|
return False
|
|
|
|
event_id = event_data.get("event_id")
|
|
if event_id:
|
|
exists = conn.execute("SELECT 1 FROM pending_tasks WHERE event_id = ?", (event_id,)).fetchone()
|
|
if exists:
|
|
return False
|
|
|
|
conn.execute("""
|
|
INSERT INTO pending_tasks (event_id, task_id, agent_name, feature_id, target_bit, pitch, received_at, status)
|
|
VALUES (?, ?, ?, ?, ?, ?, ?, 'pending')
|
|
""", (
|
|
event_id,
|
|
task_id,
|
|
event_data.get("agent_name", "").lower(),
|
|
event_data.get("feature_id"),
|
|
event_data.get("target_bit"),
|
|
event_data.get("pitch"),
|
|
int(time.time() * 1000)
|
|
))
|
|
return True
|
|
|
|
def enrich_row(self, task_id, pitch, feature_id=None, target_bit=None):
|
|
"""R-T1 (C.2.1) + F-XXX (Race-Condition-Fix): reichert eine Row in-place an
|
|
(pitch aus der Nachlieferung).
|
|
|
|
@implements: [F-XXX]
|
|
|
|
Neben pending-Rows werden auch ungueltig-Rows (pitch fehlt) zurueck auf
|
|
pending gesetzt, wenn der pitch nachgeladen wird. Damit heilt die
|
|
S2-Pitch-Nachlieferung eine Row, die S1-Queue-Hygiene bereits als
|
|
ungueltig markiert hat (Race zwischen S1 und S2 — die Nachlieferung
|
|
verliert sonst, weil der HTTP-Call langsamer ist als der synchrone
|
|
Poison-Guard im Stream-Loop). Idempotent (C.4): ein zweites Update
|
|
derselben task_id ist ein No-Op. feature_id/target_bit werden aus der
|
|
Task-Antwort mitgefuehrt (Event traegt feature_id, target_bit nur im
|
|
dispatched-Zweig; A3: der Dispatcher braucht target_bit).
|
|
"""
|
|
with sqlite3.connect(self.db_path) as conn:
|
|
conn.execute(
|
|
"UPDATE pending_tasks SET pitch = ?, feature_id = ?, target_bit = ?, status = 'pending' "
|
|
"WHERE task_id = ? AND status IN ('pending', 'ungueltig')",
|
|
(pitch, feature_id, target_bit, task_id),
|
|
)
|
|
|
|
def discard_row(self, task_id, reason):
|
|
"""R-T1 (C.2.2/C.2.3/C.2.4): verwirft eine Row mit Beleg (last_error).
|
|
|
|
Permanenz-Loesung fuer P-NEW-MCP-STALE-QUEUE: stale-Erkennung aus der
|
|
Quelle statt manueller DELETE-Aktionen. Nur pending-Rows.
|
|
"""
|
|
with sqlite3.connect(self.db_path) as conn:
|
|
conn.execute(
|
|
"UPDATE pending_tasks SET status = 'verworfen', last_error = ? "
|
|
"WHERE task_id = ? AND status = 'pending'",
|
|
(reason, task_id),
|
|
)
|
|
|
|
def _cleanup_poison(self, conn):
|
|
"""Poison-Schutz (D.5.1) + F-XXX Grace-Period:
|
|
- Rows mit attempt_count >= max_attempts -> verworfen (last_error bleibt als Beleg)
|
|
- Rows ohne nutzbaren pitch (None/leer) -> ungueltig, NICHT dispatched.
|
|
Grace-Period: nur Rows, deren received_at aelter als grace_period_s
|
|
Sekunden ist, werden ungueltig — frische Rows bleiben pending, damit
|
|
die S2-Pitch-Nachlieferung (separater Thread, HTTP-Call) den pitch
|
|
laden kann, bevor S1 sie verungueltigt (Race zwischen S1 und S2).
|
|
"""
|
|
conn.execute(
|
|
"UPDATE pending_tasks SET status='verworfen' WHERE status='pending' AND attempt_count >= ?",
|
|
(self.max_attempts,),
|
|
)
|
|
conn.execute(
|
|
"UPDATE pending_tasks SET status='ungueltig', last_error='pitch fehlt' "
|
|
"WHERE status='pending' AND (pitch IS NULL OR pitch = '') AND received_at < ?",
|
|
(int(time.time() * 1000) - self.grace_period_s * 1000,),
|
|
)
|
|
|
|
def peek_next(self, agent_name: str):
|
|
"""F-XXX Gate: liefert den naechsten Dispatch-Kandidaten OHNE Row-Update.
|
|
|
|
@implements: [F-XXX]
|
|
|
|
Identische Auswahl-Logik wie pop_next (Poison-Schutz + pending + Agent-
|
|
Match + Versuchslimit + pitch vorhanden), aber die Row bleibt pending.
|
|
None -> kein Kandidat. Das Gate (dispatcher._run_once_locked) verifiziert
|
|
den PMDB-Status VOR pop_next; deshalb braucht es den Peek ohne die
|
|
dispatched-Transition (P-NEW-F-XXX-GATE-NACH-POP-NEXT-MUSTER: ein Gate
|
|
NACH pop_next trifft eine dispatched-Row, die discard_row nicht mehr
|
|
greift).
|
|
"""
|
|
with sqlite3.connect(self.db_path) as conn:
|
|
conn.row_factory = sqlite3.Row
|
|
self._cleanup_poison(conn)
|
|
row = conn.execute(
|
|
"SELECT * FROM pending_tasks "
|
|
"WHERE status='pending' AND agent_name = ? "
|
|
" AND attempt_count < ? "
|
|
" AND pitch IS NOT NULL AND pitch != '' "
|
|
"ORDER BY received_at ASC LIMIT 1",
|
|
(agent_name.lower(), self.max_attempts),
|
|
).fetchone()
|
|
return dict(row) if row else None
|
|
|
|
def pop_next(self, agent_name: str):
|
|
"""Gets the next *gesunde* pending task for a specific agent.
|
|
|
|
Poison-Schutz: Rows mit attempt_count >= max_attempts oder ohne nutzbaren
|
|
pitch werden VOR der Auswahl bereinigt und niemals dispatched. Die
|
|
NoneType-Kette aus dem Spike (Task-3493-Klasse) ist damit entwaffnet.
|
|
"""
|
|
with sqlite3.connect(self.db_path) as conn:
|
|
conn.row_factory = sqlite3.Row
|
|
self._cleanup_poison(conn)
|
|
row = conn.execute("""
|
|
SELECT * FROM pending_tasks
|
|
WHERE status='pending' AND agent_name = ?
|
|
AND attempt_count < ?
|
|
AND pitch IS NOT NULL AND pitch != ''
|
|
ORDER BY received_at ASC LIMIT 1
|
|
""", (agent_name.lower(), self.max_attempts)).fetchone()
|
|
|
|
if row:
|
|
conn.execute(
|
|
"UPDATE pending_tasks SET status='dispatched', dispatched_at = ? WHERE id = ?",
|
|
(int(time.time() * 1000), row['id']),
|
|
)
|
|
return dict(row)
|
|
return None
|
|
|
|
def set_dispatched_pid(self, task_id_db: int, pid: int):
|
|
"""PID-Zurverfuegungstellung (D.5.6): schreibt die Popen-PID in die
|
|
Spalte dispatched_pid (Spalte existiert, wird ab Stufe 1 befuellt)."""
|
|
with sqlite3.connect(self.db_path) as conn:
|
|
conn.execute("UPDATE pending_tasks SET dispatched_pid = ? WHERE id = ?", (pid, task_id_db))
|
|
|
|
def find_dispatched_pid(self, task_id: int):
|
|
"""F-XXX S3b: liefert dispatched_pid fuer einen PMDB task_id aus einer
|
|
dispatched-Row (fuer die Steering-Verarbeitung). None wenn nicht
|
|
gefunden. Fallback zur dispatcher._active_runs-Sicht."""
|
|
with sqlite3.connect(self.db_path) as conn:
|
|
conn.row_factory = sqlite3.Row
|
|
row = conn.execute(
|
|
"SELECT dispatched_pid FROM pending_tasks WHERE task_id = ? "
|
|
"AND status = 'dispatched' ORDER BY id DESC LIMIT 1", (task_id,)
|
|
).fetchone()
|
|
return row["dispatched_pid"] if row else None
|
|
|
|
def mark_done(self, task_id_db: int):
|
|
with sqlite3.connect(self.db_path) as conn:
|
|
conn.execute("UPDATE pending_tasks SET status='acked' WHERE id = ?", (task_id_db,))
|
|
|
|
def close_dispatched(self, task_id: int, reason: str):
|
|
"""F-XXX 2a: additive Close-Methode fuer dispatched-Rows (dispatched-Konvergenz).
|
|
|
|
@implements: [F-XXX]
|
|
|
|
Schliesst eine dispatched-Row (status='acked') mit Beleg (last_error),
|
|
OHNE den Prozess anzuruehren (kein Signal, kein Doppel-Worker — der
|
|
D.5.3-Vertrag 'lebender PID bleibt unangetastet' bleibt bestehen, es wird
|
|
nur die Buchhaltung nachgezogen). discard_row greift auf dispatched-Rows
|
|
nicht (WHERE-Klausel status='pending'), deshalb braucht die dispatched-
|
|
Konvergenz diese eigene Methode. Das Adoption-Urteil faellt ausschliesslich
|
|
aus dem PMDB-Status-GET (team-Auflage 6), NIEMALS aus der PID-Liveness.
|
|
"""
|
|
with sqlite3.connect(self.db_path) as conn:
|
|
conn.execute(
|
|
"UPDATE pending_tasks SET status='acked', last_error = ? "
|
|
"WHERE task_id = ? AND status = 'dispatched'",
|
|
(reason, task_id),
|
|
)
|
|
|
|
def mark_failed(self, task_id_db: int, error: str):
|
|
"""Versuche-Isolation (D.5.2): markiert NUR die eine Row (attempt_count+1),
|
|
niemals den Loop und niemals andere Rows. Bei Erreichen des
|
|
Poison-Limits wird die Row direkt verworfen."""
|
|
with sqlite3.connect(self.db_path) as conn:
|
|
conn.execute("""
|
|
UPDATE pending_tasks
|
|
SET status='pending', attempt_count = attempt_count + 1, last_error = ?
|
|
WHERE id = ?
|
|
""", (error, task_id_db))
|
|
conn.execute(
|
|
"UPDATE pending_tasks SET status='verworfen' WHERE id = ? AND attempt_count >= ?",
|
|
(task_id_db, self.max_attempts),
|
|
)
|
|
|
|
def recover_dispatched(self, last_error: str = "restart recovery"):
|
|
"""Neustart-Recovery (D.5.3): dispatched-Rows, deren dispatched_pid nicht
|
|
mehr lebt, auf pending zuruecksetzen (attempt_count+1, last_error).
|
|
Rows mit lebendem PID bleiben unangetastet (kein Doppel-Worker).
|
|
Gibt die Anzahl zurueckgesetzter Rows zurueck.
|
|
|
|
@implements: [F-XXX]
|
|
"""
|
|
with sqlite3.connect(self.db_path) as conn:
|
|
conn.row_factory = sqlite3.Row
|
|
rows = conn.execute(
|
|
"SELECT id, dispatched_pid FROM pending_tasks WHERE status='dispatched'"
|
|
).fetchall()
|
|
recovered = 0
|
|
for row in rows:
|
|
if not self._pid_alive(row['dispatched_pid']):
|
|
conn.execute(
|
|
"UPDATE pending_tasks SET status='pending', attempt_count = attempt_count + 1, last_error = ? WHERE id = ?",
|
|
(last_error, row['id']),
|
|
)
|
|
recovered += 1
|
|
return recovered
|
|
|
|
def recover_lost_runs(self):
|
|
"""Periodische Recovery im laufenden Betrieb (F-XXX): dispatched-Rows
|
|
mit totem PID zurueck auf pending, attempt_count+1,
|
|
last_error='periodic recovery'. Gleicher Mechanismus wie die
|
|
Neustart-Recovery (recover_dispatched), nur anderer last_error-Text —
|
|
der Duplikat-Druck aus der F-XXX-Erstimplementierung ist damit
|
|
zusammengezogen (A-5).
|
|
|
|
@implements: [F-XXX]
|
|
"""
|
|
return self.recover_dispatched(last_error="periodic recovery")
|
|
|
|
def list_reconcile_rows(self):
|
|
"""F-XXX 2a: liefert alle Rows, die die Start-Reconciliation pruefen muss.
|
|
|
|
@implements: [F-XXX]
|
|
|
|
pending (inkl. der gerade von recover_dispatched zurueckgesetzten Rows)
|
|
und dispatched (verbleibende Rows mit lebender PID). acked/verworfen/
|
|
ungueltig sind ausgeschlossen (bereits konvergiert).
|
|
"""
|
|
with sqlite3.connect(self.db_path) as conn:
|
|
conn.row_factory = sqlite3.Row
|
|
rows = conn.execute(
|
|
"SELECT * FROM pending_tasks WHERE status IN ('pending', 'dispatched')"
|
|
).fetchall()
|
|
return [dict(r) for r in rows]
|
|
|
|
def get_stats(self):
|
|
"""Queue-Zaehlung fuer den connector-status-Puls (D.5.5)."""
|
|
with sqlite3.connect(self.db_path) as conn:
|
|
rows = conn.execute(
|
|
"SELECT status, count(*) FROM pending_tasks GROUP BY status"
|
|
).fetchall()
|
|
stats = {"pending": 0, "dispatched": 0, "verworfen": 0, "ungueltig": 0}
|
|
for status, cnt in rows:
|
|
if status in stats:
|
|
stats[status] = cnt
|
|
return stats
|