@qvac/harness 1.0.0 → 1.1.0

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.
Files changed (100) hide show
  1. package/CHANGELOG.md +137 -1
  2. package/README.md +28 -0
  3. package/dist-lib/index.d.ts +32 -304
  4. package/dist-lib/index.js +16 -1147
  5. package/dist-lib/lib/agent/child-run.d.ts +29 -0
  6. package/dist-lib/lib/agent/child-run.js +32 -0
  7. package/dist-lib/lib/agent/delegate.d.ts +3 -19
  8. package/dist-lib/lib/agent/delegate.js +8 -31
  9. package/dist-lib/lib/agent/index.d.ts +4 -0
  10. package/dist-lib/lib/agent/index.js +3 -0
  11. package/dist-lib/lib/agent/read-parts.d.ts +45 -0
  12. package/dist-lib/lib/agent/read-parts.js +60 -0
  13. package/dist-lib/lib/capabilities/completion-engine/driver.js +6 -2
  14. package/dist-lib/lib/capabilities/completion-engine/engine.d.ts +4 -0
  15. package/dist-lib/lib/capabilities/completion-engine/engine.js +27 -18
  16. package/dist-lib/lib/capabilities/completion-engine/round.js +5 -4
  17. package/dist-lib/lib/client/index.js +1 -3
  18. package/dist-lib/lib/connect/decode.d.ts +3 -2
  19. package/dist-lib/lib/connect/decode.js +14 -0
  20. package/dist-lib/lib/connect.d.ts +1 -0
  21. package/dist-lib/lib/connect.js +11 -5
  22. package/dist-lib/lib/context-window.d.ts +2 -0
  23. package/dist-lib/lib/context-window.js +17 -14
  24. package/dist-lib/lib/contract/models.d.ts +8 -1
  25. package/dist-lib/lib/contract-types.d.ts +9 -0
  26. package/dist-lib/lib/harness.d.ts +267 -0
  27. package/dist-lib/lib/harness.js +1154 -0
  28. package/dist-lib/lib/models/custom-model-cache.d.ts +2 -0
  29. package/dist-lib/lib/models/custom-model-cache.js +21 -0
  30. package/dist-lib/lib/models/memory-cap.d.ts +6 -0
  31. package/dist-lib/lib/models/memory-cap.js +20 -0
  32. package/dist-lib/lib/models/model-catalog.d.ts +2 -0
  33. package/dist-lib/lib/models/model-catalog.js +8 -2
  34. package/dist-lib/lib/models/model-fit.d.ts +39 -7
  35. package/dist-lib/lib/models/model-fit.js +133 -18
  36. package/dist-lib/lib/models/model-handle.d.ts +2 -1
  37. package/dist-lib/lib/models/model-pool.d.ts +3 -2
  38. package/dist-lib/lib/models/model-pool.js +30 -13
  39. package/dist-lib/lib/models/tts-model-default.d.ts +1 -1
  40. package/dist-lib/lib/models/tts-model-default.js +7 -6
  41. package/dist-lib/lib/residency/index.d.ts +21 -7
  42. package/dist-lib/lib/residency/index.js +187 -80
  43. package/dist-lib/lib/run-log/boundary.d.ts +4 -1
  44. package/dist-lib/lib/run-log/boundary.js +2 -1
  45. package/dist-lib/lib/run-log/index.d.ts +2 -1
  46. package/dist-lib/lib/run-log/index.js +2 -1
  47. package/dist-lib/lib/run-log/persisted-actor.d.ts +10 -0
  48. package/dist-lib/lib/run-log/persisted-actor.js +15 -0
  49. package/dist-lib/lib/run-log/run-journal.d.ts +3 -0
  50. package/dist-lib/lib/run-log/run-journal.js +19 -8
  51. package/dist-lib/lib/serve/requests.d.ts +3 -0
  52. package/dist-lib/lib/serve.js +3 -0
  53. package/dist-lib/lib/spawn.d.ts +4 -1
  54. package/dist-lib/lib/tools/exec/shell-guidance.d.ts +2 -0
  55. package/dist-lib/lib/tools/exec/shell-guidance.js +29 -0
  56. package/dist-lib/lib/tools/exec.js +2 -1
  57. package/dist-lib/lib/tools/files/list-dir.js +79 -32
  58. package/dist-lib/lib/tools/fs/walk.d.ts +11 -1
  59. package/dist-lib/lib/tools/fs/walk.js +64 -30
  60. package/dist-lib/lib/tools/http-request.js +5 -0
  61. package/dist-lib/lib/tools/office.js +8 -5
  62. package/dist-lib/lib/tools/pdf/pages.d.ts +1 -1
  63. package/dist-lib/lib/tools/pdf/pages.js +3 -14
  64. package/dist-lib/lib/tools/pdf/recognize.d.ts +3 -0
  65. package/dist-lib/lib/tools/pdf/recognize.js +45 -7
  66. package/dist-lib/lib/tools/tls-failure.d.ts +1 -0
  67. package/dist-lib/lib/tools/tls-failure.js +8 -0
  68. package/dist-lib/lib/tools/web-fetch.js +5 -0
  69. package/dist-lib/plugins/image/generate-image.d.ts +2 -2
  70. package/dist-lib/plugins/image/generate-image.js +9 -1
  71. package/dist-lib/plugins/image/index.js +6 -2
  72. package/dist-lib/plugins/knowledge/chunk-index.d.ts +4 -0
  73. package/dist-lib/plugins/knowledge/chunk-index.js +191 -0
  74. package/dist-lib/plugins/knowledge/index.d.ts +1 -0
  75. package/dist-lib/plugins/knowledge/index.js +1 -0
  76. package/dist-lib/plugins/knowledge/manifest.d.ts +2 -1
  77. package/dist-lib/plugins/knowledge/manifest.js +2 -9
  78. package/dist-lib/plugins/knowledge/store.d.ts +5 -1
  79. package/dist-lib/plugins/knowledge/store.js +44 -16
  80. package/dist-lib/plugins/lsp/rpc.d.ts +9 -1
  81. package/dist-lib/plugins/lsp/rpc.js +81 -17
  82. package/dist-lib/plugins/music/generate-music.d.ts +2 -2
  83. package/dist-lib/plugins/music/generate-music.js +14 -1
  84. package/dist-lib/plugins/music/index.js +4 -1
  85. package/dist-lib/plugins/sandbox-windows/prebuilds/win32-arm64/qvac-sandbox.exe +0 -0
  86. package/dist-lib/plugins/sandbox-windows/prebuilds/win32-x64/qvac-sandbox.exe +0 -0
  87. package/dist-lib/plugins/speech/speech-engine.d.ts +5 -2
  88. package/dist-lib/plugins/speech/speech-engine.js +28 -7
  89. package/dist-lib/schema/harness.js +28 -2
  90. package/dist-lib/spec/bind.js +3 -0
  91. package/dist-lib/spec/calls.js +1 -0
  92. package/dist-lib/spec/hrpc/hrpc.json +13 -0
  93. package/dist-lib/spec/hrpc/index.js +15 -3
  94. package/dist-lib/spec/hrpc/messages.js +87 -6
  95. package/dist-lib/spec/hyperschema/index.js +87 -6
  96. package/dist-lib/spec/hyperschema/schema.json +70 -2
  97. package/dist-lib/spec/hyperschema/types.d.ts +21 -1
  98. package/package.json +29 -28
  99. package/scripts/addon-externals.cjs +1 -0
  100. package/worker/harness-sidecar.mjs +12 -1
