@qvac/harness 1.0.1 → 1.2.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 (98) hide show
  1. package/CHANGELOG.md +171 -6
  2. package/README.md +39 -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 +33 -0
  6. package/dist-lib/lib/agent/child-run.js +58 -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 +7 -0
  10. package/dist-lib/lib/agent/index.js +5 -0
  11. package/dist-lib/lib/agent/read-parts.d.ts +47 -0
  12. package/dist-lib/lib/agent/read-parts.js +85 -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/model-round.d.ts +4 -1
  17. package/dist-lib/lib/capabilities/completion-engine/round.js +5 -4
  18. package/dist-lib/lib/client/index.js +1 -3
  19. package/dist-lib/lib/connect/decode.d.ts +3 -2
  20. package/dist-lib/lib/connect/decode.js +14 -0
  21. package/dist-lib/lib/connect.d.ts +1 -0
  22. package/dist-lib/lib/connect.js +11 -5
  23. package/dist-lib/lib/context-window.d.ts +2 -0
  24. package/dist-lib/lib/context-window.js +17 -14
  25. package/dist-lib/lib/contract/models.d.ts +13 -1
  26. package/dist-lib/lib/contract-types.d.ts +9 -0
  27. package/dist-lib/lib/harness.d.ts +269 -0
  28. package/dist-lib/lib/harness.js +1154 -0
  29. package/dist-lib/lib/models/custom-model-cache.d.ts +2 -0
  30. package/dist-lib/lib/models/custom-model-cache.js +21 -0
  31. package/dist-lib/lib/models/memory-cap.d.ts +6 -0
  32. package/dist-lib/lib/models/memory-cap.js +20 -0
  33. package/dist-lib/lib/models/model-catalog.d.ts +2 -0
  34. package/dist-lib/lib/models/model-catalog.js +8 -2
  35. package/dist-lib/lib/models/model-fit.d.ts +59 -10
  36. package/dist-lib/lib/models/model-fit.js +172 -35
  37. package/dist-lib/lib/models/model-handle.d.ts +2 -1
  38. package/dist-lib/lib/models/model-pool.d.ts +3 -2
  39. package/dist-lib/lib/models/model-pool.js +30 -13
  40. package/dist-lib/lib/models/tts-model-default.d.ts +1 -1
  41. package/dist-lib/lib/models/tts-model-default.js +7 -6
  42. package/dist-lib/lib/residency/completion-runtime.d.ts +1 -1
  43. package/dist-lib/lib/residency/completion-runtime.js +1 -1
  44. package/dist-lib/lib/residency/index.d.ts +31 -9
  45. package/dist-lib/lib/residency/index.js +286 -88
  46. package/dist-lib/lib/run-log/boundary.d.ts +4 -1
  47. package/dist-lib/lib/run-log/boundary.js +2 -1
  48. package/dist-lib/lib/run-log/index.d.ts +2 -1
  49. package/dist-lib/lib/run-log/index.js +2 -1
  50. package/dist-lib/lib/run-log/persisted-actor.d.ts +10 -0
  51. package/dist-lib/lib/run-log/persisted-actor.js +15 -0
  52. package/dist-lib/lib/run-log/run-journal.d.ts +3 -0
  53. package/dist-lib/lib/run-log/run-journal.js +19 -8
  54. package/dist-lib/lib/serve/requests.d.ts +3 -0
  55. package/dist-lib/lib/serve.js +3 -0
  56. package/dist-lib/lib/spawn.d.ts +4 -1
  57. package/dist-lib/lib/tools/exec.d.ts +2 -0
  58. package/dist-lib/lib/tools/exec.js +29 -1
  59. package/dist-lib/lib/tools/files/list-dir.js +79 -32
  60. package/dist-lib/lib/tools/fs/walk.d.ts +11 -1
  61. package/dist-lib/lib/tools/fs/walk.js +64 -30
  62. package/dist-lib/lib/tools/office.js +8 -5
  63. package/dist-lib/lib/tools/pdf/pages.d.ts +1 -1
  64. package/dist-lib/lib/tools/pdf/pages.js +3 -14
  65. package/dist-lib/lib/tools/pdf/recognize.d.ts +3 -0
  66. package/dist-lib/lib/tools/pdf/recognize.js +45 -7
  67. package/dist-lib/plugins/image/generate-image.d.ts +2 -2
  68. package/dist-lib/plugins/image/generate-image.js +9 -1
  69. package/dist-lib/plugins/image/index.js +6 -2
  70. package/dist-lib/plugins/knowledge/chunk-index.d.ts +4 -0
  71. package/dist-lib/plugins/knowledge/chunk-index.js +191 -0
  72. package/dist-lib/plugins/knowledge/index.d.ts +1 -0
  73. package/dist-lib/plugins/knowledge/index.js +1 -0
  74. package/dist-lib/plugins/knowledge/manifest.d.ts +2 -1
  75. package/dist-lib/plugins/knowledge/manifest.js +2 -9
  76. package/dist-lib/plugins/knowledge/store.d.ts +5 -1
  77. package/dist-lib/plugins/knowledge/store.js +44 -16
  78. package/dist-lib/plugins/lsp/rpc.d.ts +9 -1
  79. package/dist-lib/plugins/lsp/rpc.js +81 -17
  80. package/dist-lib/plugins/music/generate-music.d.ts +2 -2
  81. package/dist-lib/plugins/music/generate-music.js +14 -1
  82. package/dist-lib/plugins/music/index.js +4 -1
  83. package/dist-lib/plugins/sandbox-windows/prebuilds/win32-arm64/qvac-sandbox.exe +0 -0
  84. package/dist-lib/plugins/sandbox-windows/prebuilds/win32-x64/qvac-sandbox.exe +0 -0
  85. package/dist-lib/plugins/speech/speech-engine.d.ts +5 -2
  86. package/dist-lib/plugins/speech/speech-engine.js +28 -7
  87. package/dist-lib/schema/harness.js +28 -2
  88. package/dist-lib/spec/bind.js +3 -0
  89. package/dist-lib/spec/calls.js +1 -0
  90. package/dist-lib/spec/hrpc/hrpc.json +13 -0
  91. package/dist-lib/spec/hrpc/index.js +15 -3
  92. package/dist-lib/spec/hrpc/messages.js +87 -6
  93. package/dist-lib/spec/hyperschema/index.js +87 -6
  94. package/dist-lib/spec/hyperschema/schema.json +70 -2
  95. package/dist-lib/spec/hyperschema/types.d.ts +21 -1
  96. package/package.json +29 -28
  97. package/scripts/addon-externals.cjs +1 -0
  98. package/worker/harness-sidecar.mjs +12 -1
