@threenative/runtime-native 0.3.2 → 0.3.3

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.
@@ -53,6 +53,9 @@ const SLOW_STARTUP_DELAY_MS = 5_100;
53
53
  const FRAME_SAMPLE_BATCH_SIZE = 30;
54
54
  // Android logcat truncates long lines, so native samples use a smaller JSON batch.
55
55
  const NATIVE_FRAME_SAMPLE_BATCH_SIZE = 5;
56
+ // The wall-clock a paced fixed step gives each tick, so a synthetic workload's tick budget stands
57
+ // in for the seconds it names and the host's render loop actually presents frames while it runs.
58
+ const PRODUCTION_TICK_INTERVAL_MS = 1_000 / 60;
56
59
  const DESKTOP_SCREENSHOT_TIMEOUT_MS = 5_000;
57
60
  const PRODUCTION_PROFILE = 'production';
58
61
  const REGRESSION_PROFILE = 'regression';
@@ -299,9 +302,10 @@ async function scaffoldPlatformer(project, tools) {
299
302
  '--template', 'platformer',
300
303
  ...localSources.flatMap(([name, source]) => [packageSourceFlag(name), source]),
301
304
  ];
302
- const result = await runCommand(process.execPath, args, commandRoot);
305
+ // Scaffolding packs and installs the whole workspace, which is slow on hosted runners.
306
+ const result = await runCommand(process.execPath, args, commandRoot, undefined, 600_000);
303
307
  if (result.status !== 0) {
304
- throw new ProductionEvidenceError('TN_PROD_SCAFFOLD_FAILED', 'Scaffolding the production platformer failed.');
308
+ throw new ProductionEvidenceError('TN_PROD_SCAFFOLD_FAILED', `Scaffolding the production platformer failed.${failureSuffix(result)}`);
305
309
  }
306
310
  }
307
311
 
