-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdb.py
More file actions
644 lines (568 loc) · 21 KB
/
Copy pathdb.py
File metadata and controls
644 lines (568 loc) · 21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
from __future__ import annotations
import json
import sqlite3
from dataclasses import dataclass
from pathlib import Path
from .history import accepted_payload_hash
@dataclass(frozen=True)
class FeedbackEvent:
session_key: str
user_message_id: str
assistant_message_id: str
proactive_message_id: str | None
feedback_type: str
confidence: str
pa_score: float | None
pua_score: float | None
lag_seconds: int | None
candidate_count: int
matched_by: str
reason: str
user_content_preview: str | None = None
assistant_content_preview: str | None = None
proactive_content_preview: str | None = None
@dataclass(frozen=True)
class FeedbackOutboxRecord:
"""Describe one durable typed-event payload waiting for publication."""
row_id: int
event_id: str
payload_json: str
@dataclass(frozen=True)
class FeedbackInputRecord:
"""Describe one committed Turn identity waiting for durable processing."""
row_id: int
session_key: str
turn_id: str
client_message_id: str
user_message_id: str
user_message_ids: tuple[str, ...]
assistant_message_id: str | None
def open_db(path: Path) -> sqlite3.Connection:
"""Open the plugin-owned SQLite projection and its durable event ledger."""
# 1. Open with WAL and full synchronous durability.
path.parent.mkdir(parents=True, exist_ok=True)
conn = sqlite3.connect(path)
conn.row_factory = sqlite3.Row
_ = conn.execute("PRAGMA journal_mode = WAL")
_ = conn.execute("PRAGMA synchronous = FULL")
_ = conn.executescript(
"""
CREATE TABLE IF NOT EXISTS proactive_feedback_events (
id INTEGER PRIMARY KEY AUTOINCREMENT,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
session_key TEXT NOT NULL,
user_message_id TEXT NOT NULL,
assistant_message_id TEXT NOT NULL,
proactive_message_id TEXT,
feedback_type TEXT NOT NULL,
confidence TEXT NOT NULL,
pa_score REAL,
pua_score REAL,
lag_seconds INTEGER,
candidate_count INTEGER NOT NULL,
matched_by TEXT NOT NULL,
reason TEXT NOT NULL,
user_content_preview TEXT,
assistant_content_preview TEXT,
proactive_content_preview TEXT,
UNIQUE(user_message_id, proactive_message_id)
);
CREATE INDEX IF NOT EXISTS idx_pfe_session_created
ON proactive_feedback_events(session_key, created_at);
CREATE INDEX IF NOT EXISTS idx_pfe_proactive
ON proactive_feedback_events(proactive_message_id);
CREATE UNIQUE INDEX IF NOT EXISTS idx_pfe_one_user_per_proactive
ON proactive_feedback_events(proactive_message_id)
WHERE proactive_message_id IS NOT NULL;
CREATE TABLE IF NOT EXISTS proactive_feedback_input_inbox (
id INTEGER PRIMARY KEY AUTOINCREMENT,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
session_key TEXT NOT NULL,
turn_id TEXT NOT NULL DEFAULT '',
client_message_id TEXT NOT NULL DEFAULT '',
user_message_id TEXT NOT NULL,
user_message_ids_json TEXT NOT NULL DEFAULT '[]',
assistant_message_id TEXT,
processed_at TEXT,
UNIQUE(session_key, user_message_id)
);
CREATE INDEX IF NOT EXISTS idx_pfe_input_pending
ON proactive_feedback_input_inbox(processed_at, id);
CREATE TABLE IF NOT EXISTS proactive_feedback_session_catalog (
session_key TEXT PRIMARY KEY,
discovered_at TEXT NOT NULL DEFAULT (datetime('now'))
);
CREATE TABLE IF NOT EXISTS proactive_feedback_outbox (
row_id INTEGER PRIMARY KEY,
event_id TEXT NOT NULL UNIQUE,
payload_json TEXT NOT NULL,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
published_at TEXT
);
CREATE TABLE IF NOT EXISTS proactive_feedback_published_cursor (
name TEXT PRIMARY KEY,
row_id INTEGER NOT NULL DEFAULT 0
);
INSERT OR IGNORE INTO proactive_feedback_published_cursor(name, row_id)
VALUES ('proactive_feedback', 0);
"""
)
# 2. Preserve the v2 projection columns while adding the v3 ledger.
_ensure_column(conn, "user_content_preview")
_ensure_column(conn, "assistant_content_preview")
_ensure_column(conn, "proactive_content_preview")
_ensure_input_column(conn, "user_message_ids_json")
conn.commit()
return conn
def insert_feedback(conn: sqlite3.Connection, event: FeedbackEvent) -> int | None:
"""Append one immutable accepted feedback fact or verify an exact duplicate."""
# 1. Reject a proactive message already owned by another user reply.
if _feedback_owned_by_other(conn, event):
return None
# 2. The first accepted payload owns the Turn identity forever.
existing = _existing_feedback(conn, event)
if existing is not None:
expected_hash = accepted_payload_hash(_accepted_payload(event))
actual_hash = accepted_payload_hash(_accepted_payload_from_row(existing))
if actual_hash != expected_hash:
raise RuntimeError(
"accepted feedback payload 漂移: "
f"proactive_feedback:{int(existing['id'])}"
)
return int(existing["id"])
# 3. Append the accepted fact without touching the frozen legacy outbox.
try:
row_id = _insert_feedback_row(conn, event)
conn.commit()
except (sqlite3.Error, RuntimeError, TypeError, ValueError):
conn.rollback()
raise
return row_id
def insert_feedback_input(
conn: sqlite3.Connection,
*,
session_key: str,
turn_id: str,
client_message_id: str,
user_message_id: str,
assistant_message_id: str | None,
user_message_ids: tuple[str, ...] | None = None,
) -> int:
"""Durably record one committed Turn identity without storing message text."""
# 1. Validate the identity that the recovery reader will use.
_required_input_text(session_key, "session_key")
_required_input_text(user_message_id, "user_message_id")
ordered_user_ids = (
(user_message_id,) if user_message_ids is None else user_message_ids
)
_validate_user_message_ids(ordered_user_ids)
if ordered_user_ids[-1] != user_message_id:
raise ValueError("input inbox user_message_id 必须是 ordered IDs 的最后一项")
_optional_input_text(turn_id, "turn_id")
_optional_input_text(client_message_id, "client_message_id")
if assistant_message_id is not None:
_required_input_text(assistant_message_id, "assistant_message_id")
# 2. Preserve one durable row for duplicate committed events.
existing = conn.execute(
"""
SELECT id, processed_at, user_message_ids_json
FROM proactive_feedback_input_inbox
WHERE session_key = ? AND user_message_id = ?
LIMIT 1
""",
(session_key, user_message_id),
).fetchone()
if existing is not None:
if existing["processed_at"] is None and _decode_user_message_ids(
existing["user_message_ids_json"], user_message_id
) != ordered_user_ids:
_ = conn.execute(
"""
UPDATE proactive_feedback_input_inbox
SET user_message_ids_json = ?, assistant_message_id = ?
WHERE id = ? AND processed_at IS NULL
""",
(
json.dumps(ordered_user_ids, ensure_ascii=False),
assistant_message_id,
int(existing["id"]),
),
)
conn.commit()
return int(existing["id"])
try:
cursor = conn.execute(
"""
INSERT INTO proactive_feedback_input_inbox(
session_key, turn_id, client_message_id,
user_message_id, user_message_ids_json, assistant_message_id
)
VALUES (?, ?, ?, ?, ?, ?)
""",
(
session_key,
turn_id,
client_message_id,
user_message_id,
json.dumps(ordered_user_ids, ensure_ascii=False),
assistant_message_id,
),
)
if cursor.lastrowid is None:
raise RuntimeError("feedback input insert failed")
row_id = int(cursor.lastrowid)
_ = conn.execute(
"""
INSERT OR IGNORE INTO proactive_feedback_session_catalog(session_key)
VALUES (?)
""",
(session_key,),
)
conn.commit()
return row_id
except (sqlite3.Error, RuntimeError, ValueError):
conn.rollback()
raise
def pending_feedback_inputs(
conn: sqlite3.Connection,
*,
limit: int = 100,
) -> list[FeedbackInputRecord]:
"""Read unprocessed committed Turn identities in durable row order."""
# 1. Bound the recovery batch before reading the durable inbox.
if isinstance(limit, bool) or not isinstance(limit, int) or limit < 1:
raise ValueError("input inbox limit 必须是正整数")
rows = conn.execute(
"""
SELECT id, session_key, turn_id, client_message_id,
user_message_id, user_message_ids_json, assistant_message_id
FROM proactive_feedback_input_inbox
WHERE processed_at IS NULL
ORDER BY id ASC
LIMIT ?
""",
(limit,),
).fetchall()
return [_feedback_input_record(row) for row in rows]
def pending_feedback_input(
conn: sqlite3.Connection,
*,
row_id: int,
) -> FeedbackInputRecord | None:
"""Read one pending committed Turn identity for the in-memory wake path."""
if isinstance(row_id, bool) or not isinstance(row_id, int) or row_id < 1:
raise ValueError("input inbox row_id 必须是正整数")
row = conn.execute(
"""
SELECT id, session_key, turn_id, client_message_id,
user_message_id, user_message_ids_json, assistant_message_id
FROM proactive_feedback_input_inbox
WHERE id = ? AND processed_at IS NULL
""",
(row_id,),
).fetchone()
return None if row is None else _feedback_input_record(row)
def mark_feedback_input_processed(
conn: sqlite3.Connection,
*,
row_id: int,
) -> None:
"""Record successful handling of one durable committed Turn identity."""
# 1. Validate the receipt identity before changing the inbox state.
if isinstance(row_id, bool) or not isinstance(row_id, int) or row_id < 1:
raise ValueError("input inbox row_id 必须是正整数")
update = conn.execute(
"""
UPDATE proactive_feedback_input_inbox
SET processed_at = datetime('now')
WHERE id = ? AND processed_at IS NULL
""",
(row_id,),
)
if update.rowcount == 0:
existing = conn.execute(
"SELECT id FROM proactive_feedback_input_inbox WHERE id = ?",
(row_id,),
).fetchone()
if existing is None:
conn.rollback()
raise RuntimeError("input inbox receipt 不匹配 pending row")
conn.commit()
def feedback_session_keys(
conn: sqlite3.Connection,
*,
limit: int = 64,
) -> tuple[str, ...]:
"""Read the bounded durable session-key catalog used by formal recovery."""
if isinstance(limit, bool) or not isinstance(limit, int) or limit < 1:
raise ValueError("session catalog limit 必须是正整数")
rows = conn.execute(
"""
SELECT session_key
FROM proactive_feedback_session_catalog
ORDER BY discovered_at ASC, session_key ASC
LIMIT ?
""",
(limit,),
).fetchall()
return tuple(str(row["session_key"]) for row in rows)
def feedback_identity_exists(
conn: sqlite3.Connection,
*,
session_key: str,
user_message_id: str,
) -> bool:
"""Check whether a feedback projection already owns one user identity."""
row = conn.execute(
"""
SELECT 1
FROM proactive_feedback_events
WHERE session_key = ? AND user_message_id = ?
LIMIT 1
""",
(session_key, user_message_id),
).fetchone()
return row is not None
def _feedback_owned_by_other(
conn: sqlite3.Connection,
event: FeedbackEvent,
) -> bool:
if event.proactive_message_id is None:
return False
row = conn.execute(
"""
SELECT id
FROM proactive_feedback_events
WHERE proactive_message_id = ? AND user_message_id <> ?
LIMIT 1
""",
(event.proactive_message_id, event.user_message_id),
).fetchone()
return row is not None
def _existing_feedback(
conn: sqlite3.Connection,
event: FeedbackEvent,
) -> sqlite3.Row | None:
row = conn.execute(
"""
SELECT id, session_key, user_message_id, assistant_message_id,
proactive_message_id, feedback_type, confidence,
pa_score, pua_score, lag_seconds, candidate_count,
matched_by, reason, user_content_preview,
assistant_content_preview, proactive_content_preview
FROM proactive_feedback_events
WHERE session_key = ? AND user_message_id = ?
ORDER BY id ASC
LIMIT 1
""",
(event.session_key, event.user_message_id),
).fetchone()
return row
def _accepted_payload(event: FeedbackEvent) -> dict[str, object]:
return {
"session_key": event.session_key,
"user_message_id": event.user_message_id,
"assistant_message_id": event.assistant_message_id,
"proactive_message_id": event.proactive_message_id,
"feedback_type": event.feedback_type,
"confidence": event.confidence,
"pa_score": event.pa_score,
"pua_score": event.pua_score,
"lag_seconds": event.lag_seconds,
"candidate_count": event.candidate_count,
"matched_by": event.matched_by,
"reason": event.reason,
"user_content_preview": event.user_content_preview,
"assistant_content_preview": event.assistant_content_preview,
"proactive_content_preview": event.proactive_content_preview,
}
def _accepted_payload_from_row(row: sqlite3.Row) -> dict[str, object]:
return {
field: row[field]
for field in (
"session_key",
"user_message_id",
"assistant_message_id",
"proactive_message_id",
"feedback_type",
"confidence",
"pa_score",
"pua_score",
"lag_seconds",
"candidate_count",
"matched_by",
"reason",
"user_content_preview",
"assistant_content_preview",
"proactive_content_preview",
)
}
def _insert_feedback_row(conn: sqlite3.Connection, event: FeedbackEvent) -> int:
cursor = conn.execute(
"""
INSERT INTO proactive_feedback_events (
session_key, user_message_id, assistant_message_id,
proactive_message_id, feedback_type, confidence, pa_score, pua_score,
lag_seconds, candidate_count, matched_by, reason,
user_content_preview, assistant_content_preview, proactive_content_preview
)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""",
(
event.session_key,
event.user_message_id,
event.assistant_message_id,
event.proactive_message_id,
event.feedback_type,
event.confidence,
event.pa_score,
event.pua_score,
event.lag_seconds,
event.candidate_count,
event.matched_by,
event.reason,
event.user_content_preview,
event.assistant_content_preview,
event.proactive_content_preview,
),
)
if cursor.lastrowid is None:
raise RuntimeError("feedback insert failed")
return int(cursor.lastrowid)
def _feedback_input_record(row: sqlite3.Row) -> FeedbackInputRecord:
user_message_id = str(row["user_message_id"])
return FeedbackInputRecord(
row_id=int(row["id"]),
session_key=str(row["session_key"]),
turn_id=str(row["turn_id"]),
client_message_id=str(row["client_message_id"]),
user_message_id=user_message_id,
user_message_ids=_decode_user_message_ids(
row["user_message_ids_json"], user_message_id
),
assistant_message_id=(
None
if row["assistant_message_id"] is None
else str(row["assistant_message_id"])
),
)
def _required_input_text(value: str, field: str) -> None:
if not isinstance(value, str) or not value.strip():
raise ValueError(f"input inbox {field} 必须是非空字符串")
if value != value.strip():
raise ValueError(f"input inbox {field} 不能有首尾空白")
def _optional_input_text(value: str, field: str) -> None:
if not isinstance(value, str):
raise TypeError(f"input inbox {field} 必须是字符串")
if value != value.strip():
raise ValueError(f"input inbox {field} 不能有首尾空白")
def _validate_user_message_ids(user_message_ids: tuple[str, ...]) -> None:
if not user_message_ids:
raise ValueError("input inbox user_message_ids 不能为空")
if len(set(user_message_ids)) != len(user_message_ids):
raise ValueError("input inbox user_message_ids 不能重复")
for message_id in user_message_ids:
_required_input_text(message_id, "user_message_id")
def _decode_user_message_ids(value: object, fallback: str) -> tuple[str, ...]:
if isinstance(value, str) and value:
try:
decoded = json.loads(value)
except json.JSONDecodeError:
decoded = None
if decoded and isinstance(decoded, list) and all(
isinstance(item, str) and item for item in decoded
):
ids = tuple(decoded)
if len(set(ids)) == len(ids) and ids[-1] == fallback:
return ids
return (fallback,)
def _ensure_input_column(conn: sqlite3.Connection, name: str) -> None:
columns = {
str(row[1])
for row in conn.execute(
"PRAGMA table_info(proactive_feedback_input_inbox)"
)
}
if name not in columns:
_ = conn.execute(
"ALTER TABLE proactive_feedback_input_inbox "
"ADD COLUMN user_message_ids_json TEXT NOT NULL DEFAULT '[]'"
)
def pending_feedback_outbox(
conn: sqlite3.Connection,
*,
limit: int = 100,
) -> list[FeedbackOutboxRecord]:
"""Read unpublished payloads in durable row order."""
# 1. Bound the recovery batch before reading the durable queue.
if isinstance(limit, bool) or not isinstance(limit, int) or limit < 1:
raise ValueError("outbox limit 必须是正整数")
rows = conn.execute(
"""
SELECT row_id, event_id, payload_json
FROM proactive_feedback_outbox
WHERE published_at IS NULL
ORDER BY row_id ASC
LIMIT ?
""",
(limit,),
).fetchall()
return [
FeedbackOutboxRecord(
row_id=int(row["row_id"]),
event_id=str(row["event_id"]),
payload_json=str(row["payload_json"]),
)
for row in rows
]
def mark_feedback_published(
conn: sqlite3.Connection,
*,
row_id: int,
event_id: str,
) -> None:
"""Record one successful publication and advance the same-DB cursor."""
# 1. Validate the receipt identity before changing the cursor.
if isinstance(row_id, bool) or not isinstance(row_id, int) or row_id < 1:
raise ValueError("outbox row_id 必须是正整数")
if not isinstance(event_id, str) or not event_id:
raise ValueError("outbox event_id 必须是非空字符串")
# 2. Mark the exact outbox row and advance only its owner cursor.
update = conn.execute(
"""
UPDATE proactive_feedback_outbox
SET published_at = datetime('now')
WHERE row_id = ? AND event_id = ? AND published_at IS NULL
""",
(row_id, event_id),
)
if update.rowcount == 0:
existing = conn.execute(
"""
SELECT published_at
FROM proactive_feedback_outbox
WHERE row_id = ? AND event_id = ?
""",
(row_id, event_id),
).fetchone()
if existing is None or existing["published_at"] is None:
conn.rollback()
raise RuntimeError("outbox receipt 不匹配 pending row")
_ = conn.execute(
"""
UPDATE proactive_feedback_published_cursor
SET row_id = MAX(row_id, ?)
WHERE name = 'proactive_feedback'
""",
(row_id,),
)
conn.commit()
def _ensure_column(conn: sqlite3.Connection, name: str) -> None:
columns = {
str(row[1])
for row in conn.execute("PRAGMA table_info(proactive_feedback_events)")
}
if name not in columns:
_ = conn.execute(
f"ALTER TABLE proactive_feedback_events ADD COLUMN {name} TEXT"
)