Skip to content

Commit c906338

Browse files
ericallamTrigger.dev RepoOps
authored andcommitted
feat(cli): preload the task while a container waits after a suspend
Mono-RevId: bb751723b18702391ea49794d50f948ba2f20cbf
1 parent 8cf37d4 commit c906338

14 files changed

Lines changed: 1066 additions & 41 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/sdk": patch
3+
---
4+
5+
`metadata.parent` and `metadata.root` now update the parent and root runs when a task file was imported before its run started, as happens when a task is preloaded.
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"trigger.dev": patch
3+
---
4+
5+
With `processKeepAlive` on, a new process that replaces one that suspended now imports the init file and the last run's task file while the machine waits, so the next run of that task starts without the import. Set `TRIGGER_PRELOAD_DISABLED=1` in your environment to turn it off.

‎docs/config/config-file.mdx‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -460,6 +460,39 @@ export default defineConfig({
460460
});
461461
```
462462

463+
### Preloading after a suspend
464+
465+
With `processKeepAlive` enabled, a process can't be reused when its run suspends (for example during a long `wait`), crashes, or reaches `maxExecutionsPerProcess`, so it's replaced. In deployed environments, the new process imports your init file and the last run's task file while the machine waits for its next run. If that run is for the same task, it starts without paying for the import. With `processKeepAlive` off (the default), nothing is preloaded.
466+
467+
The import happens before the next run exists, using the previous run's environment variables. This affects code at the top level of your task files and init file:
468+
469+
- Environment variables read at import time hold the previous run's values. This is already true for a process kept alive between runs.
470+
- Run credentials such as `TRIGGER_SECRET_KEY` are not set during the import, so code that copies them into a variable at the top level gets `undefined`. Read them inside your task's `run` function, or leave them to the SDK, which reads them when it makes a request.
471+
- Side effects (opening connections, starting timers, logging) run while no run is active.
472+
- Some [secret environment variables](/deploy-environment-variables#secret-environment-variables) have a value that is only valid for the run it was given to. A client built at the top level from one of these keeps the previous run's value, so later runs fail with an authentication error from that service (for example a 401).
473+
474+
To avoid stale values, build clients that use secrets inside your task's `run` function:
475+
476+
```ts trigger/ask-user.ts
477+
import { task, wait } from "@trigger.dev/sdk";
478+
import OpenAI from "openai";
479+
480+
// Before: built at import time, can keep a previous run's API key
481+
// const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
482+
483+
export const askUser = task({
484+
id: "ask-user",
485+
run: async (payload: { question: string }) => {
486+
// After: built for each run, from this run's environment variables
487+
const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
488+
await wait.for({ minutes: 10 });
489+
return openai.responses.create({ model: "gpt-4.1", input: payload.question });
490+
},
491+
});
492+
```
493+
494+
To turn preloading off and import task files only when a run starts, add a `TRIGGER_PRELOAD_DISABLED` environment variable with the value `1` to the environment. Set in the dashboard, it applies from the next run without a redeploy. Set with [`syncEnvVars`](/deploy-environment-variables#using-the-syncenvvars-build-extension), it applies from your next deploy.
495+
463496
## Development behavior
464497

465498
You can control the working directory behavior in development:

‎packages/cli-v3/src/entryPoints/managed-run-worker.ts‎

Lines changed: 73 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -372,6 +372,30 @@ async function bootstrap() {
372372
return bootstrapCache;
373373
}
374374

375+
// Imports the init file, then the task's file. Imports are cached, so the init file runs once per process.
376+
async function importTaskFiles(
377+
workerManifest: WorkerManifest,
378+
taskManifest: WorkerManifest["tasks"][number]
379+
) {
380+
resourceCatalog.setCurrentFileContext(taskManifest.filePath, taskManifest.entryPoint);
381+
382+
if (workerManifest.initEntryPoint) {
383+
try {
384+
await import(workerImportPath(workerManifest, workerManifest.initEntryPoint));
385+
console.log(`Loaded init file from ${workerManifest.initEntryPoint}`);
386+
} catch (err) {
387+
console.error(`Failed to load init file`, err);
388+
throw err;
389+
}
390+
}
391+
392+
await import(workerImportPath(workerManifest, taskManifest.entryPoint));
393+
resourceCatalog.clearCurrentFileContext();
394+
}
395+
396+
// Set when a preload imported a task, until the first run reports it on its timeline.
397+
let _preloaded: { taskId: string; durationMs: number } | undefined;
398+
375399
let _execution: TaskRunExecution | undefined;
376400
let _prodUsageManager: ProdUsageManager | undefined;
377401
let _isRunning = false;
@@ -499,6 +523,20 @@ const zodIpc = new ZodIpcConnection({
499523

500524
standardRunTimelineMetricsManager.registerMetricsFromExecution(metrics, isWarmStart);
501525

526+
if (_preloaded?.taskId === execution.task.id) {
527+
// No duration: the import ran before the run, so it takes no time on this run's timeline.
528+
standardRunTimelineMetricsManager.registerMetric({
529+
name: "trigger.dev/start",
530+
event: "preloaded",
531+
timestamp: Date.now(),
532+
attributes: {
533+
preloadedTaskId: _preloaded.taskId,
534+
preloadDurationMs: Math.round(_preloaded.durationMs),
535+
},
536+
});
537+
}
538+
_preloaded = undefined;
539+
502540
if (_isRunning) {
503541
console.error("Worker is already running a task");
504542

@@ -574,24 +612,7 @@ const zodIpc = new ZodIpcConnection({
574612
},
575613
async () => {
576614
const beforeImport = performance.now();
577-
resourceCatalog.setCurrentFileContext(
578-
taskManifest.filePath,
579-
taskManifest.entryPoint
580-
);
581-
582-
// Load init file if it exists
583-
if (workerManifest.initEntryPoint) {
584-
try {
585-
await import(workerImportPath(workerManifest, workerManifest.initEntryPoint));
586-
console.log(`Loaded init file from ${workerManifest.initEntryPoint}`);
587-
} catch (err) {
588-
console.error(`Failed to load init file`, err);
589-
throw err;
590-
}
591-
}
592-
593-
await import(workerImportPath(workerManifest, taskManifest.entryPoint));
594-
resourceCatalog.clearCurrentFileContext();
615+
await importTaskFiles(workerManifest, taskManifest);
595616
const durationMs = performance.now() - beforeImport;
596617

597618
console.log(
@@ -742,6 +763,40 @@ const zodIpc = new ZodIpcConnection({
742763
});
743764
}
744765
},
766+
PRELOAD_TASK: async ({ taskId, env }) => {
767+
const startedAt = performance.now();
768+
769+
try {
770+
populateEnv(env, { override: true, previousEnv: _lastEnv });
771+
_lastEnv = env;
772+
773+
const { workerManifest } = await bootstrap();
774+
const taskManifest = workerManifest.tasks.find((t) => t.id === taskId);
775+
776+
if (!taskManifest) {
777+
return { ok: false, durationMs: 0, error: "task not in the worker manifest" };
778+
}
779+
780+
if (!resourceCatalog.getTask(taskId)) {
781+
await importTaskFiles(workerManifest, taskManifest);
782+
process.title = `trigger-dev-worker: ${taskId}`;
783+
}
784+
785+
const durationMs = performance.now() - startedAt;
786+
_preloaded = { taskId, durationMs };
787+
console.log(`Preloaded task ${taskId} [${taskManifest.entryPoint}] in ${durationMs}ms`);
788+
789+
return { ok: true, durationMs };
790+
} catch (err) {
791+
console.error(`Failed to preload task ${taskId}`, err);
792+
793+
return {
794+
ok: false,
795+
durationMs: performance.now() - startedAt,
796+
error: err instanceof Error ? err.message : String(err),
797+
};
798+
}
799+
},
745800
CANCEL: async ({ timeoutInMs }) => {
746801
_isCancelled = true;
747802
_cancelController.abort("run cancelled");

‎packages/cli-v3/src/entryPoints/managed/controller.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -351,6 +351,7 @@ export class ManagedRunController {
351351
});
352352

353353
const previousTaskRunEnv = this.currentExecution.taskRunEnv;
354+
const preload = this.currentExecution.takePreload();
354355

355356
// Create a fresh execution for the next run
356357
this.currentExecution = new RunExecution({
@@ -362,8 +363,10 @@ export class ManagedRunController {
362363
taskRunProcessProvider: this.taskRunProcessProvider,
363364
});
364365

366+
// A fresh process starts importing the last run's task here, and keeps going while we wait for a run.
365367
await this.currentExecution.prepareForExecution({
366368
taskRunEnv: previousTaskRunEnv,
369+
preload,
367370
});
368371
}
369372

0 commit comments

Comments
 (0)