@@ -8,9 +8,10 @@ import { ContextChoice as ContextClimb } from '../models/context-choice.js';
8
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
+ import { adrenoSafeKvCache } from '../models/kv-cache.js';
11
12
  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';
13
+ import { BUDGET_POOL, HOST_POOL, memoryCapBytes, nextVictim, poolsOver, sumPools, totalBytes, VictimRank } from '../models/memory-cap.js';
14
+ import { assetBytes, curatedListables, curatedModelAsset, customContextLength, customModelSrc, generatorRowName, modelAddonOf, speculativeDraft } from '../models/model-catalog.js';
14
15
  import { ModelFit } from '../models/model-fit.js';
15
16
  import { createModelStatusCache, invalidateModelStatusCache } from '../models/model-list.js';
16
17
  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';
@@ -23,6 +24,9 @@ const WARM_ROOM_WAIT_MS = 2_000;
23
24
  const LOAD_BUSY_MESSAGE = 'the chat model is busy; load this model once the current reply finishes';
24
25
  const UNLOAD_LEASE_WAIT_MS = 10_000;
25
26
  const DEFAULT_COMPLETION_MODEL_CAP = 1;
27
+ const MAX_PARALLEL_SLOTS = 4;
28
+ const PARALLEL_CHOICE_MS = 10 * 60_000;
29
+ const SWAP_HEADROOM = 0.9;
26
30
  const WEDGED_EVICT_LEASED_MS = 120_000;