@@ -319,7 +323,7 @@ function localWorkspacePackages() {
319
323
  async function packLocalPackage(directory, destination) {
320
324
  const before = new Set(await readdir(destination));
321
325
  const result = await runCommand('pnpm', ['pack', '--pack-destination', destination], directory);
322
- if (result.status !== 0) throw new ProductionEvidenceError('TN_PROD_PACKAGE_ARCHIVE_FAILED', `Packing local package '${basename(directory)}' failed.`);
326
+ if (result.status !== 0) throw new ProductionEvidenceError('TN_PROD_PACKAGE_ARCHIVE_FAILED', `Packing local package '${basename(directory)}' failed.${failureSuffix(result)}`);
323
327
  const archive = (await readdir(destination)).find((entry) => entry.endsWith('.tgz') && !before.has(entry));
324
328
  if (archive === undefined) throw new ProductionEvidenceError('TN_PROD_PACKAGE_ARCHIVE_FAILED', `Packing local package '${basename(directory)}' produced no archive.`);
325
329
  return join(destination, archive);
@@ -427,8 +431,9 @@ async function collectWeb(project, scenarios, artifactsRoot, options, tools) {
427
431
  const markerServer = await createFrameMarkerServer(options.profile === REGRESSION_PROFILE ? 41778 : 0);
428
432
  try {
429
433
  await installWebProfileEntry(project, markerServer.url, options.control, warmupFramesFor(options));
430
- const build = await runCommand('pnpm', ['run', 'build:web'], project);
431
- if (build.status !== 0) throw new ProductionEvidenceError('TN_PROD_WEB_BUILD_FAILED', 'The scaffolded platformer web build failed.');
434
+ // A production build can outlast the default timeout on slow hosted runners.
435
+ const build = await runCommand('pnpm', ['run', 'build:web'], project, undefined, 300_000);
436
+ if (build.status !== 0) throw new ProductionEvidenceError('TN_PROD_WEB_BUILD_FAILED', `The scaffolded platformer web build failed.${failureSuffix(build)}`);
432
437
  const artifactSha = await hashPath(join(project, 'dist'));
433
438
  const runs = [];
434
439
  const startups = [];
@@ -759,9 +764,14 @@ function createDesktopDriver(artifactPath, project, options, mailboxRoot) {
759
764
 
760
765
  function spawnNative(artifactPath, project, options, mailboxRoot) {
761
766
  const bundle = join(project, '.threenative/build/game.js');
767
+ // A packaged desktop artifact embeds the instrumented game entry under its own module root, and
768
+ // an explicit `run <absolute path>` is resolved against that root rather than the filesystem, so
769
+ // the external bundle never loads and the run reports TN_PLAYTEST_BRIDGE_MISSING at zero frames.
770
+ // Launch the embedded entry. A bare runtime supplied through `--prebuilt-artifact` carries no
771
+ // embedded entry and still needs the external bundle named on the command line.
772
+ const launchesExternalBundle = options.prebuiltArtifact !== undefined;
762
773
  const nativeArgs = [
763
- 'run',
764
- bundle,
774
+ ...(launchesExternalBundle ? ['run', bundle] : []),
765
775
  '--width', String(options.renderSize.width),
766
776
  '--height', String(options.renderSize.height),
767
777
  '--headless',
@@ -784,13 +794,13 @@ export async function installNativeProfileEntry(project, target, options) {
784
794
  const mailbox = target === 'desktop'
785
795
  ? `globalThis.TN_PLAYTEST_MAILBOX = ${JSON.stringify({ request: join(mailboxRoot, 'tn-playtest-request.json'), response: join(mailboxRoot, 'tn-playtest-response.json') })};\n`
786
796
  : '';
787
- const source = `import "./profile-native-profile.js";\nimport game from "./game.js";\n${nativeFrameInstrumentation(options.control, warmupFramesFor(options))}\n${mailbox}export default game;\n`;
797
+ const source = `import "./profile-native-profile.js";\nimport game from "./game.js";\n${nativeFrameInstrumentation(options.control, warmupFramesFor(options), true)}\n${mailbox}export default game;\n`;
788
798
  await writeFile(profileMarkerPath, profileMarker);
789
799
  await writeFile(entryPath, source);
790
- await setNativeProfileEntry(project, 'src/profile-native-entry.ts', target);
800
+ await setNativeProfileEntry(project, 'src/profile-native-entry.ts', target, options.renderSize);
791
801
  }
792
802
 
793
- export async function setNativeProfileEntry(project, entry, target) {
803
+ export async function setNativeProfileEntry(project, entry, target, renderSize = undefined) {
794
804
  const configPath = join(project, 'threenative.config.ts');
795
805
  const packagePath = join(project, 'package.json');
796
806
  const config = await readFile(configPath, 'utf8').catch(() => undefined);
@@ -799,12 +809,16 @@ export async function setNativeProfileEntry(project, entry, target) {
799
809
  /^(\s*nativeEntry\s*:\s*)["'][^"']*["'](,?.*)$/mu,
800
810
  `$1"${entry}"$2`,
801
811
  );
812
+ // The packaged desktop artifact carries the game's config embedded, and the native host reads
813
+ // its window size from there before any command-line flag, so the profiled surface is only the
814
+ // requested render size when the config states it.
815
+ const sized = renderSize === undefined ? withEntry : applyWindowSize(withEntry, renderSize);
802
816
  const rendered = target === 'desktop'
803
- ? withEntry.replace(
817
+ ? sized.replace(
804
818
  /(\bui\s*:\s*\{\s*renderer\s*:\s*)["'][^"']*["']/mu,
805
819
  `$1"native"`,
806
820
  )
807
- : withEntry;
821
+ : sized;
808
822
  if (rendered !== config) {
809
823
  await writeFile(configPath, rendered);
810
824
  }
@@ -823,28 +837,80 @@ export async function setNativeProfileEntry(project, entry, target) {
823
837
  await writeFile(packagePath, `${JSON.stringify(packageJson, null, 2)}\n`);
824
838
  }
825
839
 
840
+ function applyWindowSize(config, renderSize) {
841
+ return config
842
+ .replace(/(\bwindow\s*:\s*\{[^}]*?\bwidth\s*:\s*)\d+/mu, `$1${renderSize.width}`)
843
+ .replace(/(\bwindow\s*:\s*\{[^}]*?\bheight\s*:\s*)\d+/mu, `$1${renderSize.height}`);
844
+ }
845
+
826
846
  function productionPerformanceReader() {
827
847
  return `
848
+ // The installed bridge answers through a promise: core's playtest plugin wraps sample() to merge
849
+ // its runtime observation contributions asynchronously, so reading the returned snapshot inline
850
+ // saw a thenable and dropped every draw-call and triangle reading. Keep the last resolved
851
+ // performance read and answer it on the next frame instead.
852
+ let tnProductionLastPerformance;
828
853
  const tnProductionReadPerformance = () => {
829
854
  const bridge = globalThis.__THREENATIVE_PLAYTEST_BRIDGE__;
830
- if (typeof bridge?.sample !== "function") return {};
831
- try {
832
- const snapshot = bridge.sample({});
833
- if (snapshot === null || typeof snapshot !== "object" || typeof snapshot.then === "function") return {};
834
- const performance = snapshot.performance;
835
- return {
836
- ...(Number.isFinite(performance?.drawCalls) ? { drawCalls: performance.drawCalls } : {}),
837
- ...(performance?.phases !== undefined ? { phases: performance.phases } : {}),
838
- ...(Number.isFinite(performance?.triangles) ? { triangles: performance.triangles } : {}),
839
- };
840
- } catch {
841
- return {};
855
+ if (typeof bridge?.sample === "function") {
856
+ try {
857
+ const snapshot = bridge.sample({});
858
+ if (snapshot !== null && typeof snapshot === "object") {
859
+ if (typeof snapshot.then === "function") {
860
+ snapshot.then((resolved) => { tnProductionLastPerformance = resolved?.performance; }).catch(() => undefined);
861
+ } else {
862
+ tnProductionLastPerformance = snapshot.performance;
863
+ }
864
+ }
865
+ } catch {
866
+ }
842
867
  }
868
+ const performance = tnProductionLastPerformance;
869
+ return {
870
+ ...(Number.isFinite(performance?.drawCalls) ? { drawCalls: performance.drawCalls } : {}),
871
+ ...(performance?.phases !== undefined ? { phases: performance.phases } : {}),
872
+ ...(Number.isFinite(performance?.triangles) ? { triangles: performance.triangles } : {}),
873
+ };
874
+ };
875
+ `;
876
+ }
877
+
878
+ /**
879
+ * Pace the fixed step to wall time so a synthetic workload's tick budget is the seconds it names.
880
+ *
881
+ * The native device transport drives the simulation through `bridge.advance(ticks)`, and the host
882
+ * runs that loop synchronously: a single `advance(3600)` finishes in milliseconds, so the host's
883
+ * requestAnimationFrame loop never presents the 60 seconds of frames the scenario asked to warm up
884
+ * or measure, and the warmup boundary is never reached. Wrapping `advance` to wait one display
885
+ * interval per tick lets the host's own loop run during the wait, so the frames exist to be
886
+ * measured.
887
+ */
888
+ export function productionExecutionHold(paceTicks = false) {
889
+ return `
890
+ const tnProductionPaceEnabled = ${paceTicks === true};
891
+ const tnProductionTickIntervalMs = ${PRODUCTION_TICK_INTERVAL_MS};
892
+ let tnProductionPaceAt;
893
+ let tnProductionPaceInstalled = false;
894
+ const tnProductionInstallPace = () => {
895
+ if (!tnProductionPaceEnabled || tnProductionPaceInstalled) return;
896
+ const tnProductionBridge = globalThis.__THREENATIVE_PLAYTEST_BRIDGE__;
897
+ if (typeof tnProductionBridge?.advance !== "function") return;
898
+ const tnProductionAdvance = tnProductionBridge.advance.bind(tnProductionBridge);
899
+ tnProductionBridge.advance = async (ticks) => {
900
+ const startedAt = performance.now();
901
+ tnProductionPaceAt = Math.max(tnProductionPaceAt ?? startedAt, startedAt) + ticks * tnProductionTickIntervalMs;
902
+ const result = await tnProductionAdvance(ticks);
903
+ const waitMs = tnProductionPaceAt - performance.now();
904
+ if (waitMs > 0) await new Promise((resolve) => setTimeout(resolve, waitMs));
905
+ return result;
906
+ };
907
+ tnProductionPaceInstalled = true;
843
908
  };
909
+ tnProductionInstallPace();
844
910
  `;
845
911
  }
846
912
 
847
- export function nativeFrameInstrumentation(control, warmupFrames = 0) {
913
+ export function nativeFrameInstrumentation(control, warmupFrames = 0, paceTicks = false) {
848
914
  return `
849
915
  const tnProductionControl = ${JSON.stringify(control ?? '')};
850
916
  const tnProductionWarmupFrames = ${Math.max(0, Math.floor(warmupFrames))};
@@ -862,7 +928,9 @@ const tnProductionBusyWait = (milliseconds) => {
862
928
  while (performance.now() < deadline) {}
863
929
  };
864
930
  ${productionPerformanceReader()}
931
+ ${productionExecutionHold(paceTicks)}
865
932
  globalThis.requestAnimationFrame = (callback) => tnProductionRequestAnimationFrame((timestamp) => {
933
+ tnProductionInstallPace();
866
934
  const frameIndex = tnProductionFrameIndex++;
867
935
  const inWarmup = frameIndex < tnProductionWarmupFrames;
868
936
  if (frameIndex === tnProductionWarmupFrames) {
@@ -1788,7 +1856,7 @@ async function installAndroidArtifact(apk, device) {
1788
1856
  });
1789
1857
  const args = [...(device === undefined ? [] : ['-s', device]), 'install', '-r', apk];
1790
1858
  const result = await runCommand('adb', args, commandRoot);
1791
- if (result.status !== 0) throw new ProductionEvidenceError('TN_PROD_ANDROID_INSTALL_FAILED', 'Installing the scaffolded Android platformer failed.');
1859
+ if (result.status !== 0) throw new ProductionEvidenceError('TN_PROD_ANDROID_INSTALL_FAILED', `Installing the scaffolded Android platformer failed.${failureSuffix(result)}`);
1792
1860
  }
1793
1861
 
1794
1862
  async function hashPath(path) {
@@ -1860,7 +1928,7 @@ async function availablePort() {
1860
1928
  return address.port;
1861
1929
  }
1862
1930
 
1863
- async function runCommand(command, args, cwd, env = undefined, timeout = 120_000) {
1931
+ export async function runCommand(command, args, cwd, env = undefined, timeout = 120_000) {
1864
1932
  const started = performance.now();
1865
1933
  try {
1866
1934
  const result = await execFileAsync(command, args, {
@@ -1870,17 +1938,30 @@ async function runCommand(command, args, cwd, env = undefined, timeout = 120_000
1870
1938
  maxBuffer: 32 * 1024 * 1024,
1871
1939
  timeout,
1872
1940
  });
1873
- return { durationMs: performance.now() - started, status: 0, stderr: result.stderr, stdout: result.stdout };
1941
+ return { durationMs: performance.now() - started, status: 0, stderr: result.stderr, stdout: result.stdout, timeout, timedOut: false };
1874
1942
  } catch (error) {
1875
1943
  return {
1876
1944
  durationMs: performance.now() - started,
1877
1945
  status: typeof error?.code === 'number' ? error.code : 2,
1878
1946
  stderr: error?.stderr ?? '',
1879
1947
  stdout: error?.stdout ?? '',
1948
+ timeout,
1949
+ timedOut: error?.killed === true,
1880
1950
  };
1881
1951
  }
1882
1952
  }
1883
1953
 
1954
+ export function failureSuffix(result) {
1955
+ if (result.timedOut === true) return `: timed out after ${Math.round(result.timeout / 1_000)} s`;
1956
+ const lines = [result.stderr, result.stdout]
1957
+ .filter((value) => typeof value === 'string' && value.trim().length > 0)
1958
+ .join('\n')
1959
+ .split('\n')
1960
+ .filter((line) => line.trim().length > 0)
1961
+ .slice(-20);
1962
+ return lines.length === 0 ? '' : `\n${lines.join('\n')}`;
1963
+ }
1964
+
1884
1965
  async function removeMailbox(root) {
1885
1966
  await Promise.all([
1886
1967
  rm(join(root, 'tn-playtest-request.json'), { force: true }),