Skip to content

Commit eea6b17

Browse files
adrien2pTrigger.dev RepoOps
authored andcommitted
fix(core): keep the periodic metadata flush running when a tick lands on an in-flight request
Mono-RevId: e13406b351cc13201400cc937663fc511f550931
1 parent 3aa5c77 commit eea6b17

4 files changed

Lines changed: 291 additions & 31 deletions

File tree

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"@trigger.dev/core": patch
3+
---
4+
5+
Fix run metadata changes sometimes reaching the API only when the run finished, so realtime subscribers and parent runs didn't see progress while the task was still running. This also fixes a metadata `append` or `increment` occasionally being applied twice at the end of a run, and a new run that reused the previous run's process sometimes seeing that run's metadata values.

‎docs/runs/metadata.mdx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -368,7 +368,7 @@ export const myTask = task({
368368

369369
### flush
370370

371-
Flush the metadata to the database. The SDK will automatically flush the metadata periodically, so you don't need to call this method unless you need to ensure that the metadata is persisted immediately.
371+
Send pending metadata changes to the database now instead of waiting for the next automatic flush. The SDK flushes metadata automatically about once a second, so you only need this when you want changes sent sooner. If a flush is already in progress, `flush()` returns without waiting for it. Your changes stay queued and go out with a later automatic flush once that request finishes, or with the run's completion if the run finishes first.
372372

373373
```ts
374374
import { task, metadata } from "@trigger.dev/sdk";

‎packages/core/src/v3/runMetadata/manager.ts‎

Lines changed: 45 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,12 @@ import type { RunMetadataManager, RunMetadataUpdater } from "./types.js";
1212

1313
export class StandardMetadataManager implements RunMetadataManager {
1414
private flushTimeoutId: NodeJS.Timeout | null = null;
15-
private isFlushing: boolean = false;
15+
/** The periodic flush that is running; a tick schedules the next only while it is still this one. */
16+
private periodicFlushRun: object | undefined;
17+
/** Set once the last flush has been handed to the run's completion: nothing is sent after it. */
18+
private flushingStopped: boolean = false;
19+
/** The update request being sent. At most one is in flight, so updates stay ordered. */
20+
private inFlightFlush: Promise<void> | undefined;
1621
private store: Record<string, DeserializedJson> | undefined;
1722

1823
private queuedOperations: Set<RunMetadataChangeOperation> = new Set();
@@ -32,12 +37,15 @@ export class StandardMetadataManager implements RunMetadataManager {
3237
this.runId = undefined;
3338
this.runIdIsRoot = false;
3439

35-
if (this.flushTimeoutId) {
36-
clearTimeout(this.flushTimeoutId);
37-
this.flushTimeoutId = null;
38-
}
40+
this.stopPeriodicFlush();
3941

40-
this.isFlushing = false;
42+
// The previous run's request settles on its own, against its own run id: it
43+
// isn't this run's, so this run's first flush sends at once. Its settling
44+
// leaves this run's in-flight request alone, and its response doesn't replace
45+
// this run's metadata (see `flush` and `#send`).
46+
this.inFlightFlush = undefined;
47+
// The previous run handed its last flush to its completion; this run flushes again.
48+
this.flushingStopped = false;
4149
}
4250

4351
get parent(): RunMetadataUpdater {
@@ -352,21 +360,26 @@ export class StandardMetadataManager implements RunMetadataManager {
352360
}
353361
}
354362

355-
public async flush(requestOptions?: ApiRequestOptions): Promise<void> {
356-
if (!this.runId) {
357-
return;
363+
/**
364+
* Sends the queued changes and resolves when that request settles. When a
365+
* request is already in flight it returns at once and sends nothing, so
366+
* requests never overlap: what it leaves queued goes out with a later flush
367+
* once the in-flight request has settled, or with the run's completion
368+
* (`stopAndReturnLastFlush`) if the run ends first.
369+
*/
370+
public flush(requestOptions?: ApiRequestOptions): Promise<void> {
371+
if (!this.runId || this.flushingStopped || !this.#needsFlush() || this.inFlightFlush) {
372+
return Promise.resolve();
358373
}
359374

360-
if (!this.#needsFlush()) {
361-
return;
362-
}
363-
364-
if (this.isFlushing) {
365-
return;
366-
}
367-
368-
this.isFlushing = true;
375+
const sending = this.#send(this.runId, requestOptions).finally(() => {
376+
if (this.inFlightFlush === sending) this.inFlightFlush = undefined;
377+
});
378+
this.inFlightFlush = sending;
379+
return sending;
380+
}
369381

382+
async #send(runId: string, requestOptions?: ApiRequestOptions): Promise<void> {
370383
const operations = Array.from(this.queuedOperations);
371384
this.queuedOperations.clear();
372385

@@ -382,7 +395,7 @@ export class StandardMetadataManager implements RunMetadataManager {
382395
const collapsedRootOperations = collapseOperations(rootOperations);
383396

384397
const response = await this.apiClient.updateRunMetadata(
385-
this.runId,
398+
runId,
386399
{
387400
operations: collapsedOperations,
388401
parentOperations: collapsedParentOperations,
@@ -391,39 +404,41 @@ export class StandardMetadataManager implements RunMetadataManager {
391404
requestOptions
392405
);
393406

394-
this.store = response.metadata;
407+
// A response to an earlier run's request (settling after a `reset()`) is
408+
// not this run's metadata.
409+
if (this.runId === runId) this.store = response.metadata;
395410
} catch (error) {
396411
console.error("Failed to flush metadata", error);
397-
} finally {
398-
this.isFlushing = false;
399412
}
400413
}
401414

402415
public startPeriodicFlush(intervalMs: number = 1000) {
403-
const periodicFlush = async (intervalMs: number) => {
404-
if (this.isFlushing) {
405-
return;
406-
}
416+
const run = {};
417+
this.periodicFlushRun = run;
407418

419+
const periodicFlush = async () => {
408420
try {
421+
// A tick that lands on an in-flight request returns at once; a later tick, or the run's
422+
// completion, sends what's left.
409423
await this.flush();
410424
} catch (error) {
411425
console.error("Failed to flush metadata", error);
412-
throw error;
413426
} finally {
414-
this.isFlushing = false;
415427
scheduleNext();
416428
}
417429
};
418430

419431
const scheduleNext = () => {
420-
this.flushTimeoutId = setTimeout(() => periodicFlush(intervalMs), intervalMs);
432+
// Stopped (or restarted) while this tick was flushing: leave the timer alone.
433+
if (this.periodicFlushRun !== run) return;
434+
this.flushTimeoutId = setTimeout(periodicFlush, intervalMs);
421435
};
422436

423437
scheduleNext();
424438
}
425439

426440
stopPeriodicFlush(): void {
441+
this.periodicFlushRun = undefined;
427442
if (this.flushTimeoutId) {
428443
clearTimeout(this.flushTimeoutId);
429444
this.flushTimeoutId = null;
@@ -432,7 +447,7 @@ export class StandardMetadataManager implements RunMetadataManager {
432447

433448
async stopAndReturnLastFlush(): Promise<IOPacket> {
434449
this.stopPeriodicFlush();
435-
this.isFlushing = true;
450+
this.flushingStopped = true;
436451

437452
if (!this.#needsFlush()) {
438453
return { dataType: "application/json" };

0 commit comments

Comments
 (0)