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: claim revised sections atomically so overlapping resumes can't double-generate (#8987)

[._.]/ Adam Eivy3145f98fa796
diff --git a/server/routes/musicVideoRevision.test.js b/server/routes/musicVideoRevision.test.js
index e0170f690b..2bc9854baa 100644
--- a/server/routes/musicVideoRevision.test.js
+++ b/server/routes/musicVideoRevision.test.js
@@ -132,25 +132,49 @@ describe('selective section revision (#8987)', () => {
expect(s3).toEqual(project.scenes[2]);
});
- it('resumes to generate only the rejected section, never a section already holding a take', async () => {
+ it('resumes to generate only the rejected section, and never hands a section out twice', async () => {
const project = await reviewedProject();
const { body: { revision } } = await request(app).post(`${base(project.id)}/excerpt/mve-draft/revisions`).send({});
- const first = await request(app).post(`${base(project.id)}/revisions/${revision.id}/resume`);
- expect(first.status).toBe(200);
- expect(first.body.needsGeneration).toEqual([{ sceneId: 's2', kind: 'video' }]);
- expect(first.body.render).toBeNull();
-
- // The board submitted s2's clip; while that job is live a second resume
- // (a double click, or a resume after a restart) asks for nothing new.
- h.jobs.push({ id: 'job-live', kind: 'video', status: 'running', queuedAt: new Date().toISOString(), params: { musicVideo: { projectId: project.id, sceneId: 's2' } } });
- const again = await request(app).post(`${base(project.id)}/revisions/${revision.id}/resume`);
- expect(again.body.needsGeneration).toEqual([]);
- expect(again.body.generating).toEqual([{ sceneId: 's2', kind: 'video' }]);
+ // Two overlapping resumes (two tabs, a double submit): exactly one hands
+ // s2 out for generation; the other sees it claimed.
+ const [a, b] = await Promise.all([
+ request(app).post(`${base(project.id)}/revisions/${revision.id}/resume`),
+ request(app).post(`${base(project.id)}/revisions/${revision.id}/resume`),
+ ]);
+ expect([a.status, b.status]).toEqual([200, 200]);
+ expect([a.body.needsGeneration, b.body.needsGeneration]).toContainEqual([{ sceneId: 's2', kind: 'video' }]);
+ expect([a.body.needsGeneration, b.body.needsGeneration]).toContainEqual([]);
+ expect(a.body.render).toBeNull();
+ expect(b.body.render).toBeNull();
expect(h.procs).toHaveLength(0); // nothing renders until every rejected section has a take
expect(h.enqueueJob).not.toHaveBeenCalled();
});
+ it('re-offers a claimed section only once its lease lapses with no job in the queue', async () => {
+ vi.useFakeTimers({ toFake: ['Date'] });
+ try {
+ const project = await reviewedProject();
+ const { body: { revision } } = await request(app).post(`${base(project.id)}/excerpt/mve-draft/revisions`).send({});
+ await request(app).post(`${base(project.id)}/revisions/${revision.id}/resume`);
+
+ // The board submitted s2; while its job is live, a resume long after the
+ // lease (e.g. after a restart) still asks for nothing new.
+ vi.setSystemTime(Date.now() + 10 * 60_000);
+ h.jobs.push({ id: 'job-live', kind: 'video', status: 'running', queuedAt: new Date().toISOString(), params: { musicVideo: { projectId: project.id, sceneId: 's2' } } });
+ const live = await request(app).post(`${base(project.id)}/revisions/${revision.id}/resume`);
+ expect(live.body.needsGeneration).toEqual([]);
+ expect(live.body.generating).toEqual([{ sceneId: 's2', kind: 'video' }]);
+
+ // That job failed and produced nothing: s2 is offered again.
+ h.jobs[0].status = 'failed';
+ const failed = await request(app).post(`${base(project.id)}/revisions/${revision.id}/resume`);
+ expect(failed.body.needsGeneration).toEqual([{ sceneId: 's2', kind: 'video' }]);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
it('retries a failed render without re-submitting any generation, then completes', async () => {
const project = await reviewedProject();
const { body: { revision } } = await request(app).post(`${base(project.id)}/excerpt/mve-draft/revisions`).send({});
diff --git a/server/services/musicVideo/revision.js b/server/services/musicVideo/revision.js
index d972366229..5a6c163b82 100644
--- a/server/services/musicVideo/revision.js
+++ b/server/services/musicVideo/revision.js
@@ -37,6 +37,15 @@ export const REVISION_STATUSES = Object.freeze(['open', 'rendering', 'complete',
// A project row carries its recent revisions; the oldest SETTLED ones are
// dropped past this so a long review loop can't grow one record without bound.
export const MAX_PROJECT_REVISIONS = 20;
+// A resume that hands a section out for generation CLAIMS it for this long, so
+// a second resume (another tab, a double submit) in the window between the
+// hand-out and the job reaching the queue can't hand it out again. After the
+// lease a section with no job and no take is handed out again — the earlier
+// submission evidently never reached the queue.
+export const GENERATION_CLAIM_LEASE_MS = 90_000;
+// A job that completed but whose take never attached (a failed attach write)
+// counts as in flight only this long, so it can't wedge the revision forever.
+export const TAKE_ATTACH_GRACE_MS = 120_000;
const revisionError = (status, code, message, context) =>
new ServerError(message, { status, code, ...(context ? { context } : {}) });
@@ -177,18 +186,24 @@ export function startRevisionOnProject(project, excerptId, { sceneIds } = {}, no
const tagMatches = (job, projectId, sceneId) =>
job?.params?.musicVideo?.projectId === projectId && job.params.musicVideo.sceneId === sceneId;
+const within = (iso, windowMs, nowMs) => {
+ const t = typeof iso === 'string' ? Date.parse(iso) : NaN;
+ return Number.isFinite(t) && nowMs - t < windowMs;
+};
+
/**
* Pure: each section of a revision with its current `state`:
* - `kept` — approved; its selection is untouched;
* - `removed` — the scene was deleted since;
* - `ready` — the slot holds a take (a new one landed, or the
* director selected one) — never generated again;
- * - `generating` — a generation job for the scene is queued/running, or
- * finished but its take hasn't attached yet;
+ * - `generating` — a generation job for the scene is queued/running,
+ * finished moments ago but its take hasn't attached
+ * yet, or a resume claimed it within the lease;
* - `needs-generation` — nothing selected and nothing in flight.
* `jobs` is the media-job queue's list (queued, running and recent archive).
*/
-export function revisionSectionStates(project, revision, jobs = []) {
+export function revisionSectionStates(project, revision, jobs = [], nowMs = Date.now()) {
const scenesById = new Map((project.scenes || []).map((s) => [s.sceneId, s]));
return (revision.sections || []).map((section) => {
if (section.verdict !== 'rejected') return { ...section, state: 'kept' };
@@ -201,9 +216,10 @@ export function revisionSectionStates(project, revision, jobs = []) {
// Completed after the revision opened, but its take isn't on the scene
// yet: the attach hook is still writing it. Asking again would pay twice.
|| (job.status === 'completed' && typeof job.queuedAt === 'string' && job.queuedAt >= revision.createdAt
- && !takes.some((t) => t.jobId === job.id))
+ && within(job.completedAt, TAKE_ATTACH_GRACE_MS, nowMs) && !takes.some((t) => t.jobId === job.id))
));
- return { ...section, state: pending ? 'generating' : 'needs-generation' };
+ const claimed = within(section.claimedAt, GENERATION_CLAIM_LEASE_MS, nowMs);
+ return { ...section, state: pending || claimed ? 'generating' : 'needs-generation' };
});
}
@@ -216,6 +232,31 @@ export function resumableRevision(project, revisionId) {
return revision;
}
+/**
+ * Resume's atomic step (run under the record's write serialization): derive
+ * every section's state and CLAIM the ones about to be handed out for
+ * generation, so two overlapping resumes can never both hand out the same
+ * section. Returns `{ project, revision, needsGeneration, generating }` —
+ * `revision.sections` carry their derived `state`.
+ */
+export function claimRevisionGeneration(project, revisionId, jobs = [], nowMs = Date.now()) {
+ const revision = resumableRevision(project, revisionId);
+ const states = revisionSectionStates(project, revision, jobs, nowMs);
+ const ref = ({ sceneId, kind }) => ({ sceneId, kind });
+ const needsGeneration = states.filter((s) => s.state === 'needs-generation').map(ref);
+ const generating = states.filter((s) => s.state === 'generating').map(ref);
+ if (!needsGeneration.length) return { project, revision: { ...revision, sections: states }, needsGeneration, generating };
+ const claimedAt = new Date(nowMs).toISOString();
+ const claimIds = new Set(needsGeneration.map((s) => s.sceneId));
+ const next = { ...revision, sections: revision.sections.map((s) => (claimIds.has(s.sceneId) ? { ...s, claimedAt } : s)), updatedAt: claimedAt };
+ return {
+ project: replaceRevision(project, next),
+ revision: { ...next, sections: states.map((s) => (claimIds.has(s.sceneId) ? { ...s, claimedAt } : s)) },
+ needsGeneration,
+ generating,
+ };
+}
+
/**
* Link a draft re-render to an open revision (same write as the excerpt's
* creation, so a fast finish can always find the revision it settles).
diff --git a/server/services/musicVideo/revisionService.js b/server/services/musicVideo/revisionService.js
index d5fb74e8f9..658efc74e4 100644
--- a/server/services/musicVideo/revisionService.js
+++ b/server/services/musicVideo/revisionService.js
@@ -19,19 +19,16 @@
* against the freshest record under the backend's write serialization.
*/
-import { ServerError } from '../../lib/errorHandler.js';
import { getProject, mutateProjectRecord } from './projects.js';
import { cancelExcerptRender, startExcerptRender } from './excerptRender.js';
import {
cancelRevisionOnProject,
+ claimRevisionGeneration,
projectRevisions,
- resumableRevision,
revisionSectionStates,
startRevisionOnProject,
} from './revision.js';
-const sceneRef = ({ sceneId, kind }) => ({ sceneId, kind });
-
/** Open a revision from a reviewed excerpt. Returns `{ project, revision, skippedSceneIds }`. */
export async function startRevision(projectId, excerptId, input = {}) {
return mutateProjectRecord(projectId, (current) => startRevisionOnProject(current, excerptId, input));
@@ -44,24 +41,19 @@ export async function startRevision(projectId, excerptId, input = {}) {
* holds a take, otherwise null.
*/
export async function resumeRevision(projectId, revisionId) {
- const project = await getProject(projectId);
- if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });
- const revision = resumableRevision(project, revisionId);
// Deferred: the queue module's closure is large and only this path needs it.
const { listJobs } = await import('../mediaJobQueue/index.js');
const jobs = [...listJobs({ kind: 'video' }), ...listJobs({ kind: 'image' })];
- const sections = revisionSectionStates(project, revision, jobs);
- const needsGeneration = sections.filter((s) => s.state === 'needs-generation').map(sceneRef);
- const generating = sections.filter((s) => s.state === 'generating').map(sceneRef);
- if (needsGeneration.length || generating.length) {
- return { project, revision: { ...revision, sections }, needsGeneration, generating, render: null };
- }
+ // Derive + claim under the record's write serialization, so two overlapping
+ // resumes can never both hand the same section out for (paid) generation.
+ const claim = await mutateProjectRecord(projectId, (current) => claimRevisionGeneration(current, revisionId, jobs));
+ if (claim.needsGeneration.length || claim.generating.length) return { ...claim, render: null };
// Every rejected section holds a take: re-render the draft window. The
// excerpt render links itself to the revision in its creation write (and
// refuses one that closed or is already rendering meanwhile).
- const render = await startExcerptRender(projectId, { startSec: revision.startSec, endSec: revision.endSec }, { revisionId });
+ const render = await startExcerptRender(projectId, { startSec: claim.revision.startSec, endSec: claim.revision.endSec }, { revisionId });
const fresh = await getProject(projectId);
- const current = projectRevisions(fresh).find((r) => r.id === revisionId) || revision;
+ const current = projectRevisions(fresh).find((r) => r.id === revisionId) || claim.revision;
return { project: fresh, revision: { ...current, sections: revisionSectionStates(fresh, current, jobs) }, needsGeneration: [], generating: [], render };
}