@plasius/gpu-shader 0.1.2 → 0.1.4

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/testing.js CHANGED
@@ -15,63 +15,244 @@ Object.freeze(SUPPORTED_STABLE_WEBGPU_MATRIX_POLICIES);
15
15
  var SUPPORTED_ADDITIVE_WEBGPU_MATRIX_POLICIES = Object.freeze([]);
16
16
 
17
17
  // src/canonical-json.ts
18
- function isPlainObject(value) {
19
- const prototype = Object.getPrototypeOf(value);
20
- return prototype === Object.prototype || prototype === null;
18
+ var GPU_CONTRACT_SNAPSHOT_LIMITS = Object.freeze({
19
+ maximumDepth: 64,
20
+ maximumNodes: 262144,
21
+ maximumProperties: 131072,
22
+ maximumElements: 131072,
23
+ maximumArrayLength: 1e5,
24
+ maximumStringBytes: 1024 * 1024,
25
+ maximumAggregateStringBytes: 8 * 1024 * 1024,
26
+ maximumAggregateBytes: 16 * 1024 * 1024,
27
+ maximumInputBytes: 16 * 1024 * 1024
28
+ });
29
+ var QUALIFICATION_GPU_CONTRACT_SNAPSHOT_LIMITS = Object.freeze({
30
+ maximumDepth: 96,
31
+ maximumNodes: 4e6,
32
+ maximumProperties: 2e6,
33
+ maximumElements: 2e6,
34
+ maximumArrayLength: 25e4,
35
+ maximumStringBytes: 4 * 1024 * 1024,
36
+ maximumAggregateStringBytes: 128 * 1024 * 1024,
37
+ maximumAggregateBytes: 256 * 1024 * 1024,
38
+ maximumInputBytes: 256 * 1024 * 1024
39
+ });
40
+ var FAILURE_MESSAGES = Object.freeze({
41
+ "aggregate-bytes": "GPU contract snapshot exceeds the aggregate byte limit.",
42
+ "aggregate-string-bytes": "GPU contract snapshot exceeds the aggregate string byte limit.",
43
+ "array-length": "GPU contract snapshot exceeds the single-array element limit.",
44
+ cycle: "GPU contract snapshot contains a circular reference.",
45
+ depth: "GPU contract snapshot exceeds the nesting-depth limit.",
46
+ elements: "GPU contract snapshot exceeds the total element limit.",
47
+ inspection: "GPU contract snapshot rejected unsafe object inspection.",
48
+ nodes: "GPU contract snapshot exceeds the total node limit.",
49
+ "non-finite": "GPU contract snapshot contains a non-finite number.",
50
+ properties: "GPU contract snapshot exceeds the total property limit.",
51
+ shape: "GPU contract snapshot requires plain JSON objects with own enumerable data properties and dense arrays.",
52
+ "string-bytes": "GPU contract snapshot exceeds the individual string byte limit.",
53
+ unicode: "GPU contract snapshot contains an invalid Unicode scalar string or unpaired UTF-16 surrogate.",
54
+ value: "GPU contract snapshot contains undefined or another value that JSON cannot represent."
55
+ });
56
+ var GpuContractSnapshotError = class extends TypeError {
57
+ code;
58
+ constructor(code) {
59
+ super(FAILURE_MESSAGES[code]);
60
+ this.name = "GpuContractSnapshotError";
61
+ this.code = code;
62
+ }
63
+ };
64
+ var TYPED_ARRAY_PROTOTYPE = Reflect.getPrototypeOf(Uint8Array.prototype);
65
+ var TYPED_ARRAY_BYTE_LENGTH = Reflect.getOwnPropertyDescriptor(
66
+ TYPED_ARRAY_PROTOTYPE,
67
+ "byteLength"
68
+ )?.get;
69
+ var TYPED_ARRAY_TAG = Reflect.getOwnPropertyDescriptor(
70
+ TYPED_ARRAY_PROTOTYPE,
71
+ Symbol.toStringTag
72
+ )?.get;
73
+ var UINT8_ARRAY_SET = Uint8Array.prototype.set;
74
+ function snapshotUint8Array(value, maximumBytes) {
75
+ if (!Number.isSafeInteger(maximumBytes) || maximumBytes < 0) {
76
+ throw new TypeError("GPU contract byte limit must be a non-negative safe integer.");
77
+ }
78
+ let byteLength;
79
+ let tag;
80
+ try {
81
+ if (!TYPED_ARRAY_BYTE_LENGTH || !TYPED_ARRAY_TAG) throw new TypeError();
82
+ byteLength = Reflect.apply(TYPED_ARRAY_BYTE_LENGTH, value, []);
83
+ tag = Reflect.apply(TYPED_ARRAY_TAG, value, []);
84
+ } catch {
85
+ throw new TypeError("GPU contract bytes must be a bounded detached Uint8Array.");
86
+ }
87
+ if (tag !== "Uint8Array" || !Number.isSafeInteger(byteLength) || byteLength > maximumBytes) {
88
+ throw new TypeError("GPU contract bytes must be a bounded detached Uint8Array.");
89
+ }
90
+ const output = new Uint8Array(byteLength);
91
+ try {
92
+ Reflect.apply(UINT8_ARRAY_SET, output, [value]);
93
+ } catch {
94
+ throw new TypeError("GPU contract bytes must be a bounded detached Uint8Array.");
95
+ }
96
+ return output;
97
+ }
98
+ function fail(reason) {
99
+ throw new GpuContractSnapshotError(reason);
100
+ }
101
+ function inspected(operation) {
102
+ try {
103
+ return operation();
104
+ } catch {
105
+ return fail("inspection");
106
+ }
21
107
  }
22
- function assertUnicodeScalarString(value, path2) {
108
+ function assertLimit(value, maximum, reason) {
109
+ if (!Number.isSafeInteger(value) || value > maximum) fail(reason);
110
+ }
111
+ function quotedJsonByteLength(value, maximum) {
112
+ let raw = 0;
113
+ let quoted = 2;
23
114
  for (let index = 0; index < value.length; index += 1) {
24
115
  const code = value.charCodeAt(index);
25
- if (code >= 55296 && code <= 56319) {
116
+ if (code <= 127) {
117
+ raw += 1;
118
+ if (code <= 31) quoted += code === 8 || code === 9 || code === 10 || code === 12 || code === 13 ? 2 : 6;
119
+ else quoted += code === 34 || code === 92 ? 2 : 1;
120
+ } else if (code <= 2047) {
121
+ raw += 2;
122
+ quoted += 2;
123
+ } else if (code >= 55296 && code <= 56319) {
26
124
  const next = value.charCodeAt(index + 1);
27
- if (!(next >= 56320 && next <= 57343)) throw new TypeError(`${path2} contains an unpaired UTF-16 surrogate.`);
125
+ if (!(next >= 56320 && next <= 57343)) fail("unicode");
126
+ raw += 4;
127
+ quoted += 4;
28
128
  index += 1;
29
- } else if (code >= 56320 && code <= 57343) throw new TypeError(`${path2} contains an unpaired UTF-16 surrogate.`);
129
+ } else if (code >= 56320 && code <= 57343) fail("unicode");
130
+ else {
131
+ raw += 3;
132
+ quoted += 3;
133
+ }
134
+ if (raw > maximum) fail("string-bytes");
30
135
  }
136
+ return { raw, quoted };
31
137
  }
32
- function canonicalizeGpuContract(value) {
138
+ function assertLimits(limits) {
139
+ for (const value of Object.values(limits)) {
140
+ if (!Number.isSafeInteger(value) || value < 1) throw new TypeError("GPU contract snapshot limits must be positive safe integers.");
141
+ }
142
+ }
143
+ function snapshotGpuContract(value, limits = GPU_CONTRACT_SNAPSHOT_LIMITS) {
144
+ assertLimits(limits);
33
145
  const ancestors = /* @__PURE__ */ new Set();
34
- const visit = (current, path2) => {
35
- if (current === null) return "null";
36
- if (typeof current === "string" || typeof current === "boolean") {
37
- if (typeof current === "string") assertUnicodeScalarString(current, path2);
38
- return JSON.stringify(current);
146
+ let nodes = 0;
147
+ let properties = 0;
148
+ let elements = 0;
149
+ let aggregateStringBytes = 0;
150
+ let aggregateBytes = 0;
151
+ const addAggregate = (bytes) => {
152
+ aggregateBytes += bytes;
153
+ assertLimit(aggregateBytes, limits.maximumAggregateBytes, "aggregate-bytes");
154
+ };
155
+ const addString = (text2) => {
156
+ const measured = quotedJsonByteLength(text2, limits.maximumStringBytes);
157
+ aggregateStringBytes += measured.raw;
158
+ assertLimit(aggregateStringBytes, limits.maximumAggregateStringBytes, "aggregate-string-bytes");
159
+ return measured.quoted;
160
+ };
161
+ const visit = (current, depth) => {
162
+ if (depth > limits.maximumDepth) fail("depth");
163
+ nodes += 1;
164
+ assertLimit(nodes, limits.maximumNodes, "nodes");
165
+ if (current === null) {
166
+ addAggregate(4);
167
+ return null;
39
168
  }
40
- if (typeof current === "number") {
41
- if (!Number.isFinite(current)) {
42
- throw new TypeError(`${path2} contains a non-finite number.`);
43
- }
44
- return Object.is(current, -0) ? "0" : JSON.stringify(current);
169
+ if (typeof current === "string") {
170
+ addAggregate(addString(current));
171
+ return current;
45
172
  }
46
- if (typeof current !== "object") {
47
- throw new TypeError(`${path2} contains a value that JSON cannot represent.`);
173
+ if (typeof current === "boolean") {
174
+ addAggregate(current ? 4 : 5);
175
+ return current;
48
176
  }
49
- if (ancestors.has(current)) {
50
- throw new TypeError(`${path2} contains a circular reference.`);
177
+ if (typeof current === "number") {
178
+ if (!Number.isFinite(current)) fail("non-finite");
179
+ const normalized = Object.is(current, -0) ? 0 : current;
180
+ addAggregate(JSON.stringify(normalized).length);
181
+ return normalized;
51
182
  }
183
+ if (typeof current !== "object") fail("value");
184
+ if (ancestors.has(current)) fail("cycle");
185
+ const isArray = inspected(() => Array.isArray(current));
186
+ const prototype = inspected(() => Reflect.getPrototypeOf(current));
187
+ if (isArray ? prototype !== Array.prototype : prototype !== Object.prototype && prototype !== null) fail("shape");
52
188
  ancestors.add(current);
53
189
  try {
54
- if (Array.isArray(current)) {
55
- return `[${current.map((item, index) => visit(item, `${path2}[${index}]`)).join(",")}]`;
190
+ if (isArray) {
191
+ const lengthDescriptor = inspected(() => Reflect.getOwnPropertyDescriptor(current, "length"));
192
+ if (!lengthDescriptor || !Object.hasOwn(lengthDescriptor, "value") || lengthDescriptor.enumerable || typeof lengthDescriptor.value !== "number" || !Number.isSafeInteger(lengthDescriptor.value) || lengthDescriptor.value < 0) fail("shape");
193
+ const length = lengthDescriptor.value;
194
+ assertLimit(length, limits.maximumArrayLength, "array-length");
195
+ elements += length;
196
+ assertLimit(elements, limits.maximumElements, "elements");
197
+ const ownKeys2 = inspected(() => Reflect.ownKeys(current));
198
+ if (ownKeys2.some((key) => typeof key !== "string")) fail("shape");
199
+ if (ownKeys2.length !== length + 1) fail("shape");
200
+ const keySet = new Set(ownKeys2);
201
+ if (!keySet.delete("length")) fail("shape");
202
+ const output2 = new Array(length);
203
+ addAggregate(2 + Math.max(0, length - 1));
204
+ for (let index = 0; index < length; index += 1) {
205
+ const key = String(index);
206
+ if (!keySet.delete(key)) fail("shape");
207
+ const descriptor = inspected(() => Reflect.getOwnPropertyDescriptor(current, key));
208
+ if (!descriptor || !descriptor.enumerable || !Object.hasOwn(descriptor, "value")) fail("shape");
209
+ Object.defineProperty(output2, key, {
210
+ configurable: true,
211
+ enumerable: true,
212
+ value: visit(descriptor.value, depth + 1),
213
+ writable: true
214
+ });
215
+ }
216
+ if (keySet.size !== 0) fail("shape");
217
+ return output2;
56
218
  }
57
- if (!isPlainObject(current)) {
58
- throw new TypeError(`${path2} must contain only plain JSON objects.`);
219
+ const ownKeys = inspected(() => Reflect.ownKeys(current));
220
+ if (ownKeys.some((key) => typeof key !== "string")) fail("shape");
221
+ properties += ownKeys.length;
222
+ assertLimit(properties, limits.maximumProperties, "properties");
223
+ addAggregate(2 + Math.max(0, ownKeys.length - 1) + ownKeys.length);
224
+ const output = {};
225
+ for (const key of ownKeys) {
226
+ addAggregate(addString(key));
227
+ const descriptor = inspected(() => Reflect.getOwnPropertyDescriptor(current, key));
228
+ if (!descriptor || !descriptor.enumerable || !Object.hasOwn(descriptor, "value")) fail("shape");
229
+ Object.defineProperty(output, key, {
230
+ configurable: true,
231
+ enumerable: true,
232
+ value: visit(descriptor.value, depth + 1),
233
+ writable: true
234
+ });
59
235
  }
60
- const keys2 = Object.keys(current).sort();
61
- const properties = keys2.map((key) => {
62
- assertUnicodeScalarString(key, `${path2} key`);
63
- const member = current[key];
64
- if (member === void 0) {
65
- throw new TypeError(`${path2}.${key} is undefined.`);
66
- }
67
- return `${JSON.stringify(key)}:${visit(member, `${path2}.${key}`)}`;
68
- });
69
- return `{${properties.join(",")}}`;
236
+ return output;
70
237
  } finally {
71
238
  ancestors.delete(current);
72
239
  }
73
240
  };
74
- return visit(value, "$root");
241
+ return visit(value, 0);
242
+ }
243
+ function serializeSnapshot(value) {
244
+ if (value === null) return "null";
245
+ if (typeof value === "string" || typeof value === "boolean") return JSON.stringify(value);
246
+ if (typeof value === "number") return JSON.stringify(value);
247
+ if (Array.isArray(value)) return `[${value.map(serializeSnapshot).join(",")}]`;
248
+ const input = value;
249
+ return `{${Object.keys(input).sort().map((key) => `${JSON.stringify(key)}:${serializeSnapshot(input[key])}`).join(",")}}`;
250
+ }
251
+ function canonicalizeGpuContract(value) {
252
+ return serializeSnapshot(snapshotGpuContract(value));
253
+ }
254
+ function canonicalizeQualificationGpuContract(value) {
255
+ return serializeSnapshot(snapshotGpuContract(value, QUALIFICATION_GPU_CONTRACT_SNAPSHOT_LIMITS));
75
256
  }
76
257
 
77
258
  // src/asset-version.ts
@@ -121,11 +302,10 @@ async function computeSha256(value) {
121
302
  var stages = ["vertex", "fragment", "compute"];
122
303
  function detachedJson(value, path2) {
123
304
  try {
124
- return JSON.parse(canonicalizeGpuContract(value));
305
+ return snapshotGpuContract(value);
125
306
  } catch (cause) {
126
- const detail = cause instanceof Error ? cause.message : "Contract snapshot failed.";
127
- const boundedDetail = [...detail].slice(0, 512).join("");
128
- throw new TypeError(`${path2} must contain detached JSON contract data: ${boundedDetail}`, { cause });
307
+ const detail = cause instanceof GpuContractSnapshotError ? ` ${cause.message}` : "";
308
+ throw new TypeError(`${path2} must contain bounded detached JSON contract data.${detail}`);
129
309
  }
130
310
  }
131
311
  function object(value, path2) {
@@ -135,7 +315,7 @@ function object(value, path2) {
135
315
  function exact(value, keys2, path2) {
136
316
  const allowed = new Set(keys2);
137
317
  for (const key of Object.keys(value)) if (!allowed.has(key)) throw new TypeError(`${path2}.${key} is not part of this contract version.`);
138
- for (const key of keys2) if (!(key in value)) throw new TypeError(`${path2}.${key} is required.`);
318
+ for (const key of keys2) if (!Object.hasOwn(value, key)) throw new TypeError(`${path2}.${key} is required.`);
139
319
  }
140
320
  function text(value, path2, maximum = 512) {
141
321
  if (typeof value !== "string" || value.length === 0 || value.length > maximum || [...value].some((character) => character.charCodeAt(0) <= 31)) {
@@ -365,7 +545,7 @@ function freezeJson(value) {
365
545
  }
366
546
  function exactKeys(value, keys2) {
367
547
  const expected = new Set(keys2);
368
- return Object.keys(value).every((key) => expected.has(key)) && keys2.every((key) => key in value);
548
+ return Object.keys(value).every((key) => expected.has(key)) && keys2.every((key) => Object.hasOwn(value, key));
369
549
  }
370
550
  function safeToken(value) {
371
551
  return typeof value === "string" && /^[A-Za-z0-9][A-Za-z0-9._:/-]{0,159}$/u.test(value) && !value.includes("..");
@@ -392,13 +572,13 @@ function defineShaderCompileUnit(unit) {
392
572
  function validateCompileUnitInventory(value) {
393
573
  let snapshot;
394
574
  try {
395
- snapshot = JSON.parse(canonicalizeGpuContract(value));
396
- } catch (cause) {
575
+ snapshot = snapshotGpuContract(value, QUALIFICATION_GPU_CONTRACT_SNAPSHOT_LIMITS);
576
+ } catch {
397
577
  return {
398
578
  ok: false,
399
579
  diagnostics: [issue(
400
580
  "invalid-contract",
401
- cause instanceof Error ? cause.message : "Compile-unit inventory must contain detached JSON data."
581
+ "Compile-unit inventory must contain bounded detached JSON contract data."
402
582
  )]
403
583
  };
404
584
  }
@@ -557,7 +737,12 @@ function object3(value) {
557
737
  }
558
738
  function keys(value, expected) {
559
739
  const set = new Set(expected);
560
- return Object.keys(value).every((key) => set.has(key)) && expected.every((key) => key in value);
740
+ return Object.keys(value).every((key) => set.has(key)) && expected.every((key) => Object.hasOwn(value, key));
741
+ }
742
+ function freezeJson2(value) {
743
+ if (typeof value !== "object" || value === null || Object.isFrozen(value)) return value;
744
+ for (const child of Object.values(value)) freezeJson2(child);
745
+ return Object.freeze(value);
561
746
  }
562
747
  function canonicalEqual(left, right) {
563
748
  try {
@@ -607,7 +792,13 @@ var BASELINE = /* @__PURE__ */ new Map([
607
792
  ["win11-nvidia-edge-d3d12", "edge|windows|x64|physical|nvidia|qualified-nvidia|d3d12|playwright|self-hosted,Windows,X64,shader-validation,physical-gpu,gpu-nvidia,d3d12"]
608
793
  ]);
609
794
  function validateStableWebGpuMatrix(value) {
610
- const matrix = object3(value);
795
+ let snapshot;
796
+ try {
797
+ snapshot = snapshotGpuContract(value);
798
+ } catch {
799
+ return { ok: false, diagnostics: [issue2("Matrix must contain bounded detached JSON contract data.")] };
800
+ }
801
+ const matrix = object3(snapshot);
611
802
  const diagnostics = [];
612
803
  if (!matrix || !keys(matrix, ["contractVersion", "matrixId", "version", "policy", "cells"])) {
613
804
  return { ok: false, diagnostics: [issue2("Matrix has unknown or missing top-level fields.")] };
@@ -680,7 +871,7 @@ function validateStableWebGpuMatrix(value) {
680
871
  }
681
872
  }
682
873
  if (physical !== 15 || blocking !== 16 || software !== 1 || ids.size !== BASELINE.size) diagnostics.push(issue2("Matrix must contain the exact 15 physical baseline cells plus one SwiftShader smoke cell."));
683
- return diagnostics.length > 0 ? { ok: false, diagnostics } : { ok: true, value: matrix };
874
+ return diagnostics.length > 0 ? { ok: false, diagnostics } : { ok: true, value: freezeJson2(matrix) };
684
875
  }
685
876
 
686
877
  // src/testing/qualification-bundle.ts
@@ -774,19 +965,19 @@ function object4(value, path2) {
774
965
  }
775
966
  function detachedJson2(value, label) {
776
967
  try {
777
- return JSON.parse(canonicalizeGpuContract(value));
778
- } catch (cause) {
779
- throw new TypeError(`${label} must contain detached JSON contract data.`, { cause });
968
+ return snapshotGpuContract(value, QUALIFICATION_GPU_CONTRACT_SNAPSHOT_LIMITS);
969
+ } catch {
970
+ throw new TypeError(`${label} must contain bounded detached JSON contract data.`);
780
971
  }
781
972
  }
782
- function freezeJson2(value) {
973
+ function freezeJson3(value) {
783
974
  if (typeof value !== "object" || value === null || Object.isFrozen(value)) return value;
784
- for (const child of Object.values(value)) freezeJson2(child);
975
+ for (const child of Object.values(value)) freezeJson3(child);
785
976
  return Object.freeze(value);
786
977
  }
787
978
  function exact2(value, keys2, path2) {
788
979
  const expected = new Set(keys2);
789
- if (!Object.keys(value).every((key) => expected.has(key)) || !keys2.every((key) => key in value)) throw new TypeError(`${path2} has unknown or missing fields.`);
980
+ if (!Object.keys(value).every((key) => expected.has(key)) || !keys2.every((key) => Object.hasOwn(value, key))) throw new TypeError(`${path2} has unknown or missing fields.`);
790
981
  }
791
982
  function token2(value, path2) {
792
983
  if (typeof value !== "string" || !TOKEN.test(value) || value.includes("..")) throw new TypeError(`${path2} must be a safe token.`);
@@ -795,11 +986,8 @@ function token2(value, path2) {
795
986
  function immutableVersion2(value, path2) {
796
987
  try {
797
988
  return assertImmutableAssetVersion(value);
798
- } catch (cause) {
799
- throw new TypeError(
800
- `${path2} must be an immutable asset version: exact token required; mutable aliases, ranges, wildcards, and URLs are not allowed.`,
801
- { cause }
802
- );
989
+ } catch {
990
+ throw new TypeError(`${path2} must be an immutable asset version: exact token required; mutable aliases, ranges, wildcards, and URLs are not allowed.`);
803
991
  }
804
992
  }
805
993
  function path(value, label, extensions) {
@@ -811,8 +999,8 @@ function path(value, label, extensions) {
811
999
  function sha(value, label) {
812
1000
  try {
813
1001
  return asSha256Hex(String(value));
814
- } catch (cause) {
815
- throw new TypeError(`${label} must be a lowercase SHA-256 digest.`, { cause });
1002
+ } catch {
1003
+ throw new TypeError(`${label} must be a lowercase SHA-256 digest.`);
816
1004
  }
817
1005
  }
818
1006
  function integer2(value, label, minimum = 0, maximum = 4294967295) {
@@ -936,6 +1124,7 @@ function jsonValue(value, label, depth = 0) {
936
1124
  }
937
1125
  function validateQualificationFixture(value, unit) {
938
1126
  try {
1127
+ const compileUnit = unit === void 0 ? void 0 : detachedJson2(unit, "compile unit");
939
1128
  const fixture = object4(detachedJson2(value, "fixture"), "fixture");
940
1129
  exact2(fixture, ["contractVersion", "fixtureId", "resources", "bindGroups", "commands", "layoutProbes", "readbacks", "bounds"], "fixture");
941
1130
  if (fixture.contractVersion !== SHADER_QUALIFICATION_FIXTURE_VERSION) throw new TypeError("Unsupported qualification fixture version.");
@@ -1066,14 +1255,14 @@ function validateQualificationFixture(value, unit) {
1066
1255
  unique2(bindingIds, `${label}.entries`);
1067
1256
  bindGroups.set(id, { group: groupIndex, entries: parsedEntries });
1068
1257
  }
1069
- const pipelines = new Map(unit?.pipelines.map((pipeline2) => [pipeline2.pipelineId, pipeline2]) ?? []);
1258
+ const pipelines = new Map(compileUnit?.pipelines.map((pipeline2) => [pipeline2.pipelineId, pipeline2]) ?? []);
1070
1259
  const pipelineIds = new Set(pipelines.keys());
1071
1260
  const commandBindGroups = (value2, pipelineId, label) => {
1072
1261
  const ids = boundedArray(value2, label, 32).map((item, index) => token2(item, `${label}[${index}]`));
1073
1262
  unique2(ids, label);
1074
1263
  const pipeline2 = pipelines.get(pipelineId);
1075
1264
  if (!pipeline2) {
1076
- if (unit) throw new TypeError(`${label} pipeline is missing.`);
1265
+ if (compileUnit) throw new TypeError(`${label} pipeline is missing.`);
1077
1266
  return;
1078
1267
  }
1079
1268
  const expectedGroups = [...pipeline2.layout.bindGroups].sort((left, right) => left.group - right.group);
@@ -1098,7 +1287,7 @@ function validateQualificationFixture(value, unit) {
1098
1287
  executionCommands += 1;
1099
1288
  exact2(command, ["kind", "pipelineId", "bindGroupIds", "workgroups"], label);
1100
1289
  const id = token2(command.pipelineId, `${label}.pipelineId`);
1101
- if (unit && pipelines.get(id)?.kind !== "compute") throw new TypeError(`${label} references a missing or non-compute pipeline.`);
1290
+ if (compileUnit && pipelines.get(id)?.kind !== "compute") throw new TypeError(`${label} references a missing or non-compute pipeline.`);
1102
1291
  commandBindGroups(command.bindGroupIds, id, `${label}.bindGroupIds`);
1103
1292
  const workgroups = tuple(command.workgroups, `${label}.workgroups`, 3, 1);
1104
1293
  if (workgroups[0] * workgroups[1] * workgroups[2] > 1048576) throw new TypeError(`${label}.workgroups exceeds the hard dispatch bound.`);
@@ -1272,7 +1461,7 @@ function validateQualificationFixture(value, unit) {
1272
1461
  }
1273
1462
  unique2(probeIds, "fixture.layoutProbes probe IDs");
1274
1463
  unique2(probeSources, "fixture.layoutProbes model sources");
1275
- return { ok: true, value: freezeJson2(fixture) };
1464
+ return { ok: true, value: freezeJson3(fixture) };
1276
1465
  } catch (cause) {
1277
1466
  return { ok: false, diagnostics: [{ code: "invalid-contract", severity: "error", message: cause instanceof Error ? cause.message : "Invalid qualification fixture." }] };
1278
1467
  }
@@ -1349,7 +1538,7 @@ function validateQualificationBundleManifest(value) {
1349
1538
  const expectedUnits = [...inventory.value.compileUnits.map((unit) => unit.compileUnitId)].sort();
1350
1539
  if (unitIds.join("\n") !== expectedUnits.join("\n")) throw new TypeError("Subject compile-unit IDs differ from inventory.");
1351
1540
  orderedUniqueTokens(subject.requiredCellIds, "qualification.subject.requiredCellIds");
1352
- return { ok: true, value: freezeJson2(bundle) };
1541
+ return { ok: true, value: freezeJson3(bundle) };
1353
1542
  } catch (cause) {
1354
1543
  return { ok: false, diagnostics: [{ code: "invalid-contract", severity: "error", message: cause instanceof Error ? cause.message : "Invalid qualification bundle." }] };
1355
1544
  }
@@ -1362,7 +1551,37 @@ function object5(value, path2) {
1362
1551
  }
1363
1552
  function exact3(value, keys2, path2) {
1364
1553
  const expected = new Set(keys2);
1365
- if (!Object.keys(value).every((key) => expected.has(key)) || !keys2.every((key) => key in value)) throw new TypeError(`${path2} has unknown or missing fields.`);
1554
+ if (!Object.keys(value).every((key) => expected.has(key)) || !keys2.every((key) => Object.hasOwn(value, key))) throw new TypeError(`${path2} has unknown or missing fields.`);
1555
+ }
1556
+ function detachedQualificationContract(value) {
1557
+ try {
1558
+ return snapshotGpuContract(value, QUALIFICATION_GPU_CONTRACT_SNAPSHOT_LIMITS);
1559
+ } catch {
1560
+ throw new TypeError("Qualification data must contain bounded detached JSON contract data.");
1561
+ }
1562
+ }
1563
+ function parseQualificationJsonBytes(bytes, label) {
1564
+ let snapshot;
1565
+ try {
1566
+ snapshot = snapshotUint8Array(
1567
+ bytes,
1568
+ QUALIFICATION_GPU_CONTRACT_SNAPSHOT_LIMITS.maximumInputBytes
1569
+ );
1570
+ } catch {
1571
+ throw new TypeError(`${label} is not bounded UTF-8 JSON.`);
1572
+ }
1573
+ let parsed;
1574
+ try {
1575
+ parsed = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(snapshot));
1576
+ } catch {
1577
+ throw new TypeError(`${label} is not valid UTF-8 JSON.`);
1578
+ }
1579
+ return detachedQualificationContract(parsed);
1580
+ }
1581
+ function freezeJson4(value) {
1582
+ if (typeof value !== "object" || value === null || Object.isFrozen(value)) return value;
1583
+ for (const child of Object.values(value)) freezeJson4(child);
1584
+ return Object.freeze(value);
1366
1585
  }
1367
1586
  function token3(value, path2, maximum = 512) {
1368
1587
  if (typeof value !== "string" || value.length === 0 || value.length > maximum || [...value].some((character) => character.charCodeAt(0) <= 31)) throw new TypeError(`${path2} is not a bounded string.`);
@@ -1371,8 +1590,8 @@ function token3(value, path2, maximum = 512) {
1371
1590
  function sha2(value, path2) {
1372
1591
  try {
1373
1592
  return asSha256Hex(token3(value, path2, 64));
1374
- } catch (cause) {
1375
- throw new TypeError(`${path2} is not a SHA-256 digest.`, { cause });
1593
+ } catch {
1594
+ throw new TypeError(`${path2} is not a SHA-256 digest.`);
1376
1595
  }
1377
1596
  }
1378
1597
  function integer3(value, path2, minimum = 0) {
@@ -1405,7 +1624,7 @@ function trustedWorkflowRef(value, path2) {
1405
1624
  return result;
1406
1625
  }
1407
1626
  function parseTrustedWorkflowProvenance(value, path2 = "provenance") {
1408
- const input = object5(value, path2);
1627
+ const input = object5(detachedQualificationContract(value), path2);
1409
1628
  exact3(input, ["repository", "commit", "ref", "workflowRef", "workflowSha", "runId", "runAttempt", "job", "eventName", "oidcAttestation"], path2);
1410
1629
  const repository = token3(input.repository, `${path2}.repository`);
1411
1630
  if (!repository.startsWith("Plasius-LTD/")) throw new TypeError(`${path2}.repository is outside Plasius-LTD.`);
@@ -1424,10 +1643,10 @@ function parseTrustedWorkflowProvenance(value, path2 = "provenance") {
1424
1643
  token3(oidc.audience, `${path2}.oidcAttestation.audience`, 2048);
1425
1644
  sha2(oidc.verifiedClaimsSha256, `${path2}.oidcAttestation.verifiedClaimsSha256`);
1426
1645
  timestamp(oidc.verifiedAt, `${path2}.oidcAttestation.verifiedAt`);
1427
- return input;
1646
+ return freezeJson4(input);
1428
1647
  }
1429
1648
  function parseQualificationExecutionProducer(value, path2 = "producer") {
1430
- const input = object5(value, path2);
1649
+ const input = object5(detachedQualificationContract(value), path2);
1431
1650
  exact3(input, ["repository", "commit", "ref", "runId", "runAttempt", "job", "trustedWorkflowRepository", "trustedWorkflowRef", "trustedWorkflowSha", "runner"], path2);
1432
1651
  const repository = token3(input.repository, `${path2}.repository`);
1433
1652
  if (!repository.startsWith("Plasius-LTD/")) throw new TypeError(`${path2}.repository is outside Plasius-LTD.`);
@@ -1445,7 +1664,7 @@ function parseQualificationExecutionProducer(value, path2 = "producer") {
1445
1664
  if (!["github-hosted", "self-hosted", "device-farm"].includes(String(runner.environment))) throw new TypeError(`${path2}.runner.environment is invalid.`);
1446
1665
  token3(runner.os, `${path2}.runner.os`);
1447
1666
  token3(runner.architecture, `${path2}.runner.architecture`);
1448
- return input;
1667
+ return freezeJson4(input);
1449
1668
  }
1450
1669
  function assertProducerMatchesPreflight(producer, provenance, cell, path2, expectedJob) {
1451
1670
  if (producer.repository !== provenance.repository || !canonicalEqual2(producer.commit, provenance.commit) || producer.ref !== provenance.ref || producer.runId !== provenance.runId || producer.runAttempt !== provenance.runAttempt || producer.trustedWorkflowRepository !== "Plasius-LTD/gpu-shader" || producer.trustedWorkflowRef !== provenance.workflowRef || !canonicalEqual2(producer.trustedWorkflowSha, provenance.workflowSha) || producer.job !== expectedJob) throw new TypeError(`${path2} does not match the exact qualification workflow run or subject.`);
@@ -1454,26 +1673,32 @@ function assertProducerMatchesPreflight(producer, provenance, cell, path2, expec
1454
1673
  if (expectedJob === "physical-runner-preflight" && producer.runner.environment !== "github-hosted") throw new TypeError(`${path2} must identify its hosted orchestration job truthfully.`);
1455
1674
  }
1456
1675
  function canonicalEqual2(left, right) {
1457
- return canonicalizeGpuContract(left) === canonicalizeGpuContract(right);
1676
+ return canonicalizeQualificationGpuContract(left) === canonicalizeQualificationGpuContract(right);
1458
1677
  }
1459
1678
  function foldRunnerLabel(value) {
1460
1679
  return value.replace(/[A-Z]/gu, (character) => character.toLowerCase());
1461
1680
  }
1462
1681
  async function computeQualificationInventorySha256(bundle) {
1463
- return computeSha256(canonicalizeGpuContract(bundle.inventory));
1682
+ const snapshot = detachedQualificationContract(bundle);
1683
+ return computeSha256(canonicalizeQualificationGpuContract(snapshot.inventory));
1464
1684
  }
1465
1685
  async function computeQualificationSubjectBinding(input) {
1466
1686
  return computeSha256(`plasius.gpu.qualification-subject/v1
1467
- ${canonicalizeGpuContract(input)}`);
1687
+ ${canonicalizeQualificationGpuContract(input)}`);
1468
1688
  }
1469
1689
  async function computeValidationEvidenceId(value) {
1470
1690
  const input = object5(value, "evidence identity input");
1471
1691
  const projection = Object.fromEntries(Object.entries(input).filter(([key]) => key !== "evidenceId"));
1472
1692
  return `qualification-${(await computeSha256(`plasius.gpu.validation-evidence/v1
1473
- ${canonicalizeGpuContract(projection)}`)).slice(0, 24)}`;
1693
+ ${canonicalizeQualificationGpuContract(projection)}`)).slice(0, 24)}`;
1474
1694
  }
1475
1695
  function immutableBlobUri(value) {
1476
- const url = new URL(value);
1696
+ let url;
1697
+ try {
1698
+ url = new URL(value);
1699
+ } catch {
1700
+ throw new TypeError("Source URI must be a normalized immutable Azure Blob .tar URL.");
1701
+ }
1477
1702
  if (url.protocol !== "https:" || url.username || url.password || url.hash || url.port || !/^[a-z0-9]{3,24}\.blob\.core\.windows\.net$/u.test(url.hostname) || !/^[A-Za-z0-9][A-Za-z0-9._/-]*\.tar$/u.test(url.pathname.slice(1)) || url.pathname.split("/").some((segment, index) => index > 0 && (!segment || segment === "." || segment === ".."))) {
1478
1703
  throw new TypeError("Source URI must be a normalized immutable Azure Blob .tar URL.");
1479
1704
  }
@@ -1483,12 +1708,7 @@ function immutableBlobUri(value) {
1483
1708
  }
1484
1709
  async function createQualificationPreflight(input) {
1485
1710
  token3(input.qualificationId, "qualificationId");
1486
- let parsedMatrix;
1487
- try {
1488
- parsedMatrix = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(input.matrixBytes));
1489
- } catch (cause) {
1490
- throw new TypeError("Selected matrix artifact is not UTF-8 JSON.", { cause });
1491
- }
1711
+ const parsedMatrix = parseQualificationJsonBytes(input.matrixBytes, "Selected matrix artifact");
1492
1712
  if (!canonicalEqual2(parsedMatrix, input.matrix)) throw new TypeError("Selected matrix artifact bytes differ from the supplied matrix value.");
1493
1713
  const actualMatrixSha256 = await computeSha256(input.matrixBytes);
1494
1714
  if (actualMatrixSha256 !== input.matrixSha256) throw new TypeError("Selected matrix digest is not derived from the exact matrix manifest.");
@@ -1658,12 +1878,7 @@ function syntheticResult(unitId, cell, status, message, now) {
1658
1878
  async function aggregateShaderValidationEvidence(input) {
1659
1879
  const verifyArtifact = async (artifact, label) => {
1660
1880
  if (await computeSha256(artifact.bytes) !== artifact.sha256) throw new TypeError(`${label} artifact digest is not derived from its exact bytes.`);
1661
- let parsed;
1662
- try {
1663
- parsed = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(artifact.bytes));
1664
- } catch (cause) {
1665
- throw new TypeError(`${label} bytes are not UTF-8 JSON.`, { cause });
1666
- }
1881
+ const parsed = parseQualificationJsonBytes(artifact.bytes, `${label} bytes`);
1667
1882
  if (!canonicalEqual2(parsed, artifact.value)) throw new TypeError(`${label} parsed value differs from its exact bytes.`);
1668
1883
  };
1669
1884
  await verifyArtifact(input.preflight, "Qualification preflight");
@@ -1685,12 +1900,7 @@ async function aggregateShaderValidationEvidence(input) {
1685
1900
  exact3(sourceBlob, ["host", "versionId", "uri"], "Qualification preflight.sourceBlob");
1686
1901
  const normalizedSource = immutableBlobUri(token3(sourceBlob.uri, "Qualification preflight.sourceBlob.uri", 2048));
1687
1902
  if (!canonicalEqual2(sourceBlob, normalizedSource)) throw new TypeError("Qualification preflight source Blob claims are stale.");
1688
- let parsedMatrix;
1689
- try {
1690
- parsedMatrix = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(input.matrixBytes));
1691
- } catch (cause) {
1692
- throw new TypeError("Matrix artifact is not UTF-8 JSON.", { cause });
1693
- }
1903
+ const parsedMatrix = parseQualificationJsonBytes(input.matrixBytes, "Matrix artifact");
1694
1904
  if (!canonicalEqual2(parsedMatrix, input.matrix)) throw new TypeError("Matrix artifact bytes differ from the supplied matrix value.");
1695
1905
  const actualMatrixSha256 = await computeSha256(input.matrixBytes);
1696
1906
  if (preflight.matrixSha256 !== actualMatrixSha256) throw new TypeError("Qualification preflight matrix artifact digest is stale.");
@@ -1764,7 +1974,7 @@ async function aggregateShaderValidationEvidence(input) {
1764
1974
  if (cellArtifact || diagnostic) throw new TypeError(`Unavailable cell ${cell.cellId} has conflicting evidence.`);
1765
1975
  for (const unit of units) results.push(syntheticResult(unit, cell, "runner-unavailable", "Required physical runner was unavailable.", now));
1766
1976
  const cellResults = results.slice(-units.size);
1767
- cellRuns.push({ cellId: cell.cellId, source: "runner-preflight", sourceArtifactSha256: runner.sha256, resultsSha256: await computeSha256(canonicalizeGpuContract(cellResults)), qualificationPreflightProvenance: preflight.provenance, producer: runner.value.producer, harness: input.harness, automation: null, resultCount: units.size, status: "runner-unavailable" });
1977
+ cellRuns.push({ cellId: cell.cellId, source: "runner-preflight", sourceArtifactSha256: runner.sha256, resultsSha256: await computeSha256(canonicalizeQualificationGpuContract(cellResults)), qualificationPreflightProvenance: preflight.provenance, producer: runner.value.producer, harness: input.harness, automation: null, resultCount: units.size, status: "runner-unavailable" });
1768
1978
  continue;
1769
1979
  }
1770
1980
  if (diagnostic) {
@@ -1779,7 +1989,7 @@ async function aggregateShaderValidationEvidence(input) {
1779
1989
  const status2 = value2.status === "timeout" ? "timeout" : "failed";
1780
1990
  for (const unit of units) results.push(syntheticResult(unit, cell, status2, value2.message, now));
1781
1991
  const cellResults = results.slice(-units.size);
1782
- cellRuns.push({ cellId: cell.cellId, source: "workflow-diagnostic", sourceArtifactSha256: diagnostic.sha256, resultsSha256: await computeSha256(canonicalizeGpuContract(cellResults)), qualificationPreflightProvenance: preflight.provenance, producer: value2.producer, harness: input.harness, automation: null, resultCount: units.size, status: status2 });
1992
+ cellRuns.push({ cellId: cell.cellId, source: "workflow-diagnostic", sourceArtifactSha256: diagnostic.sha256, resultsSha256: await computeSha256(canonicalizeQualificationGpuContract(cellResults)), qualificationPreflightProvenance: preflight.provenance, producer: value2.producer, harness: input.harness, automation: null, resultCount: units.size, status: status2 });
1783
1993
  continue;
1784
1994
  }
1785
1995
  if (!cellArtifact) throw new TypeError(`Cell ${cell.cellId} has no qualification evidence.`);
@@ -1787,7 +1997,7 @@ async function aggregateShaderValidationEvidence(input) {
1787
1997
  if (!matchedRunner) throw new TypeError(`Cell evidence ${cell.cellId} producer was not matched by runner preflight.`);
1788
1998
  const value = assertCellEvidence(cellArtifact.value, cell, input.matrix, preflight, input.harness, runner.value.adapterHarness, matchedRunner, units, now);
1789
1999
  results.push(...value.results);
1790
- cellRuns.push({ cellId: cell.cellId, source: "cell-evidence", sourceArtifactSha256: cellArtifact.sha256, resultsSha256: await computeSha256(canonicalizeGpuContract(value.results)), qualificationPreflightProvenance: value.qualificationPreflightProvenance, producer: value.producer, harness: value.harness, automation: value.automation, resultCount: value.results.length, status: "passed" });
2000
+ cellRuns.push({ cellId: cell.cellId, source: "cell-evidence", sourceArtifactSha256: cellArtifact.sha256, resultsSha256: await computeSha256(canonicalizeQualificationGpuContract(value.results)), qualificationPreflightProvenance: value.qualificationPreflightProvenance, producer: value.producer, harness: value.harness, automation: value.automation, resultCount: value.results.length, status: "passed" });
1791
2001
  }
1792
2002
  const expectedResults = units.size * cells.size;
1793
2003
  if (results.length !== expectedResults) throw new TypeError("Aggregate result product is incomplete.");
@@ -1810,34 +2020,31 @@ async function aggregateShaderValidationEvidence(input) {
1810
2020
  }
1811
2021
  async function validateShaderValidationEvidence(input) {
1812
2022
  try {
1813
- const evidence = object5(input.evidence, "evidence");
2023
+ const evidence = object5(detachedQualificationContract(input.evidence), "evidence");
2024
+ const bundle = detachedQualificationContract(input.bundle);
2025
+ const matrix = detachedQualificationContract(input.matrix);
1814
2026
  exact3(evidence, ["contractVersion", "evidenceId", "status", "generatedAt", "subjectBindingSha256", "subject", "matrixRef", "toolchain", "qualificationPreflightProvenance", "counts", "cellRuns", "results"], "evidence");
1815
2027
  if (evidence.contractVersion !== SHADER_VALIDATION_EVIDENCE_VERSION) throw new TypeError("Unsupported evidence contract version.");
1816
2028
  const evidenceId = token3(evidence.evidenceId, "evidence.evidenceId");
1817
2029
  const generatedAt = timestamp(evidence.generatedAt, "evidence.generatedAt");
1818
2030
  const subjectBindingSha256 = sha2(evidence.subjectBindingSha256, "evidence.subjectBindingSha256");
1819
2031
  if (evidence.status !== "passed" && evidence.status !== "failed") throw new TypeError("Evidence status is invalid.");
1820
- let parsedMatrix;
1821
- try {
1822
- parsedMatrix = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(input.matrixBytes));
1823
- } catch (cause) {
1824
- throw new TypeError("Matrix artifact is not UTF-8 JSON.", { cause });
1825
- }
1826
- if (!canonicalEqual2(parsedMatrix, input.matrix)) throw new TypeError("Matrix artifact bytes differ from the supplied matrix value.");
2032
+ const parsedMatrix = parseQualificationJsonBytes(input.matrixBytes, "Matrix artifact");
2033
+ if (!canonicalEqual2(parsedMatrix, matrix)) throw new TypeError("Matrix artifact bytes differ from the supplied matrix value.");
1827
2034
  const matrixSha256 = await computeSha256(input.matrixBytes);
1828
- const inventorySha256 = await computeQualificationInventorySha256(input.bundle);
1829
- if (inventorySha256 !== input.bundle.subject.compileUnitInventorySha256) throw new TypeError("Bundle subject inventory digest is stale.");
2035
+ const inventorySha256 = await computeQualificationInventorySha256(bundle);
2036
+ if (inventorySha256 !== bundle.subject.compileUnitInventorySha256) throw new TypeError("Bundle subject inventory digest is stale.");
1830
2037
  const subject = object5(evidence.subject, "evidence.subject");
1831
- const expectedSubjectKeys = [...Object.keys(input.bundle.subject), "dataBundleSha256"];
2038
+ const expectedSubjectKeys = [...Object.keys(bundle.subject), "dataBundleSha256"];
1832
2039
  exact3(subject, expectedSubjectKeys, "evidence.subject");
1833
2040
  const candidateSubject = Object.fromEntries(Object.entries(subject).filter(([key]) => key !== "dataBundleSha256"));
1834
- if (!canonicalEqual2(candidateSubject, input.bundle.subject)) throw new TypeError("Evidence candidate subject differs from bundle.");
2041
+ if (!canonicalEqual2(candidateSubject, bundle.subject)) throw new TypeError("Evidence candidate subject differs from bundle.");
1835
2042
  const dataBundleSha256 = sha2(subject.dataBundleSha256, "evidence.subject.dataBundleSha256");
1836
2043
  if (input.dataBundleSha256 && input.dataBundleSha256 !== dataBundleSha256) throw new TypeError("Evidence data bundle digest differs from the exact archive.");
1837
2044
  if (subject.compileUnitInventorySha256 !== inventorySha256) throw new TypeError("Evidence compile-unit inventory digest is stale.");
1838
2045
  const matrixRef = object5(evidence.matrixRef, "evidence.matrixRef");
1839
2046
  exact3(matrixRef, ["matrixId", "version", "sha256"], "evidence.matrixRef");
1840
- if (matrixRef.matrixId !== input.matrix.matrixId || matrixRef.version !== input.matrix.version || matrixRef.sha256 !== matrixSha256) throw new TypeError("Evidence matrix artifact identity differs.");
2047
+ if (matrixRef.matrixId !== matrix.matrixId || matrixRef.version !== matrix.version || matrixRef.sha256 !== matrixSha256) throw new TypeError("Evidence matrix artifact identity differs.");
1841
2048
  const toolchain = object5(evidence.toolchain, "evidence.toolchain");
1842
2049
  exact3(toolchain, ["packageVersion", "reflectorVersion", "harness"], "evidence.toolchain");
1843
2050
  token3(toolchain.packageVersion, "evidence.toolchain.packageVersion");
@@ -1849,11 +2056,11 @@ async function validateShaderValidationEvidence(input) {
1849
2056
  const harnessSha256 = sha2(harness.sha256, "evidence.toolchain.harness.sha256");
1850
2057
  const preflightProvenance = parseTrustedWorkflowProvenance(evidence.qualificationPreflightProvenance, "evidence.qualificationPreflightProvenance");
1851
2058
  if (Date.parse(generatedAt) < Date.parse(preflightProvenance.oidcAttestation.verifiedAt)) throw new TypeError("Evidence predates trusted preflight verification.");
1852
- const expectedBinding = await computeQualificationSubjectBinding({ subject: input.bundle.subject, dataBundleSha256, compileUnitInventorySha256: inventorySha256, matrixSha256, harnessSha256 });
2059
+ const expectedBinding = await computeQualificationSubjectBinding({ subject: bundle.subject, dataBundleSha256, compileUnitInventorySha256: inventorySha256, matrixSha256, harnessSha256 });
1853
2060
  if (subjectBindingSha256 !== expectedBinding) throw new TypeError("Evidence subject binding is stale.");
1854
2061
  if (evidenceId !== await computeValidationEvidenceId(evidence)) throw new TypeError("Evidence identity is stale.");
1855
- const units = new Set(input.bundle.inventory.compileUnits.map((unit) => unit.compileUnitId));
1856
- const cells = new Map(input.matrix.cells.map((cell) => [cell.cellId, cell]));
2062
+ const units = new Set(bundle.inventory.compileUnits.map((unit) => unit.compileUnitId));
2063
+ const cells = new Map(matrix.cells.map((cell) => [cell.cellId, cell]));
1857
2064
  const expected = units.size * cells.size;
1858
2065
  const results = array2(evidence.results, "evidence.results");
1859
2066
  if (results.length !== expected) throw new TypeError("Evidence result product is incomplete.");
@@ -1903,7 +2110,7 @@ async function validateShaderValidationEvidence(input) {
1903
2110
  sha2(automation2.sha256, `${path2}.automation.sha256`);
1904
2111
  } else if (run.automation !== null) throw new TypeError(`${path2}.automation must be null when no adapter completed a cell run.`);
1905
2112
  const cellResults = parsedResults.filter((result) => result.cellId === cellId);
1906
- if (run.resultCount !== units.size || cellResults.length !== units.size || await computeSha256(canonicalizeGpuContract(cellResults)) !== resultsSha256) throw new TypeError(`${path2} result count/digest is stale.`);
2113
+ if (run.resultCount !== units.size || cellResults.length !== units.size || await computeSha256(canonicalizeQualificationGpuContract(cellResults)) !== resultsSha256) throw new TypeError(`${path2} result count/digest is stale.`);
1907
2114
  const resultStatuses = new Set(cellResults.map((result) => result.status));
1908
2115
  if (resultStatuses.size !== 1 || !resultStatuses.has(String(run.status))) throw new TypeError(`${path2}.status differs from its results.`);
1909
2116
  if (run.source === "cell-evidence" && run.status !== "passed") throw new TypeError(`${path2} cell evidence must contain passing results.`);
@@ -1912,13 +2119,13 @@ async function validateShaderValidationEvidence(input) {
1912
2119
  if (run.source === "cell-evidence" && cellResults.some((result) => result.observed.runner.id !== producer.runner.name)) throw new TypeError(`${path2} producer runner differs from its results.`);
1913
2120
  }
1914
2121
  if (evidence.status === "passed" !== (passed === expected) || input.requirePassed !== false && evidence.status !== "passed") throw new TypeError("Evidence does not satisfy the required passed gate.");
1915
- return { ok: true, value: evidence };
2122
+ return { ok: true, value: freezeJson4(evidence) };
1916
2123
  } catch (cause) {
1917
2124
  return { ok: false, diagnostics: [{ code: "invalid-contract", severity: "error", message: cause instanceof Error ? cause.message : "Invalid shader validation evidence." }] };
1918
2125
  }
1919
2126
  }
1920
2127
  function parseShaderValidationEvidenceAttestationRef(value) {
1921
- const input = object5(value, "attestationRef");
2128
+ const input = object5(detachedQualificationContract(value), "attestationRef");
1922
2129
  exact3(input, ["contractVersion", "kind", "evidence", "attestation", "producer"], "attestationRef");
1923
2130
  if (input.contractVersion !== SHADER_VALIDATION_EVIDENCE_VERSION || input.kind !== "shader-validation-evidence-attestation-ref") throw new TypeError("Unsupported evidence attestation ref.");
1924
2131
  const producer = object5(input.producer, "attestationRef.producer");
@@ -1938,7 +2145,12 @@ function parseShaderValidationEvidenceAttestationRef(value) {
1938
2145
  const attestation = object5(input.attestation, "attestationRef.attestation");
1939
2146
  exact3(attestation, ["id", "url", "bundle"], "attestationRef.attestation");
1940
2147
  token3(attestation.id, "attestationRef.attestation.id");
1941
- const url = new URL(token3(attestation.url, "attestationRef.attestation.url", 2048));
2148
+ let url;
2149
+ try {
2150
+ url = new URL(token3(attestation.url, "attestationRef.attestation.url", 2048));
2151
+ } catch {
2152
+ throw new TypeError("Attestation URL must be an exact GitHub repository attestation URL.");
2153
+ }
1942
2154
  const expectedPrefix = `/${repository}/attestations/`;
1943
2155
  if (url.protocol !== "https:" || url.hostname !== "github.com" || url.port || url.username || url.password || url.search || url.hash || !url.pathname.startsWith(expectedPrefix) || url.pathname.length <= expectedPrefix.length) throw new TypeError("Attestation URL must be an exact GitHub repository attestation URL.");
1944
2156
  const bundle = object5(attestation.bundle, "attestationRef.attestation.bundle");
@@ -1946,13 +2158,43 @@ function parseShaderValidationEvidenceAttestationRef(value) {
1946
2158
  const bundleName = token3(bundle.name, "attestationRef.attestation.bundle.name");
1947
2159
  if (!/^[A-Za-z0-9._-]+\.json$/u.test(bundleName)) throw new TypeError("Attestation bundle name must be a JSON basename.");
1948
2160
  sha2(bundle.sha256, "attestationRef.attestation.bundle.sha256");
1949
- return input;
2161
+ return freezeJson4(input);
1950
2162
  }
1951
2163
  async function verifyShaderValidationEvidenceAttestation(input) {
1952
2164
  try {
1953
- const ref = parseShaderValidationEvidenceAttestationRef(input.ref);
1954
- if (await computeSha256(input.evidenceBytes) !== ref.evidence.sha256 || await computeSha256(input.bundleBytes) !== ref.attestation.bundle.sha256) throw new TypeError("Attested evidence or bundle digest differs.");
1955
- if (!await input.verifyCryptographicBundle({ ref, evidenceBytes: input.evidenceBytes, bundleBytes: input.bundleBytes })) throw new TypeError("External build-provenance cryptographic verification failed.");
2165
+ if (typeof input !== "object" || input === null) throw new TypeError("Evidence attestation verification input is invalid.");
2166
+ let values;
2167
+ try {
2168
+ const keys2 = Reflect.ownKeys(input);
2169
+ const expected = ["ref", "evidenceBytes", "bundleBytes", "verifyCryptographicBundle"];
2170
+ if (keys2.length !== expected.length || keys2.some((key) => typeof key !== "string" || !expected.includes(key))) throw new TypeError();
2171
+ values = expected.map((key) => {
2172
+ const descriptor = Reflect.getOwnPropertyDescriptor(input, key);
2173
+ if (!descriptor?.enumerable || !Object.hasOwn(descriptor, "value")) throw new TypeError();
2174
+ return descriptor;
2175
+ });
2176
+ } catch {
2177
+ throw new TypeError("Evidence attestation verification input is invalid.");
2178
+ }
2179
+ const [refValue, evidenceValue, bundleValue, verifierValue] = values;
2180
+ if (typeof verifierValue?.value !== "function") throw new TypeError("Evidence attestation verification input is invalid.");
2181
+ const evidenceBytes = snapshotUint8Array(
2182
+ evidenceValue?.value,
2183
+ QUALIFICATION_GPU_CONTRACT_SNAPSHOT_LIMITS.maximumInputBytes
2184
+ );
2185
+ const bundleBytes = snapshotUint8Array(
2186
+ bundleValue?.value,
2187
+ QUALIFICATION_GPU_CONTRACT_SNAPSHOT_LIMITS.maximumInputBytes
2188
+ );
2189
+ const ref = parseShaderValidationEvidenceAttestationRef(refValue?.value);
2190
+ if (await computeSha256(evidenceBytes) !== ref.evidence.sha256 || await computeSha256(bundleBytes) !== ref.attestation.bundle.sha256) throw new TypeError("Attested evidence or bundle digest differs.");
2191
+ let verified;
2192
+ try {
2193
+ verified = await Reflect.apply(verifierValue.value, void 0, [{ ref, evidenceBytes, bundleBytes }]);
2194
+ } catch {
2195
+ throw new TypeError("External build-provenance cryptographic verification failed.");
2196
+ }
2197
+ if (verified !== true) throw new TypeError("External build-provenance cryptographic verification failed.");
1956
2198
  return { ok: true, value: ref };
1957
2199
  } catch (cause) {
1958
2200
  return { ok: false, diagnostics: [{ code: "invalid-contract", severity: "error", message: cause instanceof Error ? cause.message : "Evidence attestation verification failed." }] };