@ship.zone/runner 0.2.0 → 0.2.2

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_npm/mod.js CHANGED
@@ -4919,7 +4919,7 @@ var init_deno = __esm({
4919
4919
  "deno.json"() {
4920
4920
  deno_default = {
4921
4921
  name: "@ship.zone/runner",
4922
- version: "0.2.0",
4922
+ version: "0.2.2",
4923
4923
  exports: "./mod.ts",
4924
4924
  nodeModulesDir: "none",
4925
4925
  tasks: {
@@ -5174,7 +5174,7 @@ var init_log_sender = __esm({
5174
5174
  });
5175
5175
 
5176
5176
  // ts/oci-executor.ts
5177
- var runtimeEnvironmentNames, managedLabel, runnerLabel, sessionLabel, attemptLabel, runtimeProbeLabel, helperContainerPath, maximumRuntimeOutputBytes, runtimeCommandTimeoutMs, runtimeTerminationGraceMs, helperMemoryBytes, helperPids, helperCpus, probeVolumeBytes, probeVolumeEntries, maximumCommandArguments, maximumCommandArgumentBytes, maximumCommandBytes, maximumWorkspaceHelperErrorBytes, hostTmpfsProbeMaximumAgeMs, runtimeProbeVolumeMaximumAgeMs, hostTmpfsProbeNamePattern, runtimeProbeVolumeNamePattern, workspaceHelperReserveBytes, workspaceFixedInodes, WorkspaceResourceError, isRecord2, field, readRuntimeEnvironment, concatChunks, consumeCommandStream, withTimeout, terminateChild, defaultCommandRunner, requireSuccess, decode, scavengeHostTmpfsProbes, parseJson, firstObject, positiveSafeInteger, nonNegativeSafeInteger, checkedAdd3, checkedMultiply2, roundUp, calculateWorkspaceVolumeLimits, parseContainerUser, validateImage, validateWorkingDirectory, validateStepCommand, validateGeneratedName, validateHostMountPath, validateResources, labels, isolatedContainerArgs, collectStepEnvironment, buildOciRunCommand, validateLeasePolicy, buildOciHelperCreateCommand, mapArchitecture, sha256File, safeSelections, isStopReason, PreparedOciLease, OciExecutor, copyOciConfig;
5177
+ var runtimeEnvironmentNames, managedLabel, runnerLabel, sessionLabel, attemptLabel, runtimeProbeLabel, runtimeProbeOwnerLabel, helperContainerPath, maximumRuntimeOutputBytes, runtimeCommandTimeoutMs, runtimeTerminationGraceMs, helperMemoryBytes, helperPids, helperCpus, probeVolumeBytes, probeVolumeEntries, maximumCommandArguments, maximumCommandArgumentBytes, maximumCommandBytes, maximumWorkspaceHelperErrorBytes, hostTmpfsProbeMaximumAgeMs, runtimeProbeVolumeMaximumAgeMs, runtimeProbeOwnerIdPattern, hostTmpfsProbeNamePattern, runtimeProbeVolumeNamePattern, workspaceHelperDirectoryName, workspaceHelperLockName, runtimeProbeOwnerMarkerPrefix, runtimeProbeOwnerMarkerPattern, workspaceHelperExecutableMode, workspaceHelperMaximumBytes, workspaceHelperRetainedFinalCount, workspaceHelperTemporaryMaximumBytes, workspaceHelperTemporaryMaximumCount, workspaceHelperTemporaryMaximumAgeMs, workspaceHelperLockTimeoutMs, workspaceHelperLockRetryMs, workspaceHelperFinalNamePattern, workspaceHelperTemporaryNamePattern, workspaceHelperReserveBytes, workspaceFixedInodes, WorkspaceResourceError, isRecord2, field, readRuntimeEnvironment, concatChunks, consumeCommandStream, withTimeout, terminateChild, defaultCommandRunner, requireSuccess, decode, scavengeHostTmpfsProbes, parseJson, firstObject, positiveSafeInteger, nonNegativeSafeInteger, checkedAdd3, checkedMultiply2, roundUp, calculateWorkspaceVolumeLimits, parseContainerUser, validateImage, validateWorkingDirectory, validateStepCommand, validateGeneratedName, validateHostMountPath, validateResources, labels, isolatedContainerArgs, collectStepEnvironment, buildOciRunCommand, validateLeasePolicy, buildOciHelperCreateCommand, mapArchitecture, sha256Bytes, sameFileIdentity, withFsFile, readBoundedRegularFile, sha256File, writeAll2, lstatIfPresent2, safeSelections, isStopReason, PreparedOciLease, OciExecutor, copyOciConfig;
5178
5178
  var init_oci_executor = __esm({
5179
5179
  "ts/oci-executor.ts"() {
5180
5180
  init_mod();
@@ -5198,6 +5198,7 @@ var init_oci_executor = __esm({
5198
5198
  sessionLabel = "ship.zone.runner.session";
5199
5199
  attemptLabel = "ship.zone.runner.attempt";
5200
5200
  runtimeProbeLabel = "ship.zone.runner.runtime-probe";
5201
+ runtimeProbeOwnerLabel = "ship.zone.runner.runtime-probe-owner";
5201
5202
  helperContainerPath = "/runnerworkspace";
5202
5203
  maximumRuntimeOutputBytes = 1024 * 1024;
5203
5204
  runtimeCommandTimeoutMs = 3e4;
@@ -5213,8 +5214,23 @@ var init_oci_executor = __esm({
5213
5214
  maximumWorkspaceHelperErrorBytes = 512;
5214
5215
  hostTmpfsProbeMaximumAgeMs = 60 * 60 * 1e3;
5215
5216
  runtimeProbeVolumeMaximumAgeMs = 60 * 60 * 1e3;
5216
- hostTmpfsProbeNamePattern = /^foss-ci-probe-[a-f0-9]{16}$/;
5217
+ runtimeProbeOwnerIdPattern = /^[a-f0-9]{32}$/;
5218
+ hostTmpfsProbeNamePattern = /^foss-ci-probe-([a-f0-9]{32})-[a-f0-9]{16}$/;
5217
5219
  runtimeProbeVolumeNamePattern = /^foss-ci-volume-[a-f0-9]{32}$/;
5220
+ workspaceHelperDirectoryName = "workspace-helpers";
5221
+ workspaceHelperLockName = ".workspace-helper.lock";
5222
+ runtimeProbeOwnerMarkerPrefix = ".runtime-probe-owner_";
5223
+ runtimeProbeOwnerMarkerPattern = /^\.runtime-probe-owner_([a-f0-9]{32})$/;
5224
+ workspaceHelperExecutableMode = 493;
5225
+ workspaceHelperMaximumBytes = 64 * 1024 * 1024;
5226
+ workspaceHelperRetainedFinalCount = 8;
5227
+ workspaceHelperTemporaryMaximumBytes = 8 * workspaceHelperMaximumBytes;
5228
+ workspaceHelperTemporaryMaximumCount = 8;
5229
+ workspaceHelperTemporaryMaximumAgeMs = 60 * 60 * 1e3;
5230
+ workspaceHelperLockTimeoutMs = 30 * 1e3;
5231
+ workspaceHelperLockRetryMs = 25;
5232
+ workspaceHelperFinalNamePattern = /^runnerworkspace_linux_(?:amd64|arm64)_musl_[a-f0-9]{64}$/;
5233
+ workspaceHelperTemporaryNamePattern = /^\.[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}\.workspace-helper\.tmp$/;
5218
5234
  workspaceHelperReserveBytes = 1024 * 1024;
5219
5235
  workspaceFixedInodes = 3;
5220
5236
  WorkspaceResourceError = class extends RunnerError {
@@ -5380,7 +5396,10 @@ var init_oci_executor = __esm({
5380
5396
  if (!result.success) throw new RunnerError(message);
5381
5397
  }, "requireSuccess");
5382
5398
  decode = /* @__PURE__ */ __name((value) => new TextDecoder().decode(value).trim(), "decode");
5383
- scavengeHostTmpfsProbes = /* @__PURE__ */ __name(async (directory = "/dev/shm", dependencies = {}) => {
5399
+ scavengeHostTmpfsProbes = /* @__PURE__ */ __name(async (directory = "/dev/shm", dependencies = {}, runtimeProbeOwnerId) => {
5400
+ if (!runtimeProbeOwnerId || !runtimeProbeOwnerIdPattern.test(runtimeProbeOwnerId)) {
5401
+ return;
5402
+ }
5384
5403
  let uid;
5385
5404
  try {
5386
5405
  uid = dependencies.getUid ? dependencies.getUid() : typeof Deno.uid === "function" ? Deno.uid() : void 0;
@@ -5394,7 +5413,7 @@ var init_oci_executor = __esm({
5394
5413
  const remove = dependencies.remove ?? ((path, options) => Deno.remove(path, options));
5395
5414
  const isEligible = /* @__PURE__ */ __name((stat) => stat.isDirectory && !stat.isSymlink && stat.uid === uid && stat.mtime !== null && now() - stat.mtime.getTime() > hostTmpfsProbeMaximumAgeMs, "isEligible");
5396
5415
  for await (const entry of readDir(directory)) {
5397
- if (!hostTmpfsProbeNamePattern.test(entry.name)) continue;
5416
+ if (hostTmpfsProbeNamePattern.exec(entry.name)?.[1] !== runtimeProbeOwnerId) continue;
5398
5417
  const path = join3(directory, entry.name);
5399
5418
  let initial;
5400
5419
  try {
@@ -5770,13 +5789,93 @@ var init_oci_executor = __esm({
5770
5789
  throw new RunnerError(`Unsupported OCI engine architecture: ${value}`);
5771
5790
  }
5772
5791
  }, "mapArchitecture");
5773
- sha256File = /* @__PURE__ */ __name(async (path) => {
5774
- const bytes = await Deno.readFile(path);
5792
+ sha256Bytes = /* @__PURE__ */ __name(async (bytes) => {
5775
5793
  const digest = await crypto.subtle.digest("SHA-256", bytes);
5776
5794
  return [
5777
5795
  ...new Uint8Array(digest)
5778
5796
  ].map((byte) => byte.toString(16).padStart(2, "0")).join("");
5779
- }, "sha256File");
5797
+ }, "sha256Bytes");
5798
+ sameFileIdentity = /* @__PURE__ */ __name((first, second) => (first.dev === null || second.dev === first.dev) && (first.ino === null || second.ino === first.ino), "sameFileIdentity");
5799
+ withFsFile = /* @__PURE__ */ __name(async (file, operation, closeFailureMessage) => {
5800
+ let result;
5801
+ let operationError;
5802
+ let hasOperationError = false;
5803
+ try {
5804
+ result = await operation(file);
5805
+ } catch (error) {
5806
+ operationError = error;
5807
+ hasOperationError = true;
5808
+ }
5809
+ let closeError;
5810
+ let hasCloseError = false;
5811
+ try {
5812
+ file.close();
5813
+ } catch (error) {
5814
+ closeError = error;
5815
+ hasCloseError = true;
5816
+ }
5817
+ if (hasCloseError) {
5818
+ throw new ResourceCleanupError(closeFailureMessage, [
5819
+ ...hasOperationError ? [
5820
+ operationError
5821
+ ] : [],
5822
+ closeError
5823
+ ]);
5824
+ }
5825
+ if (hasOperationError) throw operationError;
5826
+ return result;
5827
+ }, "withFsFile");
5828
+ readBoundedRegularFile = /* @__PURE__ */ __name(async (path, maximumBytes, label) => {
5829
+ const pathStat = await Deno.lstat(path);
5830
+ if (!pathStat.isFile || pathStat.isSymlink || pathStat.size < 1 || pathStat.size > maximumBytes) {
5831
+ throw new RunnerError(`${label} must be a bounded regular file`);
5832
+ }
5833
+ const file = await Deno.open(path, {
5834
+ read: true
5835
+ });
5836
+ return await withFsFile(file, async (openedFile) => {
5837
+ const before = await openedFile.stat();
5838
+ if (!before.isFile || before.size < 1 || before.size > maximumBytes || before.size !== pathStat.size || !sameFileIdentity(pathStat, before)) {
5839
+ throw new RunnerError(`${label} changed while it was opened`);
5840
+ }
5841
+ const bytes = new Uint8Array(before.size);
5842
+ let offset = 0;
5843
+ while (offset < bytes.byteLength) {
5844
+ const read = await openedFile.read(bytes.subarray(offset));
5845
+ if (read === null || read <= 0) {
5846
+ throw new RunnerError(`${label} changed while it was read`);
5847
+ }
5848
+ offset += read;
5849
+ }
5850
+ const overflow = await openedFile.read(new Uint8Array(1));
5851
+ const after = await openedFile.stat();
5852
+ const currentPathStat = await Deno.lstat(path);
5853
+ if (overflow !== null || !after.isFile || after.size !== before.size || !currentPathStat.isFile || currentPathStat.isSymlink || currentPathStat.size !== before.size || !sameFileIdentity(before, after) || !sameFileIdentity(after, currentPathStat)) {
5854
+ throw new RunnerError(`${label} changed while it was read`);
5855
+ }
5856
+ return {
5857
+ bytes,
5858
+ stat: after
5859
+ };
5860
+ }, `${label} read and close failed`);
5861
+ }, "readBoundedRegularFile");
5862
+ sha256File = /* @__PURE__ */ __name(async (path) => await sha256Bytes((await readBoundedRegularFile(path, workspaceHelperMaximumBytes, "Workspace helper")).bytes), "sha256File");
5863
+ writeAll2 = /* @__PURE__ */ __name(async (file, bytes) => {
5864
+ let offset = 0;
5865
+ while (offset < bytes.byteLength) {
5866
+ const written = await file.write(bytes.subarray(offset));
5867
+ if (written <= 0) throw new RunnerError("Workspace helper write made no progress");
5868
+ offset += written;
5869
+ }
5870
+ }, "writeAll");
5871
+ lstatIfPresent2 = /* @__PURE__ */ __name(async (path) => {
5872
+ try {
5873
+ return await Deno.lstat(path);
5874
+ } catch (error) {
5875
+ if (error instanceof Deno.errors.NotFound) return void 0;
5876
+ throw error;
5877
+ }
5878
+ }, "lstatIfPresent");
5780
5879
  safeSelections = /* @__PURE__ */ __name((selections) => {
5781
5880
  if (selections.length === 0 || selections.length > 32) {
5782
5881
  throw new ProtocolError("Workspace export must select between 1 and 32 paths");
@@ -5864,7 +5963,7 @@ var init_oci_executor = __esm({
5864
5963
  this.randomId = dependencies.randomId ?? (() => crypto.randomUUID().replaceAll("-", ""));
5865
5964
  this.now = dependencies.now ?? Date.now;
5866
5965
  this.resolveHelperPathImplementation = dependencies.resolveHelperPath ?? ((target) => this.resolvePackagedHelper(target));
5867
- this.probeTmpfsImplementation = dependencies.probeTmpfs ?? ((path) => this.probeHostTmpfs(path));
5966
+ this.probeTmpfsImplementation = dependencies.probeTmpfs ? (path) => dependencies.probeTmpfs(path) : (path, runtimeProbeOwnerId) => this.probeHostTmpfs(path, runtimeProbeOwnerId);
5868
5967
  this.makeTempDir = dependencies.makeTempDir ?? ((options) => Deno.makeTempDir(options));
5869
5968
  this.chmod = dependencies.chmod ?? ((path, mode) => Deno.chmod(path, mode));
5870
5969
  this.remove = dependencies.remove ?? ((path, options) => Deno.remove(path, options));
@@ -5969,7 +6068,9 @@ var init_oci_executor = __esm({
5969
6068
  throw new RunnerError("Runner policy requires a rootless OCI engine");
5970
6069
  }
5971
6070
  const architecture = mapArchitecture(architectureValue);
5972
- const helperPath = await this.resolveHelperPathImplementation(architecture.helperTarget);
6071
+ const helperSourcePath = await this.resolveHelperPathImplementation(architecture.helperTarget);
6072
+ const helperPath = await this.materializeWorkspaceHelper(helperSourcePath, architecture.helperTarget);
6073
+ const runtimeProbeOwnerId = await this.ensureRuntimeProbeOwner();
5973
6074
  const helperStat = await Deno.stat(helperPath).catch((error) => {
5974
6075
  throw new RunnerError("Workspace helper is unavailable", {
5975
6076
  cause: error
@@ -5990,9 +6091,9 @@ var init_oci_executor = __esm({
5990
6091
  if (helperArchitecture.helperTarget !== architecture.helperTarget) {
5991
6092
  throw new RunnerError("Workspace helper architecture does not match the OCI engine");
5992
6093
  }
5993
- const workspaceBlockSize = await this.probeTmpfsImplementation(helperPath);
5994
- await this.reconcileRuntimeProbeVolumes();
5995
- await this.probeRuntimeVolume(workspaceBlockSize);
6094
+ const workspaceBlockSize = await this.probeTmpfsImplementation(helperPath, runtimeProbeOwnerId);
6095
+ await this.reconcileRuntimeProbeVolumes(runtimeProbeOwnerId);
6096
+ await this.probeRuntimeVolume(workspaceBlockSize, runtimeProbeOwnerId);
5996
6097
  const facts = {
5997
6098
  runtime,
5998
6099
  endpoint,
@@ -6442,15 +6543,328 @@ var init_oci_executor = __esm({
6442
6543
  }
6443
6544
  return await Deno.realPath(new URL(`../dist_rust/runnerworkspace_${target}_musl`, import.meta.url));
6444
6545
  }
6445
- async probeHostTmpfs(helperPath) {
6546
+ async materializeWorkspaceHelper(sourcePathArg, targetArg) {
6547
+ const sourcePath = await Deno.realPath(sourcePathArg).catch((error) => {
6548
+ throw new RunnerError("Workspace helper source is unavailable", {
6549
+ cause: error
6550
+ });
6551
+ });
6552
+ const sourceBytes = (await readBoundedRegularFile(sourcePath, workspaceHelperMaximumBytes, "Workspace helper source")).bytes;
6553
+ const sourceDigest = await sha256Bytes(sourceBytes);
6554
+ const helperDirectory = await this.ensureWorkspaceHelperDirectory();
6555
+ const destinationName = `runnerworkspace_${targetArg}_musl_${sourceDigest}`;
6556
+ const destinationPath = join3(helperDirectory, destinationName);
6557
+ return await this.withWorkspaceHelperLock(helperDirectory, async () => {
6558
+ const temporaryUsage = await this.scavengeWorkspaceHelpers(helperDirectory, destinationName, sourceDigest);
6559
+ if (await lstatIfPresent2(destinationPath)) {
6560
+ await this.validateMaterializedWorkspaceHelper(destinationPath, sourceDigest);
6561
+ return await Deno.realPath(destinationPath);
6562
+ }
6563
+ if (temporaryUsage.count >= workspaceHelperTemporaryMaximumCount || temporaryUsage.bytes > workspaceHelperTemporaryMaximumBytes - sourceBytes.byteLength) {
6564
+ throw new RunnerError("Workspace helper temporary storage limit is exhausted");
6565
+ }
6566
+ const temporaryPath = join3(helperDirectory, `.${crypto.randomUUID()}.workspace-helper.tmp`);
6567
+ try {
6568
+ const temporaryFile = await Deno.open(temporaryPath, {
6569
+ write: true,
6570
+ createNew: true,
6571
+ mode: 384
6572
+ });
6573
+ await withFsFile(temporaryFile, async (openedFile) => {
6574
+ await writeAll2(openedFile, sourceBytes);
6575
+ await openedFile.sync();
6576
+ }, "Workspace helper write and close failed");
6577
+ await this.validateMaterializedWorkspaceHelper(temporaryPath, sourceDigest, true);
6578
+ try {
6579
+ await Deno.link(temporaryPath, destinationPath);
6580
+ } catch (error) {
6581
+ if (!(error instanceof Deno.errors.AlreadyExists)) throw error;
6582
+ await this.validateMaterializedWorkspaceHelper(destinationPath, sourceDigest);
6583
+ }
6584
+ await Deno.remove(temporaryPath);
6585
+ await this.validateMaterializedWorkspaceHelper(destinationPath, sourceDigest);
6586
+ await this.syncDirectory(helperDirectory);
6587
+ return await Deno.realPath(destinationPath);
6588
+ } catch (error) {
6589
+ try {
6590
+ await Deno.remove(temporaryPath);
6591
+ } catch (cleanupError) {
6592
+ if (!(cleanupError instanceof Deno.errors.NotFound)) {
6593
+ throw new ResourceCleanupError("Workspace helper setup and cleanup failed", [
6594
+ error,
6595
+ cleanupError
6596
+ ]);
6597
+ }
6598
+ }
6599
+ throw error;
6600
+ }
6601
+ });
6602
+ }
6603
+ async ensureWorkspaceHelperDirectory() {
6604
+ const stateRoot = resolve3(this.config.stateDirectory);
6605
+ await Deno.mkdir(stateRoot, {
6606
+ recursive: true,
6607
+ mode: 448
6608
+ });
6609
+ const stateStat = await Deno.lstat(stateRoot);
6610
+ if (!stateStat.isDirectory || stateStat.isSymlink) {
6611
+ throw new RunnerError("Runner state directory must be a real directory");
6612
+ }
6613
+ if (Deno.build.os !== "windows" && stateStat.mode !== null && (stateStat.mode & 63) !== 0) {
6614
+ throw new RunnerError("Runner state directory permissions are not private");
6615
+ }
6616
+ const helperDirectory = join3(stateRoot, workspaceHelperDirectoryName);
6617
+ try {
6618
+ await Deno.mkdir(helperDirectory, {
6619
+ mode: 448
6620
+ });
6621
+ } catch (error) {
6622
+ if (!(error instanceof Deno.errors.AlreadyExists)) throw error;
6623
+ }
6624
+ const helperStat = await Deno.lstat(helperDirectory);
6625
+ if (!helperStat.isDirectory || helperStat.isSymlink) {
6626
+ throw new RunnerError("Workspace helper directory must be a real directory");
6627
+ }
6628
+ await Deno.chmod(helperDirectory, 448);
6629
+ const privateStat = await Deno.lstat(helperDirectory);
6630
+ if (!privateStat.isDirectory || privateStat.isSymlink || Deno.build.os !== "windows" && privateStat.mode !== null && (privateStat.mode & 511) !== 448) {
6631
+ throw new RunnerError("Workspace helper directory permissions are not private");
6632
+ }
6633
+ await this.syncDirectory(stateRoot);
6634
+ return await Deno.realPath(helperDirectory);
6635
+ }
6636
+ async ensureRuntimeProbeOwner() {
6637
+ const helperDirectory = await this.ensureWorkspaceHelperDirectory();
6638
+ return await this.withWorkspaceHelperLock(helperDirectory, async () => {
6639
+ const markers = [];
6640
+ for await (const entry of Deno.readDir(helperDirectory)) {
6641
+ if (!entry.name.startsWith(runtimeProbeOwnerMarkerPrefix)) continue;
6642
+ const match = runtimeProbeOwnerMarkerPattern.exec(entry.name);
6643
+ if (!match) throw new RunnerError("Runtime probe owner marker name is invalid");
6644
+ markers.push({
6645
+ name: entry.name,
6646
+ ownerId: match[1]
6647
+ });
6648
+ }
6649
+ if (markers.length > 1) {
6650
+ throw new RunnerError("Runner state contains multiple runtime probe owner markers");
6651
+ }
6652
+ if (markers.length === 1) {
6653
+ const marker = markers[0];
6654
+ await this.validateRuntimeProbeOwnerMarker(join3(helperDirectory, marker.name));
6655
+ return marker.ownerId;
6656
+ }
6657
+ const ownerId = this.randomHex();
6658
+ const markerPath = join3(helperDirectory, `${runtimeProbeOwnerMarkerPrefix}${ownerId}`);
6659
+ const markerFile = await Deno.open(markerPath, {
6660
+ read: true,
6661
+ write: true,
6662
+ createNew: true,
6663
+ mode: 384
6664
+ });
6665
+ await withFsFile(markerFile, async (openedMarkerFile) => await openedMarkerFile.sync(), "Runtime probe owner marker sync and close failed");
6666
+ await this.validateRuntimeProbeOwnerMarker(markerPath);
6667
+ await this.syncDirectory(helperDirectory);
6668
+ return ownerId;
6669
+ });
6670
+ }
6671
+ async validateRuntimeProbeOwnerMarker(pathArg) {
6672
+ const before = await Deno.lstat(pathArg);
6673
+ if (!before.isFile || before.isSymlink || before.size !== 0 || Deno.build.os !== "windows" && before.nlink !== null && before.nlink !== 1 || Deno.build.os !== "windows" && before.mode !== null && (before.mode & 4095) !== 384) {
6674
+ throw new RunnerError("Runtime probe owner marker must be a private single-link file");
6675
+ }
6676
+ const markerFile = await Deno.open(pathArg, {
6677
+ read: true
6678
+ });
6679
+ await withFsFile(markerFile, async (openedMarkerFile) => {
6680
+ const descriptorStat = await openedMarkerFile.stat();
6681
+ const current = await Deno.lstat(pathArg);
6682
+ if (!descriptorStat.isFile || !current.isFile || current.isSymlink || !sameFileIdentity(before, descriptorStat) || !sameFileIdentity(before, current) || Deno.build.os !== "windows" && descriptorStat.nlink !== null && descriptorStat.nlink !== 1 || Deno.build.os !== "windows" && current.nlink !== null && current.nlink !== 1 || Deno.build.os !== "windows" && current.mode !== null && (current.mode & 4095) !== 384) {
6683
+ throw new RunnerError("Runtime probe owner marker changed during validation");
6684
+ }
6685
+ }, "Runtime probe owner marker validation and close failed");
6686
+ }
6687
+ async withWorkspaceHelperLock(helperDirectoryArg, operation) {
6688
+ const lockPath = join3(helperDirectoryArg, workspaceHelperLockName);
6689
+ const lockFile = await Deno.open(lockPath, {
6690
+ read: true,
6691
+ write: true,
6692
+ create: true,
6693
+ mode: 384
6694
+ });
6695
+ return await withFsFile(lockFile, async (openedLockFile) => {
6696
+ const initialStat = await Deno.lstat(lockPath);
6697
+ if (!initialStat.isFile || initialStat.isSymlink || Deno.build.os !== "windows" && initialStat.nlink !== null && initialStat.nlink !== 1) {
6698
+ throw new RunnerError("Workspace helper lock must be a regular file");
6699
+ }
6700
+ await Deno.chmod(lockPath, 384);
6701
+ const pathStat = await Deno.lstat(lockPath);
6702
+ const descriptorStat = await openedLockFile.stat();
6703
+ if (!pathStat.isFile || pathStat.isSymlink || !descriptorStat.isFile || !sameFileIdentity(pathStat, descriptorStat) || Deno.build.os !== "windows" && pathStat.mode !== null && (pathStat.mode & 511) !== 384) {
6704
+ throw new RunnerError("Workspace helper lock changed while it was opened");
6705
+ }
6706
+ const lockDeadline = performance.now() + workspaceHelperLockTimeoutMs;
6707
+ while (!await openedLockFile.tryLock(true)) {
6708
+ if (performance.now() >= lockDeadline) {
6709
+ throw new RunnerError("Timed out waiting for the workspace helper lock");
6710
+ }
6711
+ await new Promise((resolvePromise) => setTimeout(resolvePromise, workspaceHelperLockRetryMs));
6712
+ }
6713
+ let result;
6714
+ let operationError;
6715
+ let hasOperationError = false;
6716
+ try {
6717
+ result = await operation();
6718
+ } catch (error) {
6719
+ operationError = error;
6720
+ hasOperationError = true;
6721
+ }
6722
+ let unlockError;
6723
+ try {
6724
+ await openedLockFile.unlock();
6725
+ } catch (error) {
6726
+ unlockError = error;
6727
+ }
6728
+ if (unlockError !== void 0) {
6729
+ throw new ResourceCleanupError(hasOperationError ? "Workspace helper operation and lock release failed" : "Unable to release workspace helper lock", [
6730
+ ...hasOperationError ? [
6731
+ operationError
6732
+ ] : [],
6733
+ unlockError
6734
+ ]);
6735
+ }
6736
+ if (hasOperationError) throw operationError;
6737
+ return result;
6738
+ }, "Workspace helper lock operation and close failed");
6739
+ }
6740
+ async scavengeWorkspaceHelpers(helperDirectoryArg, currentDestinationNameArg, currentDigestArg) {
6741
+ const finalFiles = [];
6742
+ let recentTemporaryCount = 0;
6743
+ let recentTemporaryBytes = 0;
6744
+ let removed = false;
6745
+ for await (const entry of Deno.readDir(helperDirectoryArg)) {
6746
+ const path = join3(helperDirectoryArg, entry.name);
6747
+ if (workspaceHelperTemporaryNamePattern.test(entry.name)) {
6748
+ const stat = await lstatIfPresent2(path);
6749
+ if (!stat) continue;
6750
+ if (!stat.isFile || stat.isSymlink || stat.size > workspaceHelperMaximumBytes || stat.mtime === null) {
6751
+ throw new RunnerError("Workspace helper temporary path must be a bounded regular file");
6752
+ }
6753
+ if (await this.recoverInterruptedWorkspaceHelperPublication(path, stat, join3(helperDirectoryArg, currentDestinationNameArg), currentDigestArg)) {
6754
+ removed = true;
6755
+ continue;
6756
+ }
6757
+ if (this.now() - stat.mtime.getTime() >= workspaceHelperTemporaryMaximumAgeMs) {
6758
+ const currentStat = await lstatIfPresent2(path);
6759
+ if (!currentStat) continue;
6760
+ if (!sameFileIdentity(stat, currentStat)) {
6761
+ throw new RunnerError("Workspace helper temporary path changed during cleanup");
6762
+ }
6763
+ try {
6764
+ await Deno.remove(path);
6765
+ removed = true;
6766
+ } catch (error) {
6767
+ if (!(error instanceof Deno.errors.NotFound)) throw error;
6768
+ }
6769
+ continue;
6770
+ }
6771
+ recentTemporaryCount++;
6772
+ recentTemporaryBytes += stat.size;
6773
+ continue;
6774
+ }
6775
+ if (workspaceHelperFinalNamePattern.test(entry.name)) {
6776
+ const stat = await lstatIfPresent2(path);
6777
+ if (!stat) continue;
6778
+ if (!stat.isFile || stat.isSymlink || stat.size < 1 || stat.size > workspaceHelperMaximumBytes || stat.mtime === null) {
6779
+ throw new RunnerError("Retained workspace helper must be a bounded regular file");
6780
+ }
6781
+ finalFiles.push({
6782
+ name: entry.name,
6783
+ path,
6784
+ stat
6785
+ });
6786
+ }
6787
+ }
6788
+ finalFiles.sort((first, second) => {
6789
+ if (first.name === currentDestinationNameArg) return -1;
6790
+ if (second.name === currentDestinationNameArg) return 1;
6791
+ return (second.stat.mtime?.getTime() ?? 0) - (first.stat.mtime?.getTime() ?? 0) || first.name.localeCompare(second.name);
6792
+ });
6793
+ const retainedFinalCount = finalFiles.some((entry) => entry.name === currentDestinationNameArg) ? workspaceHelperRetainedFinalCount : workspaceHelperRetainedFinalCount - 1;
6794
+ for (const stale of finalFiles.slice(retainedFinalCount)) {
6795
+ const currentStat = await lstatIfPresent2(stale.path);
6796
+ if (!currentStat) continue;
6797
+ if (!sameFileIdentity(stale.stat, currentStat)) {
6798
+ throw new RunnerError("Retained workspace helper changed during cleanup");
6799
+ }
6800
+ try {
6801
+ await Deno.remove(stale.path);
6802
+ removed = true;
6803
+ } catch (error) {
6804
+ if (!(error instanceof Deno.errors.NotFound)) throw error;
6805
+ }
6806
+ }
6807
+ if (removed) await this.syncDirectory(helperDirectoryArg);
6808
+ return {
6809
+ count: recentTemporaryCount,
6810
+ bytes: recentTemporaryBytes
6811
+ };
6812
+ }
6813
+ async recoverInterruptedWorkspaceHelperPublication(temporaryPathArg, temporaryStatArg, destinationPathArg, expectedDigestArg) {
6814
+ if (Deno.build.os === "windows" || temporaryStatArg.nlink === null || temporaryStatArg.nlink !== 2) {
6815
+ return false;
6816
+ }
6817
+ const destinationStat = await lstatIfPresent2(destinationPathArg);
6818
+ if (!destinationStat || !sameFileIdentity(temporaryStatArg, destinationStat)) return false;
6819
+ if (!destinationStat.isFile || destinationStat.isSymlink || destinationStat.size < 1 || destinationStat.size > workspaceHelperMaximumBytes || destinationStat.nlink !== 2 || destinationStat.mode === null || (destinationStat.mode & 4095) !== workspaceHelperExecutableMode) {
6820
+ throw new RunnerError("Interrupted workspace helper publication is invalid");
6821
+ }
6822
+ const validated = await readBoundedRegularFile(temporaryPathArg, workspaceHelperMaximumBytes, "Interrupted workspace helper publication");
6823
+ if (!sameFileIdentity(temporaryStatArg, validated.stat) || validated.stat.nlink !== 2 || validated.stat.mode === null || (validated.stat.mode & 4095) !== workspaceHelperExecutableMode || await sha256Bytes(validated.bytes) !== expectedDigestArg) {
6824
+ throw new RunnerError("Interrupted workspace helper publication changed during validation");
6825
+ }
6826
+ const currentTemporary = await Deno.lstat(temporaryPathArg);
6827
+ const currentDestination = await Deno.lstat(destinationPathArg);
6828
+ if (!sameFileIdentity(temporaryStatArg, currentTemporary) || !sameFileIdentity(temporaryStatArg, currentDestination) || currentTemporary.nlink !== 2 || currentDestination.nlink !== 2) {
6829
+ throw new RunnerError("Interrupted workspace helper publication changed before recovery");
6830
+ }
6831
+ await Deno.remove(temporaryPathArg);
6832
+ const recoveredDestination = await Deno.lstat(destinationPathArg);
6833
+ if (!sameFileIdentity(destinationStat, recoveredDestination) || recoveredDestination.nlink !== 1 || recoveredDestination.mode === null || (recoveredDestination.mode & 4095) !== workspaceHelperExecutableMode) {
6834
+ throw new RunnerError("Interrupted workspace helper publication did not recover safely");
6835
+ }
6836
+ return true;
6837
+ }
6838
+ async validateMaterializedWorkspaceHelper(pathArg, expectedDigestArg, setExecutableModeArg = false) {
6839
+ const before = await Deno.lstat(pathArg);
6840
+ if (!before.isFile || before.isSymlink || before.size < 1 || before.size > workspaceHelperMaximumBytes || Deno.build.os !== "windows" && before.nlink !== null && before.nlink !== 1) {
6841
+ throw new RunnerError("Materialized workspace helper must be a bounded regular file");
6842
+ }
6843
+ if (setExecutableModeArg) await Deno.chmod(pathArg, workspaceHelperExecutableMode);
6844
+ const validated = await readBoundedRegularFile(pathArg, workspaceHelperMaximumBytes, "Materialized workspace helper");
6845
+ if (!sameFileIdentity(before, validated.stat) || Deno.build.os !== "windows" && validated.stat.nlink !== null && validated.stat.nlink !== 1 || Deno.build.os !== "windows" && validated.stat.mode !== null && (validated.stat.mode & 4095) !== workspaceHelperExecutableMode) {
6846
+ throw new RunnerError("Materialized workspace helper changed during validation");
6847
+ }
6848
+ const digest = await sha256Bytes(validated.bytes);
6849
+ if (digest !== expectedDigestArg) {
6850
+ throw new RunnerError("Materialized workspace helper digest does not match its source");
6851
+ }
6852
+ }
6853
+ async syncDirectory(pathArg) {
6854
+ const directory = await Deno.open(pathArg, {
6855
+ read: true
6856
+ });
6857
+ await withFsFile(directory, async (openedDirectory) => await openedDirectory.sync(), "Workspace helper directory sync and close failed");
6858
+ }
6859
+ async probeHostTmpfs(helperPath, runtimeProbeOwnerId) {
6446
6860
  let path;
6447
6861
  let blockSize;
6448
6862
  let operationError;
6449
6863
  try {
6450
- await scavengeHostTmpfsProbes();
6864
+ await scavengeHostTmpfsProbes("/dev/shm", {}, runtimeProbeOwnerId);
6451
6865
  path = await Deno.makeTempDir({
6452
6866
  dir: "/dev/shm",
6453
- prefix: "foss-ci-probe-"
6867
+ prefix: `foss-ci-probe-${runtimeProbeOwnerId}-`
6454
6868
  });
6455
6869
  const before = await this.readFilesystemProbe(helperPath, path);
6456
6870
  const first = join3(path, "first");
@@ -6512,7 +6926,7 @@ var init_oci_executor = __esm({
6512
6926
  availableInodes
6513
6927
  };
6514
6928
  }
6515
- async reconcileRuntimeProbeVolumes() {
6929
+ async reconcileRuntimeProbeVolumes(runtimeProbeOwnerId) {
6516
6930
  const listed = await this.runRuntime([
6517
6931
  "volume",
6518
6932
  "ls",
@@ -6520,6 +6934,8 @@ var init_oci_executor = __esm({
6520
6934
  `label=${managedLabel}=true`,
6521
6935
  "--filter",
6522
6936
  `label=${runtimeProbeLabel}=true`,
6937
+ "--filter",
6938
+ `label=${runtimeProbeOwnerLabel}=${runtimeProbeOwnerId}`,
6523
6939
  "--format",
6524
6940
  "{{.Name}}"
6525
6941
  ]);
@@ -6536,7 +6952,7 @@ var init_oci_executor = __esm({
6536
6952
  const labelsValue = field(volume, "Labels", "labels");
6537
6953
  const inspectedName = field(volume, "Name", "name");
6538
6954
  const createdAtValue = field(volume, "CreatedAt", "createdAt", "Created", "created");
6539
- if (inspectedName !== name || !isRecord2(labelsValue) || labelsValue[managedLabel] !== "true" || labelsValue[runtimeProbeLabel] !== "true" || typeof createdAtValue !== "string") {
6955
+ if (inspectedName !== name || !isRecord2(labelsValue) || labelsValue[managedLabel] !== "true" || labelsValue[runtimeProbeLabel] !== "true" || labelsValue[runtimeProbeOwnerLabel] !== runtimeProbeOwnerId || typeof createdAtValue !== "string") {
6540
6956
  continue;
6541
6957
  }
6542
6958
  const createdAt = Date.parse(createdAtValue);
@@ -6551,7 +6967,7 @@ var init_oci_executor = __esm({
6551
6967
  }
6552
6968
  }
6553
6969
  }
6554
- async probeRuntimeVolume(blockSize) {
6970
+ async probeRuntimeVolume(blockSize, runtimeProbeOwnerId) {
6555
6971
  const limits = calculateWorkspaceVolumeLimits(probeVolumeBytes, probeVolumeEntries, blockSize);
6556
6972
  const name = this.createResourceName("volume");
6557
6973
  let possiblyExists = false;
@@ -6559,7 +6975,7 @@ var init_oci_executor = __esm({
6559
6975
  let hasOperationError = false;
6560
6976
  try {
6561
6977
  possiblyExists = true;
6562
- const result = await this.runRuntime(this.volumeCreateArgs(name, limits, void 0, void 0, void 0, true));
6978
+ const result = await this.runRuntime(this.volumeCreateArgs(name, limits, void 0, void 0, void 0, runtimeProbeOwnerId));
6563
6979
  requireSuccess(result, "OCI runtime cannot create local tmpfs volumes");
6564
6980
  const inspected = await this.runRuntime([
6565
6981
  "volume",
@@ -6602,7 +7018,7 @@ var init_oci_executor = __esm({
6602
7018
  }
6603
7019
  if (hasOperationError) throw operationError;
6604
7020
  }
6605
- volumeCreateArgs(name, limits, runnerId, sessionId, attemptId, runtimeProbe = false) {
7021
+ volumeCreateArgs(name, limits, runnerId, sessionId, attemptId, runtimeProbeOwnerId) {
6606
7022
  validateGeneratedName(name, "volume");
6607
7023
  const mountOptions = [
6608
7024
  `size=${limits.sizeBytes}`,
@@ -6627,8 +7043,11 @@ var init_oci_executor = __esm({
6627
7043
  ];
6628
7044
  if (runnerId && sessionId && attemptId) {
6629
7045
  args.push(...labels(runnerId, sessionId, attemptId));
6630
- } else if (runtimeProbe) {
6631
- args.push("--label", `${managedLabel}=true`, "--label", `${runtimeProbeLabel}=true`);
7046
+ } else if (runtimeProbeOwnerId) {
7047
+ if (!/^[a-f0-9]{32}$/.test(runtimeProbeOwnerId)) {
7048
+ throw new RunnerError("Runtime probe owner ID is invalid");
7049
+ }
7050
+ args.push("--label", `${managedLabel}=true`, "--label", `${runtimeProbeLabel}=true`, "--label", `${runtimeProbeOwnerLabel}=${runtimeProbeOwnerId}`);
6632
7051
  }
6633
7052
  if (this.config.oci.runtime === "podman") args.push("--opt", "nocopy");
6634
7053
  args.push(name);
@@ -7658,7 +8077,7 @@ var init_protocol_validator = __esm({
7658
8077
  });
7659
8078
 
7660
8079
  // ts/attempt-state.ts
7661
- var identifierPattern4, journalName, maximumJournalBytes, validateJournal, writeAll2, isNotFound, AttemptStateStore;
8080
+ var identifierPattern4, journalName, maximumJournalBytes, validateJournal, writeAll3, isNotFound, AttemptStateStore;
7662
8081
  var init_attempt_state = __esm({
7663
8082
  "ts/attempt-state.ts"() {
7664
8083
  init_mod();
@@ -7694,7 +8113,7 @@ var init_attempt_state = __esm({
7694
8113
  attemptId: record.attemptId
7695
8114
  };
7696
8115
  }, "validateJournal");
7697
- writeAll2 = /* @__PURE__ */ __name(async (file, bytes) => {
8116
+ writeAll3 = /* @__PURE__ */ __name(async (file, bytes) => {
7698
8117
  let offset = 0;
7699
8118
  while (offset < bytes.byteLength) {
7700
8119
  const written = await file.write(bytes.subarray(offset));
@@ -7778,7 +8197,7 @@ var init_attempt_state = __esm({
7778
8197
  createNew: true,
7779
8198
  mode: 384
7780
8199
  });
7781
- await writeAll2(file, bytes);
8200
+ await writeAll3(file, bytes);
7782
8201
  await file.sync();
7783
8202
  file.close();
7784
8203
  file = void 0;
@@ -7850,7 +8269,7 @@ var init_attempt_state = __esm({
7850
8269
  });
7851
8270
 
7852
8271
  // ts/staging-scavenger.ts
7853
- var stagingDirectoryNames, journalTemporaryNamePattern, lstatIfPresent2, removeIfPresent, scavengeRunnerStaging;
8272
+ var stagingDirectoryNames, journalTemporaryNamePattern, lstatIfPresent3, removeIfPresent, scavengeRunnerStaging;
7854
8273
  var init_staging_scavenger = __esm({
7855
8274
  "ts/staging-scavenger.ts"() {
7856
8275
  init_mod();
@@ -7865,7 +8284,7 @@ var init_staging_scavenger = __esm({
7865
8284
  "workspace-exports"
7866
8285
  ];
7867
8286
  journalTemporaryNamePattern = /^\.[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}\.(?:attempt|registration)-journal\.tmp$/;
7868
- lstatIfPresent2 = /* @__PURE__ */ __name(async (path) => {
8287
+ lstatIfPresent3 = /* @__PURE__ */ __name(async (path) => {
7869
8288
  try {
7870
8289
  return await Deno.lstat(path);
7871
8290
  } catch (error) {
@@ -7894,7 +8313,7 @@ var init_staging_scavenger = __esm({
7894
8313
  }
7895
8314
  for (const name of stagingDirectoryNames) {
7896
8315
  const path = join3(stateRoot, name);
7897
- const stat = await lstatIfPresent2(path);
8316
+ const stat = await lstatIfPresent3(path);
7898
8317
  if (!stat) continue;
7899
8318
  if (!stat.isDirectory || stat.isSymlink) {
7900
8319
  throw new RunnerError(`Runner staging path ${name} must be a real directory`);
@@ -7904,7 +8323,7 @@ var init_staging_scavenger = __esm({
7904
8323
  for await (const entry of Deno.readDir(stateRoot)) {
7905
8324
  if (!journalTemporaryNamePattern.test(entry.name)) continue;
7906
8325
  const path = join3(stateRoot, entry.name);
7907
- const stat = await lstatIfPresent2(path);
8326
+ const stat = await lstatIfPresent3(path);
7908
8327
  if (!stat) continue;
7909
8328
  if (!stat.isFile || stat.isSymlink) {
7910
8329
  throw new RunnerError("Runner journal temporary path must be a regular file");
@@ -8845,7 +9264,7 @@ var init_source_workspace = __esm({
8845
9264
  });
8846
9265
 
8847
9266
  // ts/registration-state.ts
8848
- var identifierPattern6, journalName2, maximumJournalBytes2, validateRegistrationRequest, withoutRequestId, writeAll3, isNotFound2, RegistrationStateStore;
9267
+ var identifierPattern6, journalName2, maximumJournalBytes2, validateRegistrationRequest, withoutRequestId, writeAll4, isNotFound2, RegistrationStateStore;
8849
9268
  var init_registration_state = __esm({
8850
9269
  "ts/registration-state.ts"() {
8851
9270
  init_mod();
@@ -8896,7 +9315,7 @@ var init_registration_state = __esm({
8896
9315
  name: request.name,
8897
9316
  capabilities: request.capabilities
8898
9317
  }), "withoutRequestId");
8899
- writeAll3 = /* @__PURE__ */ __name(async (file, bytes) => {
9318
+ writeAll4 = /* @__PURE__ */ __name(async (file, bytes) => {
8900
9319
  let offset = 0;
8901
9320
  while (offset < bytes.byteLength) {
8902
9321
  const written = await file.write(bytes.subarray(offset));
@@ -9002,7 +9421,7 @@ var init_registration_state = __esm({
9002
9421
  createNew: true,
9003
9422
  mode: 384
9004
9423
  });
9005
- await writeAll3(file, bytes);
9424
+ await writeAll4(file, bytes);
9006
9425
  await file.sync();
9007
9426
  file.close();
9008
9427
  file = void 0;