@north-light/cli 0.3.602 → 0.3.604
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/core/canvas/schema-pg/005-fleet-blobs.sql +1 -1
- package/dist/core/storage/attachments.d.ts +1 -1
- package/dist/daemon/due.js +4 -4
- package/dist/daemon/reconcilers/grant-effects.d.ts +5 -2
- package/dist/daemon/reconcilers/grant-effects.js +1 -1
- package/dist/daemon/reconcilers/recipe-image.d.ts +15 -1
- package/dist/daemon/reconcilers/recipe-image.js +5 -6
- package/dist/daemon/reconcilers/storage-due-work.d.ts +3 -4
- package/dist/daemon/reconcilers/storage-due-work.js +3 -2
- package/package.json +2 -2
- package/packages/crouter-identity/package.json +1 -1
- package/runtime.lock.json +13 -13
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
-- Null for a use recorded before this release, and for any use whose bytes the storage service still holds.
|
|
8
8
|
ALTER TABLE upload_uses ADD COLUMN IF NOT EXISTS blob_key text;
|
|
9
9
|
|
|
10
|
-
-- D100: the node blob-deletion pass in `storage-due-work` claims node rows
|
|
10
|
+
-- D100: the node blob-deletion pass in `storage-due-work` claims deleted node rows. Partial, so it
|
|
11
11
|
-- holds only the soft-deleted node rows, not every object. A plain CREATE INDEX (the chain runs each step in a transaction, so not
|
|
12
12
|
-- CONCURRENTLY): it blocks writes to `objects` for the time it takes to scan the table.
|
|
13
13
|
CREATE INDEX IF NOT EXISTS objects_node_deleted ON objects(deleted_at) WHERE type = 'node';
|
|
@@ -32,5 +32,5 @@ export declare function assertUploadsUsable(grantee: string, uses: readonly Atta
|
|
|
32
32
|
/** Fetch every upload a storage URL in `text` names into the blob store at `attachments/<rootId>/<sha256>` and replace
|
|
33
33
|
* exactly each URL's span with the path the node's broker downloads that file to (`<app space>/nodes/<rootId>/attachments/<name>`).
|
|
34
34
|
* The control plane writes no file there. Without configured storage the text passes through unchanged. A failure leaves
|
|
35
|
-
* at most content-keyed blobs, which are harmless and are deleted with the node
|
|
35
|
+
* at most content-keyed blobs, which are harmless and are deleted with the node. */
|
|
36
36
|
export declare function resolveStorageUrls(grantee: string, rootId: string, text: string, options?: ResolveOptions): Promise<ResolvedAttachments>;
|
package/dist/daemon/due.js
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
var D=Object.defineProperty;var a=(n,e)=>D(n,"name",{value:e,configurable:!0});import{openDb as E}from"../core/canvas/db.js";import{isPidPresent as R}from"../core/canvas/pid.js";import{isProfilePaused as p}from"../core/profiles/manifest.js";import{hasUnseenWakeMail as f}from"../core/canvas/deliveries.js";import{listPendingProviderRetries as g}from"../core/canvas/recovery.js";import{listSubmitRequestedRequests as x}from"../core/human/requests.js";import{storageConfig as I}from"../core/storage/client.js";import{emitEvent as O}from"../core/events/emit.js";import{wantsExecution as m}from"./reconcilers/node-lifecycle/wants-execution.js";import{dueAtMs as y}from"./reconcilers/fault-retry-backstop.js";import{UNUSED_UPLOAD_TTL_MS as T}from"./reconcilers/storage-due-work.js";import{
|
|
1
|
+
var D=Object.defineProperty;var a=(n,e)=>D(n,"name",{value:e,configurable:!0});import{openDb as E}from"../core/canvas/db.js";import{isPidPresent as R}from"../core/canvas/pid.js";import{isProfilePaused as p}from"../core/profiles/manifest.js";import{hasUnseenWakeMail as f}from"../core/canvas/deliveries.js";import{listPendingProviderRetries as g}from"../core/canvas/recovery.js";import{listSubmitRequestedRequests as x}from"../core/human/requests.js";import{storageConfig as I}from"../core/storage/client.js";import{emitEvent as O}from"../core/events/emit.js";import{wantsExecution as m}from"./reconcilers/node-lifecycle/wants-execution.js";import{dueAtMs as y}from"./reconcilers/fault-retry-backstop.js";import{UNUSED_UPLOAD_TTL_MS as T}from"./reconcilers/storage-due-work.js";import{IMAGE_BUILD_OWED_SQL as A,IMAGE_DELETE_OWED_SQL as M}from"./reconcilers/recipe-image.js";import{busyOnlyLanes as b,collectDue as h,declareBusyOnly as o,dueSourceLanes as v,registerDueSource as i}from"./due-sources.js";import{filterAsync as W}from"../core/async-array.js";const _=a(async(n,...e)=>await(await E()).prepare(n).all(...e),"rows"),r=a(async n=>await(await E()).prepare(n).get(),"first"),u=a(n=>{if(n==null)return null;const e=Date.parse(n);return Number.isFinite(e)?e:null},"iso"),c=a(n=>{let e=null;for(const t of n)t!==null&&(e===null||t<e)&&(e=t);return e},"earliest"),L="node_id NOT IN (SELECT node_id FROM warm_pool)";let N=!1;async function S(){if(N)return;N=!0,o("brokerSupervision","acts only on live broker processes, which already make busy true"),o("controllerDeath","acts only on live controller processes"),o("pollRunObservers","follows live pids only"),o("bashDeadline","acts only on running bash jobs, which already make busy true"),o("storageMaintenance","retention and placement housekeeping: never time-critical, and it must not wake or hold a sleeping runtime"),o("purgeDueWork","physical purge of objects soft-deleted over 30 days ago: housekeeping, and a tombstone a live object references stays due forever, so it must not wake or hold a sleeping runtime"),o("ledgerSandbox","bills awake time of executions that are busy or just exited; a sleeping runtime owes nothing until it wakes, and the lane must not wake it"),o("ledgerStorage","monthly storage billing: never time-critical, and it must not wake or hold a sleeping runtime"),o("ledgerR2","moves closed months to R2: housekeeping that must not wake or hold a sleeping runtime"),i("nodeLifecycle",{nextDue:a(async()=>c((await W(await _(`SELECT node_id, status, intent, profile_id, respawn_not_before FROM node_rows
|
|
2
2
|
WHERE status IN ('active', 'idle') AND kind != 'human' AND ${L}
|
|
3
3
|
AND pi_pid IS NULL AND respawn_not_before IS NOT NULL`),async e=>!p(e.profile_id)&&await m({node_id:e.node_id,status:e.status,intent:e.intent}))).map(e=>u(e.respawn_not_before))),"nextDue")}),i("nodeDeadline",{nextDue:a(async()=>c((await _(`SELECT deadline_at, profile_id FROM node_rows
|
|
4
4
|
WHERE deadline_at IS NOT NULL AND outcome_at IS NULL AND status IN ('active', 'idle') AND kind != 'human'`)).filter(e=>!p(e.profile_id)).map(e=>u(e.deadline_at))),"nextDue")}),i("structuredRequests",{nextDue:a(async e=>await r("SELECT 1 FROM structured_requests WHERE state != 'pending' AND effects_done_at IS NULL LIMIT 1")!==void 0?e:(await r("SELECT MIN(deadline_at) AS at FROM structured_requests WHERE state = 'pending' AND deadline_at IS NOT NULL"))?.at??null,"nextDue")}),i("recipeImage",{nextDue:a(async e=>c((await _(`SELECT image_building_at FROM environments
|
|
5
|
-
WHERE
|
|
5
|
+
WHERE ${A} OR ${M}`)).map(t=>t.image_building_at===null?e:Math.max(e,u(t.image_building_at)??e))),"nextDue")}),i("cronLane",{nextDue:a(async()=>{const e=(await _(`SELECT fire_at, profile FROM crons
|
|
6
6
|
WHERE state = 'active' AND run_state = 'idle'
|
|
7
7
|
AND NOT (held = 1 AND recur IS NULL AND expires_at IS NULL)`)).filter(s=>!p(s.profile)).map(s=>u(s.fire_at)),t=(await _("SELECT expires_at FROM crons WHERE expires_at IS NOT NULL AND run_state = 'idle'")).map(s=>u(s.expires_at));return c([...e,...t])},"nextDue")});const n=a(async e=>async()=>(await r(`SELECT MIN(next_attempt_at) AS at FROM ${e} WHERE state = 'pending' AND canceled_at IS NULL AND next_attempt_at IS NOT NULL`))?.at??null,"attempts");i("deliveryLane",{nextDue:await n("deliveries")}),i("actionLane",{nextDue:await n("daemon_actions")}),i("pendingReviewSubmit",{nextDue:a(async e=>(await x()).length>0?e:null,"nextDue")}),i("storageDueWork",{nextDue:a(async e=>{if(I()===null)return null;if(await r("SELECT 1 FROM uploads WHERE delete_pending_since IS NOT NULL LIMIT 1")!==void 0||await r("SELECT 1 FROM shares WHERE status = 'off' AND object_deleted_at IS NULL LIMIT 1")!==void 0)return e;const t=(await r("SELECT MIN(expires_at) AS at FROM shares WHERE status = 'on' AND expires_at IS NOT NULL"))?.at,s=(await r(`SELECT MIN(created_at) AS at FROM uploads u WHERE delete_pending_since IS NULL
|
|
8
|
-
AND NOT EXISTS (SELECT 1 FROM upload_uses x WHERE x.upload_id = u.upload_id)`))?.at,l=u(s);return c([u(t),l===null?null:l+T])},"nextDue")}),i("importLane",{nextDue:a(async e=>await r(`SELECT 1 FROM import_runs WHERE state IN ('loading', 'committed') AND (claimed_by IS NULL OR lease_expires_at IS NULL OR lease_expires_at <= '${new Date(e).toISOString()}')`)!==void 0?e:null,"nextDue")}),i("faultRetryBackstop",{nextDue:a(async()=>c((await g()).map(e=>y(e))),"nextDue")})}a(S,"installDueSources");const w=12e4;async function
|
|
8
|
+
AND NOT EXISTS (SELECT 1 FROM upload_uses x WHERE x.upload_id = u.upload_id)`))?.at,l=u(s);return c([u(t),l===null?null:l+T])},"nextDue")}),i("importLane",{nextDue:a(async e=>await r(`SELECT 1 FROM import_runs WHERE state IN ('loading', 'committed') AND (claimed_by IS NULL OR lease_expires_at IS NULL OR lease_expires_at <= '${new Date(e).toISOString()}')`)!==void 0?e:null,"nextDue")}),i("faultRetryBackstop",{nextDue:a(async()=>c((await g()).map(e=>y(e))),"nextDue")})}a(S,"installDueSources");const w=12e4;async function U(n){const e=await _(`SELECT n.node_id, n.status, n.intent, n.profile_id, n.pi_pid, n.frozen_at, n.respawn_not_before, n.created, n.launched_at,
|
|
9
9
|
n.turn_open_at, n.turn_closed_at,
|
|
10
10
|
(SELECT x.started_at FROM executions x WHERE x.node_id = n.node_id AND x.state != 'exited') AS exec_started_at
|
|
11
11
|
FROM node_rows n
|
|
12
|
-
WHERE n.status IN ('active', 'idle') AND n.kind != 'human' AND n.${L}`);for(const t of e){if(p(t.profile_id)||!await m({node_id:t.node_id,status:t.status,intent:t.intent}))continue;if(t.pi_pid!==null&&R(t.pi_pid)){if(t.turn_open_at!==null&&t.turn_closed_at===null)return!0;const d=u(t.exec_started_at);if(t.turn_open_at===null&&d!==null&&n-d<w||await f(t.node_id))return!0;continue}if(t.respawn_not_before!==null)continue;if(t.pi_pid!==null||t.frozen_at!==null||t.status==="active")return!0;const l=Math.max(...[t.created,t.launched_at,t.exec_started_at].map(d=>u(d)??0));if(l>0&&n-l<w||t.status==="idle"&&await f(t.node_id))return!0}return!1}a(
|
|
12
|
+
WHERE n.status IN ('active', 'idle') AND n.kind != 'human' AND n.${L}`);for(const t of e){if(p(t.profile_id)||!await m({node_id:t.node_id,status:t.status,intent:t.intent}))continue;if(t.pi_pid!==null&&R(t.pi_pid)){if(t.turn_open_at!==null&&t.turn_closed_at===null)return!0;const d=u(t.exec_started_at);if(t.turn_open_at===null&&d!==null&&n-d<w||await f(t.node_id))return!0;continue}if(t.respawn_not_before!==null)continue;if(t.pi_pid!==null||t.frozen_at!==null||t.status==="active")return!0;const l=Math.max(...[t.created,t.launched_at,t.exec_started_at].map(d=>u(d)??0));if(l>0&&n-l<w||t.status==="idle"&&await f(t.node_id))return!0}return!1}a(U,"nodesOweWork");async function V(n=Date.now()){await S();const{dueNow:e,nextDueMs:t}=await h(n,(l,d)=>{O({level:"warn",event:"daemon.due.source_failed",error:d,fields:{lane:l}})});return{busy:e||await U(n)||await r("SELECT 1 FROM crons WHERE run_state = 'running' LIMIT 1")!==void 0||await r("SELECT 1 FROM jobs j JOIN objects o ON o.id = j.object WHERE j.status = 'running' AND o.deleted_at IS NULL LIMIT 1")!==void 0,next_due_at:t===null?null:new Date(t).toISOString()}}a(V,"dueReport");async function Y(){return await S(),[...v(),...b()]}a(Y,"coveredLanes");export{w as START_GRACE_MS,Y as coveredLanes,V as dueReport,S as installDueSources};
|
|
@@ -4,5 +4,8 @@ export interface GrantEffectsRoles {
|
|
|
4
4
|
}
|
|
5
5
|
/** Do this process's part of whatever changed grant `grantId`, from its row as it reads now. Idempotent. */
|
|
6
6
|
export declare function applyGrantEffects(roles: GrantEffectsRoles, grantId: string): Promise<void>;
|
|
7
|
-
/** Subscribe this process to `grant:<id>` signals. Returns the unsubscribe.
|
|
8
|
-
|
|
7
|
+
/** Subscribe this process to `grant:<id>` signals. Returns the unsubscribe. A process that runs lanes also looks every `sweepMs` for a
|
|
8
|
+
* removal that is still owed (a cascade that failed, or one no signal or catch-up reached) and runs it again. */
|
|
9
|
+
export declare function startGrantEffects(roles: GrantEffectsRoles, tuning?: {
|
|
10
|
+
sweepMs?: number;
|
|
11
|
+
}): Promise<() => void>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var k=Object.defineProperty;var a=(t,e)=>k(t,"name",{value:e,configurable:!0});import{canvasPoolSize as x,openDb as p}from"../../core/canvas/db.js";import{isCloudRole as L}from"../../core/canvas/person.js";import{endLiveExecution as O,liveExecutionForNode as D}from"../../core/canvas/executions.js";import{emitEvent as u}from"../../core/events/emit.js";import{afterRevocationStop as M}from"../../core/grants/on-sync.js";import{allGrants as h,grantIdsWhere as y,grantStanding as E,mirrorOnly as R}from"../../core/grants/mirror.js";import{removeApp as A,removePersonData as P}from"../../core/grants/remove.js";import{wakeAllGrantWaiters as G,wakeGrantWaiters as C}from"../../core/grants/watch.js";import{discardOrphanedTokens as g,discardTokensForGrant as W}from"../../core/providers/token-cache.js";import{isUnsandboxedMachine as F}from"../../core/runtime/unsandboxed.js";import{runnerForExecution as U}from"../../core/runtime/runner/index.js";import{closeGrantStreams as B,heldGrantIds as $}from"../../core/runs/events.js";import{stopNodeSandboxes as H}from"../../core/spaces/stop.js";import{brokerSignalBus as J}from"../broker-signals/bus.js";import{withRowClaim as z}from"./row-claim.js";const K=6e4,V=a(()=>Math.max(1,Math.floor(x()/3)),"grantSlotLimit");let v=0;const b=[];async function X(t){for(;v>=V();)await new Promise(e=>{b.push(e)});v+=1;try{return await t()}finally{v-=1,b.shift()?.()}}a(X,"withGrantSlot");const Y=3e4,j=5;function d(t,e,n){u({level:"error",event:`daemon.grants.${t}`,error:e,fields:n})}a(d,"failed");function q(t,e,n){try{const r=e.sub===null||e.grantee===null?g(n):W({sub:e.sub,grantee:e.grantee,active:e.standing==="active"},n);r.tokens>0&&u({level:"info",event:"daemon.grants.outbound_tokens_discarded",fields:{grant:t,tokens:r.tokens}})}catch(r){d("outbound_tokens_discard_failed",r,{grant:t})}}a(q,"discardTokens");async function N(){try{await(await import("../../core/providers/bundles.js")).syncProviderBundles()}catch(t){u({level:"error",event:"daemon.providers.bundle_sync_failed",error:t})}}a(N,"reconcileProviderBundles");async function Q(t,e){if(C(t),e.standing==="inactive"){const n=B(t);n>0&&u({level:"info",event:"daemon.grants.streams_closed",fields:{grant:t,grantee:e.grantee,streams:n}})}await N()}a(Q,"serveEffects");async function Z(t,e){const n=await z("nodes",t,K,async r=>{const i=await D(t);if(i===null)return;await r.assertOwned(),u({level:"info",event:"daemon.grants.node_stop",node_id:t,fields:{grant:e,execution_id:i.executionId}});const l=a(async()=>{await r.assertOwned(),await O(t,{reason:"permission_revoked"}),await M(t)},"finish");if(i.runner==="process"){const m=await H(t,"permission_revoked",{holdRecovery:!0,after:l});if(!m.confirmed)throw m.error??new Error(`stop of ${t} was not confirmed`);return}const f=await U(i.runner).stop(i,{reason:"permission_revoked"});if(!f.confirmed)throw f.error??new Error(`stop of ${t} was not confirmed`);await l()})}a(Z,"stopRevokedNode");async function I(t,e){if(!(e.grantee!==null&&R({grantee:e.grantee}))){if(e.standing==="inactive"){const n=await(await p()).prepare("SELECT DISTINCT n.node_id FROM nodes n JOIN executions e ON e.node_id = n.node_id AND e.state != 'exited' WHERE n.grant_id = ?").all(t);for(const{node_id:r}of n)try{await Z(r,t)}catch(i){d("node_stop_failed",i,{grant:t,node_id:r})}}if(e.status==="removed"&&e.removal_done_at===null&&e.grantee!==null&&e.sub!==null)try{e.grantee!=="app:terminal"?await A(e.grantee,e.sub):L()?await P(e.grantee,e.sub):u({level:"info",event:"daemon.grants.removal_settled_without_cleanup",fields:{grant:t,grantee:e.grantee,sub:e.sub}}),await(await p()).prepare("UPDATE grants SET removal_done_at = ? WHERE id = ? AND rev = ? AND removal_done_at IS NULL").run(new Date().toISOString(),t,e.rev)}catch(n){d("removal_failed",n,{grant:t,grantee:e.grantee})}}}a(I,"laneEffects");async function ee(t,e){let n;await X(async()=>{const r=await E(e);q(e,r,await h()),t.serves&&(n=Q(e,r)),t.runsLanes&&r.standing!=="lagging"&&await I(e,r)}),await n}a(ee,"applyGrantEffects");async function te(t){const e=new Set;if(t.serves)for(const r of $())e.add(r);if(t.runsLanes){const r=await(await p()).prepare("SELECT DISTINCT n.grant_id FROM nodes n JOIN executions e ON e.node_id = n.node_id AND e.state != 'exited' WHERE n.grant_id IS NOT NULL").all();for(const{grant_id:i}of r)e.add(i)}const n=[];for(const r of e)(await E(r)).status===null&&n.push(r);return n}a(te,"goneGrantIds");async function Se(t,e={}){const n=new Map,r=a(o=>{const c=(n.get(o)??Promise.resolve()).then(()=>ee(t,o)).catch(s=>d("effects_failed",s,{grant:o})).finally(()=>{n.get(o)===c&&n.delete(o)});return n.set(o,c),c},"run"),i=a(async()=>{const o=t.serves?N():void 0;try{t.serves&&G(),g(await h());const c=new Set(await y(`status <> 'active' OR expires_at <= '${new Date().toISOString()}'`));for(const s of await te(t))c.add(s);await Promise.all([...c].map(r))}catch(c){d("catch_up_failed",c,{})}await o},"catchUp"),l=new Map;let f=!1;const m=a(async()=>{if(!f){f=!0;try{const o=new Set(await y(`status = 'removed' AND removal_done_at IS NULL${F()?" AND grantee = 'app:terminal'":""}`));for(const s of l.keys())o.has(s)||l.delete(s);const c=[...o].filter(s=>!n.has(s)&&(l.get(s)?.notBefore??0)<=Date.now());await Promise.all(c.map(async s=>{await r(s);const S=(l.get(s)?.failures??0)+1;l.set(s,{failures:S,notBefore:Date.now()+_*2**Math.min(S,j)})}))}catch(o){d("removal_sweep_failed",o,{})}finally{f=!1}}},"sweepRemovals"),_=e.sweepMs??Y,w=t.runsLanes?setInterval(()=>{m()},_):void 0;w?.unref();const T=await J.subscribe(o=>{r(o)},{kinds:["grant"],onListenStart:a(()=>{i()},"onListenStart")});return()=>{w!==void 0&&clearInterval(w),T()}}a(Se,"startGrantEffects");export{ee as applyGrantEffects,Se as startGrantEffects};
|
|
@@ -4,6 +4,13 @@ import type { DetachedWorkLifecycle } from './broker-supervision.js';
|
|
|
4
4
|
export declare const LEASE_MS: number;
|
|
5
5
|
/** After a failed build the same revision is not tried again for this long. */
|
|
6
6
|
export declare const RETRY_AFTER_FAILURE_MS: number;
|
|
7
|
+
/** SQL predicates over `environments`: its object is soft-deleted / is not. */
|
|
8
|
+
export declare const ENVIRONMENT_DELETED_SQL = "EXISTS (SELECT 1 FROM objects o WHERE o.id = environments.object AND o.deleted_at IS NOT NULL)";
|
|
9
|
+
export declare const ENVIRONMENT_LIVE_SQL = "NOT EXISTS (SELECT 1 FROM objects o WHERE o.id = environments.object AND o.deleted_at IS NOT NULL)";
|
|
10
|
+
/** A live environment with a recipe revision no image has been built for. */
|
|
11
|
+
export declare const IMAGE_BUILD_OWED_SQL = "(kind = 'blaxel' AND NOT EXISTS (SELECT 1 FROM objects o WHERE o.id = environments.object AND o.deleted_at IS NOT NULL) AND recipe_revision > COALESCE(image_revision, 0) AND (btrim(COALESCE(environments.setup_script, '')) <> '' OR btrim(COALESCE(environments.pi_packages, '')) <> ''\n OR EXISTS (SELECT 1 FROM environment_repos r WHERE r.environment = environments.object)))";
|
|
12
|
+
/** A deleted environment that may still have an image in the registry. */
|
|
13
|
+
export declare const IMAGE_DELETE_OWED_SQL = "(kind = 'blaxel' AND EXISTS (SELECT 1 FROM objects o WHERE o.id = environments.object AND o.deleted_at IS NOT NULL) AND (image_ref IS NOT NULL OR image_revision IS NOT NULL OR image_building_at IS NOT NULL))";
|
|
7
14
|
export type EnvironmentImage = {
|
|
8
15
|
state: 'base';
|
|
9
16
|
} | {
|
|
@@ -29,16 +36,23 @@ export interface RecipeImageDeps {
|
|
|
29
36
|
build?: (input: RecipeBuildInput) => Promise<{
|
|
30
37
|
ref: string;
|
|
31
38
|
}>;
|
|
39
|
+
/** Deletes the registry image `name` with every tag; an absent image is done, not an error. The default is Blaxel's DELETE. */
|
|
40
|
+
deleteImage?: (name: string) => Promise<void>;
|
|
32
41
|
now?: () => number;
|
|
33
42
|
}
|
|
34
43
|
export declare class RecipeImageReconciler {
|
|
35
44
|
private readonly deps;
|
|
36
45
|
constructor(deps?: RecipeImageDeps);
|
|
37
|
-
/** One pass: claim every environment with an unbuilt revision and build it detached from the tick. */
|
|
46
|
+
/** One pass: claim every live environment with an unbuilt revision and build it, and every deleted environment that may still have an image and delete it, each detached from the tick. */
|
|
38
47
|
run(nowMs: number, ctx: {
|
|
39
48
|
lifecycle: DetachedWorkLifecycle;
|
|
40
49
|
}): Promise<void>;
|
|
50
|
+
/** Takes the lease on `environmentId` if `owed` (re-evaluated in the same statement) holds and no live lease is held; returns the column asked for. */
|
|
41
51
|
private claim;
|
|
52
|
+
/** Runs `work` while renewing the lease at a third of its length; `work` gets the lease value current when it starts, and renewal changes only the stored value. */
|
|
53
|
+
private withLease;
|
|
54
|
+
/** Deletes the environment's image under the lease, then clears every image column so nothing is owed and an undelete rebuilds. A failure keeps the columns and schedules the retry. */
|
|
55
|
+
private deleteClaimed;
|
|
42
56
|
private buildClaimed;
|
|
43
57
|
private recordFailure;
|
|
44
58
|
}
|
|
@@ -1,7 +1,6 @@
|
|
|
1
|
-
var
|
|
2
|
-
|
|
3
|
-
WHERE object = ? AND
|
|
4
|
-
|
|
5
|
-
WHERE object = ? AND image_building_at = ? AND COALESCE(image_revision, 0) < ?`).run(i,l.ref,e,a,i)}finally{clearInterval(c)}}async recordFailure(e,i,r,t){const a=new Date(t+I).toISOString();if((await(await s()).prepare("UPDATE environments SET image_error = ?, image_building_at = ? WHERE object = ? AND image_building_at = ?").run(r,a,e,i)).changes===1){d({level:"error",event:"recipe_image.build_failed",fields:{environment_id:e,error:r}});for(const o of await W(e))try{await N(async l=>{await D(l,o.run_id,o.node_id,"environment.image_failed",{environment_id:e,error:r})})}catch(l){d({level:"error",event:"recipe_image.failure_event_failed",node_id:o.node_id,error:l})}}}}async function W(n){const e=await(await s()).prepare(`SELECT n.node_id, n.run_id FROM nodes n JOIN profiles p ON p.id = n.profile_id
|
|
1
|
+
var A=Object.defineProperty;var d=(o,e)=>A(o,"name",{value:e,configurable:!0});import{mkdtempSync as T}from"node:fs";import{tmpdir as h}from"node:os";import{join as R}from"node:path";import{hasUnseenWakeMail as O}from"../../core/canvas/deliveries.js";import{openDb as l,withCanvasWrite as U}from"../../core/canvas/db.js";import{emitEvent as g}from"../../core/events/emit.js";import{appendRunEvent as y}from"../../core/runs/events.js";import{blaxelConfigFromEnv as u}from"../../core/runtime/runner/blaxel/client.js";import{buildImage as I,deleteImage as W,environmentImageName as f,prepareBuildDir as C,removeBuildDir as j}from"../../core/runtime/runner/blaxel/image-build.js";import{mintInstallationToken as H}from"../api/handlers/git-credential.js";import{RECIPE_HAS_CONTENT_SQL as w,recipeOf as x}from"../api/environment-of.js";import{brokerSignalBus as $}from"../broker-signals/bus.js";const E=3*6e4,N=10*6e4,p="EXISTS (SELECT 1 FROM objects o WHERE o.id = environments.object AND o.deleted_at IS NOT NULL)",b=`NOT ${p}`,S=`(kind = 'blaxel' AND ${b} AND recipe_revision > COALESCE(image_revision, 0) AND ${w})`,L=`(kind = 'blaxel' AND ${p} AND (image_ref IS NOT NULL OR image_revision IS NOT NULL OR image_building_at IS NOT NULL))`;async function ee(o){const e=await(await l()).prepare(`SELECT ${w} AS has_content, image_revision, image_ref, image_error FROM environments WHERE object = ?`).get(o);if(e===void 0)throw new Error(`no environment ${o}`);return e.has_content?e.image_ref===null||e.image_revision===null?{state:"pending",error:e.image_error}:{state:"image",ref:e.image_ref,revision:Number(e.image_revision)}:{state:"base"}}d(ee,"resolveEnvironmentImage");async function ie(o){return await $.subscribe(e=>{o(e)},{kinds:["environment_image"]})}d(ie,"subscribeImageBuilt");async function k(o,e){const t=o.recipe.repositories.map(r=>r.github_full_name),i=t.length===0?null:await H(o.person,t),a=T(R(h(),"crtr-recipe-image-"));try{return await C({recipe:o.recipe,revision:o.revision,token:i?.token??null,dir:a}),await I(e,f(o.environmentId),a)}finally{j(a)}}d(k,"defaultBuild");class te{static{d(this,"RecipeImageReconciler")}deps;constructor(e={}){this.deps=e}async run(e,t){if(t.lifecycle.acceptsDetachedWork())try{const i=new Date(e).toISOString(),a=await l(),r=await a.prepare(`SELECT object FROM environments WHERE ${S} AND (image_building_at IS NULL OR image_building_at <= ?)`).all(i);for(const{object:n}of r){const s=await this.claim(n,e,S,"recipe_revision");s!==null&&t.lifecycle.registerDetached(this.buildClaimed(n,Number(s.recipe_revision),s.lease).catch(_=>{g({level:"error",event:"recipe_image.failed",error:_})}))}const c=await a.prepare(`SELECT object FROM environments WHERE ${L} AND (image_building_at IS NULL OR image_building_at <= ?)`).all(i);for(const{object:n}of c){const s=await this.claim(n,e,L,"object");s!==null&&t.lifecycle.registerDetached(this.withLease(n,s.lease,_=>this.deleteClaimed(n,_)).catch(_=>{g({level:"error",event:"recipe_image.delete_failed",error:_})}))}}catch(i){g({level:"error",event:"recipe_image.reconcile_failed",error:i})}}async claim(e,t,i,a){const r=new Date(t+E).toISOString(),c=await(await l()).prepare(`UPDATE environments SET image_building_at = ?
|
|
2
|
+
WHERE object = ? AND ${i} AND (image_building_at IS NULL OR image_building_at <= ?)
|
|
3
|
+
RETURNING ${a} AS recipe_revision`).get(r,e,new Date(t).toISOString());return c===void 0?null:{recipe_revision:c.recipe_revision,lease:r}}async withLease(e,t,i){const a=this.deps.now??Date.now;let r=t;const c=setInterval(()=>{const n=new Date(a()+E).toISOString();(async()=>{(await(await l()).prepare("UPDATE environments SET image_building_at = ? WHERE object = ? AND image_building_at = ?").run(n,e,r)).changes===1&&(r=n)})().catch(()=>{})},E/3);c.unref();try{await i(()=>r)}finally{clearInterval(c)}}async deleteClaimed(e,t){try{await(this.deps.deleteImage??(i=>W(u(),i)))(f(e))}catch(i){const a=i instanceof Error?i.message:String(i),r=new Date((this.deps.now??Date.now)()+N).toISOString();(await(await l()).prepare("UPDATE environments SET image_error = ?, image_building_at = ? WHERE object = ? AND image_building_at = ?").run(`deleting the image failed: ${a}`,r,e,t())).changes===1&&g({level:"error",event:"recipe_image.delete_failed",fields:{environment_id:e,error:a}});return}await(await l()).prepare("UPDATE environments SET image_ref = NULL, image_revision = NULL, image_error = NULL, image_building_at = NULL WHERE object = ? AND image_building_at = ?").run(e,t())}async buildClaimed(e,t,i){const a=this.deps.now??Date.now;await this.withLease(e,i,async r=>{const c=await x(e);if(c===null||c.revision!==t){await(await l()).prepare("UPDATE environments SET image_building_at = NULL WHERE object = ? AND image_building_at = ?").run(e,r());return}let n;try{const m=await(await l()).prepare("SELECT person FROM profiles WHERE environment_id = ? ORDER BY created_at LIMIT 1").get(e);if(m===void 0)throw new Error(`no profile runs in environment ${e}, so there is no person to take a GitHub token for`);const D={environmentId:e,revision:t,recipe:c,person:m.person};n=await(this.deps.build??(v=>k(v,u())))(D)}catch(m){await this.recordFailure(e,r(),m instanceof Error?m.message:String(m),a());return}const s=await l();(await s.prepare(`UPDATE environments SET image_revision = ?, image_ref = ?, image_error = NULL, image_building_at = NULL
|
|
4
|
+
WHERE object = ? AND image_building_at = ? AND COALESCE(image_revision, 0) < ? AND ${b}`).run(t,n.ref,e,r(),t)).changes!==1&&await s.prepare(`UPDATE environments SET image_ref = ?, image_building_at = NULL WHERE object = ? AND ${p}`).run(n.ref,e)})}async recordFailure(e,t,i,a){const r=new Date(a+N).toISOString();if((await(await l()).prepare("UPDATE environments SET image_error = ?, image_building_at = ? WHERE object = ? AND image_building_at = ?").run(i,r,e,t)).changes===1){g({level:"error",event:"recipe_image.build_failed",fields:{environment_id:e,error:i}});for(const n of await F(e))try{await U(async s=>{await y(s,n.run_id,n.node_id,"environment.image_failed",{environment_id:e,error:i})})}catch(s){g({level:"error",event:"recipe_image.failure_event_failed",node_id:n.node_id,error:s})}}}}async function F(o){const e=await(await l()).prepare(`SELECT n.node_id, n.run_id FROM nodes n JOIN profiles p ON p.id = n.profile_id
|
|
6
5
|
WHERE p.environment_id = ? AND n.status IN ('active', 'idle') AND n.run_id IS NOT NULL
|
|
7
|
-
AND NOT EXISTS (SELECT 1 FROM executions e WHERE e.node_id = n.node_id AND e.state != 'exited')`).all(
|
|
6
|
+
AND NOT EXISTS (SELECT 1 FROM executions e WHERE e.node_id = n.node_id AND e.state != 'exited')`).all(o),t=[];for(const i of e)await O(i.node_id)&&t.push(i);return t}d(F,"nodesWaitingOnImage");export{p as ENVIRONMENT_DELETED_SQL,b as ENVIRONMENT_LIVE_SQL,S as IMAGE_BUILD_OWED_SQL,L as IMAGE_DELETE_OWED_SQL,E as LEASE_MS,N as RETRY_AFTER_FAILURE_MS,te as RecipeImageReconciler,F as nodesWaitingOnImage,ee as resolveEnvironmentImage,ie as subscribeImageBuilt};
|
|
@@ -7,8 +7,6 @@ export declare const STORAGE_DUE_WORK_INTERVAL_MS = 60000;
|
|
|
7
7
|
export declare const UNUSED_UPLOAD_TTL_MS: number;
|
|
8
8
|
/** Storage deletes attempted per kind per pass; the rest wait for the next pass. */
|
|
9
9
|
export declare const STORAGE_DUE_WORK_BUDGET = 200;
|
|
10
|
-
/** A deleted node's blobs and `objects` row are removed this long after `deleted_at`; until then the owner can undelete it. */
|
|
11
|
-
export declare const NODE_BLOB_RETENTION_MS: number;
|
|
12
10
|
/** Nodes purged per pass; the rest wait for the next pass. */
|
|
13
11
|
export declare const NODE_PURGE_BUDGET = 25;
|
|
14
12
|
/** Consecutive `storage_unavailable` failures after which a pass stops early. */
|
|
@@ -35,8 +33,9 @@ export declare class StorageDueWorkReconciler {
|
|
|
35
33
|
run(now: number, ctx: StorageDueWorkContext): void;
|
|
36
34
|
/** One pass over the due-work rows. Exposed for tests. */
|
|
37
35
|
pass(now: number, lane?: LanePass): Promise<StorageDueWorkResult>;
|
|
38
|
-
/** Delete the blobs of
|
|
39
|
-
*
|
|
36
|
+
/** Delete the blobs of every deleted node, then the node's `objects` row. A node cannot be undeleted, so nothing waits. A node is
|
|
37
|
+
* skipped while a live node still has its `run_id` (an isolated run's members outlive a deleted root and read the root's
|
|
38
|
+
* attachments). The row goes only if no foreign key refers to it (`objects.owner`, `revisions.author`, `object_kinds.owner` have no
|
|
40
39
|
* cascade), which Postgres decides at the DELETE (23503), so a reference added meanwhile cannot slip through. Blobs go
|
|
41
40
|
* first, outside any transaction: a crash between the two is retried (the retry finds no blobs), and two passes at once
|
|
42
41
|
* both succeed because deleting an absent blob and an absent row are no-ops. The sweep walks `(deleted_at, id)` from a
|
|
@@ -1,2 +1,3 @@
|
|
|
1
|
-
var
|
|
2
|
-
AND
|
|
1
|
+
var m=Object.defineProperty;var f=(c,e)=>m(c,"name",{value:e,configurable:!0});import{blobStore as O}from"../../core/blobs/index.js";import{openDb as R,withCanvasWrite as g}from"../../core/canvas/db.js";import{emitEvent as u}from"../../core/events/emit.js";import{operationIdContext as w}from"../../core/events/operation-id.js";import{RunError as b}from"../../core/runs/operations.js";import{storageClient as v,storageConfig as T}from"../../core/storage/client.js";import{deleteUploadRow as N,expireShares as y,markShareObjectDeleted as k,markUploadsDeletePending as L,pendingUploadDeletes as U,sharesOwingObjectDelete as A,staleUnusedUploads as I}from"../../core/storage/tables.js";import{runThrottledLane as x}from"./throttled-lane.js";const W=6e4,j=1440*6e4,S=200,M=5*6e4,D=25,F=["conversations","events","jobs","attachments"],C=3,G=f(c=>c instanceof b&&c.code==="storage_unavailable","unavailable");class q{static{f(this,"StorageDueWorkReconciler")}deps;constructor(e={config:T,client:v}){this.deps=e}run(e,r){if(!r.lifecycle.acceptsDetachedWork())return;const t=w.fresh(()=>x("storage-due-work","",e,W,M,async s=>{await this.pass(e,s)})).then(()=>{}).catch(s=>{w.fresh(()=>u({level:"error",event:"storage.due_work.failed",error:s}))});r.lifecycle.registerDetached(t)}async pass(e,r){const t={marked_uploads:0,expired_shares:0,deleted_uploads:0,deleted_share_objects:0,purged_nodes:0,failed:0};return t.purged_nodes=await this.purgeDeletedNodes(r),this.deps.config()&&await this.settleFileTransfers(e,t),(t.purged_nodes||t.marked_uploads||t.expired_shares||t.deleted_uploads||t.deleted_share_objects)&&u({level:"info",event:"storage.due_work.settled",outcome:"succeeded",fields:{...t}}),t}async purgeDeletedNodes(e){const r=await R(),t=e?.state?JSON.parse(e.state):null,s=await r.prepare(`SELECT id, deleted_at FROM objects WHERE type = 'node' AND deleted_at IS NOT NULL
|
|
2
|
+
AND NOT EXISTS (SELECT 1 FROM nodes n WHERE n.run_id = objects.id)
|
|
3
|
+
AND (deleted_at, id) > (?, ?) ORDER BY deleted_at, id LIMIT ?`).all(t?.deleted_at??"",t?.id??"",D);if(s.length===0)return t&&await e?.save(null),0;const _=await(this.deps.blobs??O)();let p=0,i=-1;for(const[a,{id:d}]of s.entries())try{for(const o of F)for(const l of await _.list(`${o}/${d}/`))o==="conversations"&&await r.prepare("SELECT 1 FROM conversation_parts WHERE blob_key = ? LIMIT 1").get(l)!==void 0||await _.delete(l);await g(async o=>{await o.prepare("DELETE FROM objects WHERE id = ? AND type = 'node' AND deleted_at IS NOT NULL").run(d)},{savepoint:!0}),p++}catch(o){o.code!=="23503"&&(i<0&&(i=a),u({level:"warn",event:"storage.due_work.node_purge_failed",error:o,fields:{node_id:d}}))}if(i>=0){const a=s[i-1];await e?.save(a?JSON.stringify({deleted_at:a.deleted_at,id:a.id}):e.state)}else{const a=s[s.length-1];await e?.save(s.length<D?null:JSON.stringify({deleted_at:a.deleted_at,id:a.id}))}return p}async settleFileTransfers(e,r){const t=new Date(e).toISOString(),{marked:s,expired:_}=await g(async a=>{const d=await I(new Date(e-j).toISOString(),a);return await L(d,a,t),{marked:d.length,expired:(await y(t,a)).length}});r.marked_uploads=s,r.expired_shares=_;const p=(await U()).slice(0,S),i=(await A()).slice(0,S);if(p.length||i.length){const a=this.deps.client();let d,o=0,l=!1;const h=f(async n=>{if(l)return!1;try{return await n(),o=0,!0}catch(E){return r.failed++,d??=E,o=G(E)?o+1:0,o>=C&&(l=!0),!1}},"attempt");for(const n of p)await h(()=>a.deleteUpload(n.upload_id))&&(await N(n.upload_id),r.deleted_uploads++);for(const n of i)await h(()=>a.deleteShare(n.share_id))&&(await k(n.share_id),r.deleted_share_objects++);d!==void 0&&u({level:"warn",event:"storage.due_work.deletes_failed",error:d,fields:{failed:r.failed,storage_unavailable:l}})}}}export{D as NODE_PURGE_BUDGET,C as STORAGE_DOWN_AFTER,S as STORAGE_DUE_WORK_BUDGET,W as STORAGE_DUE_WORK_INTERVAL_MS,q as StorageDueWorkReconciler,j as UNUSED_UPLOAD_TTL_MS};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@north-light/cli",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.604",
|
|
4
4
|
"description": "crtr — agent runtime with memory, plugins, and marketplaces",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.js",
|
|
@@ -145,7 +145,7 @@
|
|
|
145
145
|
},
|
|
146
146
|
"license": "UNLICENSED",
|
|
147
147
|
"dependencies": {
|
|
148
|
-
"@north-light/identity": "0.3.
|
|
148
|
+
"@north-light/identity": "0.3.604",
|
|
149
149
|
"@earendil-works/chord": "1.1.0",
|
|
150
150
|
"@earendil-works/pi-agent-core": "1.1.0",
|
|
151
151
|
"@earendil-works/pi-ai": "1.1.0",
|
package/runtime.lock.json
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@north-light/cli",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.604",
|
|
4
4
|
"lockfileVersion": 3,
|
|
5
5
|
"requires": true,
|
|
6
6
|
"packages": {
|
|
7
7
|
"": {
|
|
8
8
|
"name": "@north-light/cli",
|
|
9
|
-
"version": "0.3.
|
|
9
|
+
"version": "0.3.604",
|
|
10
10
|
"hasInstallScript": true,
|
|
11
11
|
"license": "UNLICENSED",
|
|
12
12
|
"workspaces": [
|
|
@@ -28,7 +28,7 @@
|
|
|
28
28
|
"@milkdown/preset-gfm": "^7.22.3",
|
|
29
29
|
"@milkdown/prose": "^7.22.3",
|
|
30
30
|
"@milkdown/utils": "^7.22.3",
|
|
31
|
-
"@north-light/identity": "0.3.
|
|
31
|
+
"@north-light/identity": "0.3.604",
|
|
32
32
|
"cron-parser": "^5.6.0",
|
|
33
33
|
"esbuild": "^0.27.7",
|
|
34
34
|
"jose": "^6.2.12",
|
|
@@ -11956,17 +11956,17 @@
|
|
|
11956
11956
|
},
|
|
11957
11957
|
"packages/crouter-api": {
|
|
11958
11958
|
"name": "@north-light/api",
|
|
11959
|
-
"version": "0.3.
|
|
11959
|
+
"version": "0.3.604",
|
|
11960
11960
|
"license": "UNLICENSED"
|
|
11961
11961
|
},
|
|
11962
11962
|
"packages/crouter-env-docker": {
|
|
11963
11963
|
"name": "@north-light/env-docker",
|
|
11964
|
-
"version": "0.3.
|
|
11964
|
+
"version": "0.3.604",
|
|
11965
11965
|
"license": "UNLICENSED"
|
|
11966
11966
|
},
|
|
11967
11967
|
"packages/crouter-identity": {
|
|
11968
11968
|
"name": "@north-light/identity",
|
|
11969
|
-
"version": "0.3.
|
|
11969
|
+
"version": "0.3.604",
|
|
11970
11970
|
"license": "UNLICENSED",
|
|
11971
11971
|
"dependencies": {
|
|
11972
11972
|
"jose": "^6.2.1"
|
|
@@ -11974,21 +11974,21 @@
|
|
|
11974
11974
|
},
|
|
11975
11975
|
"packages/crouter-plugin": {
|
|
11976
11976
|
"name": "@north-light/plugin",
|
|
11977
|
-
"version": "0.3.
|
|
11977
|
+
"version": "0.3.604",
|
|
11978
11978
|
"license": "UNLICENSED",
|
|
11979
11979
|
"dependencies": {
|
|
11980
|
-
"@north-light/api": "0.3.
|
|
11981
|
-
"@north-light/identity": "0.3.
|
|
11980
|
+
"@north-light/api": "0.3.604",
|
|
11981
|
+
"@north-light/identity": "0.3.604"
|
|
11982
11982
|
}
|
|
11983
11983
|
},
|
|
11984
11984
|
"packages/crouter-sdk": {
|
|
11985
11985
|
"name": "@north-light/sdk",
|
|
11986
|
-
"version": "0.3.
|
|
11986
|
+
"version": "0.3.604",
|
|
11987
11987
|
"license": "UNLICENSED",
|
|
11988
11988
|
"dependencies": {
|
|
11989
|
-
"@north-light/api": "0.3.
|
|
11990
|
-
"@north-light/identity": "0.3.
|
|
11991
|
-
"@north-light/plugin": "0.3.
|
|
11989
|
+
"@north-light/api": "0.3.604",
|
|
11990
|
+
"@north-light/identity": "0.3.604",
|
|
11991
|
+
"@north-light/plugin": "0.3.604",
|
|
11992
11992
|
"jose": "^6.2.1"
|
|
11993
11993
|
},
|
|
11994
11994
|
"bin": {
|