fix(subsync): address CodeRabbit review of cancellation, cleanup, and writes

- kill a tool's whole POSIX process group on cancel (orphaned children held the
  pipes open, so the run never finished); kill running groups on exit
- refuse an in-place rewrite when the subtitle changed on disk mid-sync
- pick only a freshly added track for the secondary slot, and reset its delay
  only after selecting it
- pass cancellation to the video-reference alass and ffsubsync runs, and never
  open a picker for media the user already left
- treat a failed media-path baseline read as unknown instead of null
- align worker: honor aborts during startup and finish queued calls on the
  main thread when the worker fails to start
- temp dirs: keep failed removals registered, never sweep a dir mpv still
  plays from, and clean up when writing a cleaned reference fails
- an empty cached audio result means no usable audio, as on a fresh decode
- compare external track paths case-sensitively on POSIX
- decode ffmpeg stderr as a stream; coverage lane for subtitle tests
- make the cancellation test wait for the tool to start
This commit is contained in:
sudacode committed 2026-11-28 03:53:12 -08:00
1 parent 5b39e850f6
commit cde9362ee5
12 files changed
+244 -57

No files matched your search

+4 -1
View File
@@ -182,7 +182,10 @@ export async function runAutoSubsync(deps: TriggerSubsyncFromConfigDeps): Promis
deps.showMpvOsd(`Subsync failed: ${LOSSY_REWRITE_ERROR_MESSAGE}`);
return;
}
writeRetimedContent(outputPath, alignment.rewrittenContent, replaceTarget);
writeRetimedContent(outputPath, alignment.rewrittenContent, {
replacesSource: replaceTarget,
sourceStamp: parsedTarget.stamp,
});
await loadSyncedSubtitle(client, outputPath, targetSlot, targetTrack);
deps.showMpvOsd(formatAlignmentSummary(sourceLabel, alignment));
};
+7 -1
View File
@@ -541,7 +541,13 @@ export async function prepareRipCandidatesAndAudio(
}
if (cachedFull) {
return { audioSpeech: cachedFull, sampledAudioWindows: null, preExtractedEmbedded: null };
// An empty cached result stays cached (no re-decode) but means "no usable audio" here,
// matching resolveAudioSpeechForContext.
return {
audioSpeech: cachedFull.spans.length > 0 ? cachedFull : null,
sampledAudioWindows: null,
preExtractedEmbedded: null,
};
}
const audioSpeech = await resolveAudioSpeechForContext(context, resolved, deps);
+1 -1
View File
@@ -46,7 +46,7 @@ function getSourceTrackIdentity(track: MpvTrack): string {
typeof track['external-filename'] === 'string' &&
track['external-filename'].length > 0
) {
return `external:${track['external-filename'].toLowerCase()}`;
return `external:${normalizeSubtitlePathForCompare(track['external-filename'])}`;
}
if (typeof track.id === 'number') {
return `id:${track.id}`;
+9 -6
View File
@@ -7,8 +7,6 @@ import { cleanupTemporaryFile, pruneRetainedSubsyncTempDirs } from './subsync-fi
test('synced embedded-track temp dirs keep only the loaded file and go away once mpv drops it', () => {
const isolatedTmp = fs.mkdtempSync(path.join(os.tmpdir(), 'subsync-files-test-'));
const previousTmpDir = process.env.TMPDIR;
process.env.TMPDIR = isolatedTmp;
try {
// Left behind by a crashed session two days ago.
const staleDir = fs.mkdtempSync(path.join(isolatedTmp, 'subminer-subsync-'));
@@ -25,15 +23,20 @@ test('synced embedded-track temp dirs keep only the loaded file and go away once
cleanupTemporaryFile({ path: extractedPath, temporary: true });
assert.deepEqual(fs.readdirSync(runDir), ['track_2_retimed.ass']);
pruneRetainedSubsyncTempDirs([retimedPath]);
// An old dir whose file mpv still plays survives the sweep.
const playingDir = fs.mkdtempSync(path.join(isolatedTmp, 'subminer-subsync-'));
const playingPath = path.join(playingDir, 'track_4_retimed.srt');
fs.writeFileSync(playingPath, 'still loaded');
fs.utimesSync(playingDir, twoDaysAgo, twoDaysAgo);
pruneRetainedSubsyncTempDirs([retimedPath, playingPath], { tmpRoot: isolatedTmp });
assert.equal(fs.existsSync(runDir), true, 'mpv still lists the retimed file');
assert.equal(fs.existsSync(staleDir), false, 'stale dirs from old sessions are swept');
assert.equal(fs.existsSync(playingDir), true, 'stale but referenced dirs are kept');
pruneRetainedSubsyncTempDirs(['/media/ep02.ja.srt']);
pruneRetainedSubsyncTempDirs(['/media/ep02.ja.srt'], { tmpRoot: isolatedTmp });
assert.equal(fs.existsSync(runDir), false, 'dropped once mpv no longer lists it');
} finally {
if (previousTmpDir === undefined) delete process.env.TMPDIR;
else process.env.TMPDIR = previousTmpDir;
fs.rmSync(isolatedTmp, { recursive: true, force: true });
}
});
+87 -23
View File
@@ -205,17 +205,22 @@ export function cleanupTemporaryFile(extraction: FileExtractionResult | null): v
*/
export function pruneRetainedSubsyncTempDirs(
referencedPaths: readonly string[],
now: number = Date.now(),
options: { now?: number; tmpRoot?: string } = {},
): void {
for (const dir of retainedSubsyncTempDirs) {
const isReferenced = (dir: string): boolean => {
const prefix = `${dir}${path.sep}`;
if (referencedPaths.some((filePath) => filePath.startsWith(prefix))) continue;
return referencedPaths.some((filePath) => filePath.startsWith(prefix));
};
for (const dir of retainedSubsyncTempDirs) {
if (isReferenced(dir)) continue;
removeDirQuietly(dir);
retainedSubsyncTempDirs.delete(dir);
// Keep failed removals registered so the next prune or exit cleanup retries them.
if (!fs.existsSync(dir)) retainedSubsyncTempDirs.delete(dir);
}
if (staleSweepDone) return;
staleSweepDone = true;
const tmpRoot = os.tmpdir();
const tmpRoot = options.tmpRoot ?? os.tmpdir();
const now = options.now ?? Date.now();
let entries: string[] = [];
try {
entries = fs.readdirSync(tmpRoot);
@@ -225,7 +230,8 @@ export function pruneRetainedSubsyncTempDirs(
for (const name of entries) {
if (!name.startsWith(SUBSYNC_TEMP_DIR_PREFIX)) continue;
const dir = path.join(tmpRoot, name);
if (retainedSubsyncTempDirs.has(dir)) continue;
// mpv may still play a file from an old dir (e.g. the app restarted under a running mpv).
if (retainedSubsyncTempDirs.has(dir) || isReferenced(dir)) continue;
try {
const stat = fs.statSync(dir);
if (stat.isDirectory() && now - stat.mtimeMs > STALE_SUBSYNC_TEMP_DIR_MS) {
@@ -264,15 +270,42 @@ export function buildRetimedPath(subPath: string, replace: boolean): string {
export const LOSSY_REWRITE_ERROR_MESSAGE =
'Cannot safely rewrite subtitle file because its text encoding could not be decoded unambiguously and losslessly. Convert the file to UTF-8 and retry.';
export function readAndParseSubtitleFile(filePath: string): ParsedSubtitleFile {
/** Size + mtime of a subtitle file, compared before an in-place rewrite to catch edits made mid-sync. */
export function readSubtitleFileStamp(filePath: string): string | null {
try {
const stat = fs.statSync(filePath);
return `${stat.size}\0${stat.mtimeMs}`;
} catch {
return null;
}
}
export type ReadSubtitleFile = ParsedSubtitleFile & {
/** `readSubtitleFileStamp` taken before reading, for `RetimedWrite.sourceStamp`. */
stamp: string | null;
};
export function readAndParseSubtitleFile(filePath: string): ReadSubtitleFile {
const stamp = readSubtitleFileStamp(filePath);
const bytes = fs.readFileSync(filePath);
const decoded = decodeSubtitleBytesWithStatus(bytes);
return {
...parseSubtitleFileContent(decoded.text, filePath),
lossless: decoded.lossless,
stamp,
};
}
export interface RetimedWrite {
/** In-place `subsync.replace` rewrite of the user's subtitle (backup + source-change check). */
replacesSource: boolean;
/** Stamp of the source when it was read; a different stamp now means it was edited mid-sync. */
sourceStamp?: string | null;
}
const SOURCE_CHANGED_MESSAGE =
'The subtitle file changed on disk while syncing; discarded the result. Run subsync again.';
/** Suffix for the one-time backup of a replaced subtitle; not a subtitle extension, so mpv and sidecar discovery ignore it. */
const SUBSYNC_BACKUP_SUFFIX = '.orig';
@@ -292,9 +325,16 @@ function resolveRealPathOrSelf(filePath: string): string {
export function installRetimedFile(
stagedPath: string,
outputPath: string,
replacesSource: boolean,
{ replacesSource, sourceStamp }: RetimedWrite,
): void {
const targetPath = resolveRealPathOrSelf(outputPath);
if (
replacesSource &&
sourceStamp !== undefined &&
readSubtitleFileStamp(targetPath) !== sourceStamp
) {
throw new Error(SOURCE_CHANGED_MESSAGE);
}
const existing = fs.existsSync(targetPath) ? fs.statSync(targetPath) : null;
if (existing) {
if (replacesSource) {
@@ -326,7 +366,7 @@ export function removeIfExists(filePath: string): void {
export function writeRetimedContent(
outputPath: string,
content: string,
replacesSource: boolean,
write: RetimedWrite,
): void {
const dir = path.dirname(resolveRealPathOrSelf(outputPath));
const tmpPath = path.join(
@@ -335,7 +375,7 @@ export function writeRetimedContent(
);
try {
fs.writeFileSync(tmpPath, content, 'utf8');
installRetimedFile(tmpPath, outputPath, replacesSource);
installRetimedFile(tmpPath, outputPath, write);
} catch (error) {
removeIfExists(tmpPath);
throw error;
@@ -367,30 +407,43 @@ export async function runFfsubsyncSync(
return runCommand(ffsubsyncPath, args, undefined, signal);
}
async function readSubtitleTracks(client: MpvClientLike): Promise<MpvTrack[]> {
const trackListRaw = await client.requestProperty('track-list');
return Array.isArray(trackListRaw)
? normalizeTrackIds(trackListRaw as MpvTrack[]).filter((track) => track.type === 'sub')
: [];
}
/**
* Find the track `sub-add` created for `pathToLoad`. Only ids missing from `knownTrackIds`
* (the list before the add) count, so an older track for the same file is never picked.
*/
async function findAddedSubtitleTrackId(
client: MpvClientLike,
pathToLoad: string,
knownTrackIds: ReadonlySet<number>,
): Promise<number | null> {
const wanted = normalizeSubtitlePathForCompare(pathToLoad);
// sub-add is queued, so the track may not appear in the first track-list reply.
for (let attempt = 0; attempt < SYNCED_TRACK_LOOKUP_ATTEMPTS; attempt += 1) {
let tracks: MpvTrack[] = [];
try {
const trackListRaw = await client.requestProperty('track-list');
tracks = Array.isArray(trackListRaw) ? normalizeTrackIds(trackListRaw as MpvTrack[]) : [];
tracks = await readSubtitleTracks(client);
} catch {
return null;
}
// Re-adding a file mpv already knows appends a duplicate entry; the newest
// one holds the retimed content, so prefer the last match.
const matches = tracks.filter((track) => {
if (track.type !== 'sub') return false;
const added = tracks.filter((track) => {
const filename = track['external-filename'];
return typeof filename === 'string' && normalizeSubtitlePathForCompare(filename) === wanted;
return (
typeof track.id === 'number' &&
!knownTrackIds.has(track.id) &&
typeof filename === 'string' &&
normalizeSubtitlePathForCompare(filename) === wanted
);
});
const added = matches[matches.length - 1];
if (added && typeof added.id === 'number') {
return added.id;
const newest = added[added.length - 1];
if (newest && typeof newest.id === 'number') {
return newest.id;
}
if (attempt < SYNCED_TRACK_LOOKUP_ATTEMPTS - 1) {
await delay(SYNCED_TRACK_LOOKUP_RETRY_MS);
@@ -425,13 +478,19 @@ export async function loadSyncedSubtitle(
if (slot === 'secondary') {
// Keep the primary track untouched: load without selecting, then point
// secondary-sid at the freshly added track.
const knownTrackIds = new Set(
(await readSubtitleTracks(client).catch(() => [])).flatMap((track) =>
typeof track.id === 'number' ? [track.id] : [],
),
);
client.send({ command: buildSubAddCommand(pathToLoad, 'auto', sourceTrack) });
client.send({ command: ['set_property', 'secondary-sub-delay', 0] });
const addedTrackId = await findAddedSubtitleTrackId(client, pathToLoad);
const addedTrackId = await findAddedSubtitleTrackId(client, pathToLoad, knownTrackIds);
if (addedTrackId === null) {
throw new Error('Synchronized subtitle did not appear in the mpv track list');
}
client.send({ command: ['set_property', 'secondary-sid', addedTrackId] });
// The retimed file carries the timing now; only drop the old delay once it is selected.
client.send({ command: ['set_property', 'secondary-sub-delay', 0] });
return;
}
@@ -460,7 +519,12 @@ export function maybeWriteCleanedReferenceSrt(
}
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'subminer-subsync-cleanref-'));
const cleanPath = path.join(tempDir, 'clean_ref.srt');
fs.writeFileSync(cleanPath, formatSpansAsSrt(extracted.spans), 'utf8');
try {
fs.writeFileSync(cleanPath, formatSpansAsSrt(extracted.spans), 'utf8');
} catch (error) {
removeDirQuietly(tempDir);
throw error;
}
return { path: cleanPath, temporary: true };
} catch {
return null;
+18 -3
View File
@@ -44,6 +44,7 @@ import {
runFfsubsyncSync,
validateFfsubsyncReference,
writeRetimedContent,
readSubtitleFileStamp,
} from './subsync-files';
import {
AUDIO_SPEECH_LEAD_SEC,
@@ -181,7 +182,10 @@ async function runBuiltinSubsync(
return { ok: false, message: PLAYBACK_CHANGED_RESULT_MESSAGE };
}
writeRetimedContent(outputPath, alignment.rewrittenContent, replaceTarget);
writeRetimedContent(outputPath, alignment.rewrittenContent, {
replacesSource: replaceTarget,
sourceStamp: parsedTarget.stamp,
});
await loadSyncedSubtitle(client, outputPath, targetSlot, targetTrack);
return {
ok: true,
@@ -225,7 +229,10 @@ async function runManualOffsetSubsync(
if (!(await isPlaybackSessionUnchanged(client, context, targetTrack, targetSlot))) {
return { ok: false, message: PLAYBACK_CHANGED_RESULT_MESSAGE };
}
writeRetimedContent(outputPath, rewritten, replaceTarget);
writeRetimedContent(outputPath, rewritten, {
replacesSource: replaceTarget,
sourceStamp: parsedTarget.stamp,
});
await loadSyncedSubtitle(client, outputPath, targetSlot, targetTrack);
return {
ok: true,
@@ -255,6 +262,7 @@ async function subsyncToReference(
);
const replaceTarget = resolved.replace !== false && !targetExtraction.temporary;
const outputPath = buildRetimedPath(targetExtraction.path, replaceTarget);
const sourceStamp = readSubtitleFileStamp(targetExtraction.path);
const parsedOutput = path.parse(outputPath);
const stagedOutputPath = path.join(
parsedOutput.dir,
@@ -296,7 +304,10 @@ async function subsyncToReference(
return { ok: false, message: PLAYBACK_CHANGED_RESULT_MESSAGE };
}
installRetimedFile(stagedOutputPath, outputPath, replaceTarget);
installRetimedFile(stagedOutputPath, outputPath, {
replacesSource: replaceTarget,
sourceStamp,
});
await loadSyncedSubtitle(client, outputPath, slot, targetTrack);
return {
ok: true,
@@ -377,6 +388,7 @@ export async function runSubsyncManualUnguarded(
resolved,
client,
targetSlot,
deps,
);
}
@@ -396,6 +408,7 @@ export async function runSubsyncManualUnguarded(
resolved,
client,
targetSlot,
deps,
);
}
@@ -520,6 +533,8 @@ export async function openSubsyncManualPicker(
audioSpeechAvailable,
guidanceMessage: options.guidanceMessage ?? null,
});
// A cancelled run (media changed) must not open a picker for the old media.
if (deps.signal?.aborted) return false;
deps.openManualPicker(payload);
return true;
}
+28 -8
View File
@@ -941,8 +941,9 @@ test('runSubsyncManual keeps a retimed secondary track in the secondary slot', a
assert.equal(result.ok, true);
assert.deepEqual(sentCommands[0], ['sub-add', retimedPath, 'auto']);
assert.deepEqual(sentCommands[1], ['set_property', 'secondary-sub-delay', 0]);
assert.deepEqual(sentCommands[2], ['set_property', 'secondary-sid', 3]);
// The old delay is only dropped once the retimed track is selected.
assert.deepEqual(sentCommands[1], ['set_property', 'secondary-sid', 3]);
assert.deepEqual(sentCommands[2], ['set_property', 'secondary-sub-delay', 0]);
assert.equal(
sentCommands.some((command) => command[1] === 'sub-delay'),
false,
@@ -1556,9 +1557,14 @@ test('runSubsyncManual kills a running tool and reports cancellation when the me
fs.writeFileSync(videoPath, 'video');
fs.writeFileSync(targetPath, '1\n00:00:01,000 --> 00:00:02,000\nhi\n');
fs.writeFileSync(refPath, '1\n00:00:01,000 --> 00:00:02,000\nhi\n');
writeExecutableScript(alassPath, `#!/bin/sh\necho $$ > "${pidPath}"\nexec sleep 30\n`);
const childPidPath = path.join(tmpDir, 'alass-child.pid');
// Like ffsubsync (Python running ffmpeg): the tool itself starts a long-running child.
writeExecutableScript(
alassPath,
`#!/bin/sh\nsleep 30 &\necho $! > "${childPidPath}"\necho $$ > "${pidPath}"\nwait\n`,
);
const startedAt = Date.now();
let switchedAt: number | null = null;
const deps = makeDeps({
getMpvClient: () => ({
connected: true,
@@ -1566,7 +1572,9 @@ test('runSubsyncManual kills a running tool and reports cancellation when the me
send: () => {},
requestProperty: async (name: string) => {
if (name === 'path') {
return Date.now() - startedAt < 700 ? videoPath : path.join(tmpDir, 'ep02.mkv');
// Switch episodes only once the tool is running, however slow the machine is.
if (switchedAt === null && fs.existsSync(pidPath)) switchedAt = Date.now();
return switchedAt === null ? videoPath : path.join(tmpDir, 'ep02.mkv');
}
if (name === 'sid') return 1;
if (name === 'secondary-sid') return null;
@@ -1592,9 +1600,21 @@ test('runSubsyncManual kills a running tool and reports cancellation when the me
assert.equal(result.ok, false);
assert.match(result.message, /Playback changed/);
assert.ok(Date.now() - startedAt < 5000, 'run should stop well before the tool would finish');
const pid = Number(fs.readFileSync(pidPath, 'utf8').trim());
assert.throws(() => process.kill(pid, 0), 'the external tool should have been killed');
assert.ok(switchedAt !== null && Date.now() - switchedAt < 5000, 'stops soon after the switch');
const isAlive = (pidFile: string): boolean => {
try {
process.kill(Number(fs.readFileSync(pidFile, 'utf8').trim()), 0);
return true;
} catch {
return false;
}
};
assert.equal(isAlive(pidPath), false, 'the external tool should have been killed');
// The orphaned child is reaped asynchronously by init; give it a moment.
for (let attempt = 0; attempt < 20 && isAlive(childPidPath); attempt += 1) {
await new Promise((resolve) => setTimeout(resolve, 50));
}
assert.equal(isAlive(childPidPath), false, "the tool's own child should have been killed");
});
test('in-place replacement keeps a one-time .orig backup, the file mode, and symlinks', async () => {
+6 -4
View File
@@ -73,9 +73,10 @@ export async function runWithMediaChangeAbort<D extends SubsyncCoreDeps, T>(
task: (deps: D) => Promise<T>,
): Promise<T> {
const client = deps.getMpvClient();
const initialPath = client?.connected
? await client.requestProperty('path').catch(() => null)
: null;
// `undefined` = baseline not read yet (failed request); the first successful poll sets it.
let baselinePath: unknown = client?.connected
? await client.requestProperty('path').catch(() => undefined)
: undefined;
const controller = new AbortController();
let polling = false;
const timer = setInterval(() => {
@@ -90,7 +91,8 @@ export async function runWithMediaChangeAbort<D extends SubsyncCoreDeps, T>(
.requestProperty('path')
.then(
(currentPath) => {
if (currentPath !== initialPath) controller.abort();
if (baselinePath === undefined) baselinePath = currentPath;
else if (currentPath !== baselinePath) controller.abort();
},
() => {},
)