fix: address Codex review of telemetry fix (mkdir degrade, close, degrade tests)

This commit is contained in:
2026-07-16 08:53:50 -04:00
parent 065c8ae1b9
commit cc01d5ed62
3 changed files with 69 additions and 9 deletions
+20 -3
View File
@@ -1,7 +1,11 @@
"""SQLite 遥测记录器 — TelemetryRecorder Protocol 的生产实现。
通过 asyncio.to_thread 将 SQLite 同步写入桥接到异步接口,
确保事件循环不被阻塞。表在首次写入时懒初始化。
通过 asyncio.to_thread 将 SQLite 同步写入桥接到异步接口,确保事件循环不被阻塞。
构造时建单持久连接 + 建表(对齐 app/harness/log.py:HarnessLog 的并发写模式),
写入经进程内 threading.Lock 串行化,消除多连接并发写的 database is locked。
零丢失保证范围 = 单进程、单 recorder 实例(当前 main.py / video_split_cli 均单实例
注入)。同进程多个 recorder 指向同一 db 会退回跨连接竞争——本实现不支持该场景。
"""
from __future__ import annotations
@@ -68,6 +72,8 @@ class SQLiteTelemetryRecorder:
self._db_path = db_path
self._lock = threading.Lock()
self._conn: sqlite3.Connection | None = None
# mkdir / connect / PRAGMA / 建表统一纳入降级边界:任一失败(OSError 含
# PermissionError、sqlite3.Error)都降级为 self._conn=None,绝不冒泡拖垮初始化。
try:
Path(db_path).parent.mkdir(parents=True, exist_ok=True)
conn = sqlite3.connect(str(db_path), check_same_thread=False)
@@ -76,10 +82,21 @@ class SQLiteTelemetryRecorder:
conn.execute(self._CREATE_TABLE_SQL)
conn.commit()
self._conn = conn
except sqlite3.Error as exc:
except (OSError, sqlite3.Error) as exc:
logger.warning("遥测连接初始化失败(已降级,后续写入丢弃): {}", exc)
self._conn = None
def close(self) -> None:
"""幂等关闭持久连接(对齐 HarnessLog;进程退出前可选调以释放 fd)。
不调也不丢数据——每次 _write 已 commit 落 WAL,进程退出 OS 回收 fd、
WAL 已提交内容下次打开自动 checkpoint 恢复。
"""
with self._lock:
if self._conn is not None:
self._conn.close()
self._conn = None
def _write(
self,
*,