@zerogpu/browser-extension-sdk 0.2.0-dev.202607211328.gc9a2a62 → 0.2.0-dev.202607231429.gf080a5e
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/assets/zerogpu-assets.json +2 -2
- package/dist/extension/zerogpu-offscreen.js +269 -61
- package/dist/extension/zerogpu-offscreen.js.map +1 -1
- package/dist/manifest.json +5 -5
- package/dist/types/config/types.d.ts +7 -0
- package/dist/types/runtime/guardrails.d.ts +40 -0
- package/dist/types/runtime/lifecycle.d.ts +2 -0
- package/dist/types/runtime/tracking-pixel.d.ts +27 -0
- package/dist/types/transport/protocol.d.ts +8 -0
- package/dist/v/{zerogpu-browser-sdk.de2e6d71813f.umd.js → zerogpu-browser-sdk.07eacaf68fcd.umd.js} +270 -62
- package/dist/v/zerogpu-browser-sdk.07eacaf68fcd.umd.js.map +1 -0
- package/dist/zerogpu-browser-sdk.cjs +269 -61
- package/dist/zerogpu-browser-sdk.cjs.map +1 -1
- package/dist/zerogpu-browser-sdk.esm.js +269 -61
- package/dist/zerogpu-browser-sdk.esm.js.map +1 -1
- package/dist/zerogpu-browser-sdk.umd.js +269 -61
- package/dist/zerogpu-browser-sdk.umd.js.map +1 -1
- package/package.json +1 -1
- package/dist/v/zerogpu-browser-sdk.de2e6d71813f.umd.js.map +0 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
{
|
|
2
|
-
"sdkVersion": "0.2.0-dev.
|
|
2
|
+
"sdkVersion": "0.2.0-dev.202607231429.gf080a5e+f080a5e",
|
|
3
3
|
"channel": "development",
|
|
4
4
|
"transformersVersion": "2.17.2",
|
|
5
5
|
"wllamaVersion": "2.3.5",
|
|
@@ -14,5 +14,5 @@
|
|
|
14
14
|
"wllama/single-thread/wllama.wasm",
|
|
15
15
|
"wllama/multi-thread/wllama.wasm"
|
|
16
16
|
],
|
|
17
|
-
"builtAt": "2026-07-
|
|
17
|
+
"builtAt": "2026-07-23T14:31:11.440Z"
|
|
18
18
|
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
const SDK_VERSION = typeof "0.2.0-dev.
|
|
2
|
-
? "0.2.0-dev.
|
|
1
|
+
const SDK_VERSION = typeof "0.2.0-dev.202607231429.gf080a5e+f080a5e" === 'string' && "0.2.0-dev.202607231429.gf080a5e+f080a5e".length > 0
|
|
2
|
+
? "0.2.0-dev.202607231429.gf080a5e+f080a5e"
|
|
3
3
|
: '0.0.0-dev';
|
|
4
4
|
|
|
5
5
|
const ORCHESTRATOR_BASE_URL = typeof "https://devices.zerogpu.ai" === 'string' && "https://devices.zerogpu.ai".length > 0
|
|
@@ -996,53 +996,6 @@ const initEventReporter = (options) => {
|
|
|
996
996
|
};
|
|
997
997
|
const getEventReporter = () => singleton ?? NOOP;
|
|
998
998
|
|
|
999
|
-
/**
|
|
1000
|
-
* Host-facing lifecycle status and events. The SDK is a guest in someone
|
|
1001
|
-
* else's app: this module is how the host observes guardrail state (degraded /
|
|
1002
|
-
* recovered / shutdown) without the SDK ever throwing into it. Script-tag
|
|
1003
|
-
* consumers get the same signals as `zerogpu:*` window events, matching the
|
|
1004
|
-
* existing `zerogpu:cameraPreview` pattern.
|
|
1005
|
-
*/
|
|
1006
|
-
let lifecycleStatus = 'starting';
|
|
1007
|
-
const listeners = {
|
|
1008
|
-
degraded: new Set(),
|
|
1009
|
-
recovered: new Set(),
|
|
1010
|
-
shutdown: new Set()
|
|
1011
|
-
};
|
|
1012
|
-
const getLifecycleStatus = () => lifecycleStatus;
|
|
1013
|
-
const setLifecycleStatus = (status) => {
|
|
1014
|
-
// Shutdown is terminal (state machine B.3): recovery exists only from
|
|
1015
|
-
// warn/degrade, never from shutdown.
|
|
1016
|
-
if (lifecycleStatus === 'shutdown')
|
|
1017
|
-
return;
|
|
1018
|
-
lifecycleStatus = status;
|
|
1019
|
-
};
|
|
1020
|
-
const isShutdown = () => lifecycleStatus === 'shutdown';
|
|
1021
|
-
/** Degraded and shutting-down SDKs finish in-flight work but accept nothing new. */
|
|
1022
|
-
const isTaskGateActive = () => lifecycleStatus === 'degraded' || lifecycleStatus === 'shutdown';
|
|
1023
|
-
const onHostEvent = (name, listener) => {
|
|
1024
|
-
listeners[name]?.add(listener);
|
|
1025
|
-
return () => listeners[name]?.delete(listener);
|
|
1026
|
-
};
|
|
1027
|
-
const emitHostEvent = (name, detail = {}) => {
|
|
1028
|
-
for (const listener of listeners[name] ?? []) {
|
|
1029
|
-
try {
|
|
1030
|
-
listener(detail);
|
|
1031
|
-
}
|
|
1032
|
-
catch {
|
|
1033
|
-
// A host listener bug must never propagate into the SDK.
|
|
1034
|
-
}
|
|
1035
|
-
}
|
|
1036
|
-
try {
|
|
1037
|
-
if (typeof window !== 'undefined') {
|
|
1038
|
-
window.dispatchEvent(new CustomEvent(`zerogpu:${name}`, { detail }));
|
|
1039
|
-
}
|
|
1040
|
-
}
|
|
1041
|
-
catch {
|
|
1042
|
-
// ignore
|
|
1043
|
-
}
|
|
1044
|
-
};
|
|
1045
|
-
|
|
1046
999
|
const DEFAULT_FRAMEWORK_MULTIPLIERS = {
|
|
1047
1000
|
onnx: 2.0,
|
|
1048
1001
|
transformersjs: 2.5,
|
|
@@ -1065,6 +1018,18 @@ const DEFAULT_WATCHDOG = {
|
|
|
1065
1018
|
recoverPct: 0.6,
|
|
1066
1019
|
recoverHoldMs: 60000
|
|
1067
1020
|
};
|
|
1021
|
+
/**
|
|
1022
|
+
* Ceiling on wasm threads when the environment allows them at all
|
|
1023
|
+
* (cross-origin isolated). Diminishing returns above ~4 on the matmul kernels,
|
|
1024
|
+
* and leaving cores free keeps the host page/app responsive. Rows can raise it
|
|
1025
|
+
* via `guardrails.wasm.maxThreads`.
|
|
1026
|
+
*/
|
|
1027
|
+
const DEFAULT_WASM_MAX_THREADS = 4;
|
|
1028
|
+
/**
|
|
1029
|
+
* Same chars-per-token heuristic the registry's dispatch input guard uses —
|
|
1030
|
+
* both sides only need the order of magnitude to agree.
|
|
1031
|
+
*/
|
|
1032
|
+
const CHARS_PER_TOKEN = 4;
|
|
1068
1033
|
let policy = {};
|
|
1069
1034
|
let resolved = resolve(null);
|
|
1070
1035
|
function positive(value) {
|
|
@@ -1093,6 +1058,15 @@ function resolve(settings) {
|
|
|
1093
1058
|
sampleMs: positive(watchdog.sampleMs) ?? DEFAULT_WATCHDOG.sampleMs,
|
|
1094
1059
|
recoverPct: positive(watchdog.recoverPct) ?? DEFAULT_WATCHDOG.recoverPct,
|
|
1095
1060
|
recoverHoldMs: positive(watchdog.recoverHoldMs) ?? DEFAULT_WATCHDOG.recoverHoldMs
|
|
1061
|
+
},
|
|
1062
|
+
// 0 = feature off — all three gates are additive and inert unless the
|
|
1063
|
+
// registry serves a value for this surface (backward compatible).
|
|
1064
|
+
maxMemoryBudgetMb: positive(settings?.maxMemoryBudgetMb) ?? 0,
|
|
1065
|
+
maxInputTokens: positive(settings?.maxInputTokens) ?? 0,
|
|
1066
|
+
sampleLatencyBudgetMs: positive(settings?.sampleLatencyBudgetMs) ?? 0,
|
|
1067
|
+
wasm: {
|
|
1068
|
+
maxThreads: positive(settings?.wasm?.maxThreads) ?? DEFAULT_WASM_MAX_THREADS,
|
|
1069
|
+
proxyWorker: settings?.wasm?.proxyWorker === true
|
|
1096
1070
|
}
|
|
1097
1071
|
};
|
|
1098
1072
|
}
|
|
@@ -1120,6 +1094,81 @@ const normalizeModelSizeBytes = (raw) => {
|
|
|
1120
1094
|
return 0;
|
|
1121
1095
|
return raw < 1000000 ? raw * 1024 * 1024 : raw;
|
|
1122
1096
|
};
|
|
1097
|
+
/** Rough token count of an input — same heuristic as the registry guard. */
|
|
1098
|
+
const estimateInputTokens = (text) => Math.ceil(text.length / CHARS_PER_TOKEN);
|
|
1099
|
+
/** True when a served cap exists and the input exceeds it (0/absent cap = no gate). */
|
|
1100
|
+
const inputExceedsTokenCap = (text, capTokens = resolved.maxInputTokens) => capTokens > 0 && estimateInputTokens(text) > capTokens;
|
|
1101
|
+
const probeWasmEnvironment = () => ({
|
|
1102
|
+
isolated: typeof globalThis.crossOriginIsolated === 'boolean' &&
|
|
1103
|
+
globalThis.crossOriginIsolated &&
|
|
1104
|
+
typeof globalThis.SharedArrayBuffer === 'function',
|
|
1105
|
+
cores: typeof navigator !== 'undefined' && typeof navigator.hardwareConcurrency === 'number'
|
|
1106
|
+
? navigator.hardwareConcurrency
|
|
1107
|
+
: 1,
|
|
1108
|
+
workerAvailable: typeof globalThis.Worker === 'function'
|
|
1109
|
+
});
|
|
1110
|
+
/**
|
|
1111
|
+
* ONNX wasm execution settings for this environment + served config:
|
|
1112
|
+
* - threads: multi-threaded wasm needs SharedArrayBuffer, which exists only on
|
|
1113
|
+
* cross-origin-isolated pages (COOP/COEP on the loader). When available, use
|
|
1114
|
+
* min(hardwareConcurrency − 1, served maxThreads) — one core is left for the
|
|
1115
|
+
* page. Not isolated → 1, exactly the long-standing behavior.
|
|
1116
|
+
* - proxy: worker execution is opt-in via `guardrails.wasm.proxyWorker` (per
|
|
1117
|
+
* surface, after verifying the target WebView), and only where Worker exists.
|
|
1118
|
+
*/
|
|
1119
|
+
const resolveWasmSettings = (probe = probeWasmEnvironment()) => {
|
|
1120
|
+
const cores = Number.isFinite(probe.cores) && probe.cores > 0 ? Math.floor(probe.cores) : 1;
|
|
1121
|
+
const numThreads = probe.isolated ? Math.max(1, Math.min(cores - 1, resolved.wasm.maxThreads)) : 1;
|
|
1122
|
+
const proxy = resolved.wasm.proxyWorker && probe.workerAvailable;
|
|
1123
|
+
return { numThreads, proxy };
|
|
1124
|
+
};
|
|
1125
|
+
|
|
1126
|
+
/**
|
|
1127
|
+
* Host-facing lifecycle status and events. The SDK is a guest in someone
|
|
1128
|
+
* else's app: this module is how the host observes guardrail state (degraded /
|
|
1129
|
+
* recovered / shutdown) without the SDK ever throwing into it. Script-tag
|
|
1130
|
+
* consumers get the same signals as `zerogpu:*` window events, matching the
|
|
1131
|
+
* existing `zerogpu:cameraPreview` pattern.
|
|
1132
|
+
*/
|
|
1133
|
+
let lifecycleStatus = 'starting';
|
|
1134
|
+
const listeners = {
|
|
1135
|
+
degraded: new Set(),
|
|
1136
|
+
recovered: new Set(),
|
|
1137
|
+
shutdown: new Set()
|
|
1138
|
+
};
|
|
1139
|
+
const getLifecycleStatus = () => lifecycleStatus;
|
|
1140
|
+
const setLifecycleStatus = (status) => {
|
|
1141
|
+
// Shutdown is terminal (state machine B.3): recovery exists only from
|
|
1142
|
+
// warn/degrade, never from shutdown.
|
|
1143
|
+
if (lifecycleStatus === 'shutdown')
|
|
1144
|
+
return;
|
|
1145
|
+
lifecycleStatus = status;
|
|
1146
|
+
};
|
|
1147
|
+
const isShutdown = () => lifecycleStatus === 'shutdown';
|
|
1148
|
+
/** Degraded and shutting-down SDKs finish in-flight work but accept nothing new. */
|
|
1149
|
+
const isTaskGateActive = () => lifecycleStatus === 'degraded' || lifecycleStatus === 'shutdown';
|
|
1150
|
+
const onHostEvent = (name, listener) => {
|
|
1151
|
+
listeners[name]?.add(listener);
|
|
1152
|
+
return () => listeners[name]?.delete(listener);
|
|
1153
|
+
};
|
|
1154
|
+
const emitHostEvent = (name, detail = {}) => {
|
|
1155
|
+
for (const listener of listeners[name] ?? []) {
|
|
1156
|
+
try {
|
|
1157
|
+
listener(detail);
|
|
1158
|
+
}
|
|
1159
|
+
catch {
|
|
1160
|
+
// A host listener bug must never propagate into the SDK.
|
|
1161
|
+
}
|
|
1162
|
+
}
|
|
1163
|
+
try {
|
|
1164
|
+
if (typeof window !== 'undefined') {
|
|
1165
|
+
window.dispatchEvent(new CustomEvent(`zerogpu:${name}`, { detail }));
|
|
1166
|
+
}
|
|
1167
|
+
}
|
|
1168
|
+
catch {
|
|
1169
|
+
// ignore
|
|
1170
|
+
}
|
|
1171
|
+
};
|
|
1123
1172
|
|
|
1124
1173
|
/**
|
|
1125
1174
|
* Crash-loop guard for SDK initialization, extended into the Layer 4 crash
|
|
@@ -1587,6 +1636,65 @@ const onAllocationFailure = (message) => {
|
|
|
1587
1636
|
getLogger().error('[Watchdog] Allocation failure — emergency shutdown', { message });
|
|
1588
1637
|
};
|
|
1589
1638
|
|
|
1639
|
+
/**
|
|
1640
|
+
* Fires ad-measurement pixels from the device.
|
|
1641
|
+
*
|
|
1642
|
+
* The point of running these here rather than server-side is that the ad server
|
|
1643
|
+
* sees the end user's real IP, User-Agent and cookies; fired from a datacenter
|
|
1644
|
+
* they are filtered or flagged as fraud.
|
|
1645
|
+
*/
|
|
1646
|
+
const DEFAULT_TIMEOUT_MS = 3000;
|
|
1647
|
+
// Holds in-flight images so the GC cannot collect one mid-request, which would
|
|
1648
|
+
// cancel the beacon before it reaches the ad server.
|
|
1649
|
+
const inFlight = new Set();
|
|
1650
|
+
/**
|
|
1651
|
+
* Loads `url` as an image and resolves once the request has left the device.
|
|
1652
|
+
*
|
|
1653
|
+
* Both `load` and `error` resolve to 'fired', by design. Measurement endpoints
|
|
1654
|
+
* answer with 204s, redirect chains and non-image bodies, so `error` is the
|
|
1655
|
+
* normal outcome for a perfectly successful pixel — treating it as a failure
|
|
1656
|
+
* would report a ~100% failure rate. Only the timeout is genuinely unknown.
|
|
1657
|
+
*
|
|
1658
|
+
* Never rejects: a pixel is best-effort and must not affect inference.
|
|
1659
|
+
*/
|
|
1660
|
+
const fireTrackingPixel = (url, timeoutMs = DEFAULT_TIMEOUT_MS) => {
|
|
1661
|
+
// Non-DOM hosts (e.g. a worker) cannot fire a beacon.
|
|
1662
|
+
if (typeof Image === 'undefined')
|
|
1663
|
+
return Promise.resolve('skipped');
|
|
1664
|
+
return new Promise((resolve) => {
|
|
1665
|
+
let settled = false;
|
|
1666
|
+
let img;
|
|
1667
|
+
let timer;
|
|
1668
|
+
const settle = (status) => {
|
|
1669
|
+
if (settled)
|
|
1670
|
+
return;
|
|
1671
|
+
settled = true;
|
|
1672
|
+
if (timer !== undefined)
|
|
1673
|
+
clearTimeout(timer);
|
|
1674
|
+
if (img) {
|
|
1675
|
+
img.onload = null;
|
|
1676
|
+
img.onerror = null;
|
|
1677
|
+
inFlight.delete(img);
|
|
1678
|
+
}
|
|
1679
|
+
resolve(status);
|
|
1680
|
+
};
|
|
1681
|
+
// Everything here is best-effort: a host that blocks image construction or
|
|
1682
|
+
// src assignment must degrade to 'skipped', never throw into the caller and
|
|
1683
|
+
// never take inference down with it.
|
|
1684
|
+
try {
|
|
1685
|
+
timer = setTimeout(() => settle('timeout'), timeoutMs);
|
|
1686
|
+
img = new Image();
|
|
1687
|
+
img.onload = () => settle('fired');
|
|
1688
|
+
img.onerror = () => settle('fired');
|
|
1689
|
+
inFlight.add(img);
|
|
1690
|
+
img.src = url;
|
|
1691
|
+
}
|
|
1692
|
+
catch {
|
|
1693
|
+
settle('skipped');
|
|
1694
|
+
}
|
|
1695
|
+
});
|
|
1696
|
+
};
|
|
1697
|
+
|
|
1590
1698
|
let executing = false;
|
|
1591
1699
|
const buildInferenceInput = (request) => {
|
|
1592
1700
|
const input = request.input ?? {};
|
|
@@ -1657,6 +1765,58 @@ const executeSingleRequest = async (request) => {
|
|
|
1657
1765
|
}
|
|
1658
1766
|
};
|
|
1659
1767
|
}
|
|
1768
|
+
// Input-size gate (served `guardrails.maxInputTokens`, 0/absent = off): an
|
|
1769
|
+
// over-cap input cannot finish inside the dispatch budget on this surface —
|
|
1770
|
+
// and on WebView surfaces the attempt can OOM-kill the renderer
|
|
1771
|
+
// mid-generation. Refuse with the standard error envelope immediately so the
|
|
1772
|
+
// server routes to the next candidate/cloud in milliseconds. The registry
|
|
1773
|
+
// enforces the same cap pre-dispatch, so this is the belt to its suspenders.
|
|
1774
|
+
const inputText = typeof request.input?.text === 'string' ? request.input.text : '';
|
|
1775
|
+
if (inputExceedsTokenCap(inputText)) {
|
|
1776
|
+
getEventReporter().report('task.rejected', {
|
|
1777
|
+
code: 'not_ready',
|
|
1778
|
+
modelId: request.modelId,
|
|
1779
|
+
data: {
|
|
1780
|
+
reason: 'input_too_large',
|
|
1781
|
+
estimatedTokens: estimateInputTokens(inputText),
|
|
1782
|
+
maxInputTokens: getGuardrails().maxInputTokens
|
|
1783
|
+
}
|
|
1784
|
+
});
|
|
1785
|
+
return {
|
|
1786
|
+
requestId: request.requestId,
|
|
1787
|
+
modelId: request.modelId,
|
|
1788
|
+
modelVersion: request.modelVersion,
|
|
1789
|
+
response: { text: '' },
|
|
1790
|
+
error: true,
|
|
1791
|
+
errorMessage: 'input_too_large',
|
|
1792
|
+
metadata: {
|
|
1793
|
+
processingTime: Math.round(performance.now() - start)
|
|
1794
|
+
}
|
|
1795
|
+
};
|
|
1796
|
+
}
|
|
1797
|
+
// Kicked off only once the adapter is confirmed: a model_not_ready return
|
|
1798
|
+
// above sends the request to cloud instead, and firing then would count an
|
|
1799
|
+
// impression this device never served. Deliberately not awaited so a slow ad
|
|
1800
|
+
// server cannot add latency to inference; whatever has settled by the time
|
|
1801
|
+
// inference finishes is what gets reported.
|
|
1802
|
+
let pixelStatus = 'pending';
|
|
1803
|
+
if (request.trackingPixel) {
|
|
1804
|
+
void fireTrackingPixel(request.trackingPixel).then((status) => {
|
|
1805
|
+
pixelStatus = status;
|
|
1806
|
+
});
|
|
1807
|
+
}
|
|
1808
|
+
const pixelMetadata = async () => {
|
|
1809
|
+
if (!request.trackingPixel)
|
|
1810
|
+
return {};
|
|
1811
|
+
// Yield one turn before snapshotting. The beacon's load/error is a
|
|
1812
|
+
// macrotask, and it cannot run while synchronous inference holds the
|
|
1813
|
+
// thread — so by the time inference resolves, a request that finished long
|
|
1814
|
+
// ago is still sitting unprocessed in the queue and would be reported as
|
|
1815
|
+
// 'pending'. This waits on nothing (a genuinely slow pixel still reports
|
|
1816
|
+
// 'pending'), it just stops discarding a result that already arrived.
|
|
1817
|
+
await new Promise((resolve) => setTimeout(resolve, 0));
|
|
1818
|
+
return { trackingPixel: pixelStatus };
|
|
1819
|
+
};
|
|
1660
1820
|
try {
|
|
1661
1821
|
const input = buildInferenceInput(request);
|
|
1662
1822
|
const result = await adapter.runInference(input);
|
|
@@ -1668,7 +1828,8 @@ const executeSingleRequest = async (request) => {
|
|
|
1668
1828
|
error: false,
|
|
1669
1829
|
errorMessage: '',
|
|
1670
1830
|
metadata: {
|
|
1671
|
-
processingTime: Math.round(performance.now() - start)
|
|
1831
|
+
processingTime: Math.round(performance.now() - start),
|
|
1832
|
+
...(await pixelMetadata())
|
|
1672
1833
|
}
|
|
1673
1834
|
};
|
|
1674
1835
|
}
|
|
@@ -1695,7 +1856,11 @@ const executeSingleRequest = async (request) => {
|
|
|
1695
1856
|
error: true,
|
|
1696
1857
|
errorMessage: error.message,
|
|
1697
1858
|
metadata: {
|
|
1698
|
-
processingTime: Math.round(performance.now() - start)
|
|
1859
|
+
processingTime: Math.round(performance.now() - start),
|
|
1860
|
+
// The beacon is fired before inference runs, so a failed task can still
|
|
1861
|
+
// have delivered its impression. Reporting it only on success would
|
|
1862
|
+
// under-count the fire rate.
|
|
1863
|
+
...(await pixelMetadata())
|
|
1699
1864
|
}
|
|
1700
1865
|
};
|
|
1701
1866
|
}
|
|
@@ -1904,12 +2069,19 @@ const evaluateResourceGate = async (model, stage, deviceInfo) => {
|
|
|
1904
2069
|
const memoryGb = typeof deviceInfo?.memoryGb === 'number' && deviceInfo.memoryGb > 0
|
|
1905
2070
|
? deviceInfo.memoryGb
|
|
1906
2071
|
: guardrails.unknownMemoryGb;
|
|
1907
|
-
|
|
2072
|
+
// min(fraction × RAM, served absolute cap): the same arithmetic the
|
|
2073
|
+
// registry's admission guard applies. On embedded-WebView surfaces the
|
|
2074
|
+
// absolute cap models the renderer's real process budget, which
|
|
2075
|
+
// fraction-of-device-RAM wildly overestimates.
|
|
2076
|
+
const fractionBudgetBytes = guardrails.memoryBudgetFraction * memoryGb * BYTES_PER_GB;
|
|
2077
|
+
const absoluteBudgetBytes = guardrails.maxMemoryBudgetMb > 0 ? guardrails.maxMemoryBudgetMb * 1024 * 1024 : Infinity;
|
|
2078
|
+
const budgetBytes = Math.min(fractionBudgetBytes, absoluteBudgetBytes);
|
|
1908
2079
|
if (estimatedRuntimeBytes > budgetBytes) {
|
|
1909
2080
|
return {
|
|
1910
2081
|
code: 'model_too_large_for_memory',
|
|
1911
2082
|
message: `estimated runtime ${Math.round(estimatedRuntimeBytes)} B > budget ${Math.round(budgetBytes)} B ` +
|
|
1912
|
-
`(fraction=${guardrails.memoryBudgetFraction},
|
|
2083
|
+
`(fraction=${guardrails.memoryBudgetFraction}, maxBudgetMb=${guardrails.maxMemoryBudgetMb || 'none'}, ` +
|
|
2084
|
+
`multiplier=${multiplier}, memoryGb=${memoryGb})`
|
|
1913
2085
|
};
|
|
1914
2086
|
}
|
|
1915
2087
|
// Heap headroom — Chromium only; other engines expose nothing and the
|
|
@@ -1960,6 +2132,24 @@ const evaluateResourceGate = async (model, stage, deviceInfo) => {
|
|
|
1960
2132
|
}
|
|
1961
2133
|
};
|
|
1962
2134
|
|
|
2135
|
+
// "Ready" must be proven: a model may only announce `idle` in the hello after
|
|
2136
|
+
// its local warm-up inference completed successfully. Both failure shapes count
|
|
2137
|
+
// — an errored sample AND a completed-but-not-ok one (previously only the
|
|
2138
|
+
// former demoted the model, so an unproven device could claim readiness).
|
|
2139
|
+
// With a served `guardrails.sampleLatencyBudgetMs`, "proven" also means
|
|
2140
|
+
// "proven fast enough": a sample that completed but blew the budget demotes
|
|
2141
|
+
// the model too — a device that needs 5–10 s for a representative sample
|
|
2142
|
+
// cannot serve a real request inside the dispatch budget, and letting it claim
|
|
2143
|
+
// idle only buys it a timeout + quarantine (and, on WebView surfaces, a
|
|
2144
|
+
// mid-generation OOM kill). 0/absent budget → success-only gating (unchanged).
|
|
2145
|
+
function warmUpFailed(sample, latencyBudgetMs = 0) {
|
|
2146
|
+
if (Boolean(sample.error) || !sample.ok)
|
|
2147
|
+
return true;
|
|
2148
|
+
return (latencyBudgetMs > 0 &&
|
|
2149
|
+
typeof sample.processingTimeMs === 'number' &&
|
|
2150
|
+
Number.isFinite(sample.processingTimeMs) &&
|
|
2151
|
+
sample.processingTimeMs > latencyBudgetMs);
|
|
2152
|
+
}
|
|
1963
2153
|
// Re-registration loop: when the server idle-closes the WebSocket (or it drops
|
|
1964
2154
|
// for any reason), wait device_timeout_interval_seconds and run the full
|
|
1965
2155
|
// lifecycle again — re-registering refreshes device metrics and yields a new
|
|
@@ -2461,6 +2651,13 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
|
|
|
2461
2651
|
modelVersion: primaryModel.modelVersion ?? '1',
|
|
2462
2652
|
modelUrl: primaryModel.modelUrl,
|
|
2463
2653
|
modelRepoId: primaryModel.modelRepoId,
|
|
2654
|
+
// inferenceFramework/modelType were historically NOT persisted, so
|
|
2655
|
+
// every boot's cached-path getAdapterFactory(undefined, taskType)
|
|
2656
|
+
// returned nothing → model.cache_invalid `no_adapter_factory` →
|
|
2657
|
+
// cache purged → full reload, every single session. Persisting them
|
|
2658
|
+
// is what makes the cache actually survive a restart.
|
|
2659
|
+
inferenceFramework: primaryModel.inferenceFramework,
|
|
2660
|
+
modelType: primaryModel.modelType,
|
|
2464
2661
|
maxInputTokens: primaryModel.maxTokens,
|
|
2465
2662
|
quantized: primaryModel.quantized,
|
|
2466
2663
|
quantization: primaryModel.quantization,
|
|
@@ -2601,14 +2798,23 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
|
|
|
2601
2798
|
errorMessage: postRegisterSample.errorMessage,
|
|
2602
2799
|
processingTimeMs: postRegisterSample.processingTimeMs
|
|
2603
2800
|
};
|
|
2604
|
-
|
|
2801
|
+
const sampleLatencyBudgetMs = getGuardrails().sampleLatencyBudgetMs;
|
|
2802
|
+
if (warmUpFailed(postRegisterSample, sampleLatencyBudgetMs)) {
|
|
2803
|
+
const tooSlow = !postRegisterSample.error && postRegisterSample.ok && sampleLatencyBudgetMs > 0;
|
|
2605
2804
|
reporter.report('model.sample_failed', {
|
|
2606
2805
|
modelId: primaryModel.modelId,
|
|
2607
2806
|
durationMs: postRegisterSample.processingTimeMs,
|
|
2608
|
-
message:
|
|
2807
|
+
message: tooSlow
|
|
2808
|
+
? `sample_too_slow:${postRegisterSample.processingTimeMs}ms>budget:${sampleLatencyBudgetMs}ms`
|
|
2809
|
+
: postRegisterSample.errorMessage,
|
|
2609
2810
|
data: { phase: 'post_register' }
|
|
2610
2811
|
});
|
|
2611
|
-
logger.error('[Sample] Post-register sample failed', sampleLog);
|
|
2812
|
+
logger.error('[Sample] Post-register sample failed', { ...sampleLog, sampleLatencyBudgetMs });
|
|
2813
|
+
// "Ready" must be proven: any warm-up that did not complete successfully
|
|
2814
|
+
// (errored, merely not-ok, OR over the served latency budget) demotes the
|
|
2815
|
+
// model to error in the hello, so the registry never lists a device for
|
|
2816
|
+
// dispatches it cannot serve in time.
|
|
2817
|
+
modelStatuses[getModelStatusKey(primaryModel)] = 'error';
|
|
2612
2818
|
}
|
|
2613
2819
|
else {
|
|
2614
2820
|
reporter.report('model.sample_succeeded', {
|
|
@@ -2618,9 +2824,6 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
|
|
|
2618
2824
|
});
|
|
2619
2825
|
logger.info('[Sample] Post-register sample ok', sampleLog);
|
|
2620
2826
|
}
|
|
2621
|
-
if (postRegisterSample.error) {
|
|
2622
|
-
modelStatuses[getModelStatusKey(primaryModel)] = 'error';
|
|
2623
|
-
}
|
|
2624
2827
|
}
|
|
2625
2828
|
const helloDeviceId = registerResponse.deviceId;
|
|
2626
2829
|
const helloSlmConfig = assignedModels.map((model) => ({
|
|
@@ -3507,8 +3710,13 @@ const instantiatePipeline = async (slm, cachedFiles, onFileDownloaded) => {
|
|
|
3507
3710
|
if (env?.backends?.onnx?.env) {
|
|
3508
3711
|
env.backends.onnx.env.logLevel = transformersLogLevel;
|
|
3509
3712
|
}
|
|
3510
|
-
|
|
3511
|
-
|
|
3713
|
+
// Environment- and settings-driven (guardrails.wasm): threads activate only
|
|
3714
|
+
// on cross-origin-isolated pages (SharedArrayBuffer), proxy only when the
|
|
3715
|
+
// surface's settings opt in — everywhere else this resolves to the
|
|
3716
|
+
// long-standing single-threaded main-thread configuration.
|
|
3717
|
+
const wasmSettings = resolveWasmSettings();
|
|
3718
|
+
env.backends.onnx.wasm.proxy = wasmSettings.proxy;
|
|
3719
|
+
env.backends.onnx.wasm.numThreads = wasmSettings.numThreads;
|
|
3512
3720
|
const originalFetch = window.fetch.bind(window);
|
|
3513
3721
|
const wasmOverridePath = await getUsableOnnxWasmOverridePath(originalFetch);
|
|
3514
3722
|
if (wasmOverridePath) {
|