27
31
  function fitSrc(modelSrc) {
28
32
  if (typeof modelSrc === 'string')
@@ -44,7 +48,7 @@ function stagesBytes(srcs) {
44
48
  export class Residency {
45
49
  gate;
46
50
  sdk;
47
- fit = new ModelFit(async (input) => (await this.sdk.load()).assessModelFit(input));
51
+ 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
52
  requests = createLoadRequests((state) => this.notify(state));
49
53
  _loads;
50
54
  _emit;
@@ -60,6 +64,7 @@ export class Residency {
60
64
  _pinned = new Set();
61
65
  _borrowed = new Set();
62
66
  _replying = [];
67
+ _parallel = new Map();
63
68
  _modelStatus = createModelStatusCache();
64
69
  _llmDevice;
65
70
  _llmGpuLayers;
@@ -75,8 +80,10 @@ export class Residency {
75
80
  _hold;
76
81
  _capability;
77
82
  _sizeLoads = false;
78
- _capBytes = null;
83
+ _capPercent = null;
84
+ _budget = null;
79
85
  _reserved = new Map();
86
+ _generators = new Map();
80
87
  _contexts = new ContextClimb(() => this._contextProfile());
81
88
  _admission = new ScopeLock();
82
89
  _byHand = new Map();
@@ -135,6 +142,7 @@ export class Residency {
135
142
  this._models = this._createPool();
136
143
  }
137
144
  destroy() {
145
+ this.fit.clearRows();
138
146
  return this._models?.destroy();
139
147
  }
140
148
  setIdleTimeout(ms) {
@@ -152,45 +160,79 @@ export class Residency {
152
160
  }
153
161
  async setMemoryCap(percent) {
154
162
  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);
163
+ const { memoryBudget } = await this._capability();
164
+ this._budget = memoryBudget ?? null;
165
+ this._capPercent = percent > 0 && memoryBudget ? percent : null;
166
+ HarnessLog.info('memory cap', {
167
+ percent,
168
+ capBytes: memoryBudget && this._capOf(this._mainPool())
169
+ });
170
+ if (this._capPercent !== null) {
171
+ await this.busy(() => this._admit(() => this._makeRoom({}, { generators: true })));
172
+ }
173
+ }
174
+ budgetedBytes() {
175
+ return Object.entries(this._placed(sumPools([...this._settledPools(), ...this._generatorPools()])))
176
+ .filter(([pool]) => this._budgeted(pool))
177
+ .reduce((sum, [, bytes]) => sum + bytes, 0);
178
+ }
179
+ poolUsage() {
180
+ const used = this._placed(sumPools([...this._settledPools(), ...this._generatorPools()]));
181
+ const capacity = this.fit.capacity();
182
+ const ids = new Set([this._mainPool(), ...capacity.keys(), ...Object.keys(used)]);
183
+ return [...ids].map((id) => ({
184
+ id,
185
+ usedBytes: used[id] ?? 0,
186
+ capBytes: this._capOf(id) ?? undefined,
187
+ totalBytes: this._memoryOf(id)
188
+ }));
169
189
  }
170
190
  memoryByModel() {
171
191
  const memory = new Map();
172
- for (const { key, bytes } of this._pools().flatMap((pool) => settledEntries(pool))) {
173
- if (bytes === undefined)
192
+ for (const { key, pools } of this._pools().flatMap((pool) => settledEntries(pool))) {
193
+ if (pools === undefined)
174
194
  continue;
175
195
  const model = modelOf(key);
176
- memory.set(model, (memory.get(model) ?? 0) + bytes);
196
+ memory.set(model, (memory.get(model) ?? 0) + totalBytes(pools));
197
+ }
198
+ for (const [model, { pools }] of this._generators) {
199
+ memory.set(model, totalBytes(pools));
177
200
  }
178
201
  return memory;
179
202
  }
180
- async makeRoomForPlugin(signal, busy, srcs = []) {
181
- if (this._capBytes !== null && !this._models.destroyed) {
182
- await this._makeRoomForGenerator(srcs, signal);
183
- return;
203
+ async makeRoomForPlugin(signal, busy, load = []) {
204
+ if (this._capPercent !== null && !this._models.destroyed) {
205
+ await this._makeRoomForGenerator('srcs' in load ? load.srcs : load, signal);
184
206
  }
185
- if (!(await this._roomForPlugin(signal, PLUGIN_EVICT_WAIT_MS))) {
207
+ else if (!(await this._roomForPlugin(signal, PLUGIN_EVICT_WAIT_MS))) {
186
208
  throw typeof busy === 'string' ? new Error(busy) : busy;
187
209
  }
210
+ return 'srcs' in load ? this._holdGenerator(load) : noop;
211
+ }
212
+ _holdGenerator({ srcs, unloadIdle }) {
213
+ const [lead] = srcs;
214
+ const bytes = stagesBytes(srcs);
215
+ if (!this._sizeLoads || lead === undefined || bytes === 0) {
216
+ return noop;
217
+ }
218
+ const model = generatorRowName(lead);
219
+ const held = { pools: { [BUDGET_POOL]: bytes }, unloadIdle };
220
+ this._generators.set(model, held);
221
+ return () => {
222
+ if (this._generators.get(model) === held) {
223
+ this._generators.delete(model);
224
+ }
225
+ };
188
226
  }
189
227
  async _makeRoomForGenerator(srcs, signal) {
190
228
  if (signal?.aborted) {
191
229
  throw new AbortedError();
192
230
  }
193
- await this._makeRoom(stagesBytes(srcs), { replying: true });
231
+ const need = { [BUDGET_POOL]: stagesBytes(srcs) };
232
+ if (this._over(need).length > 0) {
233
+ await this._unloadIdleHeld();
234
+ }
235
+ await this._makeRoom(need, { replying: true });
194
236
  if (signal?.aborted) {
195
237
  throw new AbortedError();
196
238
  }
@@ -320,13 +362,14 @@ export class Residency {
320
362
  return new Map();
321
363
  }
322
364
  return this.fit
323
- .rows(() => this._rowQueries())
365
+ .rows(() => this._rowQueries(rows))
324
366
  .catch((err) => {
325
367
  HarnessLog.warn('fit estimate failed', { rows: rows.length, err: errorMessage(err) });
326
368
  return new Map();
327
369
  });
328
370
  }
329
- _rowQueries() {
371
+ _rowQueries(rows) {
372
+ const downloaded = new Set(rows.filter((row) => row.isCached).map((row) => row.registryPath));
330
373
  return new Map(curatedListables()
331
374
  .filter((listable) => listable.asset.addon === 'llm')
332
375
  .map(({ name, asset }) => {
@@ -334,10 +377,10 @@ export class Residency {
334
377
  opts: this.loadOptions(name),
335
378
  deviceConfig: this.deviceConfig()
336
379
  };
337
- return [
338
- asset.registryPath,
339
- ModelFit.query(asset, contextSize(name, asset, load) * slotCount(name, load))
340
- ];
380
+ const query = ModelFit.query(asset, contextSize(name, asset, load) * slotCount(name, load), {
381
+ native: true
382
+ });
383
+ return [asset.registryPath, { ...query, onDisk: downloaded.has(asset.registryPath) }];
341
384
  }));
342
385
  }
343
386
  async warm({ model, agent, signal }) {
@@ -356,7 +399,7 @@ export class Residency {
356
399
  return true;
357
400
  }
358
401
  if (target.needsRoom) {
359
- return this._capBytes !== null || this._roomForPlugin(signal, WARM_ROOM_WAIT_MS);
402
+ return this._capPercent !== null || this._roomForPlugin(signal, WARM_ROOM_WAIT_MS);
360
403
  }
361
404
  if (!target.loadOpts) {
362
405
  return true;
@@ -457,12 +500,12 @@ export class Residency {
457
500
  await this._unloadIdlePlugins();
458
501
  }
459
502
  async _yieldGenerators() {
460
- if (this._capBytes === null) {
503
+ if (this._capPercent === null) {
461
504
  await this.unloadIdleGenerators();
462
505
  }
463
506
  }
464
507
  async _admitByHand(model, target, signal) {
465
- if (this._capBytes === null) {
508
+ if (this._capPercent === null) {
466
509
  return this._chooseByHand(model, target, signal);
467
510
  }
468
511
  return this._admit(async () => {
@@ -470,17 +513,18 @@ export class Residency {
470
513
  return true;
471
514
  }
472
515
  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);
516
+ const replaced = sumPools(this._replacedEntries(model, target).flatMap(sizedPools));
476
517
  const alone = this._alone(model, target);
477
- const fits = capBytes === null || alone || sized.bytes === undefined || used + sized.bytes <= capBytes;
518
+ if (sized.pools && this._generatorsInTheWay(sized.pools, replaced, alone)) {
519
+ await this._unloadIdleHeld();
520
+ }
521
+ const fits = alone || sized.pools === undefined || this._over(sized.pools, replaced).length === 0;
478
522
  if ((sized.tooLarge && !alone) || !fits) {
479
523
  return false;
480
524
  }
481
525
  this._byHand.set(target.key, sized.ctxSize);
482
- if (sized.bytes !== undefined) {
483
- this._reserved.set(target.key, sized.bytes);
526
+ if (sized.pools !== undefined) {
527
+ this._reserved.set(target.key, sized.pools);
484
528
  }
485
529
  return true;
486
530
  });
@@ -493,7 +537,7 @@ export class Residency {
493
537
  if (choice?.fits === false) {
494
538
  return this._alone(model, target);
495
539
  }
496
- if (choice && !target.loadOpts.ctxSize && !signal?.aborted) {
540
+ if (choice && !signal?.aborted) {
497
541
  this.fit.keep(target.key, choice);
498
542
  }
499
543
  return true;
@@ -553,35 +597,35 @@ export class Residency {
553
597
  async beforeLoad(load) {
554
598
  if (!this._sizeLoads)
555
599
  return undefined;
556
- const bytes = this._byHand.has(load.key)
600
+ const pools = this._byHand.has(load.key)
557
601
  ? await this._admit(() => this._reserveByHand(load))
558
602
  : await this._admit(() => this._reserve(load));
559
- return { bytes, release: () => this._reserved.delete(load.key) };
603
+ return { pools, release: () => this._reserved.delete(load.key) };
560
604
  }
561
605
  async _reserveByHand(load) {
562
606
  const admittedAt = this._byHand.get(load.key);
563
607
  this._byHand.delete(load.key);
564
608
  if (load.modelConfig?.['ctx_size'] !== admittedAt) {
565
- const { bytes } = await this._sizeLoad(load);
566
- if (bytes !== undefined) {
567
- this._reserved.set(load.key, bytes);
609
+ const { pools } = await this._sizeLoad(load);
610
+ if (pools !== undefined) {
611
+ this._reserved.set(load.key, pools);
568
612
  }
569
613
  }
570
614
  return this._reserved.get(load.key);
571
615
  }
572
616
  async _reserve(load) {
573
617
  const sized = await this._sizeLoad(load);
574
- if (this._capBytes !== null) {
575
- await this._makeRoom(sized.bytes ?? 0, {
618
+ if (this._capPercent !== null) {
619
+ await this._makeRoom(sized.pools ?? {}, {
576
620
  generators: true,
577
621
  tooLarge: sized.tooLarge,
578
622
  recheck: async () => (await this._sizeLoad(load)).tooLarge
579
623
  });
580
624
  }
581
- if (sized.bytes !== undefined) {
582
- this._reserved.set(load.key, sized.bytes);
625
+ if (sized.pools !== undefined) {
626
+ this._reserved.set(load.key, sized.pools);
583
627
  }
584
- return sized.bytes;
628
+ return sized.pools;
585
629
  }
586
630
  async _sizeLoad({ model, modelSrc, modelType, modelConfig }) {
587
631
  const downloaded = downloadBytes(modelSrc);
@@ -589,26 +633,39 @@ export class Residency {
589
633
  const companions = (downloadBytes(projectionModelSrc) ?? 0) + (downloadBytes(draftModelSrc) ?? 0);
590
634
  try {
591
635
  const sdk = await this.sdk.load();
592
- const { models } = await sdk.assessModelFit({
593
- models: [{ modelSrc: fitSrc(modelSrc), modelType, modelConfig: config }]
636
+ const file = typeof modelSrc === 'string'
637
+ ? undefined
638
+ : await ModelFit.downloaded(sdk, modelSrc.name, modelSrc.sha256Checksum);
639
+ const { models, pools } = await sdk.assessModelFit({
640
+ models: [{ modelSrc: file ?? fitSrc(modelSrc), modelType, modelConfig: config }]
594
641
  });
595
- const [fit] = models;
596
- const bytes = fit?.floorBytes ?? downloaded;
642
+ this.fit.observe(pools);
643
+ const fit = ModelFit.judge(models[0]);
597
644
  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'
645
+ pools: this._withUnfitted(fit.bytes === undefined ? undefined : fit.pools, {
646
+ downloaded,
647
+ companions
648
+ }),
649
+ tooLarge: fit.verdict === 'likely-too-large',
650
+ confirmed: ModelFit.confirms(fit)
601
651
  };
602
652
  }
603
653
  catch (err) {
604
654
  HarnessLog.warn('fit estimate failed', { model, err: errorMessage(err) });
605
655
  return {
606
- bytes: downloaded === undefined ? undefined : downloaded + companions,
656
+ pools: this._withUnfitted(undefined, { downloaded, companions }),
607
657
  tooLarge: false,
608
658
  confirmed: false
609
659
  };
610
660
  }
611
661
  }
662
+ _withUnfitted(fitted, { downloaded, companions }) {
663
+ if (fitted === undefined && downloaded === undefined) {
664
+ return undefined;
665
+ }
666
+ const unfitted = (fitted ? 0 : (downloaded ?? 0)) + companions;
667
+ return sumPools([fitted ?? {}, { [BUDGET_POOL]: unfitted }]);
668
+ }
612
669
  async _chooseContext(load, tier) {
613
670
  if (this._borrowed.has(load.model)) {
614
671
  HarnessLog.info('context climb', { tier, stop: 'borrowed' });
@@ -621,19 +678,22 @@ export class Residency {
621
678
  fits: async (rung) => {
622
679
  const sized = await this._sizeLoad({
623
680
  ...load,
624
- modelConfig: { ...load.modelConfig, ctx_size: rung * slots }
681
+ modelConfig: {
682
+ gpu_layers: ModelFit.ALL_LAYERS,
683
+ ...load.modelConfig,
684
+ ctx_size: rung * slots
685
+ }
625
686
  });
626
- const room = this._capRoom(load.key);
627
- return sized.confirmed && (room === null || (sized.bytes ?? Infinity) <= room);
687
+ if (!sized.confirmed || this._capPercent === null) {
688
+ return sized.confirmed;
689
+ }
690
+ return (sized.pools !== undefined &&
691
+ this._over(sized.pools, this._reserved.get(load.key)).length === 0);
628
692
  }
629
693
  });
630
694
  HarnessLog.info('context chosen', { model: load.model, tier, ctxSize });
631
695
  return ctxSize;
632
696
  }
633
- _capRoom(key) {
634
- const cap = this._capBytes;
635
- return cap === null ? null : cap - (this._usedBytes() - (this._reserved.get(key) ?? 0));
636
- }
637
697
  async _contextProfile() {
638
698
  const { capabilityProfile, memoryBudget } = await this._capability();
639
699
  return memoryBudget ? capabilityProfile : undefined;
@@ -658,21 +718,16 @@ export class Residency {
658
718
  }
659
719
  }
660
720
  async _makeRoom(need, room) {
661
- const capBytes = this._capBytes;
662
- if (capBytes === null) {
721
+ if (this._capPercent === null) {
663
722
  return;
664
723
  }
665
724
  const tried = new Set();
666
725
  let tooLarge = room.tooLarge ?? false;
667
- while (this._usedBytes() + need > capBytes || tooLarge) {
668
- const victim = nextVictim(this._capVictims(room).filter(({ id }) => !tried.has(id)));
726
+ let over = this._over(need);
727
+ while (over.length > 0 || tooLarge) {
728
+ const victim = nextVictim(this._capVictims(room).filter(({ id, pools }) => !tried.has(id) && holdsAny(pools, over)));
669
729
  if (!victim) {
670
- HarnessLog.warn('model over memory cap', {
671
- need,
672
- used: this._usedBytes(),
673
- capBytes,
674
- tooLarge
675
- });
730
+ HarnessLog.warn('model over memory cap', { need, used: this._used(), over, tooLarge });
676
731
  return;
677
732
  }
678
733
  tried.add(victim.id);
@@ -680,6 +735,7 @@ export class Residency {
680
735
  if (tooLarge && room.recheck) {
681
736
  tooLarge = await room.recheck();
682
737
  }
738
+ over = this._over(need);
683
739
  }
684
740
  }
685
741
  _capVictims({ replying = false, generators = false }) {
@@ -689,11 +745,12 @@ export class Residency {
689
745
  id: 'generators',
690
746
  rank: VictimRank.generator,
691
747
  lastUsed: 0,
748
+ pools: undefined,
692
749
  evict: () => this.unloadIdleGenerators()
693
750
  });
694
751
  }
695
752
  for (const [index, pool] of this._pools().entries()) {
696
- for (const { key, refs, lastUsed } of settledEntries(pool)) {
753
+ for (const { key, refs, lastUsed, pools } of settledEntries(pool)) {
697
754
  const inReply = this._replying.includes(key);
698
755
  if (refs > 0 || (inReply && !replying)) {
699
756
  continue;
@@ -702,6 +759,7 @@ export class Residency {
702
759
  id: `${index}:${key}`,
703
760
  rank: this._victimRank(pool, key, inReply),
704
761
  lastUsed,
762
+ pools: pools && this._placed(pools),
705
763
  evict: () => evictIdleWithin(pool, key, { deadlineMs: WEDGED_EVICT_WAIT_MS })
706
764
  });
707
765
  }
@@ -715,8 +773,60 @@ export class Residency {
715
773
  return VictimRank.replying;
716
774
  return this._pinned.has(key) ? VictimRank.pinned : VictimRank.requested;
717
775
  }
718
- _usedBytes() {
719
- return this.settledBytes() + [...this._reserved.values()].reduce((sum, bytes) => sum + bytes, 0);
776
+ _used() {
777
+ return this._placed(sumPools([...this._settledPools(), ...this._reserved.values(), ...this._generatorPools()]));
778
+ }
779
+ _generatorPools() {
780
+ return [...this._generators.values()].map(({ pools }) => pools);
781
+ }
782
+ _generatorsInTheWay(need, freed, admitted) {
783
+ if (this._generators.size === 0 || this._over(need, freed).length === 0) {
784
+ return false;
785
+ }
786
+ return admitted || this._over(need, sumPools([freed, ...this._generatorPools()])).length === 0;
787
+ }
788
+ async _unloadIdleHeld() {
789
+ await Promise.allSettled([...this._generators.values()].map((held) => held.unloadIdle()));
790
+ }
791
+ _settledPools() {
792
+ return this._pools()
793
+ .flatMap((pool) => settledEntries(pool))
794
+ .flatMap(sizedPools);
795
+ }
796
+ _over(need, freed = {}) {
797
+ const back = this._placed(freed);
798
+ const used = Object.fromEntries(Object.entries(this._used()).map(([pool, bytes]) => [pool, bytes - (back[pool] ?? 0)]));
799
+ return poolsOver(used, this._placed(need), (pool) => this._capOf(pool));
800
+ }
801
+ _placed(pools) {
802
+ const { [BUDGET_POOL]: unplaced, ...placed } = pools;
803
+ return unplaced === undefined ? pools : sumPools([placed, { [this._mainPool()]: unplaced }]);
804
+ }
805
+ _capOf(pool) {
806
+ const memory = this._memoryOf(pool);
807
+ return this._capPercent === null || memory === undefined
808
+ ? null
809
+ : memoryCapBytes(this._capPercent, memory);
810
+ }
811
+ _memoryOf(pool) {
812
+ const named = this.fit.capacity().get(pool);
813
+ const budgeted = this._budget && this._budgeted(pool) ? this._budget.availableBytes : undefined;
814
+ if (named === undefined || budgeted === undefined) {
815
+ return named ?? budgeted;
816
+ }
817
+ return Math.min(named, budgeted);
818
+ }
819
+ _budgeted(pool) {
820
+ if (this._budget?.source === 'vram') {
821
+ return pool === this._mainPool();
822
+ }
823
+ return pool === HOST_POOL;
824
+ }
825
+ _mainPool() {
826
+ if (this._budget?.source !== 'vram') {
827
+ return HOST_POOL;
828
+ }
829
+ return [...this.fit.capacity().keys()].find((pool) => pool !== HOST_POOL) ?? BUDGET_POOL;
720
830
  }
721
831
  async _fits(model, loadOpts, { native = false } = {}) {
722
832
  const asset = curatedModelAsset(model, 'llm');
@@ -733,13 +843,26 @@ export class Residency {
733
843
  if (!asset) {
734
844
  return null;
735
845
  }
736
- const load = { opts: loadOpts, deviceConfig: this.deviceConfig() };
846
+ const deviceConfig = this.deviceConfig();
847
+ const load = { opts: loadOpts, deviceConfig };
737
848
  const tier = contextSize(model, asset, load);
738
849
  const slots = slotCount(model, load);
739
- if (loadOpts.ctxSize || this.fit.chosen(modelKey(model, loadOpts))) {
850
+ if (this.fit.chosen(modelKey(model, loadOpts))) {
740
851
  return { ctxSize: tier, slots, fits: await this._fits(model, loadOpts, { native: true }) };
741
852
  }
742
- return this.fit.ladder(asset, tier, slots);
853
+ const { device, gpuLayers } = deviceConfig;
854
+ const { k: kvCacheK, v: kvCacheV } = adrenoSafeKvCache(device, {
855
+ k: loadOpts.kvCacheK,
856
+ v: loadOpts.kvCacheV
857
+ });
858
+ return this.fit.ladder(asset, tier, {
859
+ slots,
860
+ kvCacheK,
861
+ kvCacheV,
862
+ device,
863
+ gpuLayers,
864
+ rungs: !loadOpts.ctxSize
865
+ });
743
866
  }
744
867
  async _yieldPins(model, loadOpts) {
745
868
  for (const key of this._pinned) {
@@ -845,11 +968,73 @@ export class Residency {
845
968
  releaseWork();
846
969
  }
847
970
  }
848
- servedRound(model, load) {
849
- const loadOpts = this.loadOptions(model, load);
971
+ async servedRound(model, load) {
972
+ const loadOpts = await this.sharedLoadOptions(model, load, load?.parallel);
850
973
  const key = modelKey(model, loadOpts);
851
974
  return { key, acquireRound: roundAcquirer(this, { model, key, loadOpts }) };
852
975
  }
976
+ async sharedLoadOptions(model, knobs, parallel) {
977
+ const own = this.loadOptions(model, knobs);
978
+ if (!parallel || parallel.slots < 2) {
979
+ return own;
980
+ }
981
+ const now = Date.now();
982
+ for (const [group, { at }] of this._parallel) {
983
+ if (now - at > PARALLEL_CHOICE_MS) {
984
+ this._parallel.delete(group);
985
+ }
986
+ }
987
+ const group = `${model}\0${parallel.group}`;
988
+ const load = this._parallel.get(group)?.load ?? this._slottedLoad(model, own, parallel).catch(() => null);
989
+ this._parallel.set(group, { at: now, load });
990
+ return (await load) ?? own;
991
+ }
992
+ async _slottedLoad(model, own, { slots, ctxSize }) {
993
+ const asset = curatedModelAsset(model, 'llm');
994
+ const load = { opts: own, deviceConfig: this.deviceConfig() };
995
+ if (!asset || slotCount(model, load) > 1 || this._inUse(model)) {
996
+ return null;
997
+ }
998
+ const perSlot = ctxSize ?? contextSize(model, asset, load);
999
+ for (let width = Math.min(slots, MAX_PARALLEL_SLOTS); width > 1; width = Math.floor(width / 2)) {
1000
+ const opts = { ...own, ctxSize: perSlot, slots: width };
1001
+ if (await this._fitsInPlaceOf(model, own, opts)) {
1002
+ this.fit.keep(modelKey(model, opts), { ctxSize: perSlot, slots: width, fits: true });
1003
+ HarnessLog.info('slotted load', { model, slots: width, ctxSize: perSlot });
1004
+ return opts;
1005
+ }
1006
+ }
1007
+ return null;
1008
+ }
1009
+ _inUse(model) {
1010
+ return (loadingModels(this._models).includes(model) ||
1011
+ settledEntries(this._models).some(({ key, refs }) => modelOf(key) === model && (refs > 0 || this._replying.includes(key))));
1012
+ }
1013
+ async _fitsInPlaceOf(model, own, opts) {
1014
+ const asset = curatedModelAsset(model, 'llm');
1015
+ if (!asset) {
1016
+ return false;
1017
+ }
1018
+ const config = this.deviceConfig();
1019
+ const tokens = (loadOpts) => {
1020
+ const load = { opts: loadOpts, deviceConfig: config };
1021
+ return contextSize(model, asset, load) * slotCount(model, load);
1022
+ };
1023
+ const asked = await this.fit.settle(ModelFit.query(asset, tokens(opts), { native: true }));
1024
+ if (!asked || asked.verdict === 'unknown') {
1025
+ return false;
1026
+ }
1027
+ const idle = settledEntries(this._models).filter(({ key, refs }) => refs === 0 && modelOf(key) === model);
1028
+ if (this._over(asked.pools, sumPools(idle.flatMap(sizedPools))).length > 0) {
1029
+ return false;
1030
+ }
1031
+ if (asked.verdict !== 'likely-too-large') {
1032
+ return true;
1033
+ }
1034
+ const replaced = idle.length === 1 && idle[0].key === modelKey(model, own);
1035
+ const held = replaced ? await this.fit.settle(ModelFit.query(asset, tokens(own))) : null;
1036
+ return held?.bytes !== undefined && swapFits(asked, held);
1037
+ }
853
1038
  async roomForCompletion(model, { loadOpts, signal }) {
854
1039
  const key = modelKey(model, loadOpts);
855
1040
  if (isResident(this._models, key)) {
@@ -864,7 +1049,7 @@ export class Residency {
864
1049
  }
865
1050
  }
866
1051
  async makeRoomForCompletion(model, { loadOpts, signal, deadlineMs = MODEL_ROOM_WAIT_MS }) {
867
- if (this._capBytes !== null) {
1052
+ if (this._capPercent !== null) {
868
1053
  await evictIdleWhere(this._models, this._replacedBy(model));
869
1054
  return true;
870
1055
  }
@@ -885,7 +1070,8 @@ export class Residency {
885
1070
  }
886
1071
  await this._yieldPins(model, loadOpts);
887
1072
  const key = modelKey(model, loadOpts);
888
- if (roomed && !signal?.aborted && !loadOpts.ctxSize && this.fit.chosen(key) === undefined) {
1073
+ const decides = !loadOpts.ctxSize || (loadOpts.slots ?? 1) > 1;
1074
+ if (roomed && !signal?.aborted && decides && this.fit.chosen(key) === undefined) {
889
1075
  const choice = await this._loadDecision(model, loadOpts);
890
1076
  if (choice) {
891
1077
  this.fit.keep(key, choice);
@@ -941,4 +1127,16 @@ export class Residency {
941
1127
  }
942
1128
  }
943
1129
  }
1130
+ function swapFits(asked, held) {
1131
+ return Object.entries(asked.pools).every(([pool, bytes]) => {
1132
+ const free = asked.free?.[pool];
1133
+ return free !== undefined && bytes - (held.pools[pool] ?? 0) <= free * SWAP_HEADROOM;
1134
+ });
1135
+ }
1136
+ function sizedPools({ pools }) {
1137
+ return pools ? [pools] : [];
1138
+ }
1139
+ function holdsAny(pools, over) {
1140
+ return over.length === 0 || pools === undefined || over.some((pool) => (pools[pool] ?? 0) > 0);
1141
+ }
944
1142
  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';