Skip to content

Commit ec17038

Browse files
carderneTrigger.dev RepoOps
authored andcommitted
feat(sandbox): server-side sandbox task execution policies
Add server-side support for locked-down task execution policies. Mono-RevId: 8a9082f51d0ea9c2d4459ee276180ccad23f302e
1 parent 21c2085 commit ec17038

50 files changed

Lines changed: 700 additions & 81 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎apps/supervisor/src/index.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1150,7 +1150,8 @@ class ManagedSupervisor {
11501150
dequeuedMessage: DequeuedMessage,
11511151
traceparent: string | undefined
11521152
): Promise<boolean> {
1153-
if (!this.warmStartUrl) {
1153+
// A sandbox never reuses a process or VM another run has used.
1154+
if (!this.warmStartUrl || dequeuedMessage.run.annotations?.executionMode === "SANDBOX") {
11541155
return false;
11551156
}
11561157

‎apps/webapp/app/presenters/v3/SpanPresenter.server.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -467,6 +467,7 @@ export class SpanPresenter extends BasePresenter {
467467
isAgentRun,
468468
isScheduled,
469469
isWebhook,
470+
executionPolicy: RunAnnotations.safeParse(run.annotations).data?.executionPolicy,
470471
payload,
471472
payloadType: run.payloadType,
472473
output,

‎apps/webapp/app/presenters/v3/TaskListPresenter.server.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import {
22
type PrismaClientOrTransaction,
33
type RuntimeEnvironmentType,
4+
type TaskExecutionMode,
45
type TaskTriggerSource,
56
} from "@trigger.dev/database";
67
import { $replica } from "~/db.server";
@@ -18,6 +19,7 @@ export type TaskListItem = {
1819
filePath: string;
1920
createdAt: Date;
2021
triggerSource: TaskTriggerSource;
22+
executionMode: TaskExecutionMode;
2123
};
2224

2325
class TaskListPresenter {
@@ -66,6 +68,7 @@ class TaskListPresenter {
6668
slug: true,
6769
filePath: true,
6870
triggerSource: true,
71+
executionMode: true,
6972
createdAt: true,
7073
},
7174
orderBy: {

‎apps/webapp/app/presenters/v3/UnifiedTaskListPresenter.server.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ export type UnifiedTaskListItem = {
2424
createdAt: Date;
2525
/** Agent-only: parsed `config.type` used for the Type badge. */
2626
agentType?: string;
27+
isSandbox?: boolean;
2728
};
2829

2930
export type UnifiedRunningState =
@@ -231,6 +232,7 @@ function toUnifiedItems(
231232
filePath: task.filePath,
232233
triggerSource: task.triggerSource,
233234
createdAt: task.createdAt,
235+
isSandbox: task.executionMode === "SANDBOX",
234236
});
235237
}
236238

‎apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam._index/route.tsx‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -600,6 +600,7 @@ function TaskRow({
600600
{item.kind === "AGENT" && item.agentType && (
601601
<Badge variant="extra-small">{formatAgentType(item.agentType)}</Badge>
602602
)}
603+
{item.isSandbox && <Badge variant="extra-small">Sandbox</Badge>}
603604
</div>
604605
</TableCell>
605606
<TableCell to={rowPath}>

‎apps/webapp/app/routes/engine.v1.dev.runs.$runFriendlyId.snapshots.$snapshotFriendlyId.attempts.start.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ import { machinePresetFromName } from "~/v3/machinePresets.server";
1919
import { meteringClaims } from "~/v3/utils/meteringClaims.server";
2020
import { engine } from "~/v3/runEngine.server";
2121
import { runStore } from "~/v3/runStore.server";
22+
import { pinnedRunPolicy } from "~/v3/services/worker/runExecutionPolicy.server";
2223

2324
const { action } = createActionApiRoute(
2425
{
@@ -51,7 +52,10 @@ const { action } = createActionApiRoute(
5152
}
5253

5354
// Resolved before the attempt exists, so an unavailable key leaves the run startable.
54-
const { variables } = await resolveAttemptVariables(authentication.environment);
55+
// Dev runs keep the dev key (no run tokens in dev) but only receive granted variables.
56+
const { variables } = await resolveAttemptVariables(authentication.environment, undefined, {
57+
grant: pinnedRunPolicy(run.annotations)?.policy.envVars,
58+
});
5559

5660
const engineResult = await engine.startRunAttempt({
5761
runId: RunId.toId(runFriendlyId),

‎apps/webapp/app/routes/resources.orgs.$organizationSlug.projects.$projectParam.env.$envParam.runs.$runParam.spans.$spanParam/route.tsx‎

Lines changed: 44 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ import {
1313
SignalIcon,
1414
} from "@heroicons/react/20/solid";
1515
import { type LoaderFunctionArgs } from "@remix-run/server-runtime";
16-
import { formatDurationMilliseconds } from "@trigger.dev/core/v3";
16+
import { formatDurationMilliseconds, type RunExecutionPolicy } from "@trigger.dev/core/v3";
1717
import { assertNever } from "assert-never";
1818
import { type ReactNode, useEffect } from "react";
1919
import { typedjson, useTypedFetcher } from "remix-typedjson";
@@ -41,6 +41,7 @@ import { CopyTextLink } from "~/components/primitives/CopyTextLink";
4141
import { DateTime, DateTimeAccurate } from "~/components/primitives/DateTime";
4242
import { Header2, Header3 } from "~/components/primitives/Headers";
4343
import { Paragraph } from "~/components/primitives/Paragraph";
44+
import { Badge } from "~/components/primitives/Badge";
4445
import {
4546
Popover,
4647
PopoverContent,
@@ -546,6 +547,7 @@ function RunBody({
546547
{run.isCached ? " (cached)" : null}
547548
</span>
548549
</Header2>
550+
{run.executionPolicy && <Badge variant="extra-small">Sandbox</Badge>}
549551
</div>
550552
{panelHeaderActions(
551553
headerAccessory,
@@ -1000,6 +1002,12 @@ function RunBody({
10001002
)}
10011003
</Property.Value>
10021004
</Property.Item>
1005+
{run.executionPolicy && (
1006+
<ExecutionPolicyProperties
1007+
policy={run.executionPolicy}
1008+
isDevelopment={environment.type === "DEVELOPMENT"}
1009+
/>
1010+
)}
10031011
<Property.Item>
10041012
<Property.Label>Runtime</Property.Label>
10051013
<Property.Value>
@@ -1433,6 +1441,41 @@ function MiniStat({
14331441

14341442
const EXTERNAL_DEPLOYMENT_ID_DISPLAY_LENGTH = 24;
14351443

1444+
function ExecutionPolicyProperties({
1445+
policy,
1446+
isDevelopment,
1447+
}: {
1448+
policy: RunExecutionPolicy;
1449+
isDevelopment: boolean;
1450+
}) {
1451+
return (
1452+
<>
1453+
<Property.Item>
1454+
<Property.Label>Sandbox</Property.Label>
1455+
<Property.Value>
1456+
{isDevelopment
1457+
? "Not enforced in development: runs locally with your dev environment's credentials"
1458+
: `Runs on a microVM${policy.rootKey ? "" : " without the environment secret key"}`}
1459+
</Property.Value>
1460+
</Property.Item>
1461+
<Property.Item>
1462+
<Property.Label>Run token scopes</Property.Label>
1463+
<Property.Value className="font-mono text-xs">{policy.scopes.join(", ")}</Property.Value>
1464+
</Property.Item>
1465+
<Property.Item>
1466+
<Property.Label>Environment variables</Property.Label>
1467+
<Property.Value>
1468+
{policy.envVars === "all"
1469+
? "All"
1470+
: policy.envVars.length === 0
1471+
? "None"
1472+
: policy.envVars.join(", ")}
1473+
</Property.Value>
1474+
</Property.Item>
1475+
</>
1476+
);
1477+
}
1478+
14361479
function ExternalDeploymentIdValue({
14371480
externalDeploymentId,
14381481
}: {

‎apps/webapp/app/runEngine/concerns/queues.server.ts‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { CONCURRENCY_LIMIT_NAME_PATTERN, sanitizeQueueName } from "@trigger.dev/core/v3/isomorphic";
22
import type { PrismaClientOrTransaction } from "@trigger.dev/database";
3+
import type { RunExecutionPolicy } from "@trigger.dev/core/v3";
34
import type { AuthenticatedEnvironment } from "~/services/apiAuth.server";
45
import { logger } from "~/services/logger.server";
56
import {
@@ -27,6 +28,7 @@ import {
2728
} from "@internal/cache";
2829
import { singleton } from "~/utils/singleton";
2930
import {
31+
parseExecutionPolicy,
3032
parseTaskGates,
3133
type TaskMetadataCache,
3234
type TaskMetadataEntry,
@@ -105,6 +107,7 @@ export class DefaultQueueManager implements QueueManager {
105107
let taskKind: string | undefined;
106108
let taskGates: TaskMetadataGate[] | null | undefined;
107109
let templateKey: string | null | undefined;
110+
let executionPolicy: RunExecutionPolicy | null | undefined;
108111

109112
// Determine queue name based on lockToVersion and provided options
110113
if (lockedBackgroundWorker) {
@@ -158,6 +161,7 @@ export class DefaultQueueManager implements QueueManager {
158161
taskKind = lockedMeta?.triggerSource;
159162
taskGates = lockedMeta?.gates;
160163
templateKey = lockedMeta?.templateKey;
164+
executionPolicy = lockedMeta?.executionPolicy;
161165
} else {
162166
// No queue override - resolve default queue + TTL + triggerSource via cache,
163167
// falling back to a single BackgroundWorkerTask lookup on miss.
@@ -198,6 +202,7 @@ export class DefaultQueueManager implements QueueManager {
198202
taskKind = lockedMeta.triggerSource;
199203
taskGates = lockedMeta.gates;
200204
templateKey = lockedMeta.templateKey;
205+
executionPolicy = lockedMeta.executionPolicy;
201206
}
202207
} else {
203208
// Task is not locked to a specific version, use regular logic
@@ -215,6 +220,7 @@ export class DefaultQueueManager implements QueueManager {
215220
taskKind = taskInfo.taskKind;
216221
taskGates = taskInfo.taskGates;
217222
templateKey = taskInfo.templateKey;
223+
executionPolicy = taskInfo.executionPolicy;
218224
}
219225

220226
// Sanitize the final determined queue name once
@@ -332,6 +338,7 @@ export class DefaultQueueManager implements QueueManager {
332338
taskKind,
333339
gates: gates.length > 0 ? gates : undefined,
334340
templateKey,
341+
executionPolicy: executionPolicy ?? undefined,
335342
};
336343
}
337344

@@ -341,6 +348,7 @@ export class DefaultQueueManager implements QueueManager {
341348
taskKind?: string | undefined;
342349
taskGates?: TaskMetadataGate[] | null;
343350
templateKey?: string | null;
351+
executionPolicy?: RunExecutionPolicy | null;
344352
}> {
345353
const { taskId, environment, body } = request;
346354
const { queue } = body.options ?? {};
@@ -365,6 +373,7 @@ export class DefaultQueueManager implements QueueManager {
365373
taskKind: meta?.triggerSource,
366374
taskGates: meta?.gates,
367375
templateKey: meta?.templateKey,
376+
executionPolicy: meta?.executionPolicy,
368377
};
369378
}
370379

@@ -387,6 +396,7 @@ export class DefaultQueueManager implements QueueManager {
387396
taskKind: meta.triggerSource,
388397
taskGates: meta.gates,
389398
templateKey: meta.templateKey,
399+
executionPolicy: meta.executionPolicy,
390400
};
391401
}
392402

@@ -396,6 +406,7 @@ export class DefaultQueueManager implements QueueManager {
396406
taskKind: meta.triggerSource,
397407
taskGates: meta.gates,
398408
templateKey: meta.templateKey,
409+
executionPolicy: meta.executionPolicy,
399410
};
400411
}
401412

@@ -453,6 +464,7 @@ export class DefaultQueueManager implements QueueManager {
453464
slug,
454465
ttl: row.ttl,
455466
triggerSource: row.triggerSource,
467+
executionPolicy: parseExecutionPolicy(row.executionPolicy),
456468
queueId: row.queue?.id ?? null,
457469
queueName: row.queue?.name ?? "",
458470
gates: parseTaskGates(row.gates),
@@ -476,6 +488,7 @@ export class DefaultQueueManager implements QueueManager {
476488
select: {
477489
ttl: true,
478490
triggerSource: true,
491+
executionPolicy: true,
479492
gates: true,
480493
queue: { select: { id: true, name: true } },
481494
worker: { select: { deployment: { select: { templateKey: true } } } },
@@ -527,6 +540,7 @@ export class DefaultQueueManager implements QueueManager {
527540
select: {
528541
ttl: true,
529542
triggerSource: true,
543+
executionPolicy: true,
530544
gates: true,
531545
queue: { select: { id: true, name: true } },
532546
},
@@ -543,6 +557,7 @@ export class DefaultQueueManager implements QueueManager {
543557
slug,
544558
ttl: row.ttl,
545559
triggerSource: row.triggerSource,
560+
executionPolicy: parseExecutionPolicy(row.executionPolicy),
546561
queueId: row.queue?.id ?? null,
547562
queueName: row.queue?.name ?? "",
548563
gates: parseTaskGates(row.gates),

‎apps/webapp/app/runEngine/services/triggerTask.server.ts‎

Lines changed: 48 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import {
66
import type { Tracer } from "@opentelemetry/api";
77
import { tryCatch } from "@trigger.dev/core/utils";
88
import {
9+
type RunExecutionPolicy,
910
type TriggerTaskRequestBody,
1011
formatDurationMilliseconds,
1112
RunAnnotations,
@@ -52,6 +53,7 @@ import {
5253
selfBackingWorkerGroups,
5354
} from "~/v3/workerRegions.server";
5455
import { globalFlagsRegistry } from "~/v3/globalFlagsRegistry.server";
56+
import { sandboxTasksEnabled } from "~/v3/sandboxTasksFlag.server";
5557
import {
5658
publishClaim as publishMollifierClaim,
5759
releaseClaim as releaseMollifierClaim,
@@ -450,11 +452,18 @@ export class RunEngineTriggerTaskService {
450452
const parkedOnExternalDeploymentId =
451453
externalDeploymentResolution?.outcome === "park" ? externalDeploymentId : undefined;
452454

453-
const { queueName, lockedQueueId, taskTtl, taskKind, gates, templateKey } =
454-
await this.queueConcern.resolveQueueProperties(
455-
triggerRequest,
456-
lockedToBackgroundWorker ?? undefined
457-
);
455+
const {
456+
queueName,
457+
lockedQueueId,
458+
taskTtl,
459+
taskKind,
460+
gates,
461+
templateKey,
462+
executionPolicy,
463+
} = await this.queueConcern.resolveQueueProperties(
464+
triggerRequest,
465+
lockedToBackgroundWorker ?? undefined
466+
);
458467

459468
// Resolve TTL with precedence: per-trigger > task-level > dev default
460469
let ttl: string | undefined;
@@ -545,10 +554,34 @@ export class RunEngineTriggerTaskService {
545554
orgFeatureFlags,
546555
flags: globalFlagsRegistry.current(),
547556
envType: environment.type,
548-
environmentCompat: environmentOverride.compat,
557+
// Sandboxes only run on microVMs, whatever the org's migration state.
558+
environmentCompat: executionPolicy ? "compute" : environmentOverride.compat,
549559
templateKey,
550560
});
551561

562+
if (executionPolicy && !sandboxTasksEnabled(orgFeatureFlags)) {
563+
throw new ServiceValidationError(
564+
`Task "${taskId}" is a sandbox, but sandbox tasks are not enabled for this organization.`
565+
);
566+
}
567+
568+
const onMicrovmGroup =
569+
baseWorkerQueue !== undefined &&
570+
workerGroups.find((group) => group.masterQueue === baseWorkerQueue)?.workloadType ===
571+
"MICROVM";
572+
if (
573+
executionPolicy &&
574+
environment.type !== "DEVELOPMENT" &&
575+
!migrated.compute &&
576+
!(onMicrovmGroup && templateKey)
577+
) {
578+
throw new ServiceValidationError(
579+
`Task "${taskId}" is a sandbox and needs microVM compute, which is not available ${
580+
templateKey ? "in this region" : "for this deployment (no compute template)"
581+
}.`
582+
);
583+
}
584+
552585
const triggerSource = options.triggerSource ?? "api";
553586
const triggerAction = options.triggerAction ?? "trigger";
554587
const parentAnnotations = RunAnnotations.safeParse(parentRun?.annotations).data;
@@ -561,6 +594,9 @@ export class RunEngineTriggerTaskService {
561594
externalDeploymentId,
562595
webhookDeliveryId: options.webhookDeliveryId,
563596
webhookEndpointId: options.webhookEndpointId,
597+
...(executionPolicy
598+
? { executionMode: "SANDBOX" as const, executionPolicy, sessionId: options.sessionId }
599+
: {}),
564600
};
565601

566602
const workerQueue =
@@ -570,9 +606,11 @@ export class RunEngineTriggerTaskService {
570606
region: migrated.region,
571607
envType: environment.type,
572608
orgFeatureFlags,
573-
environmentOverride,
574609
v2Enabled: env.TRIGGER_WORKER_QUEUE_V2_ENABLED === "1",
575610
splitEnabled: env.TRIGGER_WORKER_QUEUE_SCHEDULED_SPLIT_ENABLED === "1",
611+
environmentOverride: executionPolicy
612+
? { ...environmentOverride, compat: "compute" }
613+
: environmentOverride,
576614
workerGroups,
577615
rootTriggerSource: annotations.rootTriggerSource,
578616
templateFallback: migrated.templateFallback,
@@ -957,6 +995,9 @@ export class RunEngineTriggerTaskService {
957995
rootTriggerSource: string;
958996
rootScheduleId?: string | undefined;
959997
externalDeploymentId?: string | undefined;
998+
executionMode?: "SANDBOX";
999+
executionPolicy?: RunExecutionPolicy;
1000+
sessionId?: string;
9601001
};
9611002
parkedOnExternalDeploymentId?: string;
9621003
planType?: string;

0 commit comments

Comments
 (0)