@@ -9,8 +9,8 @@ import { parseGgufHeader, readGgufHeaderBytes } from '../models/gguf-header.js';
9
9
  import { resolveMainGpu } from '../models/gpu-selection.js';
10
10
  import { createIdleReaper } from '../models/idle-unload.js';
11
11
  import { createLoadRequests } from '../models/load-requests.js';
12
- import { memoryCapBytes, nextVictim, VictimRank } from '../models/memory-cap.js';
13
- import { assetBytes, curatedListables, curatedModelAsset, customContextLength, customModelSrc, modelAddonOf, speculativeDraft } from '../models/model-catalog.js';
12
+ import { BUDGET_POOL, HOST_POOL, memoryCapBytes, nextVictim, poolsOver, sumPools, totalBytes, VictimRank } from '../models/memory-cap.js';
13
+ import { assetBytes, curatedListables, curatedModelAsset, customContextLength, customModelSrc, generatorRowName, modelAddonOf, speculativeDraft } from '../models/model-catalog.js';
14
14
  import { ModelFit } from '../models/model-fit.js';
15
15
  import { createModelStatusCache, invalidateModelStatusCache } from '../models/model-list.js';
16
16
  import { awaitModelCapacity, contextSize, slotCount, createModelPool, evictIdle, evictIdleWhere, evictIdleWithin, evictModel, evictModelWithin, isResident, leaseCount, loadedModels, loadingModels, modelKey, modelOf, releaseModel, resolveLoadOptions, settledEntries, settledModels } from '../models/model-pool.js';
