@waffle-os/runtime 0.0.153 → 0.0.155

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.
Files changed (61) hide show
  1. package/browser/net/helper.ts +114 -19
  2. package/browser/net/ring.ts +18 -6
  3. package/browser/net/runtime.ts +2 -2
  4. package/browser/notification-relay.ts +105 -18
  5. package/browser/notification-wait.ts +45 -4
  6. package/browser/notification-worker.ts +169 -76
  7. package/browser/preview.ts +15 -2
  8. package/core/filesystem.ts +18 -0
  9. package/core/wasi.ts +75 -4
  10. package/dist/browser/net/helper.js +83 -18
  11. package/dist/browser/net/ring.js +6 -5
  12. package/dist/browser/net/runtime.js +2 -2
  13. package/dist/browser/notification-relay.js +78 -15
  14. package/dist/browser/notification-wait.js +37 -5
  15. package/dist/browser/notification-worker.js +146 -67
  16. package/dist/core/wasi.js +62 -4
  17. package/dist/fs/backend.js +7 -0
  18. package/dist/fs/client.js +75 -17
  19. package/dist/fs/dirty-admission.js +15 -8
  20. package/dist/fs/guest-watch.js +267 -94
  21. package/dist/fs/indexeddb-chunks.js +88 -11
  22. package/dist/fs/indexeddb.js +366 -110
  23. package/dist/fs/memory.js +106 -20
  24. package/dist/fs/multitab-backend.js +291 -74
  25. package/dist/fs/multitab-protocol.js +1 -0
  26. package/dist/fs/persistent.js +70 -16
  27. package/dist/fs/protocol.js +15 -7
  28. package/dist/fs/publication-attachment.js +9 -7
  29. package/dist/fs/service.js +62 -9
  30. package/dist/fs/shared.js +100 -6
  31. package/dist/fs/storage.js +107 -8
  32. package/dist/fs/watch-service.js +97 -2
  33. package/dist/fs/watch-subscriptions.js +121 -8
  34. package/dist/proc/command-stdio.js +1 -1
  35. package/dist/proc/intrinsics/core.js +5 -0
  36. package/dist/proc/intrinsics.js +1 -0
  37. package/dist/tooling/program/program-transformer.json +1 -1
  38. package/fs/backend.ts +17 -0
  39. package/fs/client.ts +99 -16
  40. package/fs/dirty-admission.ts +22 -7
  41. package/fs/guest-watch.ts +299 -103
  42. package/fs/indexeddb-chunks.ts +103 -9
  43. package/fs/indexeddb.ts +477 -121
  44. package/fs/memory.ts +120 -19
  45. package/fs/multitab-backend.ts +440 -95
  46. package/fs/multitab-protocol.ts +1 -0
  47. package/fs/persistent.ts +88 -16
  48. package/fs/protocol.ts +26 -7
  49. package/fs/publication-attachment.ts +9 -7
  50. package/fs/service.ts +62 -7
  51. package/fs/shared.ts +110 -8
  52. package/fs/storage.ts +128 -10
  53. package/fs/watch-service.ts +110 -3
  54. package/fs/watch-subscriptions.ts +115 -7
  55. package/package.json +1 -1
  56. package/proc/command-stdio.ts +1 -1
  57. package/proc/intrinsics/core.ts +7 -0
  58. package/proc/intrinsics.ts +1 -0
  59. package/testing/idle-workspace-cancellation-browser.ts +22 -13
  60. package/testing/indexeddb-storage-browser.ts +564 -1
  61. package/tooling/program/program-transformer.json +1 -1
@@ -13,7 +13,12 @@ import {
13
13
  pack,
14
14
  unpack,
15
15
  } from "./protocol.js";
16
- import { CLIENT_MODE, CLIENT_MODE_NO_CLIENT_CACHE, CLIENT_MODE_NO_DIRECT_IO } from "./shared.js";
16
+ import {
17
+ CLIENT_MODE,
18
+ CLIENT_MODE_NO_CLIENT_CACHE,
19
+ CLIENT_MODE_NO_DIRECT_IO,
20
+ CLIENT_MODE_NO_WATCH_DRAIN,
21
+ } from "./shared.js";
17
22
  import type { RuntimeStartupObserver } from "./startup.js";
18
23
  import type { StorageBackend } from "./storage.js";
19
24
  import { HEADER_WORDS, WATCH_OFFSET } from "./storage-geometry.js";
@@ -337,6 +342,16 @@ function waitForAbortOrCancel(
337
342
  return { promise, cleanup };
338
343
  }
339
344
 
