OrbiSubs panel: keep the missing-subtitles alarm on while the ASR is frozen

Revisión externa 1.1: las alarmas toman "corre" de systemd (ingesta y ASR activos), no de state, que pasa a error justo cuando el ASR se congela. ASR sin filas nuevas con las unidades activas también enciende sin_subs. Solo cuentan las filas del .jsonl desde que arrancaron las unidades, y status no marca error los primeros 2 min.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JAUCv2ADyD2NSg4ub9YPr1
This commit is contained in:
guy
2026-11-22 14:12:04 -03:00
parent b41593bf22
commit e30fc3dd87
3 changed files with 117 additions and 16 deletions
+27 -10
View File
@@ -9,6 +9,8 @@
// oye habla (palabras en su log): un silencio real no la dispara, ni el canal parado.
// El HLS solo guarda los .vtt de su ventana (~90 s), así que la hora del último con
// texto la recuerda el panel entre vueltas.
// Si el ASR se congela (proceso colgado con la unidad "active": no escribe más su log),
// no hay palabras con qué juzgar, pero tampoco subtítulos: también la enciende.
// - cc608: la salida SRT pierde más del CC_PCT % de los cues del 608 en CC_S, o no
// muestra ninguno (o no escribe métricas) mientras el ASR sí transcribe.
const fs = require('fs');
@@ -24,6 +26,7 @@ const CFG = {
CC_PCT: num('ALARMA_608_PCT', 5),
CC_MIN: num('ALARMA_608_MIN', 20), // cues + perdidos mínimos para sacar un %
SRT_STALE_S: 120,
ASR_STALE_S: 120, // el ASR escribe una fila cada trozo (3 s), con o sin habla
};
const TICK_S = 30;
@@ -41,15 +44,23 @@ function delta608(rows, desde) {
// Decisión pura (testeable). Devuelve { sin_subs: motivo|null, cc608: motivo|null }.
// asr: filas del log del ASR (t, words); texto: epoch s del último .vtt con texto
// visto (o desde cuándo se mira); srt: filas del log de la salida SRT o null si no tiene;
// srtMtime: epoch s de la última métrica de la salida SRT.
function evaluar({ now, asr, texto, srt, srtMtime, c = CFG }) {
// srtMtime: epoch s de la última métrica de la salida SRT; desde: epoch s desde que la
// ingesta y el ASR están activos (asr trae solo filas de esta corrida); asrUlt: epoch s
// de la última fila del ASR de esta corrida (la ventana de asr puede quedar vacía).
function evaluar({ now, asr, texto, srt, srtMtime, desde = null, asrUlt, c = CFG }) {
const out = { sin_subs: null, cc608: null };
// ASR congelado: activo hace rato y sin filas nuevas. Antes la alarma se apagaba a los
// 5 min (ya no había palabras en la ventana) o al pasar el estado a 'error' (1.1).
const ultAsr = asrUlt ?? (asr.length ? asr[asr.length - 1].t : desde);
if (desde != null && now - desde >= c.SUBS_S && ultAsr != null && now - ultAsr > c.ASR_STALE_S && now - texto > c.SUBS_S) {
out.sin_subs = `el ASR no escribe hace ${Math.round((now - ultAsr) / 60)} min (¿colgado?); ningún .vtt con texto hace ${Math.round((now - texto) / 60)} min`;
}
const palabras = d => asr.filter(r => r.t >= now - d).reduce((s, r) => s + (r.words || 0), 0);
// El log tiene que cubrir la ventana entera: recién arrancado no hay con qué juzgar.
const cubre = d => asr.length && asr[0].t <= now - d;
// Las palabras se miran en al menos 5 min (con SUBS_S bajo, para probar, igual hay habla).
const ventana = Math.max(c.SUBS_S, 300);
if (cubre(ventana) && palabras(ventana) >= c.MIN_WORDS && now - texto > c.SUBS_S) {
if (!out.sin_subs && cubre(ventana) && palabras(ventana) >= c.MIN_WORDS && now - texto > c.SUBS_S) {
out.sin_subs = `ningún .vtt con texto hace ${Math.round((now - texto) / 60)} min, con ${palabras(ventana)} palabras del ASR en ${Math.round(ventana / 60)} min`;
}
if (srt && cubre(c.CC_S)) {
@@ -126,18 +137,24 @@ async function tick(getChannels = canales) {
const now = Date.now() / 1000;
chans.forEach(ch => {
const s = st[ch.id];
// Parado o arrancando: nada que juzgar, y lo que estaba encendido se cierra.
const corre = s && s.state === 'running';
// Parado: nada que juzgar, y lo que estaba encendido se cierra. "Corre" es lo que
// dice systemd de la ingesta y el ASR, no `state`: ese pasa a 'error' cuando el ASR
// se congela, y cerraba la alarma justo cuando hacía falta (revisión externa, 1.1).
const corre = !!(s && s.up);
if (!corre) vistoTexto.delete(ch.slug);
const res = corre ? evaluarCanal(ch, now) : { sin_subs: null, cc608: null };
const res = corre ? evaluarCanal(ch, now, s.up_since) : { sin_subs: null, cc608: null };
for (const [q, kind] of aplicar(ch.slug, res, now)) console.log(`[alarmas] ${ch.slug}: ${kind} ${q}`);
});
} finally { corriendo = false; }
}
function evaluarCanal(ch, now) {
const asr = status.tailJsonl(path.join(status.LOG_DIR, `${ch.slug}.jsonl`), 1 << 20).rows
.filter(r => r.seq != null && typeof r.t === 'number' && r.t >= now - Math.max(CFG.SUBS_S, CFG.CC_S) - 60);
function evaluarCanal(ch, now, desde = null) {
// Solo filas de esta corrida: al arrancar, el .jsonl trae las de la anterior (y daba
// por cubierta la ventana con datos viejos).
const filas = status.tailJsonl(path.join(status.LOG_DIR, `${ch.slug}.jsonl`), 1 << 20).rows
.filter(r => r.seq != null && typeof r.t === 'number' && (desde == null || r.t >= desde));
const asrUlt = filas.length ? filas[filas.length - 1].t : desde;
const asr = filas.filter(r => r.t >= now - Math.max(CFG.SUBS_S, CFG.CC_S) - 60);
let srt = null, srtMtime = null;
if (ch.cfg.srt && ch.cfg.srt.enabled) {
const s = status.tailJsonl(path.join(status.LOG_DIR, `${ch.slug}-srt.jsonl`), 512 * 1024);
@@ -146,7 +163,7 @@ function evaluarCanal(ch, now) {
}
const u = ultimoVttConTexto(ch.slug);
vistoTexto.set(ch.slug, Math.max(vistoTexto.get(ch.slug) ?? now, u ?? 0));
return evaluar({ now, asr, texto: vistoTexto.get(ch.slug), srt, srtMtime });
return evaluar({ now, asr, texto: vistoTexto.get(ch.slug), srt, srtMtime, desde, asrUlt });
}
function start(getChannels = canales) {
+22 -6
View File
@@ -28,7 +28,8 @@ function unitsOf(ch) {
// Un solo `systemctl show` para todas las unidades de todos los canales.
async function systemdState(units) {
if (!units.length) return {};
const out = await sh('systemctl', ['show', '--no-pager', '-p', 'Id,LoadState,ActiveState,SubState,NRestarts,Result,UnitFileState', ...units]);
// --timestamp=unix: ActiveEnterTimestamp como @epoch (systemd ≥ 248; el CT 176 tiene 252).
const out = await sh('systemctl', ['show', '--no-pager', '--timestamp=unix', '-p', 'Id,LoadState,ActiveState,SubState,NRestarts,Result,UnitFileState,ActiveEnterTimestamp', ...units]);
const res = {};
for (const block of out.split(/\n\s*\n/)) {
const o = {};
@@ -36,7 +37,9 @@ async function systemdState(units) {
const i = line.indexOf('=');
if (i > 0) o[line.slice(0, i)] = line.slice(i + 1);
}
if (o.Id) res[o.Id] = { load: o.LoadState, active: o.ActiveState, sub: o.SubState, restarts: Number(o.NRestarts || 0), result: o.Result, file: o.UnitFileState };
// since: desde cuándo está activa (epoch s), para no juzgar el .jsonl de una corrida anterior.
const since = /^@\d+/.test(o.ActiveEnterTimestamp || '') ? Number(o.ActiveEnterTimestamp.slice(1)) : null;
if (o.Id) res[o.Id] = { load: o.LoadState, active: o.ActiveState, sub: o.SubState, restarts: Number(o.NRestarts || 0), result: o.Result, file: o.UnitFileState, since };
}
return res;
}
@@ -137,7 +140,18 @@ function summarize(ch, sd) {
else if (act.some(a => a === 'activating' || a === 'reloading')) state = 'connecting';
else state = 'error'; // a medias: algunas andan y otras no
const notes = units.filter(u => u.active !== 'active' && state !== 'stopped').map(u => `${u.key}: ${u.active}${u.result && u.result !== 'success' ? ` (${u.result})` : ''}`);
return { state, units, notes, managed: units.some(u => u.load === 'loaded') };
return { state, units, notes, managed: units.some(u => u.load === 'loaded'), ...produce(units) };
}
// ¿El canal está para producir subtítulos, según systemd? La ingesta y el ASR activos.
// Las alarmas (096) miran esto y no `state`, que pasa a 'error' justo cuando el ASR se
// congela y cerraba la alarma "sin subtítulos" (revisión externa, 1.1). up_since: desde
// cuándo, la más reciente de las dos (epoch s).
function produce(units) {
const base = units.filter(u => u.key === 'ingest' || u.key === 'asr');
const up = base.length === 2 && base.every(u => u.active === 'active');
const since = up && base.every(u => u.since) ? Math.max(...base.map(u => u.since)) : null;
return { up, up_since: since };
}
async function all(channels) {
@@ -146,8 +160,10 @@ async function all(channels) {
for (const ch of channels) {
const s = summarize(ch, sd);
const m = metrics(ch);
// Corriendo según systemd pero sin producir subtítulos: se muestra como error.
if (s.state === 'running' && !m.fresh && m.age_s !== null && m.age_s > STALE_S * 2) {
// Corriendo según systemd pero sin producir subtítulos: se muestra como error. Recién
// arrancado, el .jsonl todavía es el de la corrida anterior: no es un error.
const arrancando = s.up_since && Date.now() / 1000 - s.up_since < STALE_S * 2;
if (s.state === 'running' && !arrancando && !m.fresh && m.age_s !== null && m.age_s > STALE_S * 2) {
s.state = 'error'; s.notes.push(`sin subtítulos nuevos hace ${m.age_s} s`);
}
res[ch.id] = { ...s, metrics: m };
@@ -155,4 +171,4 @@ async function all(channels) {
return res;
}
module.exports = { all, metrics, failures, unitsOf, systemdState, summarize, tailJsonl, LOG_DIR, HLS_DIR };
module.exports = { all, metrics, failures, unitsOf, systemdState, summarize, produce, tailJsonl, STALE_S, LOG_DIR, HLS_DIR };
+68
View File
@@ -7,7 +7,10 @@ const os = require('os');
const path = require('path');
process.env.DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), 'orbisubs-alarmas-'));
process.env.LOG_DIR = path.join(process.env.DATA_DIR, 'log');
process.env.HLS_DIR = path.join(process.env.DATA_DIR, 'hls');
const A = require('../src/engine/alarmas');
const status = require('../src/engine/status');
const { db } = require('../src/db');
const now = 1_795_266_154 + 3600; // una hora después de la vuelta del PTS de ecuadortv
@@ -63,3 +66,68 @@ test('aplicar: se enciende, sigue, se apaga sola y queda registrada', () => {
assert.match(ev[0], /^Alarma: Sin subtítulos/);
assert.match(ev[1], /duró 10 min/);
});
// Revisión externa, 1.1: con el ASR congelado (proceso colgado, unidad "active") la alarma
// se apagaba sola: a los 5 min ya no había palabras en la ventana, y además status.all()
// pasa el canal a 'error' y tick lo tomaba como parado.
test('sin_subs: ASR congelado 10 min, encendida todo el rato (evaluar)', () => {
const F = now - 600; // se congeló hace 10 min
const log = asrLog(30).map(r => ({ ...r, t: r.t - 600 })).filter(r => r.t <= F);
const desde = now - 7200;
for (let T = F + A.CFG.SUBS_S + 30; T <= now; T += 30) {
const asr = log.filter(r => r.t >= T - 660);
const r = A.evaluar({ now: T, asr, texto: F, srt: null, desde, asrUlt: F });
assert.ok(r.sin_subs, `apagada a los ${T - F} s`);
}
assert.match(A.evaluar({ now, asr: [], texto: F, srt: null, desde, asrUlt: F }).sin_subs, /no escribe hace 10 min/);
// Recién arrancado con el .jsonl de la corrida anterior: sin filas nuevas todavía, nada.
assert.strictEqual(A.evaluar({ now, asr: [], texto: now - 60, srt: null, desde: now - 60, asrUlt: now - 60 }).sin_subs, null);
// Parado de verdad no llega acá (tick no evalúa), y en silencio con el ASR al día, nada.
assert.strictEqual(A.evaluar({ now, asr: asrLog(15, 0), texto: now - 3600, srt: null, desde, asrUlt: now - 3 }).sin_subs, null);
});
test('produce: corre según systemd (ingesta y ASR activos), con su hora', () => {
const u = (key, active, since) => ({ key, active, since });
assert.deepStrictEqual(status.produce([u('ingest', 'active', 100), u('asr', 'active', 200), u('srt', 'failed', 50)]), { up: true, up_since: 200 });
assert.strictEqual(status.produce([u('ingest', 'active', 100), u('asr', 'activating', null)]).up, false);
});
test('tick: ASR congelado 10 min con el estado en error, la alarma no se cierra', async () => {
const slug = 'congelado';
const realNow = Date.now;
const F = Math.floor(realNow() / 1000);
let reloj = F;
Date.now = () => reloj * 1000;
try {
fs.mkdirSync(process.env.LOG_DIR, { recursive: true });
const subs = path.join(process.env.HLS_DIR, slug, 'subs');
fs.mkdirSync(subs, { recursive: true });
// 15 min de ASR transcribiendo hasta F, y el último .vtt con texto en F.
fs.writeFileSync(path.join(process.env.LOG_DIR, `${slug}.jsonl`),
Array.from({ length: 300 }, (_, i) => JSON.stringify({ seq: i, dur: 3, t: F - 900 + i * 3, words: 5 })).join('\n') + '\n');
const vtt = path.join(subs, '1.vtt');
fs.writeFileSync(vtt, 'WEBVTT\n\n00:00:01.000 --> 00:00:02.000\nhola\n');
fs.utimesSync(vtt, F, F);
const orig = status.all;
// Lo que devuelve status.all con el ASR congelado: unidades activas, estado 'error'.
status.all = async chs => Object.fromEntries(chs.map(c => [c.id, { state: 'error', up: true, up_since: F - 3600, units: [], notes: [] }]));
const chans = () => [{ id: 1, slug, cfg: { srt: { enabled: false } } }];
try {
await A.tick(chans); // F: anda bien
assert.strictEqual(A.activas(slug).length, 0);
const encendida = [];
for (reloj = F + 30; reloj <= F + 600; reloj += 30) {
await A.tick(chans);
encendida.push(A.activas(slug).length);
}
// Se enciende pasados los 5 min y queda encendida hasta el final.
const i = encendida.indexOf(1);
assert.ok(i >= 0 && i <= 10, String(encendida));
assert.ok(encendida.slice(i).every(n => n === 1), String(encendida));
// Parado de verdad (systemd): se cierra.
status.all = async chs => Object.fromEntries(chs.map(c => [c.id, { state: 'stopped', up: false, up_since: null, units: [], notes: [] }]));
await A.tick(chans);
assert.strictEqual(A.activas(slug).length, 0);
} finally { status.all = orig; }
} finally { Date.now = realNow; }
});