@@ -44,7 +44,7 @@ function stagesBytes(srcs) {
44
44
  export class Residency {
45
45
  gate;
46
46
  sdk;
47
- fit = new ModelFit(async (input) => (await this.sdk.load()).assessModelFit(input));
47
+ fit = new ModelFit(async (input) => (await this.sdk.load()).assessModelFit(input), async ({ name, sha256Checksum }) => sha256Checksum ? ModelFit.downloaded(await this.sdk.load(), name, sha256Checksum) : undefined);
48
48
  requests = createLoadRequests((state) => this.notify(state));
49
49
  _loads;
50
50
  _emit;
@@ -75,8 +75,10 @@ export class Residency {
75
75
  _hold;
76
76
  _capability;
77
77
  _sizeLoads = false;
78
- _capBytes = null;
78
+ _capPercent = null;
79
+ _budget = null;
79
80
  _reserved = new Map();
81
+ _generators = new Map();
80
82
  _contexts = new ContextClimb(() => this._contextProfile());
81
83
  _admission = new ScopeLock();
82
84
  _byHand = new Map();
@@ -135,6 +137,7 @@ export class Residency {
135
137
  this._models = this._createPool();
136
138
  }
137
139
  destroy() {
140
+ this.fit.clearRows();
138
141
  return this._models?.destroy();
139
142
  }
140
143
  setIdleTimeout(ms) {
@@ -152,45 +155,79 @@ export class Residency {
152
155
  }
153
156
  async setMemoryCap(percent) {
154
157
  this._sizeLoads = true;
155
- const { mobile, memoryBudget } = await this._capability();
156
- this._capBytes =
157
- percent > 0 && !mobile && memoryBudget
158
- ? memoryCapBytes(percent, memoryBudget.availableBytes)
159
- : null;
160
- HarnessLog.info('memory cap', { percent, capBytes: this._capBytes });
161
- if (this._capBytes !== null) {
162
- await this.busy(() => this._admit(() => this._makeRoom(0, { generators: true })));
163
- }
164
- }
165
- settledBytes() {
166
- return this._pools()
167
- .flatMap((pool) => settledEntries(pool))
168
- .reduce((sum, { bytes }) => sum + (bytes ?? 0), 0);
158
+ const { memoryBudget } = await this._capability();
159
+ this._budget = memoryBudget ?? null;
160
+ this._capPercent = percent > 0 && memoryBudget ? percent : null;
161
+ HarnessLog.info('memory cap', {
162
+ percent,
163
+ capBytes: memoryBudget && this._capOf(this._mainPool())
164
+ });
165
+ if (this._capPercent !== null) {
166
+ await this.busy(() => this._admit(() => this._makeRoom({}, { generators: true })));
167
+ }
168
+ }
169
+ budgetedBytes() {
170
+ return Object.entries(this._placed(sumPools([...this._settledPools(), ...this._generatorPools()])))
171
+ .filter(([pool]) => this._budgeted(pool))
172
+ .reduce((sum, [, bytes]) => sum + bytes, 0);
173
+ }
174
+ poolUsage() {
175
+ const used = this._placed(sumPools([...this._settledPools(), ...this._generatorPools()]));
176
+ const capacity = this.fit.capacity();
177
+ const ids = new Set([this._mainPool(), ...capacity.keys(), ...Object.keys(used)]);
178
+ return [...ids].map((id) => ({
179
+ id,
180
+ usedBytes: used[id] ?? 0,
181
+ capBytes: this._capOf(id) ?? undefined,
182
+ totalBytes: this._memoryOf(id)
183
+ }));
169
184
  }
170
185
  memoryByModel() {
171
186
  const memory = new Map();
172
- for (const { key, bytes } of this._pools().flatMap((pool) => settledEntries(pool))) {
173
- if (bytes === undefined)
187
+ for (const { key, pools } of this._pools().flatMap((pool) => settledEntries(pool))) {
188
+ if (pools === undefined)
174
189
  continue;
175
190
  const model = modelOf(key);
176
- memory.set(model, (memory.get(model) ?? 0) + bytes);
191
+ memory.set(model, (memory.get(model) ?? 0) + totalBytes(pools));
192
+ }
193
+ for (const [model, { pools }] of this._generators) {
194
+ memory.set(model, totalBytes(pools));
177
195
  }
178
196
  return memory;
179
197
  }
180
- async makeRoomForPlugin(signal, busy, srcs = []) {
181
- if (this._capBytes !== null && !this._models.destroyed) {
182
- await this._makeRoomForGenerator(srcs, signal);
183
- return;
198
+ async makeRoomForPlugin(signal, busy, load = []) {
199
+ if (this._capPercent !== null && !this._models.destroyed) {
200
+ await this._makeRoomForGenerator('srcs' in load ? load.srcs : load, signal);
184
201
  }
185
- if (!(await this._roomForPlugin(signal, PLUGIN_EVICT_WAIT_MS))) {
202
+ else if (!(await this._roomForPlugin(signal, PLUGIN_EVICT_WAIT_MS))) {
186
203
  throw typeof busy === 'string' ? new Error(busy) : busy;
187
204
  }
205
+ return 'srcs' in load ? this._holdGenerator(load) : noop;
206
+ }
207
+ _holdGenerator({ srcs, unloadIdle }) {
208
+ const [lead] = srcs;
209
+ const bytes = stagesBytes(srcs);
210
+ if (!this._sizeLoads || lead === undefined || bytes === 0) {
211
+ return noop;
212
+ }
213
+ const model = generatorRowName(lead);
214
+ const held = { pools: { [BUDGET_POOL]: bytes }, unloadIdle };
215
+ this._generators.set(model, held);
216
+ return () => {
217
+ if (this._generators.get(model) === held) {
218
+ this._generators.delete(model);
219
+ }
220
+ };
188
221
  }
189
222
  async _makeRoomForGenerator(srcs, signal) {
190
223
  if (signal?.aborted) {
191
224
  throw new AbortedError();
192
225
  }
193
- await this._makeRoom(stagesBytes(srcs), { replying: true });
226
+ const need = { [BUDGET_POOL]: stagesBytes(srcs) };
227
+ if (this._over(need).length > 0) {
228
+ await this._unloadIdleHeld();
229
+ }
230
+ await this._makeRoom(need, { replying: true });
194
231
  if (signal?.aborted) {
195
232
  throw new AbortedError();
196
233
  }
@@ -320,13 +357,14 @@ export class Residency {
320
357
  return new Map();
321
358
  }
322
359
  return this.fit
323
- .rows(() => this._rowQueries())
360
+ .rows(() => this._rowQueries(rows))
324
361
  .catch((err) => {
325
362
  HarnessLog.warn('fit estimate failed', { rows: rows.length, err: errorMessage(err) });
326
363
  return new Map();
327
364
  });
328
365
  }
329
- _rowQueries() {
366
+ _rowQueries(rows) {
367
+ const downloaded = new Set(rows.filter((row) => row.isCached).map((row) => row.registryPath));
330
368
  return new Map(curatedListables()
331
369
  .filter((listable) => listable.asset.addon === 'llm')
332
370
  .map(({ name, asset }) => {
@@ -334,10 +372,10 @@ export class Residency {
334
372
  opts: this.loadOptions(name),
335
373
  deviceConfig: this.deviceConfig()
336
374
  };
337
- return [
338
- asset.registryPath,
339
- ModelFit.query(asset, contextSize(name, asset, load) * slotCount(name, load))
340
- ];
375
+ const query = ModelFit.query(asset, contextSize(name, asset, load) * slotCount(name, load), {
376
+ native: true
377
+ });
378
+ return [asset.registryPath, { ...query, onDisk: downloaded.has(asset.registryPath) }];
341
379
  }));
342
380
  }
343
381
  async warm({ model, agent, signal }) {
@@ -356,7 +394,7 @@ export class Residency {
356
394
  return true;
357
395
  }
358
396
  if (target.needsRoom) {
359
- return this._capBytes !== null || this._roomForPlugin(signal, WARM_ROOM_WAIT_MS);
397
+ return this._capPercent !== null || this._roomForPlugin(signal, WARM_ROOM_WAIT_MS);
360
398
  }
361
399
  if (!target.loadOpts) {
362
400
  return true;
@@ -457,12 +495,12 @@ export class Residency {
457
495
  await this._unloadIdlePlugins();
458
496
  }
459
497
  async _yieldGenerators() {
460
- if (this._capBytes === null) {
498
+ if (this._capPercent === null) {
461
499
  await this.unloadIdleGenerators();
462
500
  }
463
501
  }
464
502
  async _admitByHand(model, target, signal) {
465
- if (this._capBytes === null) {
503
+ if (this._capPercent === null) {
466
504
  return this._chooseByHand(model, target, signal);
467
505
  }
468
506
  return this._admit(async () => {
@@ -470,17 +508,18 @@ export class Residency {
470
508
  return true;
471
509
  }
472
510
  const sized = await this._sizeByHand(model, target);
473
- const capBytes = this._capBytes;
474
- const replaced = this._replacedEntries(model, target);
475
- const used = this._usedBytes() - replaced.reduce((sum, { bytes }) => sum + (bytes ?? 0), 0);
511
+ const replaced = sumPools(this._replacedEntries(model, target).flatMap(sizedPools));
476
512
  const alone = this._alone(model, target);
477
- const fits = capBytes === null || alone || sized.bytes === undefined || used + sized.bytes <= capBytes;
513
+ if (sized.pools && this._generatorsInTheWay(sized.pools, replaced, alone)) {
514
+ await this._unloadIdleHeld();
515
+ }
516
+ const fits = alone || sized.pools === undefined || this._over(sized.pools, replaced).length === 0;
478
517
  if ((sized.tooLarge && !alone) || !fits) {
479
518
  return false;
480
519
  }
481
520
  this._byHand.set(target.key, sized.ctxSize);
482
- if (sized.bytes !== undefined) {
483
- this._reserved.set(target.key, sized.bytes);
521
+ if (sized.pools !== undefined) {
522
+ this._reserved.set(target.key, sized.pools);
484
523
  }
485
524
  return true;
486
525
  });
@@ -553,35 +592,35 @@ export class Residency {
553
592
  async beforeLoad(load) {
554
593
  if (!this._sizeLoads)
555
594
  return undefined;
556
- const bytes = this._byHand.has(load.key)
595
+ const pools = this._byHand.has(load.key)
557
596
  ? await this._admit(() => this._reserveByHand(load))
558
597
  : await this._admit(() => this._reserve(load));
559
- return { bytes, release: () => this._reserved.delete(load.key) };
598
+ return { pools, release: () => this._reserved.delete(load.key) };
560
599
  }
561
600
  async _reserveByHand(load) {
562
601
  const admittedAt = this._byHand.get(load.key);
563
602
  this._byHand.delete(load.key);
564
603
  if (load.modelConfig?.['ctx_size'] !== admittedAt) {
565
- const { bytes } = await this._sizeLoad(load);
566
- if (bytes !== undefined) {
567
- this._reserved.set(load.key, bytes);
604
+ const { pools } = await this._sizeLoad(load);
605
+ if (pools !== undefined) {
606
+ this._reserved.set(load.key, pools);
568
607
  }
569
608
  }
570
609
  return this._reserved.get(load.key);
571
610
  }
572
611
  async _reserve(load) {
573
612
  const sized = await this._sizeLoad(load);
574
- if (this._capBytes !== null) {
575
- await this._makeRoom(sized.bytes ?? 0, {
613
+ if (this._capPercent !== null) {
614
+ await this._makeRoom(sized.pools ?? {}, {
576
615
  generators: true,
577
616
  tooLarge: sized.tooLarge,
578
617
  recheck: async () => (await this._sizeLoad(load)).tooLarge
579
618
  });
580
619
  }
581
- if (sized.bytes !== undefined) {
582
- this._reserved.set(load.key, sized.bytes);
620
+ if (sized.pools !== undefined) {
621
+ this._reserved.set(load.key, sized.pools);
583
622
  }
584
- return sized.bytes;
623
+ return sized.pools;
585
624
  }
586
625
  async _sizeLoad({ model, modelSrc, modelType, modelConfig }) {
587
626
  const downloaded = downloadBytes(modelSrc);
@@ -589,26 +628,39 @@ export class Residency {
589
628
  const companions = (downloadBytes(projectionModelSrc) ?? 0) + (downloadBytes(draftModelSrc) ?? 0);
590
629
  try {
591
630
  const sdk = await this.sdk.load();
592
- const { models } = await sdk.assessModelFit({
593
- models: [{ modelSrc: fitSrc(modelSrc), modelType, modelConfig: config }]
631
+ const file = typeof modelSrc === 'string'
632
+ ? undefined
633
+ : await ModelFit.downloaded(sdk, modelSrc.name, modelSrc.sha256Checksum);
634
+ const { models, pools } = await sdk.assessModelFit({
635
+ models: [{ modelSrc: file ?? fitSrc(modelSrc), modelType, modelConfig: config }]
594
636
  });
595
- const [fit] = models;
596
- const bytes = fit?.floorBytes ?? downloaded;
637
+ this.fit.observe(pools);
638
+ const fit = ModelFit.judge(models[0]);
597
639
  return {
598
- bytes: bytes === undefined ? undefined : bytes + companions,
599
- tooLarge: fit?.verdict === 'likely-too-large',
600
- confirmed: fit?.verdict === 'likely-fits' && fit.evidence === 'native-fit'
640
+ pools: this._withUnfitted(fit.bytes === undefined ? undefined : fit.pools, {
641
+ downloaded,
642
+ companions
643
+ }),
644
+ tooLarge: fit.verdict === 'likely-too-large',
645
+ confirmed: ModelFit.confirms(fit)
601
646
  };
602
647
  }
603
648
  catch (err) {
604
649
  HarnessLog.warn('fit estimate failed', { model, err: errorMessage(err) });
605
650
  return {
606
- bytes: downloaded === undefined ? undefined : downloaded + companions,
651
+ pools: this._withUnfitted(undefined, { downloaded, companions }),
607
652
  tooLarge: false,
608
653
  confirmed: false
609
654
  };
610
655
  }
611
656
  }
657
+ _withUnfitted(fitted, { downloaded, companions }) {
658
+ if (fitted === undefined && downloaded === undefined) {
659
+ return undefined;
660
+ }
661
+ const unfitted = (fitted ? 0 : (downloaded ?? 0)) + companions;
662
+ return sumPools([fitted ?? {}, { [BUDGET_POOL]: unfitted }]);
663
+ }
612
664
  async _chooseContext(load, tier) {
613
665
  if (this._borrowed.has(load.model)) {
614
666
  HarnessLog.info('context climb', { tier, stop: 'borrowed' });
@@ -623,17 +675,16 @@ export class Residency {
623
675
  ...load,
624
676
  modelConfig: { ...load.modelConfig, ctx_size: rung * slots }
625
677
  });
626
- const room = this._capRoom(load.key);
627
- return sized.confirmed && (room === null || (sized.bytes ?? Infinity) <= room);
678
+ if (!sized.confirmed || this._capPercent === null) {
679
+ return sized.confirmed;
680
+ }
681
+ return (sized.pools !== undefined &&
682
+ this._over(sized.pools, this._reserved.get(load.key)).length === 0);
628
683
  }
629
684
  });
630
685
  HarnessLog.info('context chosen', { model: load.model, tier, ctxSize });
631
686
  return ctxSize;
632
687
  }
633
- _capRoom(key) {
634
- const cap = this._capBytes;
635
- return cap === null ? null : cap - (this._usedBytes() - (this._reserved.get(key) ?? 0));
636
- }
637
688
  async _contextProfile() {
638
689
  const { capabilityProfile, memoryBudget } = await this._capability();
639
690
  return memoryBudget ? capabilityProfile : undefined;
@@ -658,21 +709,16 @@ export class Residency {
658
709
  }
659
710
  }
660
711
  async _makeRoom(need, room) {
661
- const capBytes = this._capBytes;
662
- if (capBytes === null) {
712
+ if (this._capPercent === null) {
663
713
  return;
664
714
  }
665
715
  const tried = new Set();
666
716
  let tooLarge = room.tooLarge ?? false;
667
- while (this._usedBytes() + need > capBytes || tooLarge) {
668
- const victim = nextVictim(this._capVictims(room).filter(({ id }) => !tried.has(id)));
717
+ let over = this._over(need);
718
+ while (over.length > 0 || tooLarge) {
719
+ const victim = nextVictim(this._capVictims(room).filter(({ id, pools }) => !tried.has(id) && holdsAny(pools, over)));
669
720
  if (!victim) {
670
- HarnessLog.warn('model over memory cap', {
671
- need,
672
- used: this._usedBytes(),
673
- capBytes,
674
- tooLarge
675
- });
721
+ HarnessLog.warn('model over memory cap', { need, used: this._used(), over, tooLarge });
676
722
  return;
677
723
  }
678
724
  tried.add(victim.id);
@@ -680,6 +726,7 @@ export class Residency {
680
726
  if (tooLarge && room.recheck) {
681
727
  tooLarge = await room.recheck();
682
728
  }
729
+ over = this._over(need);
683
730
  }
684
731
  }
685
732
  _capVictims({ replying = false, generators = false }) {
@@ -689,11 +736,12 @@ export class Residency {
689
736
  id: 'generators',
690
737
  rank: VictimRank.generator,
691
738
  lastUsed: 0,
739
+ pools: undefined,
692
740
  evict: () => this.unloadIdleGenerators()
693
741
  });
694
742
  }
695
743
  for (const [index, pool] of this._pools().entries()) {
696
- for (const { key, refs, lastUsed } of settledEntries(pool)) {
744
+ for (const { key, refs, lastUsed, pools } of settledEntries(pool)) {
697
745
  const inReply = this._replying.includes(key);
698
746
  if (refs > 0 || (inReply && !replying)) {
699
747
  continue;
@@ -702,6 +750,7 @@ export class Residency {
702
750
  id: `${index}:${key}`,
703
751
  rank: this._victimRank(pool, key, inReply),
704
752
  lastUsed,
753
+ pools: pools && this._placed(pools),
705
754
  evict: () => evictIdleWithin(pool, key, { deadlineMs: WEDGED_EVICT_WAIT_MS })
706
755
  });
707
756
  }
@@ -715,8 +764,60 @@ export class Residency {
715
764
  return VictimRank.replying;
716
765
  return this._pinned.has(key) ? VictimRank.pinned : VictimRank.requested;
717
766
  }
718
- _usedBytes() {
719
- return this.settledBytes() + [...this._reserved.values()].reduce((sum, bytes) => sum + bytes, 0);
767
+ _used() {
768
+ return this._placed(sumPools([...this._settledPools(), ...this._reserved.values(), ...this._generatorPools()]));
769
+ }
770
+ _generatorPools() {
771
+ return [...this._generators.values()].map(({ pools }) => pools);
772
+ }
773
+ _generatorsInTheWay(need, freed, admitted) {
774
+ if (this._generators.size === 0 || this._over(need, freed).length === 0) {
775
+ return false;
776
+ }
777
+ return admitted || this._over(need, sumPools([freed, ...this._generatorPools()])).length === 0;
778
+ }
779
+ async _unloadIdleHeld() {
780
+ await Promise.allSettled([...this._generators.values()].map((held) => held.unloadIdle()));
781
+ }
782
+ _settledPools() {
783
+ return this._pools()
784
+ .flatMap((pool) => settledEntries(pool))
785
+ .flatMap(sizedPools);
786
+ }
787
+ _over(need, freed = {}) {
788
+ const back = this._placed(freed);
789
+ const used = Object.fromEntries(Object.entries(this._used()).map(([pool, bytes]) => [pool, bytes - (back[pool] ?? 0)]));
790
+ return poolsOver(used, this._placed(need), (pool) => this._capOf(pool));
791
+ }
792
+ _placed(pools) {
793
+ const { [BUDGET_POOL]: unplaced, ...placed } = pools;
794
+ return unplaced === undefined ? pools : sumPools([placed, { [this._mainPool()]: unplaced }]);
795
+ }
796
+ _capOf(pool) {
797
+ const memory = this._memoryOf(pool);
798
+ return this._capPercent === null || memory === undefined
799
+ ? null
800
+ : memoryCapBytes(this._capPercent, memory);
801
+ }
802
+ _memoryOf(pool) {
803
+ const named = this.fit.capacity().get(pool);
804
+ const budgeted = this._budget && this._budgeted(pool) ? this._budget.availableBytes : undefined;
805
+ if (named === undefined || budgeted === undefined) {
806
+ return named ?? budgeted;
807
+ }
808
+ return Math.min(named, budgeted);
809
+ }
810
+ _budgeted(pool) {
811
+ if (this._budget?.source === 'vram') {
812
+ return pool === this._mainPool();
813
+ }
814
+ return pool === HOST_POOL;
815
+ }
816
+ _mainPool() {
817
+ if (this._budget?.source !== 'vram') {
818
+ return HOST_POOL;
819
+ }
820
+ return [...this.fit.capacity().keys()].find((pool) => pool !== HOST_POOL) ?? BUDGET_POOL;
720
821
  }
721
822
  async _fits(model, loadOpts, { native = false } = {}) {
722
823
  const asset = curatedModelAsset(model, 'llm');
@@ -864,7 +965,7 @@ export class Residency {
864
965
  }
865
966
  }
866
967
  async makeRoomForCompletion(model, { loadOpts, signal, deadlineMs = MODEL_ROOM_WAIT_MS }) {
867
- if (this._capBytes !== null) {
968
+ if (this._capPercent !== null) {
868
969
  await evictIdleWhere(this._models, this._replacedBy(model));
869
970
  return true;
870
971
  }
@@ -941,4 +1042,10 @@ export class Residency {
941
1042
  }
942
1043
  }
943
1044
  }
1045
+ function sizedPools({ pools }) {
1046
+ return pools ? [pools] : [];
1047
+ }
1048
+ function holdsAny(pools, over) {
1049
+ return over.length === 0 || pools === undefined || over.some((pool) => (pools[pool] ?? 0) > 0);
1050
+ }
944
1051
  function noop() { }
@@ -10,5 +10,8 @@ export interface RunLogBoundaryOptions {
10
10
  redactRecord?: (record: RunRecord) => RunRecord;
11
11
  redactStep?: (step: EngineStep) => EngineStep;
12
12
  }
13
- export declare function openBoundaryJournal(options: RunLogBoundaryOptions): RunJournal;
13
+ export interface RunLogBoundaryMode {
14
+ transient?: boolean;
15
+ }
16
+ export declare function openBoundaryJournal(options: RunLogBoundaryOptions, mode?: RunLogBoundaryMode): RunJournal;
14
17
  export declare function boundaryBoot(journal: RunJournal): EngineBoot;
@@ -1,9 +1,10 @@
1
1
  import { applyEngineStep, captureEngineStep, captureRunRecord, createEngineStep, prepareEngineBoot } from './protocol.js';
2
2
  import { ENGINE_BOUNDARY_BOOT, RunJournal } from './run-journal.js';
3
- export function openBoundaryJournal(options) {
3
+ export function openBoundaryJournal(options, mode = {}) {
4
4
  const log = boundaryLog(options);
5
5
  return new RunJournal(log, {
6
6
  boot: log[ENGINE_BOUNDARY_BOOT](),
7
+ transient: mode.transient,
7
8
  redact: options.redact,
8
9
  redactShared: options.redactShared,
9
10
  redactOperationResult: options.redactOperationResult,
@@ -2,7 +2,7 @@ import { inspectRun, recordLog, renderRunLogHtml } from './inspect.ts';
2
2
  import { RunLogWatch } from './live.ts';
3
3
  import { createRunLogRedactor } from './redact.ts';
4
4
  import { parsePersistedSnapshot, replayRun } from './replay.ts';
5
- import { createPersistedActor } from './persisted-actor.ts';
5
+ import { createPersistedActor, createTransientActor } from './persisted-actor.ts';
6
6
  import { boundaryBoot, openBoundaryJournal } from './boundary.ts';
7
7
  import { applyEngineStep, buildEngineBoot, contextFromBoot, createEngineBoot, requestFromBoot, validateEngineBoot } from './protocol.ts';
8
8
  import { RunJournal, acquireRun, forkRepeatsSettledWrite, readRequests, readRunLog, recoveryAdvice, safeForkLength, unresolvedWriteIds, unsettledRedactedIds } from './run-journal.ts';
@@ -33,6 +33,7 @@ export declare class RunLog extends RunJournal {
33
33
  static openBoundary: typeof openBoundaryJournal;
34
34
  static boundaryBoot: typeof boundaryBoot;
35
35
  static createPersistedActor: typeof createPersistedActor;
36
+ static createTransientActor: typeof createTransientActor;
36
37
  static acquireRun: typeof acquireRun;
37
38
  }
38
39
  export { InvalidEngineStep } from './protocol.ts';
@@ -2,7 +2,7 @@ import { inspectRun, recordLog, renderRunLogHtml } from './inspect.js';
2
2
  import { RunLogWatch } from './live.js';
3
3
  import { createRunLogRedactor } from './redact.js';
4
4
  import { parsePersistedSnapshot, replayRun } from './replay.js';
5
- import { createPersistedActor } from './persisted-actor.js';
5
+ import { createPersistedActor, createTransientActor } from './persisted-actor.js';
6
6
  import { boundaryBoot, openBoundaryJournal } from './boundary.js';
7
7
  import { RUN_LOG_PROTOCOL_VERSION, RUN_LOG_VERSION, applyEngineStep, buildEngineBoot, contextFromBoot, createEngineBoot, requestFromBoot, validateEngineBoot } from './protocol.js';
8
8
  import { XSTATE_VERSION, RunJournal, acquireRun, forkRepeatsSettledWrite, readRequests, readRunLog, recoveryAdvice, safeForkLength, unresolvedWriteIds, unsettledRedactedIds } from './run-journal.js';
@@ -33,6 +33,7 @@ export class RunLog extends RunJournal {
33
33
  static openBoundary = openBoundaryJournal;
34
34
  static boundaryBoot = boundaryBoot;
35
35
  static createPersistedActor = createPersistedActor;
36
+ static createTransientActor = createTransientActor;
36
37
  static acquireRun = acquireRun;
37
38
  }
38
39
  export { InvalidEngineStep } from './protocol.js';
@@ -1,3 +1,4 @@
1
+ import { CompletionMachine } from '../machine/index.ts';
1
2
  import { type AnyStateMachine, type Actor } from 'xstate';
2
3
  import { RunJournal } from './run-journal.ts';
3
4
  import type { MachineLog } from './protocol-types.ts';
@@ -10,4 +11,13 @@ export interface PersistedActor<Machine extends AnyStateMachine> {
10
11
  dispose(): Promise<void>;
11
12
  };
12
13
  }
14
+ export interface TransientActor<Machine extends AnyStateMachine> {
15
+ actor: Actor<Machine>;
16
+ persistence: {
17
+ checkpoint(): Promise<void>;
18
+ flush(): Promise<void>;
19
+ dispose(): Promise<void>;
20
+ };
21
+ }
22
+ export declare function createTransientActor(machine: ReturnType<typeof CompletionMachine.create>, journal: RunJournal, onFailure?: (error: Error) => void): TransientActor<ReturnType<typeof CompletionMachine.create>>;
13
23
  export declare function createPersistedActor<Machine extends AnyStateMachine>(core: MachineLog | RunJournal, machine: Machine, onFailure?: (error: Error) => void, now?: () => number): Promise<PersistedActor<Machine>>;
@@ -6,6 +6,21 @@ import { brandCapturedRecord, isCapturedJson } from './protocol.js';
6
6
  const CHECKPOINT_EVERY = 64;
7
7
  const ROOT_ACTOR_ID = 'qvac-completion-machine';
8
8
  const UNRECORDED = new Set(['OUTPUT', 'xstate.stop']);
9
+ export function createTransientActor(machine, journal, onFailure) {
10
+ const actor = createActor(machine, { id: ROOT_ACTOR_ID, input: undefined });
11
+ const noPersistence = () => Promise.resolve();
12
+ journal.onFailure = onFailure;
13
+ return {
14
+ actor,
15
+ persistence: {
16
+ checkpoint: noPersistence,
17
+ flush: () => journal.flush(),
18
+ async dispose() {
19
+ actor.stop();
20
+ }
21
+ }
22
+ };
23
+ }
9
24
  const noClock = () => 0;
10
25
  export async function createPersistedActor(core, machine, onFailure, now = noClock) {
11
26
  const journal = core instanceof RunJournal ? core : new RunJournal(core);
@@ -67,6 +67,7 @@ export declare class RunJournal {
67
67
  sealed: boolean;
68
68
  onFailure?: (error: Error) => void;
69
69
  readonly core: MachineLog;
70
+ readonly transient: boolean;
70
71
  restored: boolean;
71
72
  private readonly redact;
72
73
  private readonly redactShared;
@@ -97,6 +98,7 @@ export declare class RunJournal {
97
98
  pendingArgumentsWereRedacted(snapshot: unknown): boolean | null;
98
99
  append(record: RunRecord): Promise<void>;
99
100
  private fail;
101
+ private storeReceipt;
100
102
  hasPendingFlush(): boolean;
101
103
  flush(): Promise<void>;
102
104
  resolve(resolutions: readonly RecoveryResolution[]): Promise<void>;
@@ -109,6 +111,7 @@ interface RunJournalOptions {
109
111
  redactOperationResult?: <Value>(operation: Operation, value: Value) => Value;
110
112
  redactRecord?: (record: RunRecord) => RunRecord;
111
113
  boot?: EngineBoot;
114
+ transient?: boolean;
112
115
  }
113
116
  export declare function acquireRun(owner: object, runId: string): () => void;
114
117
  export declare class EventCodec {