@waffle-os/runtime 0.0.154 → 0.0.156

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 (42) hide show
  1. package/core/filesystem.ts +22 -0
  2. package/core/wasi.ts +78 -5
  3. package/dist/core/filesystem.js +1 -0
  4. package/dist/core/wasi.js +71 -6
  5. package/dist/fs/backend.js +22 -1
  6. package/dist/fs/client.js +11 -3
  7. package/dist/fs/cold-read-cache.js +23 -0
  8. package/dist/fs/guest-watch.js +267 -94
  9. package/dist/fs/indexeddb-chunks.js +88 -11
  10. package/dist/fs/indexeddb.js +78 -14
  11. package/dist/fs/memory.js +17 -1
  12. package/dist/fs/multitab-backend.js +198 -64
  13. package/dist/fs/multitab-protocol.js +1 -0
  14. package/dist/fs/persistent.js +19 -1
  15. package/dist/fs/service.js +30 -1
  16. package/dist/fs/shared.js +4 -0
  17. package/dist/fs/storage.js +107 -8
  18. package/dist/fs/watch-service.js +97 -2
  19. package/dist/fs/watch-subscriptions.js +121 -8
  20. package/dist/proc/intrinsics/core.js +5 -0
  21. package/dist/proc/intrinsics.js +1 -0
  22. package/dist/tooling/program/program-transformer.json +1 -1
  23. package/fs/backend.ts +27 -1
  24. package/fs/client.ts +11 -0
  25. package/fs/cold-read-cache.ts +38 -0
  26. package/fs/guest-watch.ts +298 -102
  27. package/fs/indexeddb-chunks.ts +103 -9
  28. package/fs/indexeddb.ts +98 -11
  29. package/fs/memory.ts +18 -0
  30. package/fs/multitab-backend.ts +273 -72
  31. package/fs/multitab-protocol.ts +1 -0
  32. package/fs/persistent.ts +38 -1
  33. package/fs/service.ts +28 -0
  34. package/fs/shared.ts +4 -0
  35. package/fs/storage.ts +128 -10
  36. package/fs/watch-service.ts +110 -3
  37. package/fs/watch-subscriptions.ts +115 -7
  38. package/package.json +1 -1
  39. package/proc/intrinsics/core.ts +7 -0
  40. package/proc/intrinsics.ts +1 -0
  41. package/testing/indexeddb-storage-browser.ts +129 -0
  42. 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";
@@ -577,7 +582,15 @@ export class MultiTabBackend implements FilesystemBackend {
577
582
  private watchCells?: Int32Array;
578
583
 
579
584
  // Lifecycle & role state
580
- 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
+ }
581
594
  private phase: "opening" | "waiting-storage" | "ready" | "retiring" | "failed" | "closed" =
582
595
  "opening";
583
596
  private steppingDown = false;
