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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
address review (codex): close two sweep-lifecycle races
[._.]/ Adam Eivya5b07d51d17b
diff --git a/server/services/localModelAssessmentSweep.js b/server/services/localModelAssessmentSweep.jsindex e3a074761c..41f0e27eb4 100644--- a/server/services/localModelAssessmentSweep.js+++ b/server/services/localModelAssessmentSweep.js@@ -49,6 +49,15 @@ import { getAssessmentReport, runAssessment } from './localModelAssessments.js';// model at a time anyway.let sweep = null;+// Held across `startSweep`'s `await getAssessmentReport()`. The `sweep` object+// itself cannot be published until the targets are known, so without this a+// second request arriving during that await passes the "already running" check,+// and both requests go on to assign `sweep` and launch a detached loop — two+// overnight queues measuring the same models against each other, with only the+// second one's status visible. The slot has to be reserved SYNCHRONOUSLY, before+// the first await, or the check and the claim are not atomic.+let startingSweep = false;+// A sweep is sequential BY DESIGN. Two models measured at once contend for the// same memory and the same GPU, and every number either one produces would// describe that contention rather than the model — which is the one thing this@@ -115,6 +124,7 @@ export function cancelSweep() {export function __resetSweep() {sweep?.controller?.abort();sweep = null;+ startingSweep = false;}// The sweep loop runs OUTSIDE the request lifecycle — there is no `next(err)` to@@ -187,7 +197,20 @@ async function runSweepLoop(run, targets, contextTokens, emit) {* sweep is already running or the scope covers nothing*/export async function startSweep({ scope = 'unmeasured', contextTokens, onProgress } = {}) {- if (sweep?.status === 'running') return { ...snapshot(), rejected: 'a sweep is already running' };+ if (sweep?.status === 'running' || startingSweep) return { ...snapshot(), rejected: 'a sweep is already running' };+ // Reserved here, synchronously, so the check above and this claim cannot be+ // split by the await inside. Released in the `finally` — by which point either+ // `sweep` is published (and the `running` check covers the slot) or the start+ // was refused and the slot is free again.+ startingSweep = true;+ try {+ return await beginSweep({ scope, contextTokens, onProgress });+ } finally {+ startingSweep = false;+ }+}++async function beginSweep({ scope, contextTokens, onProgress }) {const resolvedScope = SWEEP_SCOPES.includes(scope) ? scope : 'unmeasured';// Read the report ONCE, here, rather than per model: it lists installed modelsdiff --git a/server/services/localModelAssessmentSweep.test.js b/server/services/localModelAssessmentSweep.test.jsindex c9ee8aae20..f0343c4e7a 100644--- a/server/services/localModelAssessmentSweep.test.js+++ b/server/services/localModelAssessmentSweep.test.js@@ -112,6 +112,37 @@ describe('startSweep', () => {expect(second.rejected).toBe('a sweep is already running');});+ // The "already running" check and the slot claim must not be split by the+ // report await: two requests landing in that window would each publish a+ // `sweep` and launch a detached loop, so two overnight queues would measure the+ // same models against each other with only the second one's status visible.+ it('refuses a second sweep that arrives while the first is still reading the report', async () => {+ let releaseReport;+ getAssessmentReport.mockImplementationOnce(() => new Promise((resolve) => { releaseReport = resolve; }));+ runAssessment.mockResolvedValue(measured());++ const first = startSweep({ scope: 'unmeasured' });+ // Arrives before the report resolves — the first sweep object does not exist yet.+ const second = await startSweep({ scope: 'unmeasured' });+ expect(second.rejected).toBe('a sweep is already running');++ releaseReport(report({ unassessed: [{ backend: 'ollama', modelId: 'a' }] }));+ expect((await first).status).toBe('running');+ await settle();+ expect(runAssessment).toHaveBeenCalledTimes(1);+ });++ // A refused start must free the slot again, or one empty scope wedges the+ // feature until the process restarts.+ it('frees the slot when the start is refused', async () => {+ getAssessmentReport.mockResolvedValueOnce(report());+ expect((await startSweep({ scope: 'all' })).rejected).toBe('nothing to measure for that scope');++ getAssessmentReport.mockResolvedValue(report({ unassessed: [{ backend: 'ollama', modelId: 'a' }] }));+ runAssessment.mockResolvedValue(measured());+ expect((await startSweep({ scope: 'unmeasured' })).status).toBe('running');+ });+it('refuses a scope that covers nothing', async () => {getAssessmentReport.mockResolvedValue(report());const result = await startSweep({ scope: 'all' });diff --git a/server/services/localModelAssessments.js b/server/services/localModelAssessments.jsindex 6ba4e89675..627bc494ba 100644--- a/server/services/localModelAssessments.js+++ b/server/services/localModelAssessments.js@@ -336,6 +336,22 @@ export async function runAssessment({ backend, modelId, contextTokens = DEFAULT_throw new ServerError(claim.message, { status: 409, code: 'HEAVY_LOCAL_JOB_BUSY', context: { holder: claim.holder } });}try {+ // The claim wait is bounded but can be minutes long, and it does not observe+ // the abort signal. A cancel that landed while we waited must not turn into a+ // measurement now that the machine is free — that would relaunch llama-server+ // under the cancelled run's tuning and hold the claim against the sweep that+ // replaced it. Nothing was measured, so nothing is recorded.+ if (signal?.aborted) {+ console.log(`📏 Local LLM: ${backend}/${modelId} cancelled while waiting for the accelerator — not measured`);+ emit({ event: 'complete', cancelled: true, message: `${modelId}: cancelled before it started — nothing recorded` });+ // Same record SHAPE as the mid-run cancel below, so a consumer reads one+ // contract either way — just with nothing in it, because nothing ran.+ // `unknown` is the verdict for "no evidence", which is exactly the case.+ return {+ backend, modelId, cancelled: true, verdict: 'unknown', samples: [],+ performance: summarizePerformance([]),+ };+ }return await measureModel({ backend, modelId, contexts, tuning, signal, emit });} finally {await claim.release();diff --git a/server/services/localModelAssessments.test.js b/server/services/localModelAssessments.test.jsindex b1de8152ad..e5e6782fc7 100644--- a/server/services/localModelAssessments.test.js+++ b/server/services/localModelAssessments.test.js@@ -214,6 +214,29 @@ describe('runAssessment — machine-wide accelerator claim', () => {}});+ // The claim wait does not observe the abort signal, so a run cancelled WHILE+ // waiting would otherwise wake up and measure — relaunching llama-server under+ // the abandoned run's tuning and holding the machine against its replacement.+ it('does not measure a run that was cancelled while waiting for the claim', async () => {+ runLocalLlmTest.mockResolvedValue(okRun());+ const controller = new AbortController();+ controller.abort();++ const result = await svc.runAssessment({+ backend: 'ollama', modelId: 'example-model:7b', contextTokens: [512], signal: controller.signal,+ });++ expect(result.cancelled).toBe(true);+ expect(runLocalLlmTest).not.toHaveBeenCalled();+ expect(relaunchLlamaServerWithTuning).not.toHaveBeenCalled();+ // Nothing measured means nothing recorded.+ expect(await svc.loadAssessments()).toEqual([]);+ // ...and the claim went back, so the replacement sweep can start.+ const after = await claimHeavyLocalJob({ kind: 'probe', id: 'after-cancel' });+ expect(after.ok).toBe(true);+ await after.release();+ });+it('releases the claim afterwards, so the next measurement can run', async () => {runLocalLlmTest.mockResolvedValue(okRun());await svc.runAssessment({ backend: 'ollama', modelId: 'example-model:7b', contextTokens: [512] });