Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix: persist voice fine-tuning jobs to disk so checkpoints stay promotable (#5664)

Adam Eivyb51222ac1566
diff --git a/server/lib/sseUtils.js b/server/lib/sseUtils.js
index 8feb81532a..f668612b09 100644
--- a/server/lib/sseUtils.js
+++ b/server/lib/sseUtils.js
@@ -78,7 +78,9 @@ export const closeJobAfterDelay = (jobs, jobId, delay = SSE_CLEANUP_DELAY_MS, ex
for (const c of expectedJob.clients || []) c.end();
return;
}
- if (job) for (const c of job.clients) c.end();
+ // `clients` is absent on job maps that use this purely for eviction (the
+ // voice fine-tuning registry has no SSE route), so guard like the branch above.
+ if (job) for (const c of job.clients || []) c.end();
jobs.delete(jobId);
}, delay);
};
diff --git a/server/routes/voice.js b/server/routes/voice.js
index 934cf6e230..da2b843183 100644
--- a/server/routes/voice.js
+++ b/server/routes/voice.js
@@ -340,8 +340,8 @@ router.post('/profiles/:id/fine-tune/start', asyncHandler(async (req, res) => {
}));
router.get('/profiles/:id/fine-tune/:jobId', asyncHandler(async (req, res) => {
- const { jobId } = validateRequest(fineTuneJobParamsSchema, req.params);
- const result = getFineTuningJobStatus(jobId);
+ const { id: profileId, jobId } = validateRequest(fineTuneJobParamsSchema, req.params);
+ const result = await getFineTuningJobStatus(jobId, profileId);
res.json(result);
}));
diff --git a/server/services/voice/fineTuning.js b/server/services/voice/fineTuning.js
index 3e03dba2e2..7352743674 100644
--- a/server/services/voice/fineTuning.js
+++ b/server/services/voice/fineTuning.js
@@ -10,11 +10,13 @@
import { randomUUID } from 'node:crypto';
import { existsSync } from 'node:fs';
-import { mkdir, readdir, stat } from 'node:fs/promises';
+import { mkdir, readdir } from 'node:fs/promises';
import { join } from 'node:path';
import { spawn } from '../../lib/childProcess.js';
import { ServerError } from '../../lib/errorHandler.js';
+import { atomicWrite, readJSONFile } from '../../lib/fileUtils.js';
import { safeChildProcessOptions } from '../../lib/processEnv.js';
+import { closeJobAfterDelay } from '../../lib/sseUtils.js';
import {
DEFAULT_CLONE_MODEL,
QWEN3_TTS_RUNNER_SCRIPT,
@@ -26,9 +28,64 @@ import {
promoteFineTunedProfile,
} from './profiles.js';
-// In-memory active training job map
+// In-memory active training job map. Entries are evicted once terminal (see
+// `finalizeJob`); the durable record is the `job.json` sidecar written beside
+// the run's checkpoints, so a restart mid-training does not orphan them.
const activeJobs = new Map();
+// Sidecar record written into `<profileDir>/fine-tune/<jobId>/`. It lives with
+// the checkpoints it indexes so the record and its artifacts are deleted
+// together, rather than in a separate store that could outlive them.
+const JOB_RECORD_FILE = 'job.json';
+
+const jobRecordPath = (profileId, jobId) =>
+ join(profileArtifactDirectory(profileId), 'fine-tune', jobId, JOB_RECORD_FILE);
+
+// Drops the runtime-only handles (abort controller, child process, write chain,
+// finalize latch) that cannot — and must not — be serialized.
+const serializableJob = ({
+ controller: _controller,
+ child: _child,
+ persistChain: _persistChain,
+ finalized: _finalized,
+ ...record
+}) => record;
+
+/**
+ * Write the job record to disk. Writes are chained per job because `close` and
+ * `error` can both fire for one child and each rewrites the same file.
+ */
+const persistJob = (jobState) => {
+ jobState.persistChain = (jobState.persistChain || Promise.resolve())
+ .then(() => atomicWrite(jobRecordPath(jobState.profileId, jobState.id), serializableJob(jobState)))
+ .catch((err) => console.error(`❌ Failed to persist fine-tune job ${jobState.id}: ${err.message}`));
+ return jobState.persistChain;
+};
+
+/**
+ * Resolve a job from memory, falling back to its on-disk record. Returns null
+ * when neither exists.
+ */
+async function loadJob(jobId, profileId) {
+ const active = activeJobs.get(jobId);
+ if (active) return active;
+ if (!profileId) return null;
+ return readJSONFile(jobRecordPath(profileId, jobId), null);
+}
+
+/**
+ * Persist the terminal state, then evict the in-memory entry after the SSE
+ * grace window so a status poll racing completion still hits memory while the
+ * map stays bounded. Runs at most once per job — `error` and `close` can both
+ * fire for the same child.
+ */
+const finalizeJob = (jobState) => {
+ if (jobState.finalized) return;
+ jobState.finalized = true;
+ persistJob(jobState);
+ closeJobAfterDelay(activeJobs, jobState.id);
+};
+
/**
* Validate training dataset readiness for a given voice profile.
*/
@@ -123,9 +180,11 @@ export async function startFineTuningJob({
completedAt: null,
error: null,
controller: abortController,
+ child: null,
};
activeJobs.set(jobId, jobState);
+ await persistJob(jobState);
const args = [
QWEN3_TTS_RUNNER_SCRIPT,
@@ -138,6 +197,8 @@ export async function startFineTuningJob({
];
const child = spawn(python, args, safeChildProcessOptions({ signal: abortController.signal }));
+ // Keep a handle on the child so a future shutdown hook can reach in-flight training.
+ jobState.child = child;
let lineBuffer = '';
child.stdout.on('data', (chunk) => {
@@ -186,12 +247,14 @@ export async function startFineTuningJob({
}
jobState.completedAt = new Date().toISOString();
}
+ finalizeJob(jobState);
});
child.on('error', (err) => {
jobState.status = 'failed';
jobState.error = err.message;
jobState.completedAt = new Date().toISOString();
+ finalizeJob(jobState);
});
return {
@@ -204,15 +267,15 @@ export async function startFineTuningJob({
}
/**
- * Get the current status and checkpoints of a fine-tuning job.
+ * Get the current status and checkpoints of a fine-tuning job, from memory
+ * while it is live and from its `job.json` sidecar afterwards.
*/
-export function getFineTuningJobStatus(jobId) {
- const job = activeJobs.get(jobId);
+export async function getFineTuningJobStatus(jobId, profileId) {
+ const job = await loadJob(jobId, profileId);
if (!job) {
throw new ServerError('Fine-tuning job not found', { status: 404, code: 'JOB_NOT_FOUND' });
}
- const { controller: _c, ...serializable } = job;
- return serializable;
+ return serializableJob(job);
}
/**
@@ -235,7 +298,7 @@ export function cancelFineTuningJob(jobId) {
* Explicitly promote a selected checkpoint to the character's voice profile.
*/
export async function promoteCheckpoint({ profileId, jobId, checkpointId }) {
- const job = activeJobs.get(jobId);
+ const job = await loadJob(jobId, profileId);
if (!job) {
throw new ServerError('Fine-tuning job not found', { status: 404, code: 'JOB_NOT_FOUND' });
}
diff --git a/server/services/voice/fineTuning.test.js b/server/services/voice/fineTuning.test.js
index 956202d9b0..63ea503755 100644
--- a/server/services/voice/fineTuning.test.js
+++ b/server/services/voice/fineTuning.test.js
@@ -1,7 +1,8 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
-import { mkdtemp, rm, mkdir, writeFile } from 'node:fs/promises';
+import { mkdtemp, rm, mkdir, writeFile, readFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
+import { SSE_CLEANUP_DELAY_MS } from '../../lib/sseUtils.js';
let voiceProfilesRoot = '';
const queryMock = vi.fn();
@@ -47,15 +48,31 @@ beforeEach(async () => {
});
afterEach(async () => {
- await rm(voiceProfilesRoot, { recursive: true, force: true });
+ // maxRetries absorbs the ENOTEMPTY race with a job.json write still in flight
+ // from a child that exited as the test ended.
+ await rm(voiceProfilesRoot, { recursive: true, force: true, maxRetries: 5, retryDelay: 20 });
});
+const seedSourceAudio = async () => {
+ const sourceDir = join(voiceProfilesRoot, PROFILE.id, 'source');
+ await mkdir(sourceDir, { recursive: true });
+ await writeFile(join(sourceDir, 'sample.wav'), Buffer.from('RIFFdata'));
+};
+
+const jobRecordPath = (jobId) => join(voiceProfilesRoot, PROFILE.id, 'fine-tune', jobId, 'job.json');
+
+// The sidecar is rewritten from the child's terminal handler, so every test that
+// outlives a run waits for that write instead of racing the temp-dir teardown.
+const waitForTerminalJobRecord = (jobId) => vi.waitFor(async () => {
+ const record = JSON.parse(await readFile(jobRecordPath(jobId), 'utf8'));
+ expect(record.status).not.toBe('running');
+ return record;
+}, { timeout: 5_000, interval: 20 });
+
describe('fineTuning', () => {
it('validates dataset readiness and checks source recordings', async () => {
queryMock.mockResolvedValueOnce({ rows: [{ data: PROFILE }] });
- const profileDir = join(voiceProfilesRoot, PROFILE.id, 'source');
- await mkdir(profileDir, { recursive: true });
- await writeFile(join(profileDir, 'sample.wav'), Buffer.from('RIFFdata'));
+ await seedSourceAudio();
const result = await validateFineTuningDataset(PROFILE.id);
expect(result.ready).toBe(true);
@@ -65,9 +82,7 @@ describe('fineTuning', () => {
it('runs fine tuning lifecycle, emits checkpoints, and promotes checkpoint', async () => {
queryMock.mockResolvedValue({ rows: [{ data: PROFILE }] });
- const profileDir = join(voiceProfilesRoot, PROFILE.id, 'source');
- await mkdir(profileDir, { recursive: true });
- await writeFile(join(profileDir, 'sample.wav'), Buffer.from('RIFFdata'));
+ await seedSourceAudio();
const startRes = await startFineTuningJob({
profileId: PROFILE.id,
@@ -79,11 +94,12 @@ describe('fineTuning', () => {
status: 'running',
});
- await vi.waitFor(() => {
- expect(getFineTuningJobStatus(startRes.jobId).status).toBe('completed');
+ await vi.waitFor(async () => {
+ expect((await getFineTuningJobStatus(startRes.jobId, PROFILE.id)).status).toBe('completed');
}, { timeout: 5_000, interval: 20 });
- const status = getFineTuningJobStatus(startRes.jobId);
+ await waitForTerminalJobRecord(startRes.jobId);
+ const status = await getFineTuningJobStatus(startRes.jobId, PROFILE.id);
expect(status.status).toBe('completed');
expect(status.checkpoints.length).toBeGreaterThan(0);
@@ -100,9 +116,7 @@ describe('fineTuning', () => {
it('cancels an active fine tuning job', async () => {
queryMock.mockResolvedValue({ rows: [{ data: PROFILE }] });
- const profileDir = join(voiceProfilesRoot, PROFILE.id, 'source');
- await mkdir(profileDir, { recursive: true });
- await writeFile(join(profileDir, 'sample.wav'), Buffer.from('RIFFdata'));
+ await seedSourceAudio();
const startRes = await startFineTuningJob({
profileId: PROFILE.id,
@@ -115,5 +129,88 @@ describe('fineTuning', () => {
jobId: startRes.jobId,
status: 'cancelled',
});
+ await waitForTerminalJobRecord(startRes.jobId);
+ });
+
+ it('persists a job.json sidecar beside the checkpoints when the run finishes', async () => {
+ queryMock.mockResolvedValue({ rows: [{ data: PROFILE }] });
+ await seedSourceAudio();
+
+ const { jobId } = await startFineTuningJob({
+ profileId: PROFILE.id,
+ epochs: 2,
+ checkpointInterval: 20,
+ });
+ await vi.waitFor(async () => {
+ expect((await getFineTuningJobStatus(jobId, PROFILE.id)).status).toBe('completed');
+ }, { timeout: 5_000, interval: 20 });
+
+ const record = await waitForTerminalJobRecord(jobId);
+
+ expect(record.status).toBe('completed');
+ expect(record.id).toBe(jobId);
+ expect(record.profileId).toBe(PROFILE.id);
+ expect(record.checkpoints.length).toBeGreaterThan(0);
+ expect(record.completedAt).toEqual(expect.any(String));
+ // Runtime-only handles must never reach disk.
+ expect(record.controller).toBeUndefined();
+ expect(record.child).toBeUndefined();
+ });
+
+ it('promotes a checkpoint from the sidecar after a restart drops the in-memory job', async () => {
+ queryMock.mockResolvedValue({ rows: [{ data: PROFILE }] });
+ await seedSourceAudio();
+
+ const { jobId } = await startFineTuningJob({
+ profileId: PROFILE.id,
+ epochs: 2,
+ checkpointInterval: 20,
+ });
+ const status = await vi.waitFor(async () => {
+ const current = await getFineTuningJobStatus(jobId, PROFILE.id);
+ expect(current.status).toBe('completed');
+ expect(current.checkpoints.length).toBeGreaterThan(0);
+ return current;
+ }, { timeout: 5_000, interval: 20 });
+ await waitForTerminalJobRecord(jobId);
+
+ // A restart loses `activeJobs` entirely; the sidecar is the only record left.
+ vi.resetModules();
+ const restarted = await import('./fineTuning.js');
+
+ await expect(restarted.getFineTuningJobStatus(jobId)).rejects.toThrow(/not found/i);
+ const promoted = await restarted.promoteCheckpoint({
+ profileId: PROFILE.id,
+ jobId,
+ checkpointId: status.checkpoints[0].id,
+ });
+ expect(promoted).toMatchObject({ kind: 'fine-tuned', approval: { status: 'approved' } });
+ });
+
+ it('evicts the in-memory job entry after the grace window and keeps serving from disk', async () => {
+ vi.useFakeTimers({ shouldAdvanceTime: true });
+ try {
+ queryMock.mockResolvedValue({ rows: [{ data: PROFILE }] });
+ await seedSourceAudio();
+
+ const { jobId } = await startFineTuningJob({
+ profileId: PROFILE.id,
+ epochs: 2,
+ checkpointInterval: 20,
+ });
+ // Without a profileId the in-memory map is the only lookup source, so this
+ // resolving proves the entry is still resident.
+ await vi.waitFor(async () => {
+ expect((await getFineTuningJobStatus(jobId)).status).toBe('completed');
+ }, { timeout: 5_000, interval: 20 });
+ await waitForTerminalJobRecord(jobId);
+
+ await vi.advanceTimersByTimeAsync(SSE_CLEANUP_DELAY_MS + 100);
+
+ await expect(getFineTuningJobStatus(jobId)).rejects.toThrow(/not found/i);
+ expect((await getFineTuningJobStatus(jobId, PROFILE.id)).status).toBe('completed');
+ } finally {
+ vi.useRealTimers();
+ }
});
});