@@ -678,6 +691,7 @@ export class MultiTabBackend implements FilesystemBackend {
678
691
  private byFileId = new Map<bigint, LocalHandleEntry>();
679
692
  private nextLocalWatchId = 1;
680
693
  private localWatches = new Map<number, LocalWatchEntry>();
694
+ private hostWatchToLocal = new Map<number, LocalWatchEntry>();
681
695
 
682
696
  private constructor(private readonly options: MultiTabBackendOptions) {
683
697
  this.scope = multitabScope(options.implementation, options.name);
@@ -792,15 +806,27 @@ export class MultiTabBackend implements FilesystemBackend {
792
806
  this.configureSharedBuffer(buffer);
793
807
  if (this.persistent) {
794
808
  this.persistent.attachShared(buffer, this.sharedMaxBytes, this.retainedSegments);
795
- this.persistent.shared.setClientMode(CLIENT_MODE_NO_DIRECT_IO | CLIENT_MODE_NO_CLIENT_CACHE);
796
809
  }
810
+ this.syncClientMode();
797
811
  }
798
812
 
799
813
  private configureSharedBuffer(buffer: SharedArrayBuffer): void {
800
- const header = new Int32Array(buffer, 0, HEADER_WORDS);
801
- Atomics.store(header, CLIENT_MODE, CLIENT_MODE_NO_DIRECT_IO | CLIENT_MODE_NO_CLIENT_CACHE);
802
814
  const ring = new WatchRing(buffer, WATCH_OFFSET);
803
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
+ }
804
830
  }
805
831
 
806
832
  private wakeWatchWord(): void {
@@ -1144,15 +1170,14 @@ export class MultiTabBackend implements FilesystemBackend {
1144
1170
  if (!entry || entry.stale) throw new FilesystemError(8);
1145
1171
  if (this.role === "host") {
1146
1172
  const admittedTerm = this.hostTerm;
1147
- if (this.leaseOnlyLapsed(admittedTerm)) {
1173
+ if (!this.hostReadyForLocal(admittedTerm)) {
1148
1174
  return this.watchOpenAfterRenewal(owner, handle, recursive, cancelled, admittedTerm);
1149
1175
  }
1150
- this.assertHostReadyForLocal(admittedTerm);
1151
1176
  if (entry.remoteHandle === undefined) throw new FilesystemError(8);
1152
1177
  this.watchService ??= new WatchService(this.persistent!);
1153
1178
  const hostWatchId = this.watchService.open(owner, entry.remoteHandle, recursive, cancelled);
1154
1179
  const localWatchId = this.nextLocalWatchId++;
1155
- this.localWatches.set(localWatchId, {
1180
+ const localEntry: LocalWatchEntry = {
1156
1181
  localWatchId,
1157
1182
  localOwner: owner,
1158
1183
  fileId: entry.fileId,
@@ -1161,7 +1186,9 @@ export class MultiTabBackend implements FilesystemBackend {
1161
1186
  hostWatchId,
1162
1187
  overflowed: false,
1163
1188
  closed: false,
1164
- });
1189
+ };
1190
+ this.localWatches.set(localWatchId, localEntry);
1191
+ this.hostWatchToLocal.set(hostWatchId, localEntry);
1165
1192
  return localWatchId;
1166
1193
  }
1167
1194
  if (this.needsFailoverWait()) {
@@ -1249,31 +1276,152 @@ export class MultiTabBackend implements FilesystemBackend {
1249
1276
  watch: LocalWatchEntry,
1250
1277
  cancelled: () => boolean,
1251
1278
  ): Promise<HeldWatchBatch> {
1252
- if (this.disposing || cancelled()) throw new FilesystemError(11);
1253
- if (this.leaseOnlyLapsed(watch.hostTerm)) {
1254
- // A renewal that cannot finish in time reports one overflow below, not a failure.
1255
- await this.renewLapsedLease(watch.hostTerm, cancelled).catch(() => {});
1256
- } else {
1257
- await raceWithAbort(this.renewLeaseNow(), this.disposeAbort.signal, cancelled);
1258
- }
1259
- if (this.disposing || cancelled()) throw new FilesystemError(11);
1260
1279
  const overflow: HeldWatchBatch = {
1261
1280
  batch: { kind: "overflow", events: [] },
1262
1281
  release() {},
1263
1282
  rollback() {},
1264
1283
  };
1265
- // Only a term that really ended makes the overflow permanent for this watch.
1266
- const termEnded =
1267
- watch.hostTerm !== this.hostTerm ||
1268
- this.role !== "host" ||
1269
- this.ownershipLost ||
1270
- this.leaseClosed;
1271
- if (watch.overflowed || termEnded || !this.watchService) {
1272
- watch.overflowed = true;
1273
- return overflow;
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;
1274
1300
  }
1275
- if (!this.isLeaseValid()) return overflow;
1276
- return this.watchService.readHeld(owner, watch.hostWatchId!);
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> {
1305
+ if (this.disposing || cancelled()) throw new FilesystemError(11);
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;
1326
+ }
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
+ };
1277
1425
  }
1278
1426
 
1279
1427
  watchClose(owner: number, localWatchId: number): void {
@@ -1281,6 +1429,9 @@ export class MultiTabBackend implements FilesystemBackend {
1281
1429
  if (!watch || watch.localOwner !== owner) return;
1282
1430
  watch.closed = true;
1283
1431
  this.localWatches.delete(localWatchId);
1432
+ if (watch.hostWatchId !== undefined && this.hostWatchToLocal.get(watch.hostWatchId) === watch) {
1433
+ this.hostWatchToLocal.delete(watch.hostWatchId);
1434
+ }
1284
1435
  if (
1285
1436
  this.role === "host" &&
1286
1437
  watch.hostTerm === this.hostTerm &&
@@ -1685,7 +1836,9 @@ export class MultiTabBackend implements FilesystemBackend {
1685
1836
  });
1686
1837
 
1687
1838
  if (this.sharedBuffer) {
1688
- 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
+ );
1689
1842
  }
1690
1843
 
1691
1844
  // Brand-new workspace: flush initial root BEFORE first host-ready so workspaceId + root FileIdentity are durable.
@@ -1908,6 +2061,7 @@ export class MultiTabBackend implements FilesystemBackend {
1908
2061
  !!claimName &&
1909
2062
  !!snap.held?.some((l) => l.name === claimName && l.clientId === this.selfLockClientId);
1910
2063
  if (!hasStorage || !hasClaim) return false;
2064
+ // After the lock query: verifyStorageEpoch may answer from an open commit's epoch read.
1911
2065
  return this.persistent.verifyStorageEpoch();
1912
2066
  }
1913
2067
 
@@ -5440,7 +5594,13 @@ export class MultiTabBackend implements FilesystemBackend {
5440
5594
  });
5441
5595
  }
5442
5596
 
5443
- 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 {
5444
5604
  if (this.terminalFailure || this.persistent?.isTerminallyFailed()) {
5445
5605
  throw new FilesystemError(29, describeReason(this.terminalFailure?.reason));
5446
5606
  }
@@ -5455,9 +5615,9 @@ export class MultiTabBackend implements FilesystemBackend {
5455
5615
  if (this.steppingDown && (!this.disposing || this.disposeHostTerm !== admittedTerm)) {
5456
5616
  throw new FilesystemError(11, "host is stepping down");
5457
5617
  }
5458
- if (!this.isLeaseValid()) {
5459
- throw new FilesystemError(11, "host lease expired");
5460
- }
5618
+ if (this.isLeaseValid()) return true;
5619
+ if (this.lapseIsRenewable(admittedTerm)) return false;
5620
+ throw new FilesystemError(11, "host lease expired");
5461
5621
  }
5462
5622
 
5463
5623
  /**
@@ -5465,8 +5625,12 @@ export class MultiTabBackend implements FilesystemBackend {
5465
5625
  * worker. This tab is still the Host of this term, so a local operation renews and retries.
5466
5626
  */
5467
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 {
5468
5633
  return (
5469
- !this.isLeaseValid() &&
5470
5634
  !this.leaseClosed &&
5471
5635
  !this.ownershipLost &&
5472
5636
  !this.terminalFailure &&
@@ -5481,8 +5645,7 @@ export class MultiTabBackend implements FilesystemBackend {
5481
5645
 
5482
5646
  private assertLocalAttempt(admittedTerm: bigint, cancelled?: () => boolean): void {
5483
5647
  if (cancelled?.()) throw new FilesystemError(11, "operation cancelled");
5484
- if (this.leaseOnlyLapsed(admittedTerm)) throw LEASE_LAPSED;
5485
- this.assertHostReadyForLocal(admittedTerm);
5648
+ if (!this.hostReadyForLocal(admittedTerm)) throw LEASE_LAPSED;
5486
5649
  }
5487
5650
 
5488
5651
  /** Abandon a local attempt's wait: cancelled, a new term, or a lease renewal cannot restore. */
@@ -5504,20 +5667,23 @@ export class MultiTabBackend implements FilesystemBackend {
5504
5667
  } catch (error) {
5505
5668
  if (error !== LEASE_LAPSED) throw error;
5506
5669
  }
5507
- // A lost term or a step-down fails in the next attempt's assertHostReadyForLocal.
5670
+ // A lost term or a step-down fails in the next attempt's hostReadyForLocal.
5508
5671
  await this.renewLapsedLease(admittedTerm, cancelled, budget);
5509
5672
  }
5510
5673
  }
5511
5674
 
5512
- /** Renews a lapsed lease, then asserts this tab is still the Host of the term. */
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
+ */
5513
5679
  private async assertHostAfterRenewal(
5514
5680
  admittedTerm: bigint,
5515
5681
  cancelled: (() => boolean) | undefined,
5516
5682
  budget: LeaseRenewalBudget,
5517
5683
  ): Promise<void> {
5518
- if (this.leaseOnlyLapsed(admittedTerm))
5684
+ while (!this.hostReadyForLocal(admittedTerm)) {
5519
5685
  await this.renewLapsedLease(admittedTerm, cancelled, budget);
5520
- this.assertHostReadyForLocal(admittedTerm);
5686
+ }
5521
5687
  }
5522
5688
 
5523
5689
  /**
@@ -5553,6 +5719,56 @@ export class MultiTabBackend implements FilesystemBackend {
5553
5719
  if (cancelled?.()) throw new FilesystemError(11, "operation cancelled");
5554
5720
  }
5555
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
+ }
5767
+ throw new FilesystemError(11, "host lease expired");
5768
+ }
5769
+ return undefined;
5770
+ }
5771
+
5556
5772
  private async executeLocalOnHost(
5557
5773
  operation: string,
5558
5774
  args: any[],
@@ -5566,40 +5782,23 @@ export class MultiTabBackend implements FilesystemBackend {
5566
5782
 
5567
5783
  // If lease expired before execution: renew first (or fail ECANCELED if disposing!)
5568
5784
  if (!this.isLeaseValid()) {
5569
- if (this.disposing) throw new FilesystemError(11, "host lease expired during dispose");
5570
- if (this.leaseOnlyLapsed(admittedTerm)) {
5571
- await this.renewLapsedLease(admittedTerm, cancelled, budget);
5572
- } else {
5573
- await raceWithAbort(
5574
- this.renewLeaseNow(this.currentAttemptId),
5575
- this.disposeAbort.signal,
5576
- cancelled,
5577
- );
5578
- }
5579
- if (cancelled?.()) throw new FilesystemError(11, "operation cancelled");
5580
- if (this.disposing) throw new FilesystemError(11, "filesystem is disposing");
5581
- if (!this.isLeaseValid()) {
5582
- await this.awaitPendingFenceLoss(cancelled);
5583
- if (cancelled?.()) throw new FilesystemError(11, "operation cancelled");
5584
- if (this.disposing) throw new FilesystemError(11, "filesystem is disposing");
5585
- if (this.terminalFailure) {
5586
- throw new FilesystemError(29, describeReason(this.terminalFailure.reason));
5587
- }
5588
- if (this.ownershipLost) throw new FilesystemError(11, "filesystem ownership lost");
5589
- if (this.role === "peer" || this.role === "failover" || this.role === "waiting") {
5590
- const nextCookieTag = this.revalidateCookieForPeerForward(
5591
- operation,
5592
- args,
5593
- responseCookieTag,
5594
- );
5595
- return this.executeOnPeer(operation, args, data, nextCookieTag, cancelled);
5596
- }
5597
- throw new FilesystemError(11, "host lease expired");
5598
- }
5785
+ const forwarded = await this.renewBeforeLocalHostCall(
5786
+ admittedTerm,
5787
+ budget,
5788
+ operation,
5789
+ args,
5790
+ data,
5791
+ responseCookieTag,
5792
+ cancelled,
5793
+ );
5794
+ if (forwarded) return forwarded.result;
5599
5795
  }
5600
5796
 
5601
5797
  if (cancelled?.()) throw new FilesystemError(11, "operation cancelled");
5602
- 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
+ }
5603
5802
  const persistent = this.persistent!;
5604
5803
  const translated = this.translateArgsToHost(operation, args);
5605
5804
  if (!translated) throw new FilesystemError(8);
@@ -7126,7 +7325,8 @@ export class MultiTabBackend implements FilesystemBackend {
7126
7325
  case "readdir":
7127
7326
  case "readdirPage":
7128
7327
  case "resolve":
7129
- case "realpath": {
7328
+ case "realpath":
7329
+ case "probe": {
7130
7330
  const remote = mapHandle(args[0]);
7131
7331
  if (remote === undefined) return undefined;
7132
7332
  return [remote, ...args.slice(1)];
@@ -7155,6 +7355,7 @@ export class MultiTabBackend implements FilesystemBackend {
7155
7355
  }
7156
7356
 
7157
7357
  private markLocalWatchesOverflow(): void {
7358
+ this.hostWatchToLocal.clear();
7158
7359
  for (const watch of this.localWatches.values()) {
7159
7360
  watch.overflowed = true;
7160
7361
  }
@@ -193,6 +193,7 @@ const PURE_STATELESS_READ_OPS = new Set<string>([
193
193
  "readlink",
194
194
  "resolve",
195
195
  "realpath",
196
+ "probe",
196
197
  "readdirPage",
197
198
  ]);
198
199
 
package/fs/persistent.ts CHANGED
@@ -148,6 +148,12 @@ export class PersistentBackend extends MemoryBackend {
148
148
  get hasLoadedIndex(): boolean {
149
149
  return this.loadedIndex;
150
150
  }
151
+ /**
152
+ * Whether the storage still belongs to this connection's epoch. IndexedDB may answer from an
153
+ * epoch read made by one of its own open commits (see IndexedDBStorage.verifyEpoch). That is
154
+ * sound only because the caller, the multitab lease renewal, confirms it still holds the
155
+ * storage Web Lock first: keep the lock query before this call.
156
+ */
151
157
  async verifyStorageEpoch(signal?: AbortSignal): Promise<boolean> {
152
158
  if ("verifyEpoch" in this.storage && typeof this.storage.verifyEpoch === "function") {
153
159
  return (this.storage as { verifyEpoch(s?: AbortSignal): Promise<boolean> }).verifyEpoch(
@@ -406,17 +412,48 @@ export class PersistentBackend extends MemoryBackend {
406
412
  const cached = this.coldReads.read(key, offset, count);
407
413
  if (cached) {
408
414
  this.storage.checkPayload(key, size);
415
+ this.coldReads.noteRead(key, offset + count);
409
416
  return this.cachedDescriptorRange(cached, cancelled);
410
417
  }
418
+ // A sequential scan fetches a page-aligned readahead window in one storage read; its pages
419
+ // are verified with it and serve the next requests from the cache.
420
+ const window = this.coldReads.readWindow(key, offset, count, size);
411
421
  const backing = this.coldBacking(node, key, undefined, cancelled);
422
+ this.coldReads.noteRead(key, offset + count);
412
423
  const drained = Promise.withResolvers<void>();
413
424
  this.ownWork(drained.promise);
414
- return this.readDescriptorRange(backing, offset, count, cancelled).finally(() => {
425
+ const reply = this.readDescriptorWindow(backing, offset, count, window, cancelled);
426
+ return reply.finally(() => {
415
427
  const release = Promise.resolve().then(() => backing.retention.release());
416
428
  void release.then(drained.resolve, drained.reject);
417
429
  return release;
418
430
  });
419
431
  }
432
+ private async readDescriptorWindow(
433
+ backing: Extract<ReadBacking, { kind: "cold" }>,
434
+ offset: number,
435
+ count: number,
436
+ window: { offset: number; length: number },
437
+ cancelled: () => boolean,
438
+ ): Promise<Uint8Array> {
439
+ if (window.offset === offset && window.length === count)
440
+ return this.readDescriptorRange(backing, offset, count, cancelled);
441
+ try {
442
+ const bytes = await this.readDescriptorRange(
443
+ backing,
444
+ window.offset,
445
+ window.length,
446
+ cancelled,
447
+ );
448
+ return bytes.slice(offset - window.offset, offset - window.offset + count);
449
+ } catch (error) {
450
+ if (cancelled() || this.stopped) throw new FilesystemError(11);
451
+ if (error instanceof FilesystemError && error.errno === 11) throw error;
452
+ // An error in speculative readahead bytes must not fail a valid read; retry only the
453
+ // caller's requested range, which still enforces ownership and cancellation.
454
+ return this.readDescriptorRange(backing, offset, count, cancelled);
455
+ }
456
+ }
420
457
  private async readDescriptorRange(
421
458
  backing: Extract<ReadBacking, { kind: "cold" }>,
422
459
  offset: number,
package/fs/service.ts CHANGED
@@ -967,6 +967,7 @@ export class FilesystemService {
967
967
  "readdirPage",
968
968
  "resolve",
969
969
  "realpath",
970
+ "probe",
970
971
  ].includes(operation)
971
972
  )
972
973
  this.check(session, a, held);
@@ -1065,6 +1066,33 @@ export class FilesystemService {
1065
1066
  else held.release();
1066
1067
  return held.batch;
1067
1068
  }
1069
+ if (operation === "watchDrain") {
1070
+ if (this.backend.watchDrain) {
1071
+ const register = (held: import("./watch-service.js").HeldWatchDrain) => {
1072
+ if (cancelled()) {
1073
+ held.rollback();
1074
+ throw new FilesystemError(11);
1075
+ }
1076
+ if (held.hasEvents)
1077
+ session.watchTransactions.set(requestId, {
1078
+ cancel: held.rollback,
1079
+ release: held.release,
1080
+ });
1081
+ else held.release();
1082
+ return { entries: held.entries, more: held.more };
1083
+ };
1084
+ const draining = this.backend.watchDrain(session.connection.owner, cancelled);
1085
+ return draining instanceof Promise
1086
+ ? this.trackRequestWork(session, draining).then(register)
1087
+ : register(draining);
1088
+ }
1089
+ if (!this.watchService) return { entries: [], more: false };
1090
+ const held = this.watchService.drainHeld(session.connection.owner);
1091
+ if (held.hasEvents)
1092
+ session.watchTransactions.set(requestId, { cancel: held.rollback, release: held.release });
1093
+ else held.release();
1094
+ return { entries: held.entries, more: held.more };
1095
+ }
1068
1096
  if (operation === "watchClose") {
1069
1097
  if (this.backend.watchClose) {
1070
1098
  this.backend.watchClose(session.connection.owner, a);
package/fs/shared.ts CHANGED
@@ -86,6 +86,7 @@ const PINNED_PAGES = 29;
86
86
  export const CLIENT_MODE = 30;
87
87
  export const CLIENT_MODE_NO_DIRECT_IO = 1;
88
88
  export const CLIENT_MODE_NO_CLIENT_CACHE = 2;
89
+ export const CLIENT_MODE_NO_WATCH_DRAIN = 4;
89
90
  const MODE = 12;
90
91
  const FILE_SIZE = 1;
91
92
  // File times are unsigned 64-bit nanoseconds in two words each, starting on an even word.
@@ -302,6 +303,9 @@ export class SharedFilesystemState {
302
303
  isClientCacheDisabled(): boolean {
303
304
  return (atomicsLoad(this.cells, CLIENT_MODE) & CLIENT_MODE_NO_CLIENT_CACHE) !== 0;
304
305
  }
306
+ isWatchDrainDisabled(): boolean {
307
+ return (atomicsLoad(this.cells, CLIENT_MODE) & CLIENT_MODE_NO_WATCH_DRAIN) !== 0;
308
+ }
305
309
  /** Reset all per-mount filesystem state in place across Host remount/demotion while preserving
306
310
  * tab-lifetime header invariants (`MAGIC`, `maxSegments`, owner/probe words, `WATCH_OFFSET`,
307
311
  * `watch.cells[3]`, `CLIENT_MODE`, `UNLINK_GENERATION`) and reusing tab-lifetime segments at their exact indexes. */