@threenative/runtime-native 0.3.2 → 0.3.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.
@@ -5,6 +5,8 @@ import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
5
5
  import { join, relative, sep } from "node:path";
6
6
 
7
7
  export const PHYSICAL_EVIDENCE_SCHEMA = "physicalDeviceEvidenceV1";
8
+ /** v2 keeps every v1 block and re-reads only the lifecycle and the unmeasured timings. */
9
+ export const PHYSICAL_EVIDENCE_V2_SCHEMA = "physicalDeviceEvidenceV2";
8
10
  export const REQUIRED_PREREQUISITES = ["prd053", "prd054", "prd046", "prd048"];
9
11
  export const REQUIRED_GATE_IDS = [
10
12
  "evidence-schema",
@@ -21,6 +23,13 @@ export const REQUIRED_GATE_IDS = [
21
23
  "repository-collection",
22
24
  ];
23
25
 
26
+ /** The operations a v2 lifecycle certifies, in the order the device reads them; any later phase is a resume. */
27
+ const LIFECYCLE_OPERATIONS = ["background", "foreground", "rotate"];
28
+ /** v2 lifecycle times are offsets from the run's own clock. A wall-clock reading is a time no read produced. */
29
+ const RUN_RELATIVE_CLOCK = "run-relative-ms";
30
+ /** Timings the collector never measured, recorded as unmeasured rather than filled from the run's start. */
31
+ const UNMEASURED_TIMINGS = ["readyAt", "firstFrameAt", "frame300At"];
32
+
24
33
  const ROOT_KEYS = new Set([
25
34
  "schemaVersion",
26
35
  "identity",
@@ -287,6 +296,99 @@ function validateLifecycle(value, errors, execution) {
287
296
  if (value.stateContinuity !== true) add(errors, `${path}.stateContinuity`, "must be true for a physical resume report");
288
297
  }
289
298
 
299
+ /**
300
+ * The v2 execution block: the facts the run measured, with the three timings it did not.
301
+ *
302
+ * `sessionNonce` is gone because a device observation carries no nonce — the session claim is the
303
+ * one process every reading and this block share. The unmeasured timings are `null` rather than
304
+ * absent, so a reader can tell "not measured" from "not written about", and a string in any of
305
+ * them is refused: a value copied from the run's own start would read as a measurement.
306
+ */
307
+ function validateExecutionV2(value, errors) {
308
+ const path = "execution";
309
+ if (!objectAt(value, path, errors, new Set(["installStartedAt", "launchStartedAt", ...UNMEASURED_TIMINGS, "pid", "frames", "nonBlankCaptureSha256", "gpuErrorCount", "arm64", "nativeGpu", "processLiveness", "assertionCount"]))) return;
310
+ timestampAt(value.installStartedAt, `${path}.installStartedAt`, errors);
311
+ timestampAt(value.launchStartedAt, `${path}.launchStartedAt`, errors);
312
+ for (const key of UNMEASURED_TIMINGS) {
313
+ if (value[key] !== null) add(errors, `${path}.${key}`, "must be null: this run never measured it, and a time taken from the run's start would be a reading no device produced");
314
+ }
315
+ finiteNumberAt(value.pid, `${path}.pid`, errors, { integer: true, minimum: 1 });
316
+ finiteNumberAt(value.frames, `${path}.frames`, errors, { integer: true, minimum: 300 });
317
+ hashAt(value.nonBlankCaptureSha256, `${path}.nonBlankCaptureSha256`, errors);
318
+ finiteNumberAt(value.gpuErrorCount, `${path}.gpuErrorCount`, errors, { integer: true, minimum: 0 });
319
+ if (value.gpuErrorCount !== 0) add(errors, `${path}.gpuErrorCount`, "must equal zero");
320
+ if (value.arm64 !== true) add(errors, `${path}.arm64`, "must be true");
321
+ if (value.nativeGpu !== true) add(errors, `${path}.nativeGpu`, "must be true; software GPU is not physical evidence");
322
+ booleanAt(value.processLiveness, `${path}.processLiveness`, errors);
323
+ finiteNumberAt(value.assertionCount, `${path}.assertionCount`, errors, { integer: true, minimum: 1 });
324
+ if (value.processLiveness !== true) add(errors, `${path}.processLiveness`, "must be true for a passing physical report");
325
+ }
326
+
327
+ /**
328
+ * The v2 lifecycle block: one row per device-read operation, the readings it carried, and three
329
+ * step counts bracketing the away period.
330
+ *
331
+ * Nothing here is attributed to a phase that did not produce it — no wall-clock `at`, no session
332
+ * nonce, no per-phase step count, no fourth phase. Every claim v1 asserted as a standalone boolean
333
+ * is instead re-derived from these numbers below, and refused when the readings deny it.
334
+ */
335
+ function validateLifecycleV2(value, errors, execution) {
336
+ const path = "lifecycle";
337
+ if (!objectAt(value, path, errors, new Set(["clock", "operations", "framesPaused", "framesAdvanced", "physics"]))) return;
338
+ if (value.clock !== RUN_RELATIVE_CLOCK) add(errors, `${path}.clock`, `must be ${RUN_RELATIVE_CLOCK}; the runner reads offsets from the run's own clock, and a wall-clock time here would be one no read produced`);
339
+ if (!Array.isArray(value.operations)) add(errors, `${path}.operations`, "must be an array");
340
+ else if (value.operations.length < LIFECYCLE_OPERATIONS.length) add(errors, `${path}.operations`, `must carry at least ${LIFECYCLE_OPERATIONS.length} device-read operations`);
341
+ else {
342
+ let previous;
343
+ for (const [index, operation] of value.operations.entries()) {
344
+ const opPath = `${path}.operations[${index}]`;
345
+ if (!objectAt(operation, opPath, errors, new Set(["operation", "offsetMs", "frames", "focused", "framesPaused", "pid", "windowRotation", "requestedRotation"]))) continue;
346
+ const expected = LIFECYCLE_OPERATIONS[index] ?? "foreground";
347
+ if (operation.operation !== expected) add(errors, `${opPath}.operation`, `must be the ${expected} operation this claim rests on`);
348
+ if (operation.focused !== (operation.operation !== "background")) add(errors, `${opPath}.focused`, `must be ${String(operation.operation !== "background")}; the device reports unfocused only while the app is away`);
349
+ if (index === 0 && operation.framesPaused !== true) add(errors, `${opPath}.framesPaused`, "must be true; the backgrounded reading itself has to show the frame counter stopping");
350
+ finiteNumberAt(operation.offsetMs, `${opPath}.offsetMs`, errors, { minimum: 0 });
351
+ finiteNumberAt(operation.frames, `${opPath}.frames`, errors, { integer: true, minimum: 0 });
352
+ finiteNumberAt(operation.pid, `${opPath}.pid`, errors, { integer: true, minimum: 1 });
353
+ if (operation.pid !== execution?.pid) add(errors, `${opPath}.pid`, "must be the one process the rest of the evidence recorded");
354
+ if (Number.isFinite(operation.offsetMs) && Number.isFinite(previous?.offsetMs) && operation.offsetMs <= previous.offsetMs) add(errors, `${opPath}.offsetMs`, `is ${String(operation.offsetMs)}, not after the previous operation's ${String(previous.offsetMs)}`);
355
+ if (Number.isInteger(operation.frames) && Number.isInteger(previous?.frames) && operation.frames < previous.frames) add(errors, `${opPath}.frames`, `is ${String(operation.frames)}, below the previous operation's ${String(previous.frames)}; a device frame count does not run backwards`);
356
+ if (expected === "rotate") {
357
+ if (operation.windowRotation !== operation.requestedRotation) add(errors, `${opPath}.windowRotation`, `is ${String(operation.windowRotation)}, not the requested rotation ${String(operation.requestedRotation)}; the device has to have turned, not merely been asked to`);
358
+ if (operation.windowRotation === previous?.windowRotation) add(errors, `${opPath}.windowRotation`, `is still ${String(operation.windowRotation)}, so the device never turned`);
359
+ }
360
+ previous = operation;
361
+ }
362
+ }
363
+ const [away, resumed] = [value.operations?.[0], value.operations?.at(-1)];
364
+ booleanAt(value.framesPaused, `${path}.framesPaused`, errors);
365
+ booleanAt(value.framesAdvanced, `${path}.framesAdvanced`, errors);
366
+ if (value.framesPaused !== true) add(errors, `${path}.framesPaused`, "must be true for a passing physical report");
367
+ if (value.framesAdvanced !== true) add(errors, `${path}.framesAdvanced`, "must be true for a passing physical report");
368
+ if (isRecord(away) && Number.isInteger(away.frames) && Number.isInteger(resumed?.frames)) {
369
+ if (value.framesPaused !== away.framesPaused) add(errors, `${path}.framesPaused`, `is ${String(value.framesPaused)}, but the backgrounded reading recorded ${String(away.framesPaused)}`);
370
+ if (value.framesAdvanced !== (resumed.frames > away.frames)) add(errors, `${path}.framesAdvanced`, `is ${String(value.framesAdvanced)}, but the readings' own frame counts ${resumed.frames > away.frames ? "advance" : "do not advance"} past the backgrounded one`);
371
+ }
372
+ validateLifecycleStepsV2(value.physics, errors);
373
+ }
374
+
375
+ /** Three step counts around the away period: a claim the counts have to agree with, not replace. */
376
+ function validateLifecycleStepsV2(value, errors) {
377
+ const path = "lifecycle.physics";
378
+ if (!objectAt(value, path, errors, new Set(["steps", "stepsPaused", "stepsAdvanced"]))) return;
379
+ const stepsPath = `${path}.steps`;
380
+ if (!objectAt(value.steps, stepsPath, errors, new Set(["beforeBackground", "afterForeground", "afterAdvance"]))) return;
381
+ for (const key of ["beforeBackground", "afterForeground", "afterAdvance"]) finiteNumberAt(value.steps[key], `${stepsPath}.${key}`, errors, { integer: true, minimum: 0 });
382
+ booleanAt(value.stepsPaused, `${path}.stepsPaused`, errors);
383
+ booleanAt(value.stepsAdvanced, `${path}.stepsAdvanced`, errors);
384
+ if (value.stepsPaused !== true) add(errors, `${path}.stepsPaused`, "must be true for a passing physical report");
385
+ if (value.stepsAdvanced !== true) add(errors, `${path}.stepsAdvanced`, "must be true for a passing physical report");
386
+ const { beforeBackground, afterForeground, afterAdvance } = value.steps;
387
+ if (![beforeBackground, afterForeground, afterAdvance].every((step) => Number.isInteger(step) && step >= 0)) return;
388
+ if (afterForeground !== beforeBackground) add(errors, stepsPath, `the simulation stepped from ${String(beforeBackground)} to ${String(afterForeground)} while the app was away`);
389
+ if (afterAdvance <= afterForeground) add(errors, stepsPath, `the simulation did not advance after the return (${String(afterForeground)} to ${String(afterAdvance)})`);
390
+ }
391
+
290
392
  function validateMultitouch(value, errors, path) {
291
393
  if (!objectAt(value, path, errors, new Set(["status", "reportPath", "reportSha256", "candidateSha", "deviceClass", "maxPointers", "simultaneousMovementAndJump", "onePointerControl"]))) return;
292
394
  enumAt(value.status, `${path}.status`, errors, ["pass"]);
@@ -403,7 +505,7 @@ function validateConsumption(value, errors, candidateSha) {
403
505
  for (const key of ["multitouch", "physics"]) if (value[key]?.candidateSha !== candidateSha) add(errors, `${path}.${key}.candidateSha`, `must match candidate SHA ${candidateSha ?? "from source"}`);
404
506
  }
405
507
 
406
- export function validatePhysicalDeviceEvidence(evidence, options = {}) {
508
+ export function validatePhysicalDeviceEvidenceV1(evidence, options = {}) {
407
509
  const errors = [];
408
510
  if (!objectAt(evidence, "evidence", errors, ROOT_KEYS)) return { valid: false, errors };
409
511
  if (evidence.schemaVersion !== 1) add(errors, "schemaVersion", "must equal 1");
@@ -423,6 +525,32 @@ export function validatePhysicalDeviceEvidence(evidence, options = {}) {
423
525
  return { valid: errors.length === 0, errors: [...new Set(errors)] };
424
526
  }
425
527
 
528
+ export function validatePhysicalDeviceEvidenceV2(evidence, options = {}) {
529
+ const errors = [];
530
+ if (!objectAt(evidence, "evidence", errors, ROOT_KEYS)) return { valid: false, errors };
531
+ if (evidence.schemaVersion !== 2) add(errors, "schemaVersion", "must equal 2");
532
+ validateIdentity(evidence.identity, errors);
533
+ validateSource(evidence.source, errors, options);
534
+ validateDevice(evidence.device, errors, options);
535
+ validateSigning(evidence.signing, errors);
536
+ const candidateSha = options.candidateSha ?? evidence.source?.headSha;
537
+ validatePrerequisites(evidence.prerequisites, errors, { candidateSha });
538
+ validateExecutionV2(evidence.execution, errors);
539
+ validateLifecycleV2(evidence.lifecycle, errors, evidence.execution);
540
+ validateConsumption(evidence.consumption, errors, candidateSha);
541
+ validateTelemetry(evidence.telemetry, errors);
542
+ validateArtifacts(evidence.artifacts, errors);
543
+ validateGateEvidence(evidence.gateEvidence, errors);
544
+ if (evidence.identity?.verdict === "pass" && evidence.identity?.blockers?.length > 0) add(errors, "identity.blockers", "a pass report cannot contain blockers");
545
+ return { valid: errors.length === 0, errors: [...new Set(errors)] };
546
+ }
547
+
548
+ export function validatePhysicalDeviceEvidence(evidence, options = {}) {
549
+ return evidence?.schemaVersion === 2
550
+ ? validatePhysicalDeviceEvidenceV2(evidence, options)
551
+ : validatePhysicalDeviceEvidenceV1(evidence, options);
552
+ }
553
+
426
554
  export function assertValidPhysicalDeviceEvidence(evidence, options = {}) {
427
555
  const result = validatePhysicalDeviceEvidence(evidence, options);
428
556
  if (!result.valid) throw new EvidenceValidationError(result.errors);
@@ -435,6 +563,12 @@ export function physicalDeviceEvidenceV1(evidence, options = {}) {
435
563
 
436
564
  physicalDeviceEvidenceV1.schema = PHYSICAL_EVIDENCE_SCHEMA;
437
565
 
566
+ export function physicalDeviceEvidenceV2(evidence, options = {}) {
567
+ return validatePhysicalDeviceEvidenceV2(evidence, options);
568
+ }
569
+
570
+ physicalDeviceEvidenceV2.schema = PHYSICAL_EVIDENCE_V2_SCHEMA;
571
+
438
572
  export function sha256(value) {
439
573
  return createHash("sha256").update(value).digest("hex");
440
574
  }
@@ -31,19 +31,44 @@ export function nearestRank(values, percentile) {
31
31
 
32
32
  export function meanFps(frameIntervalsMs) {
33
33
  if (!Array.isArray(frameIntervalsMs) || frameIntervalsMs.length === 0) return undefined;
34
- if (frameIntervalsMs.some((value) => !Number.isFinite(value) || value <= 0)) return undefined;
35
- const mean = frameIntervalsMs.reduce((total, value) => total + value, 0) / frameIntervalsMs.length;
34
+ // Two presented frames can land inside one `performance.now()` quantum, which reads as a
35
+ // zero-length interval, and a cadence-limited browser produces them routinely. That is the
36
+ // clock's resolution rather than a measurement of the workload, and refusing the whole series
37
+ // over one of them discarded every other reading and blocked the comparison that had them.
38
+ // Excluding them can only understate the frame rate, and a series with nothing measurable left
39
+ // is still unmeasured.
40
+ //
41
+ // The exemption is the clock's alone: NaN, a negative and Infinity are malformed readings, and
42
+ // dropping them would publish a passing frame rate computed from the samples that happened to
43
+ // survive. Any invalid nonzero reading leaves the whole series unmeasured.
44
+ if (frameIntervalsMs.some((value) => !Number.isFinite(value) || value < 0)) return undefined;
45
+ const measurable = frameIntervalsMs.filter((value) => value > 0);
46
+ if (measurable.length === 0) return undefined;
47
+ const mean = measurable.reduce((total, value) => total + value, 0) / measurable.length;
36
48
  return 1_000 / mean;
37
49
  }
38
50
 
39
- export function oneSecondFrameFloors(intervals) {
40
- if (!Array.isArray(intervals) || intervals.length === 0) return [];
41
- const first = intervals[0]?.timestampMs;
42
- const last = intervals.at(-1)?.timestampMs;
51
+ /** How many of a series the clock could not resolve, so the evidence never hides the loss. */
52
+ export function unmeasurableIntervalCount(frameIntervalsMs) {
53
+ if (!Array.isArray(frameIntervalsMs)) return 0;
54
+ return frameIntervalsMs.filter((value) => value === 0).length;
55
+ }
56
+
57
+ /**
58
+ * Presented frames per second, from the elapsed milliseconds at which each presented frame landed.
59
+ *
60
+ * The count that used to be bucketed here was one record per rAF *callback*, and both arms run three
61
+ * callbacks per displayed frame, so a 40 fps display answered 120 and any `minOneSecondFps` floor
62
+ * passed on cadence it never presented. The stamps are the presented series, one per frame.
63
+ */
64
+ export function oneSecondFrameFloors(presentedStampsMs) {
65
+ if (!Array.isArray(presentedStampsMs) || presentedStampsMs.length === 0) return [];
66
+ const first = presentedStampsMs[0];
67
+ const last = presentedStampsMs.at(-1);
43
68
  if (!Number.isFinite(first) || !Number.isFinite(last) || last - first < 1_000) return [];
44
69
  const buckets = Math.floor((last - first) / 1_000);
45
- return Array.from({ length: buckets }, (_, bucket) => intervals.filter(({ timestampMs }) => {
46
- const offset = timestampMs - first;
70
+ return Array.from({ length: buckets }, (_, bucket) => presentedStampsMs.filter((stamp) => {
71
+ const offset = stamp - first;
47
72
  return offset >= bucket * 1_000 && offset < (bucket + 1) * 1_000;
48
73
  }).length);
49
74
  }
@@ -55,7 +80,9 @@ export function evaluateFrameBudget(metrics, budget = {}) {
55
80
  const p99 = finiteMetric(metrics.p99FrameMs) ? metrics.p99FrameMs : nearestRank(metrics.frameIntervalsMs, 0.99);
56
81
  const medianFrameMs = nearestRank(metrics.frameIntervalsMs, 0.5);
57
82
  if (budget.minFps !== undefined && (!finiteMetric(medianFrameMs) || Math.round(100_000 / medianFrameMs) / 100 < budget.minFps)) failures.push('TN_PROD_PERFORMANCE_BUDGET');
58
- const floors = metrics.oneSecondFps ?? oneSecondFrameFloors(metrics.intervals ?? []);
83
+ // Read the published presented-frame floors or nothing: the callback records this used to bucket
84
+ // are not a frame count, and an absent floor fails the budget rather than passing it unseen.
85
+ const floors = Array.isArray(metrics.oneSecondFps) ? metrics.oneSecondFps : [];
59
86
  const drawCalls = maximumMetric(metrics, 'drawCalls');
60
87
  const triangles = maximumMetric(metrics, 'triangles');
61
88
  if (budget.minMeanFps !== undefined && (mean === undefined || mean < budget.minMeanFps)) failures.push('TN_PROD_PERFORMANCE_BUDGET');
@@ -332,9 +359,13 @@ function strictlyIncreasing(values) {
332
359
 
333
360
  function maximumMetric(metrics, key) {
334
361
  if (Array.isArray(metrics.intervals) && metrics.intervals.length > 0) {
335
- const values = metrics.intervals.map((sample) => sample?.[key]);
336
- if (values.some((value) => !finiteMetric(value))) return undefined;
337
- return Math.max(...values);
362
+ // The first frame of each collection window settles before the asynchronous renderer read
363
+ // resolves, so it carries no draw-call or triangle reading. Match the producer, which takes the
364
+ // maximum over the readings that exist; a series with no reading at all stays unmeasured.
365
+ const values = metrics.intervals
366
+ .map((sample) => sample?.[key])
367
+ .filter((value) => finiteMetric(value));
368
+ return values.length > 0 ? Math.max(...values) : undefined;
338
369
  }
339
370
  return finiteMetric(metrics[key]) ? metrics[key] : undefined;
340
371
  }