HEL-906 rework: persistence fail-closed stop + conservative pre-record accounting

- asr_usage: ledger write/read failure, corruption or mid-window vanish now
  stop all window outbound (fail-closed), preserve known consumption
  (monotonic, no zero-budget default), log + record guard_stop (durable
  across same-window restarts)
- asr_usage: conservative reserve before send (failed/cancelled sends are
  NOT refunded) + separately tracked confirmed-delivered seconds; replay
  restores both
- stt_funasr: reserve_audio before ws.send, note_audio_delivered after
  successful await only
- tests: 24 deterministic offline cases incl. manager's budget-regression
  repro, read/corrupt/missing rejection, record-then-raise/cancel fake ws,
  guard_stop across restart

Co-authored-by: multica-agent <github@multica.ai>
This commit is contained in:
总工
2026-10-28 09:02:51 +08:00
co-authored by multica-agent
parent ccfc04edcd
commit cf395d4e06
3 changed files with 469 additions and 84 deletions
+279 -33
View File
@@ -6,10 +6,14 @@
1. 纯计数/闸/账本恢复(guard 单元):fail-closed 默认、按实际帧样本计时、
触线前拒绝、重试口径、落盘恢复、跨窗口隔离、崩溃少计有界。
2. 真实接缝:用假 livekit/websockets 模块(隔离假 provider、假帧)导入
真实的 voice/stt_funasr.py 与 voice/worker.py,驱动真实 ``_run`` 送数
路径——建连检查、发送前拒绝、发送后计数、接收侧死亡、流异常重试、
utterance 聚合落账全部走产品代码;worker entrypoint 布线(guard 注入、
房间名标识、触线 ctx.shutdown、未布防拒绝)逐项断言。
真实的 voice/stt_funasr.py 与 voice/worker.py,驱动真实 ``_run`` 送数
路径——建连检查、发送前拒绝、保守预记/确证送达、接收侧死亡、流异常
重试、utterance 聚合落账全部走产品代码;worker entrypoint 布线(guard
注入、房间名标识、触线 ctx.shutdown、未布防拒绝)逐项断言。
3. 2026-10-28 总管定点复核返工:账本写失败→重放不得回退预算(复现脚本的
回归路径)、读失败/损坏/中途丢失 fail-closed 停机并保全已知消耗、
guard_stop 跨重启仍停、假 ws 先记 payload 再 raise/取消后预算仍包含
该帧(保守计费不退还、确证量单列)。
零真实 ASR/TTS/LiveKit 调用(fake 连接全部在进程内),零安装。
"""
@@ -82,19 +86,31 @@ class FakeResampler:
class FakeWS:
"""进程内 FunASR websocket 假 provider:记录每个出站字节."""
"""进程内 FunASR websocket 假 provider:记录每个出站字节.
fail_send 模拟「帧可能已出站」的不确定失败:先把 payload 记入 sent
再 raise/cancel(控制消息不受 fail_bytes_after 影响)。
"""
def __init__(self, server_msgs: list[str] | None = None, recv_fail: bool = False) -> None:
self.sent: list[bytes | str] = []
self.server_msgs = list(server_msgs or [])
self.recv_fail = recv_fail
self.closed = False
self.fail_send = False
self.fail_send = "" # "" | "raise" | "cancel"
self.fail_bytes_after: int | None = None # 第 N 个音频帧之后开始失败
async def send(self, payload: bytes | str) -> None:
if self.fail_send:
raise OSError("send refused")
self.sent.append(payload)
self.sent.append(payload) # 先记:即使随后失败,帧也可能已经出站
if isinstance(payload, (bytes, bytearray)) and self.fail_send:
if self.fail_bytes_after is not None and self.fail_bytes_after > 0:
self.fail_bytes_after -= 1
return # 前 N 个音频帧正常送达
self.fail_bytes_after = None # 计数耗尽:之后的音频帧都按失败语义
if self.fail_send == "raise":
raise OSError("send failed after outbound")
if self.fail_send == "cancel":
raise asyncio.CancelledError()
async def close(self) -> None:
self.closed = True
@@ -447,15 +463,32 @@ def test_guard_audio_counted_by_actual_frame_samples(tmp_path):
guard.note_connect_result(call, ok=True)
# 16k 直接路径:160 样本 = 0.01s;重采样路径按输出帧 16k 计
for _ in range(10):
guard.precheck_audio(call, 16000, 160)
guard.note_audio_sent(call, 16000, 160, 320)
guard.reserve_audio(call, 16000, 160, 320)
guard.note_audio_delivered(call, 16000, 160, 320)
for _ in range(5):
guard.precheck_audio(call, 16000, 160)
guard.note_audio_sent(call, 16000, 160, 320) # 重发按重复计
guard.reserve_audio(call, 16000, 160, 320)
guard.note_audio_delivered(call, 16000, 160, 320) # 重发按重复计
guard.stream_end(call, "closed")
assert guard.calls[call].audio_seconds == pytest.approx(0.15)
assert guard.calls[call].confirmed_audio_seconds == pytest.approx(0.15)
audio = [r for r in read_records(tmp_path) if r["kind"] == "audio"]
assert sum(r["seconds"] for r in audio) == pytest.approx(0.15)
assert sum(r["confirmed_seconds"] for r in audio) == pytest.approx(0.15)
def test_guard_uncertain_outbound_not_refunded(tmp_path):
"""发送前预记、失败/取消不退还(保守计费);确证量只记成功返回的帧."""
guard = make_guard(tmp_path)
call = guard.begin_stream("room-a")
guard.reserve_audio(call, 16000, 160) # 发送失败的帧:保守预记保留
guard.reserve_audio(call, 16000, 160)
guard.note_audio_delivered(call, 16000, 160) # 只有这帧确证送达
guard.flush_audio(call)
assert guard.calls[call].audio_seconds == pytest.approx(0.02)
assert guard.calls[call].confirmed_audio_seconds == pytest.approx(0.01)
audio = [r for r in read_records(tmp_path) if r["kind"] == "audio"][-1]
assert audio["seconds"] == pytest.approx(0.02)
assert audio["confirmed_seconds"] == pytest.approx(0.01)
def test_guard_blocks_crossing_frame_before_send(tmp_path):
@@ -464,14 +497,14 @@ def test_guard_blocks_crossing_frame_before_send(tmp_path):
call = guard.begin_stream("room-a")
guard.check_connect(call)
guard.note_connect_result(call, ok=True)
guard.precheck_audio(call, 16000, 16000) # 1.0s
guard.note_audio_sent(call, 16000, 16000, 32000)
guard.reserve_audio(call, 16000, 16000, 32000) # 1.0s
guard.note_audio_delivered(call, 16000, 16000, 32000)
guard.flush_audio(call)
guard.precheck_audio(call, 16000, 16000) # 恰好等于上限:允许(≤上限)
guard.note_audio_sent(call, 16000, 16000, 32000)
guard.reserve_audio(call, 16000, 16000) # 恰好等于上限:允许(≤上限)
guard.note_audio_delivered(call, 16000, 16000, 32000)
guard.flush_audio(call)
with pytest.raises(AsrWindowClosed): # 第 3 秒会在发送前拒绝
guard.precheck_audio(call, 16000, 16000)
guard.reserve_audio(call, 16000, 16000)
assert stops == ["window-audio-exhausted"] # 回调恰好一次
# 同窗新通也立即拒绝(新连接/新音频都不放行)
with pytest.raises(AsrWindowClosed):
@@ -526,16 +559,18 @@ def test_guard_ledger_recovery_same_window_no_reset(tmp_path):
guard1.check_connect(call)
guard1.note_connect_result(call, ok=False, error="x")
for _ in range(150):
guard1.precheck_audio(call, 16000, 160)
guard1.note_audio_sent(call, 16000, 160, 320)
guard1.reserve_audio(call, 16000, 160, 320)
guard1.note_audio_delivered(call, 16000, 160, 320)
guard1.flush_audio(call)
guard1.stream_end(call, "closed")
# 模拟进程重启:同窗口同账本重建 guard,预算与逐通历史都在
guard2 = make_guard(tmp_path, max_audio_seconds=3.0)
assert guard2.window_audio_seconds == pytest.approx(1.5)
assert guard2.window_confirmed_seconds == pytest.approx(1.5)
cu = guard2.calls["room-a"]
assert (cu.connect_attempts, cu.connect_failures, cu.connect_retries) == (2, 1, 0)
assert cu.audio_seconds == pytest.approx(1.5)
assert cu.confirmed_audio_seconds == pytest.approx(1.5)
assert cu.retry_pending is True # 最后一次连接事实是失败
# 耗尽同窗口剩余预算后拒绝;重开同窗口 id 不能重置
call = guard2.begin_stream("room-a")
@@ -543,8 +578,8 @@ def test_guard_ledger_recovery_same_window_no_reset(tmp_path):
guard2.note_connect_result(call, ok=True) # retry_pending=True → 这是 retry
with pytest.raises(AsrWindowClosed):
for _ in range(200):
guard2.precheck_audio(call, 16000, 160)
guard2.note_audio_sent(call, 16000, 160, 320)
guard2.reserve_audio(call, 16000, 160, 320)
guard2.note_audio_delivered(call, 16000, 160, 320)
guard2.flush_audio(call)
@@ -556,15 +591,15 @@ def test_guard_window_isolation_does_not_stop_others(tmp_path):
g1.check_connect(call)
g1.note_connect_result(call, ok=True)
for _ in range(10):
g1.precheck_audio(call, 16000, 160)
g1.note_audio_sent(call, 16000, 160, 320)
g1.reserve_audio(call, 16000, 160, 320)
g1.note_audio_delivered(call, 16000, 160, 320)
g2 = make_guard(tmp_path, window_id="w2", max_audio_seconds=100.0)
call = g2.begin_stream("room-a") # 同账本、不同窗口:完全不受 W1 影响
g2.check_connect(call)
g2.note_connect_result(call, ok=True)
for _ in range(10):
g2.precheck_audio(call, 16000, 160)
g2.note_audio_sent(call, 16000, 160, 320)
g2.reserve_audio(call, 16000, 160, 320)
g2.note_audio_delivered(call, 16000, 160, 320)
g2.stream_end(call, "closed")
assert g2.calls["room-a"].audio_seconds == pytest.approx(0.1)
@@ -576,15 +611,16 @@ def test_guard_crash_undercount_bounded_by_flush(tmp_path):
guard.check_connect(call)
guard.note_connect_result(call, ok=True)
for _ in range(30):
guard.precheck_audio(call, 16000, 160)
guard.note_audio_sent(call, 16000, 160, 320) # 0.3s < flush 阈值
guard.reserve_audio(call, 16000, 160, 320)
guard.note_audio_delivered(call, 16000, 160, 320) # 0.3s < flush 阈值
# 模拟进程直接消失(没有 stream_end/flush)
replayed = summarize_ledger(tmp_path / "asr-usage.jsonl", "w-test")
assert replayed["windows"]["w-test"]["audio_seconds"] == 0.0
# 正常路径(flush/stream_end)计数完整落账
guard2 = make_guard(tmp_path, flush_seconds=5.0)
call = guard2.begin_stream("room-b")
guard2.note_audio_sent(call, 16000, 16000, 32000)
guard2.reserve_audio(call, 16000, 16000, 32000)
guard2.note_audio_delivered(call, 16000, 16000, 32000)
guard2.stream_end(call, "closed")
assert summarize_ledger(tmp_path / "asr-usage.jsonl", "w-test")["windows"][
"w-test"]["calls"]["room-b"]["audio_seconds"] == pytest.approx(1.0)
@@ -595,7 +631,8 @@ def test_summarize_cli_reproducible(tmp_path, monkeypatch):
call = guard.begin_stream("room-a")
guard.check_connect(call)
guard.note_connect_result(call, ok=True)
guard.note_audio_sent(call, 16000, 16000, 32000)
guard.reserve_audio(call, 16000, 16000, 32000)
guard.note_audio_delivered(call, 16000, 16000, 32000)
guard.stream_end(call, "closed")
repo_root = Path(__file__).resolve().parents[1]
proc = subprocess.run(
@@ -631,11 +668,13 @@ async def test_seam_counts_fed_audio_both_sample_rates(fake_sdk, tmp_path):
cu = guard.calls["cg-voice-abc"]
# 16k 直接路径 0.3s + 48k→16k 重采样路径 0.3s(按实际输出帧计时)
assert cu.audio_seconds == pytest.approx(0.6)
assert cu.confirmed_audio_seconds == pytest.approx(0.6) # 全部送达成功
assert cu.connect_attempts == 2 # 两轮 utterance 两次建连
assert (cu.connect_failures, cu.connect_retries) == (0, 0)
records = read_records(tmp_path)
audio_records = [r for r in records if r["kind"] == "audio"]
assert [round(r["seconds"], 6) for r in audio_records] == [0.3, 0.3] # utterance 边界聚合
assert [round(r["confirmed_seconds"], 6) for r in audio_records] == [0.3, 0.3]
assert all(r["call"] == "cg-voice-abc" for r in records)
ends = [r for r in records if r["kind"] == "call_end"]
assert [r["reason"] for r in ends] == ["closed"]
@@ -719,9 +758,10 @@ async def test_seam_window_exhaustion_stops_before_crossing(fake_sdk, tmp_path):
stt = funasr.FunASRSTT(usage=guard, call_label="room-cap")
with pytest.raises(AsrWindowClosed):
await drive(funasr, stt, [frame_16k() for _ in range(6)] + [None])
# 0.05s = 5 帧放行,第 6 帧发送前拒绝:出站字节恰好 5 帧
# 0.05s = 5 帧放行,第 6 帧发送前拒绝:出站字节恰好 5 帧(provider 未被触线帧触碰)
assert len(fake_sdk.websockets.bytes_sent()) == 5
assert guard.calls["room-cap"].audio_seconds == pytest.approx(0.05)
assert guard.calls["room-cap"].confirmed_audio_seconds == pytest.approx(0.05)
assert stops == ["window-audio-exhausted"]
records = read_records(tmp_path)
assert records[-1]["kind"] == "call_end"
@@ -808,10 +848,10 @@ async def test_worker_entrypoint_wires_guard(fake_sdk, tmp_path, monkeypatch, ca
assert "asr_window=" in out and "hel902-w1" in out
# 触线回调真的接到 ctx.shutdown:预检越限帧 → 结束本通 job
call = guard.begin_stream("cg-voice-room1")
guard.note_audio_sent(call, 16000, 16000, 32000)
guard.reserve_audio(call, 16000, 16000, 32000)
guard.flush_audio(call)
with pytest.raises(AsrWindowClosed):
guard.precheck_audio(call, 16000, 16000 * 2700) # 会越 2700s 上限的帧
guard.reserve_audio(call, 16000, 16000 * 2700) # 会越 2700s 上限的帧
assert ctx.shutdown_calls, "on_exhausted 必须真的调用 ctx.shutdown 结束本通"
@@ -829,3 +869,209 @@ async def test_worker_entrypoint_default_is_fail_closed(fake_sdk, monkeypatch, c
with pytest.raises(AsrWindowClosed):
guard.begin_stream("cg-voice-room2")
assert "asr_window=" in capsys.readouterr().out
# ---------------------------------------------------------------------------
# 4) 2026-10-28 总管定点复核返工:持久化 fail-closed 与不确定出站口径
# ---------------------------------------------------------------------------
class FakeClock:
def __init__(self, t: float = 0.0) -> None:
self.t = t
def __call__(self) -> float:
return self.t
def advance(self, dt: float) -> None:
self.t += dt
def _rework_guard(tmp_path: Path, clock: FakeClock, *, on_exhausted=None,
**overrides) -> AsrUsageGuard:
values = dict(window_id="w-rework", max_audio_seconds=10.0,
flush_seconds=1e9, resync_seconds=5.0)
values.update(overrides)
return AsrUsageGuard(AsrWindowPolicy(**values), tmp_path / "asr-usage.jsonl",
clock=clock, on_exhausted=on_exhausted)
def _feed(guard: AsrUsageGuard, call: str, seconds: float, *, deliver: bool = True) -> None:
frames = round(seconds * 100)
for _ in range(frames):
guard.reserve_audio(call, 16000, 160, 320)
if deliver:
guard.note_audio_delivered(call, 16000, 160, 320)
def test_ledger_write_failure_never_regresses_budget(tmp_path, monkeypatch):
"""总管复现的回归路径:写失败→flush 丢缓冲→重放按旧账回退,修复后不再发生."""
import pathlib
stops: list[str] = []
clock = FakeClock(0.0)
guard = _rework_guard(tmp_path, clock, max_audio_seconds=1.5,
on_exhausted=stops.append)
call = guard.begin_stream("room")
guard.check_connect(call)
guard.note_connect_result(call, ok=True)
_feed(guard, call, 0.8)
guard.flush_audio(call) # 0.8s 落账成功
assert guard.window_audio_seconds == pytest.approx(0.8)
real_open = pathlib.Path.open
def fail_append(self, mode="r", *args, **kwargs):
if "a" in (mode or ""):
raise OSError("append refused (injected)")
return real_open(self, mode, *args, **kwargs)
monkeypatch.setattr(pathlib.Path, "open", fail_append)
_feed(guard, call, 0.5)
guard.flush_audio(call) # 0.5s 落账失败:内存保全、立即停机、不许回退
assert guard.window_audio_seconds == pytest.approx(1.3)
assert guard.persistence_stop_reason == "ledger-write-failed"
assert stops == ["ledger-write-failed"] # 停机回调恰好一次并带原因
clock.advance(6.0) # 越过 resync:重放不得把内存拉回旧账本值 0.8
with pytest.raises(AsrWindowClosed) as ei:
_feed(guard, call, 0.6) # 复现脚本里的「再送 0.6s」:现在被拒
assert "ledger-write-failed" in str(ei.value)
assert guard.window_audio_seconds == pytest.approx(1.3) # 无预算倒退
# 写失败注入仍生效期间 block 记录同样写不落账——停机事实以日志与内存为准
assert not [r for r in read_records(tmp_path) if r["kind"] == "block"]
# 停机状态在 summary/summary_line 可见(操作员可核对)
assert guard.summary()["persistence_stop_reason"] == "ledger-write-failed"
assert "ledger-write-failed" in guard.summary_line()
def test_ledger_read_failure_stops_outbound_preserving_memory(tmp_path, monkeypatch):
import pathlib
clock = FakeClock(0.0)
guard = _rework_guard(tmp_path, clock)
call = guard.begin_stream("room")
guard.check_connect(call)
guard.note_connect_result(call, ok=True)
_feed(guard, call, 1.0)
guard.flush_audio(call)
def boom(self, *args, **kwargs):
raise OSError("read refused (injected)")
monkeypatch.setattr(pathlib.Path, "read_text", boom)
clock.advance(6.0) # resync 触发严格读:读失败 → fail-closed
with pytest.raises(AsrWindowClosed):
guard.reserve_audio(call, 16000, 160, 320)
assert guard.persistence_stop_reason == "ledger-read-failed"
assert guard.window_audio_seconds == pytest.approx(1.0) # 不清零、不倒退
with pytest.raises(AsrWindowClosed): # 新通也不放行
guard.begin_stream("room-2")
def test_ledger_corruption_stops_outbound(tmp_path):
clock = FakeClock(0.0)
guard = _rework_guard(tmp_path, clock)
call = guard.begin_stream("room")
guard.check_connect(call)
guard.note_connect_result(call, ok=True)
_feed(guard, call, 1.0)
guard.flush_audio(call)
with (tmp_path / "asr-usage.jsonl").open("a", encoding="utf-8") as fh:
fh.write("{corrupt-not-json\n") # 中途损坏一行
clock.advance(6.0)
with pytest.raises(AsrWindowClosed):
guard.reserve_audio(call, 16000, 160, 320)
assert guard.persistence_stop_reason == "ledger-corrupt"
assert guard.window_audio_seconds == pytest.approx(1.0) # 损坏不套用、内存保全
with pytest.raises(AsrWindowClosed):
guard.check_connect("room")
def test_ledger_missing_after_seen_stops_outbound(tmp_path):
clock = FakeClock(0.0)
guard = _rework_guard(tmp_path, clock)
call = guard.begin_stream("room")
guard.check_connect(call)
guard.note_connect_result(call, ok=True)
_feed(guard, call, 1.0)
guard.flush_audio(call) # 账本已存在(读过/写过)
(tmp_path / "asr-usage.jsonl").unlink() # 中途消失 = 已落账事实丢失
clock.advance(6.0)
with pytest.raises(AsrWindowClosed):
guard.reserve_audio(call, 16000, 160, 320)
assert guard.persistence_stop_reason == "ledger-missing"
assert guard.window_audio_seconds == pytest.approx(1.0)
# 停机事实已落回重建的账本(guard_stop):汇总 CLI 可见
assert summarize_ledger(tmp_path / "asr-usage.jsonl", "w-rework")[
"windows"]["w-rework"]["stopped"] is True
def test_guard_stop_record_keeps_window_stopped_across_restart(tmp_path):
ledger = tmp_path / "asr-usage.jsonl"
lines = [
{"kind": "audio", "window": "w", "call": "room", "seconds": 2.0,
"confirmed_seconds": 2.0, "t": 1},
{"kind": "guard_stop", "window": "w", "reason": "ledger-corrupt", "t": 2},
]
ledger.write_text("".join(json.dumps(x) + "\n" for x in lines), encoding="utf-8")
guard = AsrUsageGuard(
AsrWindowPolicy(window_id="w", max_audio_seconds=10.0), ledger)
# 同窗重启不恢复出站;已知消耗(2.0s)仍被重放保全
assert guard.persistence_stop_reason == "ledger-corrupt"
assert guard.window_audio_seconds == pytest.approx(2.0)
with pytest.raises(AsrWindowClosed):
guard.begin_stream("room-new")
async def test_seam_uncertain_outbound_counted_conservatively(fake_sdk, tmp_path):
"""假 ws 先记下 payload 再 raise/取消:预算仍包含该帧,确证量不包含."""
import cybergril.voice.stt_funasr as funasr
guard = make_guard(tmp_path)
def flaky(mode: str, ok_frames: int) -> FakeWS:
ws = FakeWS(server_msgs=[])
ws.fail_send = mode
ws.fail_bytes_after = ok_frames
return ws
# 场景 1:第 3 帧送出后 raise(帧可能已出站)
fake_sdk.websockets.ws_factory = lambda: flaky("raise", 2)
stt = funasr.FunASRSTT(usage=guard, call_label="room-raise")
with pytest.raises(OSError):
await drive(funasr, stt, [frame_16k() for _ in range(3)] + [None])
cu = guard.calls["room-raise"]
assert cu.audio_seconds == pytest.approx(0.03) # 保守计费含失败帧
assert cu.confirmed_audio_seconds == pytest.approx(0.02) # 确证只有前两帧
ws_raise = fake_sdk.websockets.sockets[-1]
assert len([p for p in ws_raise.sent if isinstance(p, bytes)]) == 3 # 帧确实已出站
rec = [r for r in read_records(tmp_path)
if r["kind"] == "audio" and r["call"] == "room-raise"][-1]
assert rec["seconds"] == pytest.approx(0.03)
assert rec["confirmed_seconds"] == pytest.approx(0.02)
assert [r for r in read_records(tmp_path)
if r["kind"] == "call_end" and r["call"] == "room-raise"][-1]["reason"] == "error"
# 场景 2:第 2 帧送出后被取消:同样不退还预记
fake_sdk.websockets.ws_factory = lambda: flaky("cancel", 1)
stt2 = funasr.FunASRSTT(usage=guard, call_label="room-cancel")
with pytest.raises(asyncio.CancelledError):
await drive(funasr, stt2, [frame_16k() for _ in range(2)] + [None])
cu2 = guard.calls["room-cancel"]
assert cu2.audio_seconds == pytest.approx(0.02)
assert cu2.confirmed_audio_seconds == pytest.approx(0.01)
ws_cancel = fake_sdk.websockets.sockets[-1]
assert len([p for p in ws_cancel.sent if isinstance(p, bytes)]) == 2
# 触线拒绝仍然不碰 provider:越限帧在 reserve 阶段就拒绝,ws.send 不执行
guard_cap = AsrUsageGuard(
make_policy(max_audio_seconds=0.01), tmp_path / "cap.jsonl")
fake_sdk.websockets.ws_factory = None
stt3 = funasr.FunASRSTT(usage=guard_cap, call_label="room-cap2")
with pytest.raises(AsrWindowClosed):
await drive(funasr, stt3, [frame_16k() for _ in range(3)] + [None])
ws_cap = fake_sdk.websockets.sockets[-1]
assert len([p for p in ws_cap.sent if isinstance(p, bytes)]) == 1 # 只有第 1 帧出站