- asr_usage.py (stdlib-only): append-only JSONL ledger, per-call/window audio seconds counted from actually-sent frames (sample-rate aware, resend counted), connect attempt/failure/retry semantics (normal per-utterance reconnects are not retries), fail-closed default (real cap=0 unless a window is armed), pre-send blocking so no byte crosses the cap, ledger replay for restart recovery and cross-window isolation, resumable summarize CLI - stt_funasr.py: guard hooks on the real send path (check_connect before open_utt, precheck before send, count after send, recv-side death recorded, per-utterance flush aggregation); usage=None keeps prior behavior - worker.py: entrypoint builds guard from env per job, room name as call id, on_exhausted -> ctx.shutdown ends the call, window summary in start log - tests: 17 deterministic offline tests incl. fake livekit/websockets SDK driving the real _run seam, sample-rate variants, silence/cancel/failure/ reconnect/repeated-end, cap rejection before crossing, ledger persistence across restart, room deletion keeps history, other windows unaffected Co-authored-by: multica-agent <github@multica.ai>
465 lines
20 KiB
Python
465 lines
20 KiB
Python
"""连续通话 ASR 实际用量计数与一次性窗口闸(HEL-906).
|
||
|
||
补齐 HEL-905 复审留下的 §4 待补阻塞:连续通话内 FunASR 的**实际送入音频
|
||
量**与**连接尝试/重连/失败**没有本仓库可执行的程序计数。本模块只依赖
|
||
标准库(API 进程与离线测试环境都能直接导入),计数全部发生在专属
|
||
worker 的真实送数路径上:
|
||
|
||
- FunASRSTT(voice/stt_funasr.py)在每次 websocket 建连前 check_connect、
|
||
建连结果 note_connect_result、每个真实发送帧发送前 precheck_audio、
|
||
发送成功后 note_audio_sent;worker(voice/worker.py)按 job 注入 guard
|
||
并把 on_exhausted 接到 ctx.shutdown。
|
||
- 音频按**实际发送帧**的 sample_rate 与样本数计时(重采样后的输出帧按其
|
||
自身采样率计),同一帧重复发送按重复计;墙钟、开房/删房流水不参与
|
||
音频计时,事后成功流水也不追溯改数。
|
||
- 连接事实逐条落账:每次建连尝试(含失败)、失败后的重试(retry)、
|
||
接收侧死亡(connection_died)。FunASR 一句一连的惰性建连里,正常说完
|
||
一轮后的下一次建连不是 retry,只有上一次尝试失败/连接死亡/流异常结束
|
||
之后的建连才计 retry。
|
||
|
||
账本(追加写 JSONL,默认 /opt/voice-agent-cybergril/asr-usage.jsonl)独立
|
||
于实例侧会话账本 ``<db>-voice-sessions.json``:删房成功会把通话从会话账
|
||
本移除,但这里的逐通历史(call_start/audio/connect_attempt/
|
||
connection_died/call_end/block)永不改写、不随删房消失;窗口总量由重放
|
||
账本恢复,同 window_id 重启进程不能重置预算,旧窗口耗尽状态也被持久化
|
||
(不得把旧余额或新开账当作新许可)。
|
||
|
||
窗口语义沿用 think/budget.py 的 fail-closed 先例:
|
||
|
||
- 未布防(CYBERGRIL_ASR_WINDOW_ID 未设,产品默认):一切新连接与新音频
|
||
在发送前拒绝(真实 cap=0),拒绝本身落账;
|
||
- 布防(获批的一次性窗口启动时由窗口负责人显式设置环境变量):触线即
|
||
在发送前拒绝(AsrWindowClosed),worker 经 on_exhausted 结束本通 job;
|
||
上限只能收紧不能放宽,候选值见 docs/rework/hel902/r5-followup-package.md §4。
|
||
|
||
程序能保证 / 剩余只能监看(如实边界):
|
||
|
||
- 保证:布防进程内逐帧发送前硬停(帧不越上限一个字节)、逐通与全窗
|
||
计数不因删房/重启丢失、同窗重启不能重置预算。
|
||
- 跨进程有界收敛:账本是共同事实,每次建连检查与 resync_seconds 间隔
|
||
重放账本;两进程并行通话时对端最近 ≤ max(resync, flush) 间隔的音频
|
||
可能未计入本轮判定(有界过冲)。
|
||
- 只能监看:进程崩溃前 ≤ flush_seconds 的已发音频可能少计;接收侧死亡
|
||
未伴随发送失败时按 connection_died 计连接事实、不改已计音频;真实
|
||
FunASR/LiveKit 行为仍以窗口前 .12 实测为准。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import argparse
|
||
import contextlib
|
||
import json
|
||
import os
|
||
import secrets
|
||
import time
|
||
from dataclasses import dataclass, field
|
||
from pathlib import Path
|
||
|
||
DEFAULT_ASR_USAGE_LEDGER = "/opt/voice-agent-cybergril/asr-usage.jsonl"
|
||
DEFAULT_FLUSH_SECONDS = 5.0
|
||
DEFAULT_RESYNC_SECONDS = 5.0
|
||
|
||
# 允许浮点求和后恰好等于上限(“≤上限”而不是“<上限”)
|
||
_EPSILON = 1e-9
|
||
|
||
|
||
class AsrWindowClosed(Exception):
|
||
"""The armed window (or the fail-closed default) refuses this connection/audio."""
|
||
|
||
|
||
@dataclass(frozen=True)
|
||
class AsrWindowPolicy:
|
||
window_id: str = "" # 空 = 未布防:真实 cap=0,拒绝一切 ASR 连接/音频
|
||
max_audio_seconds: float = 0.0 # 全窗口实际送入 ASR 音频上限
|
||
max_connect_retries_per_call: int = 0 # 每通连接重试上限(失败后的再建连)
|
||
flush_seconds: float = DEFAULT_FLUSH_SECONDS # 音频计数聚合落账阈值
|
||
resync_seconds: float = DEFAULT_RESYNC_SECONDS # 跨进程账本重放间隔
|
||
|
||
@property
|
||
def armed(self) -> bool:
|
||
return bool(self.window_id)
|
||
|
||
|
||
def _env_float(env: dict, name: str, default: float) -> float:
|
||
raw = (env.get(name) or "").strip()
|
||
if not raw:
|
||
return default
|
||
try:
|
||
value = float(raw)
|
||
except ValueError:
|
||
return 0.0 # 配置损坏按 fail-closed 处理
|
||
return value if value > 0 else 0.0
|
||
|
||
|
||
def _env_int(env: dict, name: str, default: int) -> int:
|
||
raw = (env.get(name) or "").strip()
|
||
if not raw:
|
||
return default
|
||
try:
|
||
value = int(raw)
|
||
except ValueError:
|
||
return 0
|
||
return value if value > 0 else 0
|
||
|
||
|
||
def policy_from_env(environ: dict | None = None) -> AsrWindowPolicy:
|
||
env = dict(os.environ) if environ is None else environ
|
||
return AsrWindowPolicy(
|
||
window_id=(env.get("CYBERGRIL_ASR_WINDOW_ID") or "").strip(),
|
||
max_audio_seconds=_env_float(env, "CYBERGRIL_ASR_WINDOW_MAX_AUDIO_SECONDS", 0.0),
|
||
max_connect_retries_per_call=_env_int(
|
||
env, "CYBERGRIL_ASR_MAX_CONNECT_RETRIES_PER_CALL", 0
|
||
),
|
||
flush_seconds=_env_float(env, "CYBERGRIL_ASR_USAGE_FLUSH_SECONDS", DEFAULT_FLUSH_SECONDS),
|
||
resync_seconds=_env_float(env, "CYBERGRIL_ASR_USAGE_RESYNC_SECONDS", DEFAULT_RESYNC_SECONDS),
|
||
)
|
||
|
||
|
||
@dataclass
|
||
class _AudioBuf:
|
||
seconds: float = 0.0
|
||
frames: int = 0
|
||
bytes: int = 0
|
||
sample_rate: int = 0
|
||
|
||
|
||
@dataclass
|
||
class CallUsage:
|
||
streams: int = 0
|
||
connect_attempts: int = 0
|
||
connect_failures: int = 0
|
||
connect_retries: int = 0
|
||
audio_seconds: float = 0.0
|
||
retry_pending: bool = False # 上一次连接事实是失败 → 下次建连是 retry
|
||
_would_retry: bool = False # check_connect 为本次在途尝试标记的 retry 身份
|
||
|
||
|
||
@dataclass
|
||
class _ReplayState:
|
||
window_audio_seconds: float = 0.0
|
||
calls: dict[str, CallUsage] = field(default_factory=dict)
|
||
|
||
|
||
def summarize_ledger(path: Path | str, window_id: str | None = None) -> dict:
|
||
"""重放账本成汇总(操作员核对口径;不修改账本).
|
||
|
||
window_id 为 None 时按账本里出现过的窗口分组汇总。
|
||
"""
|
||
windows: dict[str, _ReplayState] = {}
|
||
records = 0
|
||
parse_errors = 0
|
||
try:
|
||
lines = Path(path).read_text(encoding="utf-8").splitlines()
|
||
except OSError:
|
||
lines = []
|
||
for line in lines:
|
||
line = line.strip()
|
||
if not line:
|
||
continue
|
||
records += 1
|
||
try:
|
||
rec = json.loads(line)
|
||
except ValueError:
|
||
parse_errors += 1
|
||
continue
|
||
wid = str(rec.get("window", ""))
|
||
if window_id is not None and wid != window_id:
|
||
continue
|
||
state = windows.setdefault(wid, _ReplayState())
|
||
call = str(rec.get("call", ""))
|
||
cu = state.calls.setdefault(call, CallUsage())
|
||
kind = rec.get("kind")
|
||
if kind == "call_start":
|
||
cu.streams += 1
|
||
elif kind == "connect_attempt":
|
||
cu.connect_attempts += 1
|
||
if rec.get("retry"):
|
||
cu.connect_retries += 1
|
||
if not bool(rec.get("ok")):
|
||
cu.connect_failures += 1
|
||
cu.retry_pending = not bool(rec.get("ok"))
|
||
elif kind == "connection_died":
|
||
cu.connect_failures += 1
|
||
cu.retry_pending = True
|
||
elif kind == "audio":
|
||
seconds = float(rec.get("seconds", 0.0) or 0.0)
|
||
cu.audio_seconds = round(cu.audio_seconds + seconds, 6)
|
||
state.window_audio_seconds = round(state.window_audio_seconds + seconds, 6)
|
||
elif kind == "call_end" and str(rec.get("reason")) == "error":
|
||
cu.retry_pending = True
|
||
return {
|
||
"records": records,
|
||
"parse_errors": parse_errors,
|
||
"windows": {
|
||
wid: {
|
||
"audio_seconds": round(st.window_audio_seconds, 6),
|
||
"calls": {
|
||
call: {
|
||
"streams": cu.streams,
|
||
"connect_attempts": cu.connect_attempts,
|
||
"connect_failures": cu.connect_failures,
|
||
"connect_retries": cu.connect_retries,
|
||
"audio_seconds": round(cu.audio_seconds, 6),
|
||
"retry_pending": cu.retry_pending,
|
||
}
|
||
for call, cu in st.calls.items()
|
||
},
|
||
}
|
||
for wid, st in windows.items()
|
||
},
|
||
}
|
||
|
||
|
||
class AsrUsageGuard:
|
||
"""worker 侧计数与闸(每个 job 一个实例,注入 FunASRSTT)."""
|
||
|
||
def __init__(
|
||
self,
|
||
policy: AsrWindowPolicy,
|
||
ledger_path: Path | str | None = None,
|
||
*,
|
||
clock=time.time,
|
||
on_exhausted=None,
|
||
) -> None:
|
||
self.policy = policy
|
||
self.ledger_path = Path(ledger_path) if ledger_path else None
|
||
self._clock = clock
|
||
self._on_exhausted = on_exhausted
|
||
self._exhausted_fired = False
|
||
self._unlabeled = 0
|
||
self._pending: dict[str, _AudioBuf] = {}
|
||
self.calls: dict[str, CallUsage] = {}
|
||
self.window_audio_seconds = 0.0
|
||
self.ledger_errors = 0
|
||
self._last_resync = -1e18
|
||
self._replay()
|
||
|
||
# -- 账本 ---------------------------------------------------------------
|
||
def _replay(self) -> None:
|
||
self._last_resync = self._clock()
|
||
if self.ledger_path is None or not self.ledger_path.is_file():
|
||
return
|
||
state = summarize_ledger(self.ledger_path, self.policy.window_id)["windows"].get(
|
||
self.policy.window_id
|
||
)
|
||
if state is None:
|
||
return
|
||
# 只重放计数事实;重放结果不覆盖本进程在途未落账的音频缓冲
|
||
self.window_audio_seconds = float(state["audio_seconds"])
|
||
for call, cu in state["calls"].items():
|
||
local = self.calls.setdefault(call, CallUsage())
|
||
local.streams = max(local.streams, cu["streams"])
|
||
local.connect_attempts = max(local.connect_attempts, cu["connect_attempts"])
|
||
local.connect_failures = max(local.connect_failures, cu["connect_failures"])
|
||
local.connect_retries = max(local.connect_retries, cu["connect_retries"])
|
||
local.audio_seconds = max(local.audio_seconds, cu["audio_seconds"])
|
||
local.retry_pending = bool(cu.get("retry_pending", False))
|
||
|
||
def _maybe_resync(self) -> None:
|
||
if self.policy.resync_seconds < 0:
|
||
return
|
||
if self._clock() - self._last_resync < self.policy.resync_seconds:
|
||
return
|
||
self._replay()
|
||
|
||
def _append(self, record: dict) -> None:
|
||
if self.ledger_path is None:
|
||
return
|
||
line = json.dumps(
|
||
{**record, "window": self.policy.window_id, "t": round(self._clock(), 3)},
|
||
ensure_ascii=False,
|
||
separators=(",", ":"),
|
||
)
|
||
try:
|
||
self.ledger_path.parent.mkdir(parents=True, exist_ok=True)
|
||
with self.ledger_path.open("a", encoding="utf-8") as fh:
|
||
fh.write(line + "\n")
|
||
except OSError:
|
||
# 账本写失败不破坏通话,只降级可核算性;进程内闸仍按内存计数执行
|
||
self.ledger_errors += 1
|
||
|
||
def _block(self, call: str, what: str, reason: str, detail: str = "") -> None:
|
||
self._append({"kind": "block", "call": call, "what": what, "reason": reason,
|
||
"detail": detail})
|
||
if not self._exhausted_fired:
|
||
self._exhausted_fired = True
|
||
if self._on_exhausted is not None:
|
||
with contextlib.suppress(Exception):
|
||
self._on_exhausted(reason)
|
||
raise AsrWindowClosed(f"asr window stop [{reason}] {what} call={call} {detail}".strip())
|
||
|
||
# -- worker 接缝(stt_funasr / worker 真实调用) -------------------------
|
||
def _pending_total(self) -> float:
|
||
return round(sum(b.seconds for b in self._pending.values()), 6)
|
||
|
||
def begin_stream(self, call: str = "") -> str:
|
||
"""一个 RecognizeStream 开始(worker 按房间名标识;返回生效 call id)."""
|
||
if not call:
|
||
self._unlabeled += 1
|
||
call = f"call-{self._unlabeled}-{secrets.token_hex(3)}"
|
||
self._maybe_resync()
|
||
if not self.policy.armed:
|
||
self._block(call, "new_stream", "window-not-armed")
|
||
if self.window_audio_seconds + self._pending_total() >= \
|
||
self.policy.max_audio_seconds - _EPSILON:
|
||
self._block(call, "new_stream", "window-audio-exhausted")
|
||
cu = self.calls.setdefault(call, CallUsage())
|
||
cu.streams += 1
|
||
self._append({"kind": "call_start", "call": call, "stream_seq": cu.streams})
|
||
return call
|
||
|
||
def check_connect(self, call: str) -> None:
|
||
"""建连前检查(可抛 AsrWindowClosed;之后必须 note_connect_result)."""
|
||
self._maybe_resync()
|
||
cu = self.calls.setdefault(call, CallUsage())
|
||
would_retry = cu.retry_pending
|
||
if not self.policy.armed:
|
||
self._block(call, "new_connection", "window-not-armed")
|
||
if self.window_audio_seconds + self._pending_total() >= \
|
||
self.policy.max_audio_seconds - _EPSILON:
|
||
self._block(call, "new_connection", "window-audio-exhausted")
|
||
if would_retry and cu.connect_retries >= self.policy.max_connect_retries_per_call:
|
||
self._block(
|
||
call, "new_connection", "connect-retries-exhausted",
|
||
detail=f"retries={cu.connect_retries}",
|
||
)
|
||
cu._would_retry = would_retry
|
||
|
||
def note_connect_result(self, call: str, *, ok: bool, error: str = "") -> None:
|
||
cu = self.calls.setdefault(call, CallUsage())
|
||
cu.connect_attempts += 1
|
||
retry = cu._would_retry
|
||
if retry:
|
||
cu.connect_retries += 1
|
||
if not ok:
|
||
cu.connect_failures += 1
|
||
cu.retry_pending = not ok
|
||
cu._would_retry = False
|
||
self._append({"kind": "connect_attempt", "call": call, "seq": cu.connect_attempts,
|
||
"ok": ok, "retry": retry, "error": (error or "")[:200]})
|
||
|
||
def note_connection_died(self, call: str, error: str = "") -> None:
|
||
"""连接接收侧死亡(未伴随建连失败):计连接失败并置 retry 标记."""
|
||
cu = self.calls.setdefault(call, CallUsage())
|
||
cu.connect_failures += 1
|
||
cu.retry_pending = True
|
||
self._append({"kind": "connection_died", "call": call, "error": (error or "")[:200]})
|
||
|
||
def precheck_audio(self, call: str, sample_rate: int, samples: int) -> None:
|
||
"""发送前检查:这一帧会让窗口越限就在发送前拒绝(帧不越限一个字节)."""
|
||
self._maybe_resync()
|
||
seconds = samples / sample_rate
|
||
if not self.policy.armed:
|
||
self._block(call, "audio", "window-not-armed")
|
||
pending = self._pending.get(call)
|
||
pending_seconds = pending.seconds if pending else 0.0
|
||
total = self.window_audio_seconds + pending_seconds + seconds
|
||
if total > self.policy.max_audio_seconds + _EPSILON:
|
||
self._block(
|
||
call, "audio", "window-audio-exhausted",
|
||
detail=(f"window={self.window_audio_seconds:.3f}s pending={pending_seconds:.3f}s "
|
||
f"frame={seconds:.3f}s cap={self.policy.max_audio_seconds:.3f}s"),
|
||
)
|
||
|
||
def note_audio_sent(self, call: str, sample_rate: int, samples: int, nbytes: int = 0) -> None:
|
||
"""真实发送成功后计数(重发按重复计);达到 flush 阈值聚合落账."""
|
||
cu = self.calls.setdefault(call, CallUsage())
|
||
seconds = round(samples / sample_rate, 6)
|
||
cu.audio_seconds = round(cu.audio_seconds + seconds, 6)
|
||
buf = self._pending.setdefault(call, _AudioBuf())
|
||
buf.seconds = round(buf.seconds + seconds, 6)
|
||
buf.frames += 1
|
||
buf.bytes += nbytes
|
||
buf.sample_rate = sample_rate
|
||
if buf.seconds >= self.policy.flush_seconds:
|
||
self.flush_audio(call)
|
||
|
||
def flush_audio(self, call: str) -> None:
|
||
"""把该通缓冲中的音频计数聚合落账(utterance 边界 / 流结束时调用)."""
|
||
buf = self._pending.pop(call, None)
|
||
if buf is None or buf.seconds <= 0:
|
||
return
|
||
self.window_audio_seconds = round(self.window_audio_seconds + buf.seconds, 6)
|
||
self._append({"kind": "audio", "call": call, "seconds": buf.seconds,
|
||
"frames": buf.frames, "bytes": buf.bytes, "sample_rate": buf.sample_rate})
|
||
|
||
def stream_end(self, call: str, reason: str) -> None:
|
||
"""一个 RecognizeStream 结束(closed/error/window_exhausted)."""
|
||
self.flush_audio(call)
|
||
cu = self.calls.get(call)
|
||
if cu is not None and reason == "error":
|
||
cu.retry_pending = True
|
||
self._append({
|
||
"kind": "call_end", "call": call, "reason": reason,
|
||
"audio_seconds": round(cu.audio_seconds, 6) if cu else 0.0,
|
||
"connect_attempts": cu.connect_attempts if cu else 0,
|
||
"connect_failures": cu.connect_failures if cu else 0,
|
||
"connect_retries": cu.connect_retries if cu else 0,
|
||
})
|
||
|
||
# -- 观测 ---------------------------------------------------------------
|
||
def pending_audio_seconds(self, call: str) -> float:
|
||
buf = self._pending.get(call)
|
||
return buf.seconds if buf else 0.0
|
||
|
||
def summary(self) -> dict:
|
||
pending = round(sum(b.seconds for b in self._pending.values()), 6)
|
||
return {
|
||
"window": self.policy.window_id,
|
||
"armed": self.policy.armed,
|
||
"max_audio_seconds": self.policy.max_audio_seconds,
|
||
"max_connect_retries_per_call": self.policy.max_connect_retries_per_call,
|
||
"audio_seconds_flushed": round(self.window_audio_seconds, 6),
|
||
"audio_seconds_with_pending": round(self.window_audio_seconds + pending, 6),
|
||
"ledger": str(self.ledger_path) if self.ledger_path else "",
|
||
"ledger_errors": self.ledger_errors,
|
||
"calls": {
|
||
call: {
|
||
"streams": cu.streams,
|
||
"connect_attempts": cu.connect_attempts,
|
||
"connect_failures": cu.connect_failures,
|
||
"connect_retries": cu.connect_retries,
|
||
"audio_seconds": round(cu.audio_seconds, 6),
|
||
}
|
||
for call, cu in self.calls.items()
|
||
},
|
||
}
|
||
|
||
def summary_line(self) -> str:
|
||
s = self.summary()
|
||
return (
|
||
f"window={s['window'] or 'not-armed'} "
|
||
f"audio={s['audio_seconds_with_pending']:.3f}/{s['max_audio_seconds']:.3f}s "
|
||
f"retries<= {s['max_connect_retries_per_call']}/call "
|
||
f"ledger={s['ledger']}"
|
||
)
|
||
|
||
|
||
def build_usage_from_env(
|
||
environ: dict | None = None,
|
||
*,
|
||
clock=time.time,
|
||
on_exhausted=None,
|
||
ledger_path: Path | str | None = None,
|
||
) -> AsrUsageGuard:
|
||
"""worker entrypoint 的唯一构造入口(env 只在窗口启动时由负责人显式设置)."""
|
||
env = os.environ if environ is None else environ
|
||
path = ledger_path or env.get("CYBERGRIL_ASR_USAGE_LEDGER") or DEFAULT_ASR_USAGE_LEDGER
|
||
return AsrUsageGuard(policy_from_env(env), path, clock=clock, on_exhausted=on_exhausted)
|
||
|
||
|
||
def main(argv: list[str] | None = None) -> int:
|
||
parser = argparse.ArgumentParser(
|
||
prog="python -m cybergril.voice.asr_usage",
|
||
description="重放 ASR 用量账本为汇总 JSON(只读,不修改账本)",
|
||
)
|
||
parser.add_argument("ledger", help="asr-usage.jsonl 路径")
|
||
parser.add_argument("--window", default=None, help="只汇总指定 window id")
|
||
args = parser.parse_args(argv)
|
||
print(json.dumps(summarize_ledger(args.ledger, args.window), ensure_ascii=False, indent=1))
|
||
return 0
|
||
|
||
|
||
if __name__ == "__main__":
|
||
raise SystemExit(main())
|