345
+ /** Ends one local Host attempt whose only problem is a lapsed lease; the caller renews and retries. */
346
+ class LeaseLapsedError extends Error {}
347
+ const LEASE_LAPSED = new LeaseLapsedError("host lease lapsed");
348
+ /** How long one call may spend renewing a lapsed lease, in lease durations from its first lapse. */
349
+ const LEASE_RENEWAL_BUDGET_LEASES = 4;
350
+ /** One call's renewal deadline, set at its first lapse and shared by every retry of that call. */
351
+ interface LeaseRenewalBudget {
352
+ deadline?: number;
353
+ }
354
+
340
355
  async function raceWithAbort(
341
356
  promise: Promise<unknown>,
342
357
  signal: AbortSignal,
@@ -567,7 +582,15 @@ export class MultiTabBackend implements FilesystemBackend {
567
582
  private watchCells?: Int32Array;
568
583
 
569
584
  // Lifecycle & role state
570
- private role: "init" | "host" | "peer" | "failover" | "waiting" | "failed" | "closed" = "init";
585
+ private roleState: "init" | "host" | "peer" | "failover" | "waiting" | "failed" | "closed" =
586
+ "init";
587
+ private get role() {
588
+ return this.roleState;
589
+ }
590
+ private set role(next: "init" | "host" | "peer" | "failover" | "waiting" | "failed" | "closed") {
591
+ this.roleState = next;
592
+ this.syncClientMode();
593
+ }
571
594
  private phase: "opening" | "waiting-storage" | "ready" | "retiring" | "failed" | "closed" =
572
595
  "opening";
573
596
  private steppingDown = false;
@@ -601,6 +624,9 @@ export class MultiTabBackend implements FilesystemBackend {
601
624
 
602
625
  // Host authority state
603
626
  private persistent?: PersistentBackend;
627
+ /** Bumped when entries are rebound, and by the outgoing backend's count plus one when the
628
+ * persistent backend changes, so unlinkGeneration() only ever moves forward. */
629
+ private unlinkEvents = 0;
604
630
  private watchService?: WatchService;
605
631
  private hostQueue: Promise<void> = Promise.resolve();
606
632
  private readonly barrier = new BarrierGate();
@@ -665,6 +691,7 @@ export class MultiTabBackend implements FilesystemBackend {
665
691
  private byFileId = new Map<bigint, LocalHandleEntry>();
666
692
  private nextLocalWatchId = 1;
667
693
  private localWatches = new Map<number, LocalWatchEntry>();
694
+ private hostWatchToLocal = new Map<number, LocalWatchEntry>();
668
695
 
669
696
  private constructor(private readonly options: MultiTabBackendOptions) {
670
697
  this.scope = multitabScope(options.implementation, options.name);
@@ -779,15 +806,27 @@ export class MultiTabBackend implements FilesystemBackend {
779
806
  this.configureSharedBuffer(buffer);
780
807
  if (this.persistent) {
781
808
  this.persistent.attachShared(buffer, this.sharedMaxBytes, this.retainedSegments);
782
- this.persistent.shared.setClientMode(CLIENT_MODE_NO_DIRECT_IO | CLIENT_MODE_NO_CLIENT_CACHE);
783
809
  }
810
+ this.syncClientMode();
784
811
  }
785
812
 
786
813
  private configureSharedBuffer(buffer: SharedArrayBuffer): void {
787
- const header = new Int32Array(buffer, 0, HEADER_WORDS);
788
- Atomics.store(header, CLIENT_MODE, CLIENT_MODE_NO_DIRECT_IO | CLIENT_MODE_NO_CLIENT_CACHE);
789
814
  const ring = new WatchRing(buffer, WATCH_OFFSET);
790
815
  this.watchCells = ring.cells;
816
+ this.syncClientMode();
817
+ }
818
+
819
+ private syncClientMode(): void {
820
+ const mode =
821
+ CLIENT_MODE_NO_DIRECT_IO |
822
+ CLIENT_MODE_NO_CLIENT_CACHE |
823
+ (this.roleState === "host" ? 0 : CLIENT_MODE_NO_WATCH_DRAIN);
824
+ if (this.persistent) {
825
+ this.persistent.shared.setClientMode(mode);
826
+ } else if (this.sharedBuffer) {
827
+ const header = new Int32Array(this.sharedBuffer, 0, HEADER_WORDS);
828
+ Atomics.store(header, CLIENT_MODE, mode);
829
+ }
791
830
  }
792
831
 
793
832
  private wakeWatchWord(): void {
@@ -814,6 +853,19 @@ export class MultiTabBackend implements FilesystemBackend {
814
853
  return Promise.resolve();
815
854
  }
816
855
 
856
+ private setPersistent(next: PersistentBackend | undefined): void {
857
+ if (next === this.persistent) return;
858
+ this.unlinkEvents += (this.persistent?.unlinkGeneration() ?? 0) + 1;
859
+ this.persistent = next;
860
+ }
861
+
862
+ /** Exact for the host, whose unlinks all go through its persistent backend. Any other role
863
+ * learns unlinks from the wire, so it reports NaN and every capability trim rescans. */
864
+ unlinkGeneration(): number {
865
+ if (this.role !== "host" || !this.persistent) return NaN;
866
+ return this.unlinkEvents + this.persistent.unlinkGeneration();
867
+ }
868
+
817
869
  isUnlinked(handle: FileHandle): boolean {
818
870
  const entry = this.byLocalHandle.get(handle);
819
871
  if (!entry) return false;
@@ -867,11 +919,16 @@ export class MultiTabBackend implements FilesystemBackend {
867
919
  const admittedTerm = this.hostTerm;
868
920
  const entry = this.byLocalHandle.get(handle);
869
921
  if (!entry || entry.stale || entry.remoteHandle === undefined) return undefined;
922
+ // A lease that lapsed only because renewal ran late keeps the read going; execute() renews
923
+ // it before the bytes are used.
870
924
  return this.persistent!.prepareDescriptorRead(
871
925
  entry.remoteHandle,
872
926
  offset,
873
927
  length,
874
- () => cancelled() || !this.isPreparedReadValid() || this.hostTerm !== admittedTerm,
928
+ () =>
929
+ cancelled() ||
930
+ this.hostTerm !== admittedTerm ||
931
+ (!this.isPreparedReadValid() && !this.leaseOnlyLapsed(admittedTerm)),
875
932
  );
876
933
  }
877
934
 
@@ -1060,7 +1117,8 @@ export class MultiTabBackend implements FilesystemBackend {
1060
1117
  }
1061
1118
  if (this.role === "host") {
1062
1119
  const admittedTerm = this.hostTerm;
1063
- this.assertHostReadyForLocal(admittedTerm);
1120
+ const budget: LeaseRenewalBudget = {};
1121
+ await this.assertHostAfterRenewal(admittedTerm, undefined, budget);
1064
1122
  let resolvedTarget: FileHandle | string | undefined = target;
1065
1123
  if (typeof target === "number") {
1066
1124
  const entry = this.byLocalHandle.get(target);
@@ -1070,7 +1128,7 @@ export class MultiTabBackend implements FilesystemBackend {
1070
1128
  this.enterHostAdmitted();
1071
1129
  try {
1072
1130
  await this.hostQueue;
1073
- this.assertHostReadyForLocal(admittedTerm);
1131
+ await this.assertHostAfterRenewal(admittedTerm, undefined, budget);
1074
1132
  await this.persistent!.flush(resolvedTarget);
1075
1133
  } finally {
1076
1134
  this.leaveHostAdmitted();
@@ -1112,12 +1170,14 @@ export class MultiTabBackend implements FilesystemBackend {
1112
1170
  if (!entry || entry.stale) throw new FilesystemError(8);
1113
1171
  if (this.role === "host") {
1114
1172
  const admittedTerm = this.hostTerm;
1115
- this.assertHostReadyForLocal(admittedTerm);
1173
+ if (!this.hostReadyForLocal(admittedTerm)) {
1174
+ return this.watchOpenAfterRenewal(owner, handle, recursive, cancelled, admittedTerm);
1175
+ }
1116
1176
  if (entry.remoteHandle === undefined) throw new FilesystemError(8);
1117
1177
  this.watchService ??= new WatchService(this.persistent!);
1118
1178
  const hostWatchId = this.watchService.open(owner, entry.remoteHandle, recursive, cancelled);
1119
1179
  const localWatchId = this.nextLocalWatchId++;
1120
- this.localWatches.set(localWatchId, {
1180
+ const localEntry: LocalWatchEntry = {
1121
1181
  localWatchId,
1122
1182
  localOwner: owner,
1123
1183
  fileId: entry.fileId,
@@ -1126,7 +1186,9 @@ export class MultiTabBackend implements FilesystemBackend {
1126
1186
  hostWatchId,
1127
1187
  overflowed: false,
1128
1188
  closed: false,
1129
- });
1189
+ };
1190
+ this.localWatches.set(localWatchId, localEntry);
1191
+ this.hostWatchToLocal.set(hostWatchId, localEntry);
1130
1192
  return localWatchId;
1131
1193
  }
1132
1194
  if (this.needsFailoverWait()) {
@@ -1197,32 +1259,169 @@ export class MultiTabBackend implements FilesystemBackend {
1197
1259
  throw new FilesystemError(11);
1198
1260
  }
1199
1261
 
1262
+ /** A watch opened while the lease lapsed only late: renew, then open it as usual. */
1263
+ private async watchOpenAfterRenewal(
1264
+ owner: number,
1265
+ handle: FileHandle,
1266
+ recursive: boolean,
1267
+ cancelled: () => boolean,
1268
+ admittedTerm: bigint,
1269
+ ): Promise<number> {
1270
+ await this.renewLapsedLease(admittedTerm, cancelled);
1271
+ return this.watchOpen(owner, handle, recursive, cancelled);
1272
+ }
1273
+
1200
1274
  private async watchReadHostAfterRenew(
1201
1275
  owner: number,
1202
1276
  watch: LocalWatchEntry,
1203
1277
  cancelled: () => boolean,
1204
1278
  ): Promise<HeldWatchBatch> {
1279
+ const overflow: HeldWatchBatch = {
1280
+ batch: { kind: "overflow", events: [] },
1281
+ release() {},
1282
+ rollback() {},
1283
+ };
1284
+ const budget: LeaseRenewalBudget = {};
1285
+ await this.renewWatchLeaseOnce(watch.hostTerm, cancelled);
1286
+ for (;;) {
1287
+ if (this.disposing || cancelled()) throw new FilesystemError(11);
1288
+ // Only a term that really ended makes the overflow permanent for this watch.
1289
+ const termEnded =
1290
+ watch.hostTerm !== this.hostTerm ||
1291
+ this.role !== "host" ||
1292
+ this.ownershipLost ||
1293
+ this.leaseClosed;
1294
+ if (watch.overflowed || termEnded || !this.watchService) {
1295
+ watch.overflowed = true;
1296
+ return overflow;
1297
+ }
1298
+ if (this.isLeaseValid()) return this.watchService.readHeld(owner, watch.hostWatchId!);
1299
+ if (!(await this.renewWatchLease(watch.hostTerm, cancelled, budget))) return overflow;
1300
+ }
1301
+ }
1302
+
1303
+ /** The first renewal of a watch read or drain whose lease was not held when it arrived. */
1304
+ private async renewWatchLeaseOnce(admittedTerm: bigint, cancelled: () => boolean): Promise<void> {
1205
1305
  if (this.disposing || cancelled()) throw new FilesystemError(11);
1206
- let ok = false;
1207
- await raceWithAbort(
1208
- this.renewLeaseNow().then((renewed) => {
1209
- ok = renewed;
1210
- }),
1211
- this.disposeAbort.signal,
1212
- cancelled,
1213
- );
1214
- if (this.disposing || cancelled()) throw new FilesystemError(11);
1215
- if (
1216
- !ok ||
1217
- !this.isLeaseValid() ||
1218
- watch.overflowed ||
1219
- watch.hostTerm !== this.hostTerm ||
1220
- !this.watchService
1221
- ) {
1222
- watch.overflowed = true;
1223
- return { batch: { kind: "overflow", events: [] }, release() {}, rollback() {} };
1306
+ if (this.leaseOnlyLapsed(admittedTerm)) return;
1307
+ await raceWithAbort(this.renewLeaseNow(), this.disposeAbort.signal, cancelled);
1308
+ }
1309
+
1310
+ /**
1311
+ * Renews a lapse for a watch read or drain within one budget. False when the lapse is not
1312
+ * renewable or the renewal cannot finish in time: the caller reports one overflow, not a failure.
1313
+ */
1314
+ private async renewWatchLease(
1315
+ admittedTerm: bigint,
1316
+ cancelled: () => boolean,
1317
+ budget: LeaseRenewalBudget,
1318
+ ): Promise<boolean> {
1319
+ if (!this.leaseOnlyLapsed(admittedTerm)) return false;
1320
+ try {
1321
+ await this.renewLapsedLease(admittedTerm, cancelled, budget);
1322
+ return true;
1323
+ } catch {
1324
+ if (this.disposing || cancelled()) throw new FilesystemError(11);
1325
+ return false;
1224
1326
  }
1225
- return this.watchService.readHeld(owner, watch.hostWatchId!);
1327
+ }
1328
+
1329
+ watchDrain(
1330
+ owner: number,
1331
+ cancelled: () => boolean,
1332
+ ):
1333
+ | import("./watch-service.js").HeldWatchDrain
1334
+ | Promise<import("./watch-service.js").HeldWatchDrain> {
1335
+ if (this.role === "host") {
1336
+ const admittedTerm = this.hostTerm;
1337
+ if (!this.isLeaseValid()) {
1338
+ return this.watchDrainHostAfterRenew(owner, admittedTerm, cancelled);
1339
+ }
1340
+ return this.drainHostWatches(owner);
1341
+ }
1342
+ throw new FilesystemError(58);
1343
+ }
1344
+
1345
+ private overflowOwnerWatches(
1346
+ owner: number,
1347
+ permanent: boolean,
1348
+ ): import("./watch-service.js").HeldWatchDrain {
1349
+ const entries: import("../core/filesystem.js").WatchDrainEntry[] = [];
1350
+ for (const watch of this.localWatches.values()) {
1351
+ if (watch.closed || watch.localOwner !== owner) continue;
1352
+ if (permanent || watch.hostTerm !== this.hostTerm) watch.overflowed = true;
1353
+ entries.push({ id: watch.localWatchId, batch: { kind: "overflow", events: [] } });
1354
+ }
1355
+ return { entries, more: false, hasEvents: false, release() {}, rollback() {} };
1356
+ }
1357
+
1358
+ private async watchDrainHostAfterRenew(
1359
+ owner: number,
1360
+ admittedTerm: bigint,
1361
+ cancelled: () => boolean,
1362
+ ): Promise<import("./watch-service.js").HeldWatchDrain> {
1363
+ const budget: LeaseRenewalBudget = {};
1364
+ await this.renewWatchLeaseOnce(admittedTerm, cancelled);
1365
+ for (;;) {
1366
+ if (this.disposing || cancelled()) throw new FilesystemError(11);
1367
+ const termEnded =
1368
+ admittedTerm !== this.hostTerm ||
1369
+ this.role !== "host" ||
1370
+ this.ownershipLost ||
1371
+ this.leaseClosed ||
1372
+ !!this.terminalFailure ||
1373
+ !this.watchService;
1374
+ if (termEnded) return this.overflowOwnerWatches(owner, true);
1375
+ if (this.isLeaseValid()) return this.drainHostWatches(owner);
1376
+ if (!(await this.renewWatchLease(admittedTerm, cancelled, budget)))
1377
+ return this.overflowOwnerWatches(owner, false);
1378
+ }
1379
+ }
1380
+
1381
+ private drainHostWatches(owner: number): import("./watch-service.js").HeldWatchDrain {
1382
+ if (this.terminalFailure || !this.watchService) {
1383
+ return this.overflowOwnerWatches(owner, true);
1384
+ }
1385
+ const entries: import("../core/filesystem.js").WatchDrainEntry[] = [];
1386
+ const seen = new Set<number>();
1387
+ const held = this.watchService.drainHeld(owner);
1388
+ for (const entry of held.entries) {
1389
+ const local = this.hostWatchToLocal.get(entry.id);
1390
+ if (!local || local.closed || local.localOwner !== owner) continue;
1391
+ if (local.overflowed || local.hostTerm !== this.hostTerm) {
1392
+ local.overflowed = true;
1393
+ seen.add(local.localWatchId);
1394
+ entries.push({ id: local.localWatchId, batch: { kind: "overflow", events: [] } });
1395
+ continue;
1396
+ }
1397
+ seen.add(local.localWatchId);
1398
+ entries.push(
1399
+ "batch" in entry
1400
+ ? { id: local.localWatchId, batch: entry.batch }
1401
+ : { id: local.localWatchId, errno: entry.errno },
1402
+ );
1403
+ }
1404
+ // Only scan localWatches when a term change or explicit overflow may exist outside WatchService.
1405
+ if (this.hostWatchToLocal.size !== this.localWatches.size) {
1406
+ for (const watch of this.localWatches.values()) {
1407
+ if (watch.closed || watch.localOwner !== owner || seen.has(watch.localWatchId)) continue;
1408
+ if (
1409
+ watch.overflowed ||
1410
+ watch.hostTerm !== this.hostTerm ||
1411
+ watch.hostWatchId === undefined
1412
+ ) {
1413
+ watch.overflowed = true;
1414
+ entries.push({ id: watch.localWatchId, batch: { kind: "overflow", events: [] } });
1415
+ }
1416
+ }
1417
+ }
1418
+ return {
1419
+ entries,
1420
+ more: held.more,
1421
+ hasEvents: held.hasEvents,
1422
+ release: held.release,
1423
+ rollback: held.rollback,
1424
+ };
1226
1425
  }
1227
1426
 
1228
1427
  watchClose(owner: number, localWatchId: number): void {
@@ -1230,6 +1429,9 @@ export class MultiTabBackend implements FilesystemBackend {
1230
1429
  if (!watch || watch.localOwner !== owner) return;
1231
1430
  watch.closed = true;
1232
1431
  this.localWatches.delete(localWatchId);
1432
+ if (watch.hostWatchId !== undefined && this.hostWatchToLocal.get(watch.hostWatchId) === watch) {
1433
+ this.hostWatchToLocal.delete(watch.hostWatchId);
1434
+ }
1233
1435
  if (
1234
1436
  this.role === "host" &&
1235
1437
  watch.hostTerm === this.hostTerm &&
@@ -1343,7 +1545,7 @@ export class MultiTabBackend implements FilesystemBackend {
1343
1545
 
1344
1546
  if (this.persistent) {
1345
1547
  const residual = this.persistent;
1346
- this.persistent = undefined;
1548
+ this.setPersistent(undefined);
1347
1549
  this.watchService = undefined;
1348
1550
  await this.retireFailedMountBackend(residual);
1349
1551
  }
@@ -1634,7 +1836,9 @@ export class MultiTabBackend implements FilesystemBackend {
1634
1836
  });
1635
1837
 
1636
1838
  if (this.sharedBuffer) {
1637
- backend.shared.setClientMode(CLIENT_MODE_NO_DIRECT_IO | CLIENT_MODE_NO_CLIENT_CACHE);
1839
+ backend.shared.setClientMode(
1840
+ CLIENT_MODE_NO_DIRECT_IO | CLIENT_MODE_NO_CLIENT_CACHE | CLIENT_MODE_NO_WATCH_DRAIN,
1841
+ );
1638
1842
  }
1639
1843
 
1640
1844
  // Brand-new workspace: flush initial root BEFORE first host-ready so workspaceId + root FileIdentity are durable.
@@ -1688,7 +1892,7 @@ export class MultiTabBackend implements FilesystemBackend {
1688
1892
  }
1689
1893
 
1690
1894
  // Mount fixed hostTerm & bind PersistentBackend
1691
- this.persistent = backend;
1895
+ this.setPersistent(backend);
1692
1896
  this.watchService = new WatchService(backend);
1693
1897
  this.hostTerm = backend.initialReservationEra;
1694
1898
  this.hostStorageEpoch = storageEpoch;
@@ -1768,7 +1972,7 @@ export class MultiTabBackend implements FilesystemBackend {
1768
1972
  ): Promise<void> {
1769
1973
  if (this.terminalFailure) throw wrapReleaseError(this.terminalFailure.reason, false);
1770
1974
  if (backend) {
1771
- this.persistent = undefined;
1975
+ this.setPersistent(undefined);
1772
1976
  this.watchService = undefined;
1773
1977
  await this.retireFailedMountBackend(backend);
1774
1978
  } else {
@@ -1857,6 +2061,7 @@ export class MultiTabBackend implements FilesystemBackend {
1857
2061
  !!claimName &&
1858
2062
  !!snap.held?.some((l) => l.name === claimName && l.clientId === this.selfLockClientId);
1859
2063
  if (!hasStorage || !hasClaim) return false;
2064
+ // After the lock query: verifyStorageEpoch may answer from an open commit's epoch read.
1860
2065
  return this.persistent.verifyStorageEpoch();
1861
2066
  }
1862
2067
 
@@ -2185,7 +2390,7 @@ export class MultiTabBackend implements FilesystemBackend {
2185
2390
  }
2186
2391
 
2187
2392
  this.captureRetainedSegments(persistent);
2188
- this.persistent = undefined;
2393
+ this.setPersistent(undefined);
2189
2394
  this.watchService = undefined;
2190
2395
  if (this.sharedBuffer) persistent.shared.resetForRemount(this.retainedSegments);
2191
2396
  await this.releaseAttemptAndElectionLocks();
@@ -2257,7 +2462,7 @@ export class MultiTabBackend implements FilesystemBackend {
2257
2462
  this.closeAllHostPeerSessions();
2258
2463
  if (this.persistent) {
2259
2464
  const persistent = this.persistent;
2260
- this.persistent = undefined;
2465
+ this.setPersistent(undefined);
2261
2466
  this.watchService = undefined;
2262
2467
  await persistent.retireFenced().catch(() => {});
2263
2468
  this.captureRetainedSegments(persistent);
@@ -2319,7 +2524,7 @@ export class MultiTabBackend implements FilesystemBackend {
2319
2524
  this.closeAllHostPeerSessions();
2320
2525
  if (this.persistent) {
2321
2526
  const persistent = this.persistent;
2322
- this.persistent = undefined;
2527
+ this.setPersistent(undefined);
2323
2528
  this.watchService = undefined;
2324
2529
  await persistent.retireFenced().catch(() => {});
2325
2530
  this.captureRetainedSegments(persistent);
@@ -2344,7 +2549,7 @@ export class MultiTabBackend implements FilesystemBackend {
2344
2549
  this.closeAllHostPeerSessions();
2345
2550
  if (this.persistent) {
2346
2551
  const persistent = this.persistent;
2347
- this.persistent = undefined;
2552
+ this.setPersistent(undefined);
2348
2553
  this.watchService = undefined;
2349
2554
  await persistent.retireFenced().catch(() => {});
2350
2555
  this.captureRetainedSegments(persistent);
@@ -5389,7 +5594,13 @@ export class MultiTabBackend implements FilesystemBackend {
5389
5594
  });
5390
5595
  }
5391
5596
 
5392
- private assertHostReadyForLocal(admittedTerm: bigint): void {
5597
+ /**
5598
+ * Throws unless this tab is still the Host of the term and may run local work. Returns false
5599
+ * when the lease lapsed only because renewal ran late, so the caller renews and checks again.
5600
+ * It samples the lease once: a second sample could see a lapse the first did not and fail a
5601
+ * call that a renewal would have kept.
5602
+ */
5603
+ private hostReadyForLocal(admittedTerm: bigint): boolean {
5393
5604
  if (this.terminalFailure || this.persistent?.isTerminallyFailed()) {
5394
5605
  throw new FilesystemError(29, describeReason(this.terminalFailure?.reason));
5395
5606
  }
@@ -5404,9 +5615,158 @@ export class MultiTabBackend implements FilesystemBackend {
5404
5615
  if (this.steppingDown && (!this.disposing || this.disposeHostTerm !== admittedTerm)) {
5405
5616
  throw new FilesystemError(11, "host is stepping down");
5406
5617
  }
5407
- if (!this.isLeaseValid()) {
5618
+ if (this.isLeaseValid()) return true;
5619
+ if (this.lapseIsRenewable(admittedTerm)) return false;
5620
+ throw new FilesystemError(11, "host lease expired");
5621
+ }
5622
+
5623
+ /**
5624
+ * The lease lapsed only because renewal ran late, for example behind a long task on this
5625
+ * worker. This tab is still the Host of this term, so a local operation renews and retries.
5626
+ */
5627
+ private leaseOnlyLapsed(admittedTerm: bigint): boolean {
5628
+ return !this.isLeaseValid() && this.lapseIsRenewable(admittedTerm);
5629
+ }
5630
+
5631
+ /** Whether a lapse of the lease would be renewable: everything leaseOnlyLapsed checks but time. */
5632
+ private lapseIsRenewable(admittedTerm: bigint): boolean {
5633
+ return (
5634
+ !this.leaseClosed &&
5635
+ !this.ownershipLost &&
5636
+ !this.terminalFailure &&
5637
+ !this.persistent?.isTerminallyFailed() &&
5638
+ !!this.persistent &&
5639
+ this.role === "host" &&
5640
+ this.hostTerm === admittedTerm &&
5641
+ !this.steppingDown &&
5642
+ !this.disposing
5643
+ );
5644
+ }
5645
+
5646
+ private assertLocalAttempt(admittedTerm: bigint, cancelled?: () => boolean): void {
5647
+ if (cancelled?.()) throw new FilesystemError(11, "operation cancelled");
5648
+ if (!this.hostReadyForLocal(admittedTerm)) throw LEASE_LAPSED;
5649
+ }
5650
+
5651
+ /** Abandon a local attempt's wait: cancelled, a new term, or a lease renewal cannot restore. */
5652
+ private localAttemptStale(admittedTerm: bigint, cancelled?: () => boolean): boolean {
5653
+ if (cancelled?.() || this.hostTerm !== admittedTerm) return true;
5654
+ return !this.isLeaseValid() && !this.leaseOnlyLapsed(admittedTerm);
5655
+ }
5656
+
5657
+ /** Runs a local attempt; a lapsed lease is renewed, then the whole attempt runs again. */
5658
+ private async retryAfterLeaseRenewal<T>(
5659
+ admittedTerm: bigint,
5660
+ cancelled: (() => boolean) | undefined,
5661
+ budget: LeaseRenewalBudget,
5662
+ attempt: () => Promise<T>,
5663
+ ): Promise<T> {
5664
+ for (;;) {
5665
+ try {
5666
+ return await attempt();
5667
+ } catch (error) {
5668
+ if (error !== LEASE_LAPSED) throw error;
5669
+ }
5670
+ // A lost term or a step-down fails in the next attempt's hostReadyForLocal.
5671
+ await this.renewLapsedLease(admittedTerm, cancelled, budget);
5672
+ }
5673
+ }
5674
+
5675
+ /**
5676
+ * Renews a lapsed lease until this tab holds it, then returns; throws once this tab is no
5677
+ * longer the Host of the term or the call's renewal budget runs out.
5678
+ */
5679
+ private async assertHostAfterRenewal(
5680
+ admittedTerm: bigint,
5681
+ cancelled: (() => boolean) | undefined,
5682
+ budget: LeaseRenewalBudget,
5683
+ ): Promise<void> {
5684
+ while (!this.hostReadyForLocal(admittedTerm)) {
5685
+ await this.renewLapsedLease(admittedTerm, cancelled, budget);
5686
+ }
5687
+ }
5688
+
5689
+ /**
5690
+ * Renews until the lease holds or this tab stops being the Host of the term. On a loaded
5691
+ * worker a renewal can confirm the locks yet finish past its own deadline, which proves
5692
+ * nothing about now, so it tries again one poll interval later. A renewal that keeps failing
5693
+ * that way, or keeps throwing, gives up once the call's budget passes.
5694
+ */
5695
+ private async renewLapsedLease(
5696
+ admittedTerm: bigint,
5697
+ cancelled?: () => boolean,
5698
+ budget: LeaseRenewalBudget = {},
5699
+ ): Promise<void> {
5700
+ const fresh = budget.deadline === undefined;
5701
+ const deadline = (budget.deadline ??=
5702
+ performance.now() + this.timings.leaseDurationMs * LEASE_RENEWAL_BUDGET_LEASES);
5703
+ for (let attempt = 0; this.leaseOnlyLapsed(admittedTerm); attempt++) {
5704
+ if ((attempt > 0 || !fresh) && performance.now() >= deadline) {
5705
+ throw new FilesystemError(11, "host lease could not be renewed");
5706
+ }
5707
+ if (attempt > 0) await this.pauseBeforeRenewal(cancelled);
5708
+ await raceWithAbort(
5709
+ this.renewLeaseNow(this.currentAttemptId),
5710
+ this.disposeAbort.signal,
5711
+ cancelled,
5712
+ );
5713
+ if (cancelled?.()) throw new FilesystemError(11, "operation cancelled");
5714
+ }
5715
+ }
5716
+
5717
+ private async pauseBeforeRenewal(cancelled?: () => boolean): Promise<void> {
5718
+ await raceWithAbort(delay(this.timings.waitPollMs), this.disposeAbort.signal, cancelled);
5719
+ if (cancelled?.()) throw new FilesystemError(11, "operation cancelled");
5720
+ }
5721
+
5722
+ /**
5723
+ * The lease was not held when a local Host call started: renew it, or forward the call when
5724
+ * this tab has become a Peer. Returns the forwarded result, or undefined to run the call here.
5725
+ */
5726
+ private async renewBeforeLocalHostCall(
5727
+ admittedTerm: bigint,
5728
+ budget: LeaseRenewalBudget,
5729
+ operation: string,
5730
+ args: any[],
5731
+ data: Uint8Array,
5732
+ responseCookieTag?: bigint,
5733
+ cancelled?: () => boolean,
5734
+ ): Promise<{ result: unknown } | undefined> {
5735
+ if (this.disposing) throw new FilesystemError(11, "host lease expired during dispose");
5736
+ if (this.leaseOnlyLapsed(admittedTerm)) {
5737
+ await this.renewLapsedLease(admittedTerm, cancelled, budget);
5738
+ } else {
5739
+ await raceWithAbort(
5740
+ this.renewLeaseNow(this.currentAttemptId),
5741
+ this.disposeAbort.signal,
5742
+ cancelled,
5743
+ );
5744
+ }
5745
+ if (cancelled?.()) throw new FilesystemError(11, "operation cancelled");
5746
+ if (this.disposing) throw new FilesystemError(11, "filesystem is disposing");
5747
+ // A lease renewed with little time left can lapse again before this check; that lapse is
5748
+ // renewed below like any other, not treated as a lost term.
5749
+ if (!this.isLeaseValid() && !this.leaseOnlyLapsed(admittedTerm)) {
5750
+ await this.awaitPendingFenceLoss(cancelled);
5751
+ if (cancelled?.()) throw new FilesystemError(11, "operation cancelled");
5752
+ if (this.disposing) throw new FilesystemError(11, "filesystem is disposing");
5753
+ if (this.terminalFailure) {
5754
+ throw new FilesystemError(29, describeReason(this.terminalFailure.reason));
5755
+ }
5756
+ if (this.ownershipLost) throw new FilesystemError(11, "filesystem ownership lost");
5757
+ if (this.role === "peer" || this.role === "failover" || this.role === "waiting") {
5758
+ const nextCookieTag = this.revalidateCookieForPeerForward(
5759
+ operation,
5760
+ args,
5761
+ responseCookieTag,
5762
+ );
5763
+ return {
5764
+ result: await this.executeOnPeer(operation, args, data, nextCookieTag, cancelled),
5765
+ };
5766
+ }
5408
5767
  throw new FilesystemError(11, "host lease expired");
5409
5768
  }
5769
+ return undefined;
5410
5770
  }
5411
5771
 
5412
5772
  private async executeLocalOnHost(
@@ -5418,42 +5778,27 @@ export class MultiTabBackend implements FilesystemBackend {
5418
5778
  ): Promise<unknown> {
5419
5779
  if (cancelled?.()) throw new FilesystemError(11, "operation cancelled");
5420
5780
  const admittedTerm = this.hostTerm;
5781
+ const budget: LeaseRenewalBudget = {};
5421
5782
 
5422
5783
  // If lease expired before execution: renew first (or fail ECANCELED if disposing!)
5423
5784
  if (!this.isLeaseValid()) {
5424
- if (this.disposing) throw new FilesystemError(11, "host lease expired during dispose");
5425
- let ok = false;
5426
- await raceWithAbort(
5427
- this.renewLeaseNow(this.currentAttemptId).then((renewed) => {
5428
- ok = renewed;
5429
- }),
5430
- this.disposeAbort.signal,
5785
+ const forwarded = await this.renewBeforeLocalHostCall(
5786
+ admittedTerm,
5787
+ budget,
5788
+ operation,
5789
+ args,
5790
+ data,
5791
+ responseCookieTag,
5431
5792
  cancelled,
5432
5793
  );
5433
- if (cancelled?.()) throw new FilesystemError(11, "operation cancelled");
5434
- if (this.disposing) throw new FilesystemError(11, "filesystem is disposing");
5435
- if (!ok || !this.isLeaseValid()) {
5436
- await this.awaitPendingFenceLoss(cancelled);
5437
- if (cancelled?.()) throw new FilesystemError(11, "operation cancelled");
5438
- if (this.disposing) throw new FilesystemError(11, "filesystem is disposing");
5439
- if (this.terminalFailure) {
5440
- throw new FilesystemError(29, describeReason(this.terminalFailure.reason));
5441
- }
5442
- if (this.ownershipLost) throw new FilesystemError(11, "filesystem ownership lost");
5443
- if (this.role === "peer" || this.role === "failover" || this.role === "waiting") {
5444
- const nextCookieTag = this.revalidateCookieForPeerForward(
5445
- operation,
5446
- args,
5447
- responseCookieTag,
5448
- );
5449
- return this.executeOnPeer(operation, args, data, nextCookieTag, cancelled);
5450
- }
5451
- throw new FilesystemError(11, "host lease expired");
5452
- }
5794
+ if (forwarded) return forwarded.result;
5453
5795
  }
5454
5796
 
5455
5797
  if (cancelled?.()) throw new FilesystemError(11, "operation cancelled");
5456
- this.assertHostReadyForLocal(admittedTerm);
5798
+ if (!this.hostReadyForLocal(admittedTerm)) {
5799
+ await this.assertHostAfterRenewal(admittedTerm, cancelled, budget);
5800
+ if (cancelled?.()) throw new FilesystemError(11, "operation cancelled");
5801
+ }
5457
5802
  const persistent = this.persistent!;
5458
5803
  const translated = this.translateArgsToHost(operation, args);
5459
5804
  if (!translated) throw new FilesystemError(8);
@@ -5465,21 +5810,25 @@ export class MultiTabBackend implements FilesystemBackend {
5465
5810
  operation === "sync" ? (translated[0] as number) : (translated[0] as string | undefined);
5466
5811
  await this.hostQueue;
5467
5812
  if (cancelled?.()) throw new FilesystemError(11, "operation cancelled");
5468
- this.assertHostReadyForLocal(admittedTerm);
5813
+ await this.assertHostAfterRenewal(admittedTerm, cancelled, budget);
5469
5814
  await persistent.flush(target);
5470
5815
  return operation === "sync" ? 0 : undefined;
5471
5816
  }
5472
5817
  if (operation === "read") {
5473
- return await this.executeLocalHostRead(persistent, admittedTerm, translated, cancelled);
5818
+ return await this.retryAfterLeaseRenewal(admittedTerm, cancelled, budget, () =>
5819
+ this.executeLocalHostRead(persistent, admittedTerm, translated, cancelled),
5820
+ );
5474
5821
  }
5475
- const result = await this.executeLocalHostGeneral(
5476
- persistent,
5477
- admittedTerm,
5478
- operation,
5479
- translated,
5480
- data,
5481
- responseCookieTag,
5482
- cancelled,
5822
+ const result = await this.retryAfterLeaseRenewal(admittedTerm, cancelled, budget, () =>
5823
+ this.executeLocalHostGeneral(
5824
+ persistent,
5825
+ admittedTerm,
5826
+ operation,
5827
+ translated,
5828
+ data,
5829
+ responseCookieTag,
5830
+ cancelled,
5831
+ ),
5483
5832
  );
5484
5833
  return this.mapLocalHostHandles(persistent, admittedTerm, operation, result);
5485
5834
  } finally {
@@ -5494,18 +5843,12 @@ export class MultiTabBackend implements FilesystemBackend {
5494
5843
  cancelled?: () => boolean,
5495
5844
  ): Promise<Uint8Array> {
5496
5845
  const [remoteHandle, length, offset] = translated as [number, number, number];
5497
- const assertValid = () => {
5498
- if (cancelled?.()) throw new FilesystemError(11, "operation cancelled");
5499
- this.assertHostReadyForLocal(admittedTerm);
5500
- };
5846
+ const assertValid = () => this.assertLocalAttempt(admittedTerm, cancelled);
5501
5847
  for (;;) {
5502
5848
  assertValid();
5503
5849
  const startVer = this.readVersion();
5504
- const prep = persistent.prepareDescriptorRead(
5505
- remoteHandle,
5506
- offset,
5507
- length,
5508
- () => !!cancelled?.() || this.hostTerm !== admittedTerm || !this.isLeaseValid(),
5850
+ const prep = persistent.prepareDescriptorRead(remoteHandle, offset, length, () =>
5851
+ this.localAttemptStale(admittedTerm, cancelled),
5509
5852
  );
5510
5853
  if (prep) {
5511
5854
  const accepted = await this.revalidateColdReadBytes(prep, startVer, assertValid);
@@ -5534,10 +5877,7 @@ export class MultiTabBackend implements FilesystemBackend {
5534
5877
  responseCookieTag?: bigint,
5535
5878
  cancelled?: () => boolean,
5536
5879
  ): Promise<unknown> {
5537
- const assertValid = () => {
5538
- if (cancelled?.()) throw new FilesystemError(11, "operation cancelled");
5539
- this.assertHostReadyForLocal(admittedTerm);
5540
- };
5880
+ const assertValid = () => this.assertLocalAttempt(admittedTerm, cancelled);
5541
5881
  for (;;) {
5542
5882
  assertValid();
5543
5883
  const preparing = persistent.prepare(operation, translated);
@@ -5562,9 +5902,8 @@ export class MultiTabBackend implements FilesystemBackend {
5562
5902
  result = step.result;
5563
5903
  });
5564
5904
  if (dirtyRetryChange !== undefined) {
5565
- await persistent.waitForDirtyCapacity(
5566
- dirtyRetryChange,
5567
- () => !!cancelled?.() || this.hostTerm !== admittedTerm || !this.isLeaseValid(),
5905
+ await persistent.waitForDirtyCapacity(dirtyRetryChange, () =>
5906
+ this.localAttemptStale(admittedTerm, cancelled),
5568
5907
  );
5569
5908
  continue;
5570
5909
  }
@@ -6704,6 +7043,7 @@ export class MultiTabBackend implements FilesystemBackend {
6704
7043
  entry.remoteSessionId = sessionId;
6705
7044
  entry.pinToken = wire.pinToken;
6706
7045
  entry.unlinked = !!wire.unlinked;
7046
+ this.unlinkEvents++;
6707
7047
  entry.stale = false;
6708
7048
  }
6709
7049
  } finally {
@@ -6713,6 +7053,7 @@ export class MultiTabBackend implements FilesystemBackend {
6713
7053
 
6714
7054
  private rebindLocalHandlesOnHost(term: bigint): void {
6715
7055
  const persistent = this.persistent!;
7056
+ this.unlinkEvents++;
6716
7057
  for (const entry of this.byLocalHandle.values()) {
6717
7058
  const node = persistent.nodeByFileId(entry.fileId);
6718
7059
  if (!node) {
@@ -6825,6 +7166,7 @@ export class MultiTabBackend implements FilesystemBackend {
6825
7166
  pinToken: number | undefined,
6826
7167
  unlinked?: boolean,
6827
7168
  ): LocalHandleEntry {
7169
+ if (unlinked) this.unlinkEvents++;
6828
7170
  const existing = this.byFileId.get(fileId);
6829
7171
  if (existing) {
6830
7172
  if (remoteSessionId !== undefined && pinToken !== undefined) {
@@ -6902,6 +7244,7 @@ export class MultiTabBackend implements FilesystemBackend {
6902
7244
  }
6903
7245
 
6904
7246
  private detachHandlesForRemount(): void {
7247
+ this.unlinkEvents++;
6905
7248
  for (const entry of this.byLocalHandle.values()) {
6906
7249
  entry.remoteHandle = undefined;
6907
7250
  entry.remoteTerm = undefined;
@@ -6981,7 +7324,8 @@ export class MultiTabBackend implements FilesystemBackend {
6981
7324
  case "setTimes":
6982
7325
  case "readdir":
6983
7326
  case "readdirPage":
6984
- case "resolve": {
7327
+ case "resolve":
7328
+ case "realpath": {
6985
7329
  const remote = mapHandle(args[0]);
6986
7330
  if (remote === undefined) return undefined;
6987
7331
  return [remote, ...args.slice(1)];
@@ -7010,6 +7354,7 @@ export class MultiTabBackend implements FilesystemBackend {
7010
7354
  }
7011
7355
 
7012
7356
  private markLocalWatchesOverflow(): void {
7357
+ this.hostWatchToLocal.clear();
7013
7358
  for (const watch of this.localWatches.values()) {
7014
7359
  watch.overflowed = true;
7015
7360
  }