mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-10-17 01:25:26 +02:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Every cloud-harness-managed stack gets one platform-owned "Paperclip Computer" sandbox environment, reconciled from `PAPERCLIP_MANAGED_CONFIG` on boot > - That reconciler deliberately refuses to overwrite a row it classifies as operator-modified, to protect a self-hosted operator's hand-edited environment (#10979) > - But for the cloud-harness-managed row specifically, no operator has any path to hand-edit it at all — so a hash mismatch there can only be drift between two platform-driven reconciliation passes, never a real customization > - Roughly 10 staging stacks got stuck on a broken sandbox image because of exactly this: a `sandbox_image` campaign correctly delivered a fixed snapshot, but the reconciler classified the row as operator-modified and silently skipped applying it > - This pull request adds an explicit `platformFullyManaged` flag so the cloud-harness caller can assert that guarantee and let its own drift self-heal, without weakening the protection for every other caller (self-hosted kubernetes-execution-mode, tests, admin routes) where an operator genuinely can edit the row > - The benefit is that a sandbox-image rollout can no longer get silently stuck fleet-wide, while self-hosted operator customization keeps exactly the protection #10979 built ## Linked Issues or Issue Description No public issue exists for this internal-instance-discovered bug; opening directly per CONTRIBUTING.md path B, following the bug report template fields. **What happened?** After a `sandbox_image` campaign delivered a fixed Daytona snapshot fleet-wide, ~10 of 79 active staging stacks kept booting agents against the old, broken snapshot. Their `PAPERCLIP_MANAGED_CONFIG` env var and the reconciler's own bookkeeping (`built_in_managed_resources`) both correctly showed the new snapshot — but `environments.config.snapshot`, the field the runtime actually reads to acquire a sandbox lease, was never updated on those rows. **Expected behavior** A `sandbox_image` campaign (or any `PAPERCLIP_MANAGED_CONFIG` delivery) to the cloud-harness-managed sandbox environment should always converge that row's `config` to the newly-desired value, since no operator can have a competing edit to protect. **Steps to reproduce** 1. Boot a cloud-harness-managed stack; let the reconciler create the managed sandbox row and record its stock hash in `built_in_managed_resources`. 2. Somehow cause the row's live content hash to no longer match the recorded binding hash without an operator ever touching it (in the field, this happened via drift between two platform-driven reconciliation passes carried out across a catalog-version bump — the exact trigger wasn't fully pinned down, but is irrelevant to the fix). 3. Deliver a new `PAPERCLIP_MANAGED_CONFIG` (e.g. via a `sandbox_image` campaign). 4. Observe `ensureManagedSandboxEnvironment` classify the row `operator_modified` and skip writing `config`, even though `updateAvailable: true` is reported and the binding itself already advanced to the new stock hash. **Paperclip version or commit** `master` as of this PR. **Deployment mode** Cloud-managed stacks with `enableManagedSandboxOnly` declared (any Paperclip Cloud–provisioned staging or production stack). Related PR for context (not a duplicate — this is additive to it, not a revert): #10979, which introduced the `operator_modified` classification this PR narrowly opts the cloud-harness path out of. ## What Changed - `server/src/services/environments.ts`: added `platformFullyManaged?: boolean` to `ManagedSandboxEnvironmentInput`. When set, a plain content-hash mismatch against a real prior binding (i.e. `operator_modified` that isn't an archive-reaffirmation) is reclassified as `stock_update_available` before the skip-vs-apply branch, so it flows through the normal update path instead of being frozen. - `server/src/services/managed-environments.ts`: pass `platformFullyManaged: true` from both `ensureManagedSandboxEnvironment` call sites — the main boot ensure and the provider-recovery reactivation path. These are the *only* two callers driven by `PAPERCLIP_MANAGED_CONFIG`; `ensureKubernetesEnvironment` (self-hosted `kubernetes-execution-mode` bootstrap) and every other caller are untouched and keep the original protective default. - `server/src/services/managed-environments.test.ts`: updated the two `toHaveBeenCalledWith` assertions that now include the flag. - `server/src/__tests__/environment-service.test.ts`: two new tests — one confirming the bypass applies drift under `platformFullyManaged`, one confirming archive-reaffirmation still wins even under the flag. Archive-reaffirmation is deliberately *not* bypassed even under `platformFullyManaged`: a `sandbox_image` update must never resurrect a row something else deliberately kept archived after Paperclip's own provider-unavailability archival. That's a distinct, still-real signal, orthogonal to config drift. ## Verification - `vitest run` on `managed-environments.test.ts` and `managed-resource-drift.test.ts`: 26/26 pass, including the two updated assertions. - `environment-service.test.ts` — the file both new tests live in, and the file holding the two pre-existing tests this change must not regress ("classifies operator drift, preserves the row, and exposes the pending stock update" and "preserves an existing unmanaged sandbox row holding the desired name") — requires a real embedded-Postgres instance (`describeEmbeddedPostgres`) not available in the sandbox this was developed in; `getEmbeddedPostgresTestSupport()` reports unsupported there, so the whole file is skipped locally. I traced the reconciliation logic by hand against all four relevant tests (the two new ones plus the two pre-existing ones) line by line to confirm the expected outcomes, but **CI running this suite for real is the actual gate here**, not this description — please don't merge on a green run of everything else alone if this suite doesn't show as executed. - `tsc --noEmit`: zero errors in any of the four touched files. The pre-existing ~229 errors elsewhere in `server` are unrelated missing-module issues from packages needing a build step first, confirmed unchanged by this diff. - Manually reproduced the underlying bug against real staging data (a `paperclip-cloud`-managed stack whose `environments` row was stuck exactly this way) before writing the fix, and confirmed via direct SQL inspection that the recorded `built_in_managed_resources` baseline already held the correct desired snapshot on every affected stack — i.e. the reconciler already *knew* the right answer, it was just refusing to apply it. That data point is what ruled out "the campaign didn't actually deliver the update" as the cause. ## Risks - Scope is intentionally narrow: only the two `PAPERCLIP_MANAGED_CONFIG`-driven call sites pass the new flag; every other caller of `ensureManagedSandboxEnvironment`/`ensureKubernetesEnvironment` is byte-for-byte unchanged. The two pre-existing regression tests that specifically cover self-hosted operator-edit protection don't pass this flag and are unmodified. - The main residual risk is the unresolved root cause of *why* the hash drifted in the first place (a race between two close-together reconciliation passes, or a catalog-version-dependent change to what gets hashed, most likely) — this PR makes that drift self-healing rather than fixing whatever produces it. If the drift is being caused by a genuine concurrency bug (rather than an expected, occasional side effect of a stock-field/catalog-version change), that bug still exists and could recur; it just no longer gets stuck when it does. - Low risk of behavior change for real self-hosted deployments: none of them can reach the new code path, since only the two now-flagged call sites exist inside `managed-environments.ts`, itself gated to `PAPERCLIP_MANAGED_CONFIG` (which self-hosted `kubernetes-execution-mode` explicitly refuses to run alongside — see the existing mutual-exclusivity check this PR does not touch). ## Model Used Claude Sonnet 5 (`claude-sonnet-5`), via Claude Code, with tool use (file edits, shell/git, `gh` CLI, direct Postgres inspection of live staging data via `psql`/`pg`, Railway SSH for on-host diagnosis). No extended-thinking mode. Standard Claude Code context window. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass — see Verification: the file holding the four load-bearing tests can't run in this sandbox (no embedded-Postgres support); traced by hand instead, CI is the real gate - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes — none applicable beyond the inline doc comments this PR adds - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green — pending CI run on this PR - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups — pending review - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
422 lines
19 KiB
TypeScript
422 lines
19 KiB
TypeScript
/**
|
|
* Managed-environment bootstrap (harness → app contract).
|
|
*
|
|
* Managed-cloud instances may declare sandbox environments in the
|
|
* `environments` section of `PAPERCLIP_MANAGED_CONFIG` (parsed fail-closed in
|
|
* `managed-config.ts`). On boot, each declared environment is idempotently
|
|
* ensured as the instance-level Paperclip-managed sandbox row via the
|
|
* provider-agnostic `ensureManagedSandboxEnvironment` — the control plane
|
|
* provisions, tenants use, for any bundled sandbox provider plugin.
|
|
*
|
|
* The failure posture mirrors bundled plugin provisioning
|
|
* (`bundled-plugins.ts`), deliberately split:
|
|
*
|
|
* 1. **Validation fails closed at parse time** (`managed-config.ts`): a
|
|
* malformed section refuses startup with a precise error.
|
|
* 2. **The DB ensure step is fail-safe per entry**: an ensure failure is
|
|
* logged and boot continues degraded (environment unavailable) rather
|
|
* than crash-looping a fleet.
|
|
*
|
|
* Ensuring is additionally synchronized with provider availability: the
|
|
* caller's `pluginsReady` promise (the bundled-plugin install/load pass) is
|
|
* awaited first, and an entry whose provider plugin is not installed, `ready`,
|
|
* AND running a live worker (`workerManager.isRunning`; a `ready` record whose
|
|
* activation failed has no worker and cannot serve leases) afterwards is
|
|
* skipped (counted failed) instead of being written as an active row —
|
|
* otherwise the heartbeat would resume queued runs against an environment
|
|
* whose lease acquisition cannot succeed yet. When such an entry was
|
|
* provisioned by an earlier boot, its still-active row is archived
|
|
* (`archiveManagedSandboxEnvironment`) for the same reason. Re-activation
|
|
* happens on the next healthy boot's ensure, or earlier: when the plugin
|
|
* record is `ready` and only the worker is down (a crash in restart-backoff),
|
|
* a one-shot `ready` listener on the worker handle re-runs the ensure as soon
|
|
* as the worker manager respawns the worker, so a transient crash does not
|
|
* leave the environment archived until someone restarts the server.
|
|
*
|
|
* Removing an entry from the document stops future refreshes but never
|
|
* deletes or archives the row — there is intentionally no unprovision path
|
|
* here, matching `plugins.autoInstall` semantics (leases may still reference
|
|
* the row; withdrawal is an explicit operator action). Archiving above is
|
|
* scoped to a declared-but-unavailable provider, not to document removal.
|
|
*
|
|
* Provider credentials are never part of the declared config: every bundled
|
|
* sandbox provider falls back to its documented process environment variable
|
|
* (e.g. `DAYTONA_API_KEY`) when `config` omits the key, so the deployment
|
|
* delivers secrets as env vars and the managed document stays secret-free.
|
|
*/
|
|
|
|
import type { Db } from "@paperclipai/db";
|
|
import { logger } from "../middleware/logger.js";
|
|
import { environmentService } from "./environments.js";
|
|
import type { ManagedSandboxEnvironmentReconcileAction } from "./environments.js";
|
|
import { instanceSettingsService } from "./instance-settings.js";
|
|
import type { ManagedInstanceConfig } from "./managed-config.js";
|
|
import type { ManagedResourceStockStatus } from "./managed-resource-drift.js";
|
|
import { parseExecutionPolicyBootstrapEnv } from "./execution-policy-bootstrap.js";
|
|
import { resolvePluginSandboxProviderDriverByKey } from "./plugin-environment-driver.js";
|
|
import type { PluginWorkerManager } from "./plugin-worker-manager.js";
|
|
|
|
export interface ApplyManagedEnvironmentsOptions {
|
|
env?: Record<string, string | undefined>;
|
|
/**
|
|
* Resolves when the bundled-plugin startup pass (install + load; the
|
|
* `ensureBundledPlugins` chain in `createApp`) has finished. Awaited before
|
|
* any environment is ensured so an active row never precedes its provider
|
|
* driver. The promise never rejects (the chain catches internally).
|
|
*/
|
|
pluginsReady?: Promise<unknown>;
|
|
/**
|
|
* The app's plugin worker manager, consulted per entry so an environment is
|
|
* only ensured while its provider plugin has a live worker (a `ready`
|
|
* registry record whose activation failed cannot serve leases). Fails
|
|
* closed: without a worker manager every entry is treated as unavailable.
|
|
*
|
|
* `getWorker` is `PluginWorkerManager.getWorker` narrowed to the `ready`
|
|
* subscription used for post-archive recovery: a worker in crash-restart
|
|
* backoff re-emits `ready` when the manager respawns it, and the listener
|
|
* re-ensures the archived environment (see `applyManagedEnvironments`).
|
|
*/
|
|
workerManager?: Pick<PluginWorkerManager, "isRunning"> & {
|
|
getWorker(pluginId: string):
|
|
| {
|
|
on(event: "ready", listener: (payload: { pluginId: string }) => void): void;
|
|
off(event: "ready", listener: (payload: { pluginId: string }) => void): void;
|
|
}
|
|
| undefined;
|
|
};
|
|
/** Test seam: overrides the environment service built from `db`. */
|
|
environments?: Pick<
|
|
ReturnType<typeof environmentService>,
|
|
| "ensureManagedSandboxEnvironment"
|
|
| "archiveManagedSandboxEnvironment"
|
|
| "getById"
|
|
| "update"
|
|
| "findManagedSandboxEnvironment"
|
|
>;
|
|
/** Test seam: overrides the instance-settings service built from `db`. */
|
|
instanceSettings?: Pick<ReturnType<typeof instanceSettingsService>, "get" | "update">;
|
|
/** Test seam: overrides the sandbox-provider plugin driver lookup. */
|
|
resolveSandboxProviderDriver?: (input: {
|
|
db: Db;
|
|
driverKey: string;
|
|
}) => Promise<{ plugin: { id: string; pluginKey: string; status: string } } | null>;
|
|
}
|
|
|
|
export interface ManagedEnvironmentReconciliationOutcome {
|
|
environmentId: string;
|
|
name: string;
|
|
provider: string;
|
|
action: ManagedSandboxEnvironmentReconcileAction;
|
|
stockStatus: ManagedResourceStockStatus;
|
|
updateAvailable: boolean;
|
|
}
|
|
|
|
export interface ApplyManagedEnvironmentsResult {
|
|
ensured: number;
|
|
failed: number;
|
|
added: number;
|
|
updated: number;
|
|
unchanged: number;
|
|
skipped: number;
|
|
/** Managed reconciliation never removes rows in preserve-only mode. */
|
|
removed: number;
|
|
/** Preserve-only reconciliation never creates replacement backups. */
|
|
backedUp: number;
|
|
outcomes: ManagedEnvironmentReconciliationOutcome[];
|
|
}
|
|
|
|
/**
|
|
* Ensure every environment declared in the managed-config document. Returns
|
|
* null when there is nothing to do (self-hosted, or no `environments`
|
|
* section); otherwise the ensured/failed counts. Idempotent; safe to call on
|
|
* every boot.
|
|
*/
|
|
export async function applyManagedEnvironments(
|
|
db: Db,
|
|
managedConfig: ManagedInstanceConfig | null,
|
|
opts: ApplyManagedEnvironmentsOptions = {},
|
|
): Promise<ApplyManagedEnvironmentsResult | null> {
|
|
if (!managedConfig) return null;
|
|
|
|
const settings = opts.instanceSettings ?? instanceSettingsService(db);
|
|
const environments = opts.environments ?? environmentService(db);
|
|
const managedSandboxOnlyDeclared = managedConfig.features.enableManagedSandboxOnly === true;
|
|
|
|
// Mode-off default cleanup runs BEFORE any ensure, and regardless of
|
|
// whether the document still declares environments or the provider is
|
|
// available: a reconciliation-stamped default must not outlive the mode
|
|
// through the paths that skip per-entry reconciliation entirely — the
|
|
// declaration was removed, the provider is down, or the row was
|
|
// archived. Only a default that points at the managed row AND carries
|
|
// the `managedDefaultStamped` marker reverts; tenant-chosen defaults
|
|
// (no marker) are untouched.
|
|
if (!managedSandboxOnlyDeclared) {
|
|
try {
|
|
const managedRow = await environments.findManagedSandboxEnvironment(undefined, {
|
|
includeArchived: true,
|
|
});
|
|
if (
|
|
managedRow &&
|
|
managedRow.metadata?.managedDefaultStamped === true &&
|
|
((await settings.get()).defaultEnvironmentId ?? null) === managedRow.id
|
|
) {
|
|
await settings.update({ defaultEnvironmentId: null });
|
|
const { managedDefaultStamped: _cleared, ...remainingMetadata } = managedRow.metadata ?? {};
|
|
await environments.update(managedRow.id, { metadata: remainingMetadata });
|
|
logger.info(
|
|
{ environmentId: managedRow.id },
|
|
"instance default environment reverted from the managed sandbox environment (managed-sandbox-only is not declared)",
|
|
);
|
|
}
|
|
} catch (err) {
|
|
logger.error(
|
|
{ err },
|
|
"failed to revert the stamped managed sandbox instance default (degraded: stale default until the next boot)",
|
|
);
|
|
}
|
|
}
|
|
|
|
if (managedConfig.environments.length === 0) return null;
|
|
|
|
// The forced-execution-mode bootstrap (`PAPERCLIP_EXECUTION_MODE=kubernetes`)
|
|
// and this one both own the single Paperclip-managed sandbox row
|
|
// (`environments_managed_sandbox_idx`). Configuring both is contradictory;
|
|
// refuse startup rather than let bootstrap ordering pick a winner.
|
|
const env = opts.env ?? process.env;
|
|
if (parseExecutionPolicyBootstrapEnv(env)) {
|
|
throw new Error(
|
|
`PAPERCLIP_EXECUTION_MODE and the PAPERCLIP_MANAGED_CONFIG "environments" section are mutually exclusive: both manage the single instance sandbox environment`,
|
|
);
|
|
}
|
|
|
|
// The heartbeat resumes queued runs right after this bootstrap step, and
|
|
// lease acquisition fails hard on a provider whose plugin is missing or not
|
|
// ready. Wait for the bundled-plugin startup pass to finish, then refuse to
|
|
// ensure (and in particular to re-activate) a row whose provider driver did
|
|
// not come up — a degraded boot without the row beats an active environment
|
|
// that fails every lease until the plugin recovers.
|
|
await opts.pluginsReady;
|
|
|
|
const resolveDriver = opts.resolveSandboxProviderDriver ?? resolvePluginSandboxProviderDriverByKey;
|
|
|
|
/**
|
|
* Point the instance default at the managed sandbox row when no
|
|
* deliberate choice stands in the way: an unset default, a default on
|
|
* the (hidden-under-this-mode) local row, or a dangling reference all
|
|
* move to the managed environment, so pickers and run selection agree
|
|
* that "the default" is the platform sandbox. A tenant-chosen custom
|
|
* environment (ssh, their own sandbox) is never overridden.
|
|
*
|
|
* Gated symmetrically on the document declaring
|
|
* `enableManagedSandboxOnly`:
|
|
*
|
|
* - Declared: stamp the managed row as the default, so pickers and run
|
|
* selection agree the platform sandbox is "the default". The stamp is
|
|
* recorded as `managedDefaultStamped` in the row's platform-owned
|
|
* metadata (which boot reconciliation preserves and the client write
|
|
* floor protects), so a stamped default is distinguishable from one
|
|
* the tenant chose deliberately.
|
|
* - Not declared: local execution is a legitimate default again, so a
|
|
* default THIS reconciliation stamped earlier (points at the managed
|
|
* row AND carries the stamp marker) reverts to unset — otherwise
|
|
* turning the mode off would keep routing default-following runs
|
|
* into the sandbox off a stale stamp. A default the tenant selected
|
|
* themselves — the managed row without the marker, or any custom
|
|
* environment — is untouched in both directions.
|
|
*
|
|
* Idempotent and best-effort — a failure degrades to the run-time
|
|
* policy, which refuses local under managed-sandbox-only regardless.
|
|
*/
|
|
const ensureManagedInstanceDefault = async (managedEnvironment: {
|
|
id: string;
|
|
metadata: Record<string, unknown> | null;
|
|
}): Promise<void> => {
|
|
if (!managedSandboxOnlyDeclared) return;
|
|
try {
|
|
const current = (await settings.get()).defaultEnvironmentId ?? null;
|
|
if (current === managedEnvironment.id) return;
|
|
if (current !== null) {
|
|
const currentEnvironment = await environments.getById(current);
|
|
if (currentEnvironment && currentEnvironment.driver !== "local") return;
|
|
}
|
|
// Marker first: a crash between the two writes must never leave a
|
|
// stamped default that the revert path cannot attribute.
|
|
await environments.update(managedEnvironment.id, {
|
|
metadata: { ...(managedEnvironment.metadata ?? {}), managedDefaultStamped: true },
|
|
});
|
|
await settings.update({ defaultEnvironmentId: managedEnvironment.id });
|
|
logger.info(
|
|
{ environmentId: managedEnvironment.id, previousDefaultEnvironmentId: current },
|
|
"instance default environment set to the managed sandbox environment",
|
|
);
|
|
} catch (err) {
|
|
logger.error(
|
|
{ err, environmentId: managedEnvironment.id },
|
|
"failed to reconcile the instance default environment with the managed sandbox environment",
|
|
);
|
|
}
|
|
};
|
|
|
|
// Recovery path for a `ready` plugin whose worker was down at check time:
|
|
// that shape is usually a crash in restart-backoff, and the manager's
|
|
// respawn re-emits `ready` on the same handle. A one-shot listener re-runs
|
|
// the idempotent ensure so the recovered provider becomes selectable again
|
|
// without waiting for the next boot (this pass has already archived the
|
|
// row). The post-subscribe `isRunning` re-check closes the race where the
|
|
// worker recovered between the gate check and the subscription. No handle
|
|
// means no respawn is coming (activation never started a worker), so the
|
|
// degraded-until-next-boot posture stands.
|
|
const scheduleRecoveryReactivation = (
|
|
spec: ManagedInstanceConfig["environments"][number],
|
|
pluginId: string,
|
|
): void => {
|
|
const manager = opts.workerManager;
|
|
const handle = manager?.getWorker(pluginId);
|
|
if (!handle) return;
|
|
let reactivated = false;
|
|
const reactivate = (): void => {
|
|
if (reactivated) return;
|
|
reactivated = true;
|
|
handle.off("ready", reactivate);
|
|
void environments
|
|
.ensureManagedSandboxEnvironment({
|
|
name: spec.name,
|
|
description: spec.description,
|
|
provider: spec.provider,
|
|
config: { ...spec.config },
|
|
stockVersion: managedConfig.catalogVersion,
|
|
platformFullyManaged: true,
|
|
})
|
|
.then((result) => {
|
|
logger.info(
|
|
{
|
|
environmentId: result.environment.id,
|
|
name: spec.name,
|
|
provider: spec.provider,
|
|
action: result.action,
|
|
stockStatus: result.stockStatus,
|
|
updateAvailable: result.updateAvailable,
|
|
},
|
|
"managed sandbox environment reactivated after provider worker recovery",
|
|
);
|
|
})
|
|
.catch((err: unknown) => {
|
|
logger.error(
|
|
{ err, name: spec.name, provider: spec.provider },
|
|
"failed to reactivate managed sandbox environment after provider worker recovery (degraded: environment unavailable until next boot)",
|
|
);
|
|
});
|
|
};
|
|
handle.on("ready", reactivate);
|
|
if (manager?.isRunning(pluginId)) reactivate();
|
|
};
|
|
|
|
let ensured = 0;
|
|
let failed = 0;
|
|
let added = 0;
|
|
let updated = 0;
|
|
let unchanged = 0;
|
|
let skipped = 0;
|
|
const outcomes: ManagedEnvironmentReconciliationOutcome[] = [];
|
|
for (const spec of managedConfig.environments) {
|
|
try {
|
|
const resolved = await resolveDriver({ db, driverKey: spec.provider });
|
|
// `ready` in the registry is necessary but not sufficient: activation
|
|
// can fail after install leaves the record `ready`, in which case no
|
|
// worker is running and the driver cannot serve leases.
|
|
const workerRunning =
|
|
resolved != null && (opts.workerManager?.isRunning(resolved.plugin.id) ?? false);
|
|
if (!resolved || resolved.plugin.status !== "ready" || !workerRunning) {
|
|
failed += 1;
|
|
// A row provisioned by an earlier boot must not stay active either —
|
|
// archive it so run scheduling stops selecting it. Best-effort: an
|
|
// archive failure is logged, and the entry is already counted failed.
|
|
const archived = await environments
|
|
.archiveManagedSandboxEnvironment({ provider: spec.provider })
|
|
.catch((archiveErr: unknown) => {
|
|
logger.error(
|
|
{ err: archiveErr, name: spec.name, provider: spec.provider },
|
|
"failed to archive the managed sandbox environment of an unavailable provider",
|
|
);
|
|
return null;
|
|
});
|
|
logger.error(
|
|
{
|
|
name: spec.name,
|
|
provider: spec.provider,
|
|
pluginKey: resolved?.plugin.pluginKey ?? null,
|
|
pluginStatus: resolved?.plugin.status ?? null,
|
|
workerRunning,
|
|
archivedEnvironmentId: archived?.id ?? null,
|
|
},
|
|
"managed sandbox environment provider plugin is not installed, ready, and running; skipping ensure and archiving any previously provisioned row (degraded: environment unavailable)",
|
|
);
|
|
// Only a `ready` record can recover without another boot: the worker
|
|
// manager restarts crashed workers, but nothing (re)installs a missing
|
|
// or non-ready plugin at runtime.
|
|
if (resolved && resolved.plugin.status === "ready") {
|
|
scheduleRecoveryReactivation(spec, resolved.plugin.id);
|
|
}
|
|
continue;
|
|
}
|
|
const reconciliation = await environments.ensureManagedSandboxEnvironment({
|
|
name: spec.name,
|
|
description: spec.description,
|
|
provider: spec.provider,
|
|
config: { ...spec.config },
|
|
stockVersion: managedConfig.catalogVersion,
|
|
platformFullyManaged: true,
|
|
});
|
|
if (reconciliation.action === "skipped") skipped += 1;
|
|
else {
|
|
ensured += 1;
|
|
if (reconciliation.action === "added") added += 1;
|
|
else if (reconciliation.action === "updated") updated += 1;
|
|
else unchanged += 1;
|
|
}
|
|
outcomes.push({
|
|
environmentId: reconciliation.environment.id,
|
|
name: reconciliation.environment.name,
|
|
provider: spec.provider,
|
|
action: reconciliation.action,
|
|
stockStatus: reconciliation.stockStatus,
|
|
updateAvailable: reconciliation.updateAvailable,
|
|
});
|
|
await ensureManagedInstanceDefault(reconciliation.environment);
|
|
const logContext = {
|
|
environmentId: reconciliation.environment.id,
|
|
name: reconciliation.environment.name,
|
|
provider: spec.provider,
|
|
action: reconciliation.action,
|
|
stockStatus: reconciliation.stockStatus,
|
|
updateAvailable: reconciliation.updateAvailable,
|
|
};
|
|
if (reconciliation.action === "skipped") {
|
|
logger.warn(
|
|
logContext,
|
|
"managed sandbox environment has operator modifications; preserving row and skipping stock update",
|
|
);
|
|
} else {
|
|
logger.info(logContext, "managed sandbox environment reconciled");
|
|
}
|
|
} catch (err) {
|
|
failed += 1;
|
|
logger.error(
|
|
{ err, name: spec.name, provider: spec.provider },
|
|
"failed to ensure managed sandbox environment; continuing boot (degraded: environment unavailable)",
|
|
);
|
|
}
|
|
}
|
|
return {
|
|
ensured,
|
|
failed,
|
|
added,
|
|
updated,
|
|
unchanged,
|
|
skipped,
|
|
removed: 0,
|
|
backedUp: 0,
|
|
outcomes,
|
|
};
|
|
}
|