@rljson/fs-agent 0.0.79 → 0.0.81

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.
@@ -477,6 +477,79 @@ Additionally, all sync callbacks are **debounced** (default 300ms) to coalesce
477
477
  rapid filesystem events (e.g. multi-file saves, editor autosave) into a single
478
478
  sync operation.
479
479
 
480
+ ## Anti-Entropy (`src/fs-anti-entropy.ts`)
481
+
482
+ Nothing in the message path ever asks whether a message arrived. A lost push is
483
+ not resent until the folder changes again; a lost forward is repeated only by
484
+ the hub's heartbeat, which the connector drops as a duplicate or delivers as
485
+ "not newest". The anti-entropy closes that gap.
486
+
487
+ **Trigger.** `syncFromDb` subscribes to two events on the connector's socket
488
+ directly — `${route}:bootstrap` and the server's state beacon
489
+ `stateBeaconEvent(route)` = `${route}:state` — not through `listen`, whose
490
+ dedup is exactly what hides the repeat that would show a disagreement. Each
491
+ announcement (`r`, `o`, `p`) goes to `FsAntiEntropy.observe()`.
492
+
493
+ The beacon is the signal to run on. The connector does not listen to it, so it
494
+ enters no apply path; the bootstrap heartbeat does, which is why the CARAT One
495
+ Client runs with it off. The event name comes from `@rljson/db`
496
+ (`stateBeaconEvent`), next to the Connector that deliberately ignores it; the
497
+ server imports the same function.
498
+
499
+ **Decision** (`antiEntropyDecision`, pure):
500
+
501
+ 1. `r === _currentRef` → in sync.
502
+ 2. `_currentRef === _lastPushedRef` and `o` is our connector's origin →
503
+ **push**: the hub holds an earlier push of ours and missed the later one.
504
+ 3. `p` contains `_currentRef` or `_lastAppliedRef` → **pull**: we missed the
505
+ hub's state.
506
+ 4. `_currentRef === _lastPushedRef` and `r === _lastAppliedRef` → **push**:
507
+ the hub still holds what our push was made from.
508
+ 5. otherwise → **merge**.
509
+
510
+ Rule 4 comes AFTER the ancestry check: a peer that deletes what we added can
511
+ return the folder to exactly the state we last applied — same hash, but made
512
+ from ours. Measured under load: pushing there put the deleted file back on
513
+ every node.
514
+
515
+ Rule 2 precedes rule 3 because of a collision the hash cannot resolve:
516
+ "B deleted the file A created" (hub `S0` made from `S1`, A at `S1`) and "A
517
+ deleted its own file and that push was lost" (hub `S1` made from `S0`, A at the
518
+ re-derived `S0`) are identical in refs and ancestry. Only the origin of the
519
+ hub's state tells them apart, and each wrong answer puts a deleted file back.
520
+
521
+ `_lastPushedRef` is set only where the agent authors a state (initial push,
522
+ debounced push, merge revision) — never by an apply, which can leave the folder
523
+ short of what it applied. Re-announcing such a state would roll peers back.
524
+
525
+ **Repair**, only once this node has been out of step with the hub for
526
+ `graceMs` **without its own state moving**, and nothing is pending,
527
+ processing or applying. The divergence is keyed on `_currentRef` alone: a node
528
+ keeping up with the traffic changes its own state with every forward it
529
+ applies, while a node that lost a message sits still. Keying on the hub's
530
+ state as well restarted the grace period on every change there, so a node
531
+ that missed every forward while another machine kept writing was never
532
+ repaired (review, ONE-446). The repair answers the latest announcement:
533
+
534
+ - push → `_sendRef(connector, _currentRef, [hubRef])`
535
+ - pull → `scheduleProcess(hubRef, …, p)` — the ordinary `processRef`
536
+ - merge → the same with `p` on the first attempt, then with `[]`, which makes
537
+ the apply additive (union), after which the next round pushes it
538
+
539
+ Repeated repairs of one divergence back off exponentially up to
540
+ `maxBackoffMs`. `processing` covers the pauses between `processRef` retries,
541
+ where `_remoteApplyInFlight` is clear.
542
+
543
+ **Why not a copy of the mongo anti-entropy.** That one is triggered by noticing
544
+ a PEER's root, so a node that receives nothing never starts it, and it applies
545
+ a peer tombstone without a recency check. This one is triggered by the hub's
546
+ own announcement and never applies anything outside the ordinary rules.
547
+
548
+ **Tested by** `test/client-server/heals-after-forced-divergence.spec.ts`: three
549
+ clients, a real server with heartbeat, one ref message dropped on purpose per
550
+ case — including both halves of the collision above — plus a control run with
551
+ the repair off that must stay divergent.
552
+
480
553
  ## Known Constraints
481
554
 
482
555
  ### macOS Finder Paste and Rename
package/README.public.md CHANGED
@@ -761,6 +761,53 @@ retried up to `processRefRetries` times with increasing delay
761
761
  (`attempt * processRefRetryDelayMs`). This prevents a single transient
762
762
  timeout from permanently breaking the sync pipeline.
763
763
 
764
+ ## Anti-Entropy — healing a lost message
765
+
766
+ Every change reaches a peer as exactly one message. If that message is lost —
767
+ a push the hub never received, a forward a peer never received, an apply that
768
+ gave up — nothing would ever send it again, and two machines would sit on two
769
+ states for good. The anti-entropy notices and repairs that, with nobody doing
770
+ anything.
771
+
772
+ It is driven by the hub's periodic announcement of its state, so the server
773
+ must send one. Use the **state beacon** (`@rljson/server` 0.0.67+): it goes on
774
+ its own event, which the connector never processes, so it costs nothing in
775
+ the apply path. The bootstrap heartbeat works too, but a periodic heartbeat
776
+ is delivered into every agent's apply path and has been measured
777
+ net-harmful in production.
778
+
779
+ ```typescript
780
+ const server = new Server(route, io, bs, {
781
+ syncConfig: { causalOrdering: true, includeClientIdentity: true },
782
+ stateBeaconMs: 30_000,
783
+ });
784
+
785
+ const agent = new FsAgent('./my-project', bs, {
786
+ antiEntropy: {
787
+ enabled: true, // default: true
788
+ graceMs: 10_000, // how long this node may sit still, out of step, before a repair (default: 10s)
789
+ maxBackoffMs: 300_000 // cap for repeated repairs of one divergence (default: 5 min)
790
+ },
791
+ });
792
+ ```
793
+
794
+ Each announcement carries the hub's tree ref — a content hash of the whole
795
+ folder, so comparing it with our own is the per-folder checksum comparison —
796
+ plus who produced it and what it descends from. A divergence that outlives
797
+ `graceMs` while nothing is applying is repaired:
798
+
799
+ | Hub state | Repair |
800
+ |---|---|
801
+ | an earlier push of ours, or what our push was made from | **push** — re-announce our state |
802
+ | made from the state we are in | **pull** — apply it, deletions included |
803
+ | neither can be shown | **merge** — apply it; if that makes no progress, additively |
804
+
805
+ Every repair goes through the ordinary apply and push paths, with their
806
+ ancestry and mass-delete rules; the anti-entropy never deletes anything
807
+ itself. Without a beacon or heartbeat it never fires. `agent.antiEntropyStatus`
808
+ reports whether this node and the hub agree, since when they have not, and
809
+ the last repair — a lasting divergence is the one trace a lost message leaves.
810
+
764
811
  ## Bounce-Back Prevention
765
812
 
766
813
  Bidirectional sync can cause infinite loops when both clients detect each
@@ -477,6 +477,79 @@ Additionally, all sync callbacks are **debounced** (default 300ms) to coalesce
477
477
  rapid filesystem events (e.g. multi-file saves, editor autosave) into a single
478
478
  sync operation.
479
479
 
480
+ ## Anti-Entropy (`src/fs-anti-entropy.ts`)
481
+
482
+ Nothing in the message path ever asks whether a message arrived. A lost push is
483
+ not resent until the folder changes again; a lost forward is repeated only by
484
+ the hub's heartbeat, which the connector drops as a duplicate or delivers as
485
+ "not newest". The anti-entropy closes that gap.
486
+
487
+ **Trigger.** `syncFromDb` subscribes to two events on the connector's socket
488
+ directly — `${route}:bootstrap` and the server's state beacon
489
+ `stateBeaconEvent(route)` = `${route}:state` — not through `listen`, whose
490
+ dedup is exactly what hides the repeat that would show a disagreement. Each
491
+ announcement (`r`, `o`, `p`) goes to `FsAntiEntropy.observe()`.
492
+
493
+ The beacon is the signal to run on. The connector does not listen to it, so it
494
+ enters no apply path; the bootstrap heartbeat does, which is why the CARAT One
495
+ Client runs with it off. The event name comes from `@rljson/db`
496
+ (`stateBeaconEvent`), next to the Connector that deliberately ignores it; the
497
+ server imports the same function.
498
+
499
+ **Decision** (`antiEntropyDecision`, pure):
500
+
501
+ 1. `r === _currentRef` → in sync.
502
+ 2. `_currentRef === _lastPushedRef` and `o` is our connector's origin →
503
+ **push**: the hub holds an earlier push of ours and missed the later one.
504
+ 3. `p` contains `_currentRef` or `_lastAppliedRef` → **pull**: we missed the
505
+ hub's state.
506
+ 4. `_currentRef === _lastPushedRef` and `r === _lastAppliedRef` → **push**:
507
+ the hub still holds what our push was made from.
508
+ 5. otherwise → **merge**.
509
+
510
+ Rule 4 comes AFTER the ancestry check: a peer that deletes what we added can
511
+ return the folder to exactly the state we last applied — same hash, but made
512
+ from ours. Measured under load: pushing there put the deleted file back on
513
+ every node.
514
+
515
+ Rule 2 precedes rule 3 because of a collision the hash cannot resolve:
516
+ "B deleted the file A created" (hub `S0` made from `S1`, A at `S1`) and "A
517
+ deleted its own file and that push was lost" (hub `S1` made from `S0`, A at the
518
+ re-derived `S0`) are identical in refs and ancestry. Only the origin of the
519
+ hub's state tells them apart, and each wrong answer puts a deleted file back.
520
+
521
+ `_lastPushedRef` is set only where the agent authors a state (initial push,
522
+ debounced push, merge revision) — never by an apply, which can leave the folder
523
+ short of what it applied. Re-announcing such a state would roll peers back.
524
+
525
+ **Repair**, only once this node has been out of step with the hub for
526
+ `graceMs` **without its own state moving**, and nothing is pending,
527
+ processing or applying. The divergence is keyed on `_currentRef` alone: a node
528
+ keeping up with the traffic changes its own state with every forward it
529
+ applies, while a node that lost a message sits still. Keying on the hub's
530
+ state as well restarted the grace period on every change there, so a node
531
+ that missed every forward while another machine kept writing was never
532
+ repaired (review, ONE-446). The repair answers the latest announcement:
533
+
534
+ - push → `_sendRef(connector, _currentRef, [hubRef])`
535
+ - pull → `scheduleProcess(hubRef, …, p)` — the ordinary `processRef`
536
+ - merge → the same with `p` on the first attempt, then with `[]`, which makes
537
+ the apply additive (union), after which the next round pushes it
538
+
539
+ Repeated repairs of one divergence back off exponentially up to
540
+ `maxBackoffMs`. `processing` covers the pauses between `processRef` retries,
541
+ where `_remoteApplyInFlight` is clear.
542
+
543
+ **Why not a copy of the mongo anti-entropy.** That one is triggered by noticing
544
+ a PEER's root, so a node that receives nothing never starts it, and it applies
545
+ a peer tombstone without a recency check. This one is triggered by the hub's
546
+ own announcement and never applies anything outside the ordinary rules.
547
+
548
+ **Tested by** `test/client-server/heals-after-forced-divergence.spec.ts`: three
549
+ clients, a real server with heartbeat, one ref message dropped on purpose per
550
+ case — including both halves of the collision above — plus a control run with
551
+ the repair off that must stay divergent.
552
+
480
553
  ## Known Constraints
481
554
 
482
555
  ### macOS Finder Paste and Rename
@@ -761,6 +761,53 @@ retried up to `processRefRetries` times with increasing delay
761
761
  (`attempt * processRefRetryDelayMs`). This prevents a single transient
762
762
  timeout from permanently breaking the sync pipeline.
763
763
 
764
+ ## Anti-Entropy — healing a lost message
765
+
766
+ Every change reaches a peer as exactly one message. If that message is lost —
767
+ a push the hub never received, a forward a peer never received, an apply that
768
+ gave up — nothing would ever send it again, and two machines would sit on two
769
+ states for good. The anti-entropy notices and repairs that, with nobody doing
770
+ anything.
771
+
772
+ It is driven by the hub's periodic announcement of its state, so the server
773
+ must send one. Use the **state beacon** (`@rljson/server` 0.0.67+): it goes on
774
+ its own event, which the connector never processes, so it costs nothing in
775
+ the apply path. The bootstrap heartbeat works too, but a periodic heartbeat
776
+ is delivered into every agent's apply path and has been measured
777
+ net-harmful in production.
778
+
779
+ ```typescript
780
+ const server = new Server(route, io, bs, {
781
+ syncConfig: { causalOrdering: true, includeClientIdentity: true },
782
+ stateBeaconMs: 30_000,
783
+ });
784
+
785
+ const agent = new FsAgent('./my-project', bs, {
786
+ antiEntropy: {
787
+ enabled: true, // default: true
788
+ graceMs: 10_000, // how long this node may sit still, out of step, before a repair (default: 10s)
789
+ maxBackoffMs: 300_000 // cap for repeated repairs of one divergence (default: 5 min)
790
+ },
791
+ });
792
+ ```
793
+
794
+ Each announcement carries the hub's tree ref — a content hash of the whole
795
+ folder, so comparing it with our own is the per-folder checksum comparison —
796
+ plus who produced it and what it descends from. A divergence that outlives
797
+ `graceMs` while nothing is applying is repaired:
798
+
799
+ | Hub state | Repair |
800
+ |---|---|
801
+ | an earlier push of ours, or what our push was made from | **push** — re-announce our state |
802
+ | made from the state we are in | **pull** — apply it, deletions included |
803
+ | neither can be shown | **merge** — apply it; if that makes no progress, additively |
804
+
805
+ Every repair goes through the ordinary apply and push paths, with their
806
+ ancestry and mass-delete rules; the anti-entropy never deletes anything
807
+ itself. Without a beacon or heartbeat it never fires. `agent.antiEntropyStatus`
808
+ reports whether this node and the hub agree, since when they have not, and
809
+ the last repair — a lasting divergence is the one trace a lost message leaves.
810
+
764
811
  ## Bounce-Back Prevention
765
812
 
766
813
  Bidirectional sync can cause infinite loops when both clients detect each
@@ -1,5 +1,6 @@
1
1
  import { Bs } from '@rljson/bs';
2
2
  import { ClientId, SyncConfig } from '@rljson/rljson';
3
+ import { AntiEntropyOptions, AntiEntropyStatus } from './fs-anti-entropy.ts';
3
4
  import { FsBlobAdapter } from './fs-blob-adapter.ts';
4
5
  import { StoreFsTreeOptions } from './fs-db-adapter.ts';
5
6
  import { FsScanner, FsTree } from './fs-scanner.ts';
@@ -59,6 +60,15 @@ export interface FsAgentOptions {
59
60
  * (the default). See `doc/conflict-resolution-design.md`.
60
61
  */
61
62
  resolveConflicts?: boolean;
63
+ /**
64
+ * Repair a divergence from the hub that no message is going to fix — a
65
+ * push the hub never received, a forward this node never received, an
66
+ * apply that gave up. Driven by the hub's periodic announcement: the state
67
+ * beacon (`stateBeaconMs` on the server — the one to use) or the bootstrap
68
+ * heartbeat (`syncConfig.bootstrapHeartbeatMs`). Without either it never
69
+ * fires. On by default. See `src/fs-anti-entropy.ts`.
70
+ */
71
+ antiEntropy?: AntiEntropyOptions;
62
72
  }
63
73
  /** Restore options */
64
74
  export interface RestoreOptions {
@@ -296,6 +306,19 @@ export declare class FsAgent {
296
306
  private _stopSync?;
297
307
  private _stopSyncFromDb?;
298
308
  private _lastSentRef?;
309
+ /**
310
+ * The ref this agent last pushed as its OWN work.
311
+ *
312
+ * Not the same as {@link _lastSentRef}, which an apply also sets when it
313
+ * leaves the folder equal to — or short of — what it applied. Only a state
314
+ * this agent authored may be re-announced by the anti-entropy: re-announcing
315
+ * one it is still catching up to would roll its peers back.
316
+ */
317
+ private _lastPushedRef?;
318
+ /** Tuning for the anti-entropy, as passed in. */
319
+ private readonly _antiEntropyOptions?;
320
+ /** The running anti-entropy, while {@link syncFromDb} is active. */
321
+ private _antiEntropy?;
299
322
  /**
300
323
  * The incoming ref most recently applied. Retired from the connector's dedup
301
324
  * sets when the next one supersedes it, so a peer returning the tree to that
@@ -410,6 +433,14 @@ export declare class FsAgent {
410
433
  * Gets the current timeout configuration
411
434
  */
412
435
  get timeouts(): Required<TimeoutConfig>;
436
+ /**
437
+ * Whether this node and the hub agree, and what the anti-entropy has done
438
+ * about it when they did not. `null` until {@link syncFromDb} runs.
439
+ *
440
+ * A divergence that lasts is the one thing a lost message leaves behind, and
441
+ * until now nothing reported it: this is what a diagnostics view should show.
442
+ */
443
+ get antiEntropyStatus(): AntiEntropyStatus | null;
413
444
  /**
414
445
  * Records the ref this folder is now at, so a restart can still say what it
415
446
  * descends from.
package/dist/fs-agent.js CHANGED
@@ -4,9 +4,122 @@ import { watch, writeFileSync, existsSync, readFileSync, appendFileSync } from "
4
4
  import { stat, readFile, mkdir, writeFile, readdir, rename, unlink, utimes, rm } from "fs/promises";
5
5
  import { dirname, join } from "path";
6
6
  import { hip } from "@rljson/hash";
7
- import { Db } from "@rljson/db";
7
+ import { stateBeaconEvent, Db } from "@rljson/db";
8
8
  import { IoMem, createSocketPair } from "@rljson/io";
9
9
  import { Server, Client } from "@rljson/server";
10
+ const DEFAULT_ANTI_ENTROPY = {
11
+ enabled: true,
12
+ graceMs: 1e4,
13
+ maxBackoffMs: 3e5
14
+ };
15
+ function antiEntropyDecision(hub, view) {
16
+ const { origin, currentRef, lastAppliedRef, lastPushedRef } = view;
17
+ const predecessors = hub.predecessors ?? [];
18
+ if (!currentRef) return "unknown";
19
+ if (hub.ref === currentRef) return "in-sync";
20
+ const authored = currentRef === lastPushedRef;
21
+ if (authored && hub.origin === origin) return "push";
22
+ const statesIAmIn = [currentRef, lastAppliedRef];
23
+ if (predecessors.some((r) => statesIAmIn.includes(r))) return "pull";
24
+ if (authored && hub.ref === lastAppliedRef) return "push";
25
+ return "merge";
26
+ }
27
+ class FsAntiEntropy {
28
+ constructor(options, _deps) {
29
+ this._deps = _deps;
30
+ this._options = { ...DEFAULT_ANTI_ENTROPY, ...options };
31
+ this._now = _deps.now ?? Date.now;
32
+ this._log = _deps.log ?? ((m) => console.warn(m));
33
+ }
34
+ _options;
35
+ _now;
36
+ _log;
37
+ /**
38
+ * Identifies the divergence being watched: OUR state, and only ours.
39
+ *
40
+ * It used to include the hub's state, so every change on the hub restarted
41
+ * the grace period — and a node that missed every forward while another
42
+ * machine wrote every few seconds never got a repair at all, showing "weicht
43
+ * ab, noch kein Reparaturversuch" for good (review, ONE-446). What makes a
44
+ * divergence a lost message is that THIS node is not moving: a node keeping
45
+ * up with the traffic changes its own state with every forward it applies.
46
+ * Which hub state the repair answers is read from the latest announcement.
47
+ */
48
+ _key = null;
49
+ _divergedSince = null;
50
+ /** Earliest moment the next repair of {@link _key} may start. */
51
+ _nextRepairAt = 0;
52
+ /** Repairs started for {@link _key}. */
53
+ _attempts = 0;
54
+ _hubRef = null;
55
+ _localRef = null;
56
+ _repairs = 0;
57
+ _lastRepair = null;
58
+ /** Whether repairs are switched on. */
59
+ get enabled() {
60
+ return this._options.enabled;
61
+ }
62
+ /** A snapshot of what this instance has seen and done. */
63
+ get status() {
64
+ return {
65
+ diverged: this._divergedSince !== null,
66
+ divergedSince: this._divergedSince,
67
+ hubRef: this._hubRef,
68
+ localRef: this._localRef,
69
+ repairs: this._repairs,
70
+ lastRepair: this._lastRepair ? { ...this._lastRepair } : null
71
+ };
72
+ }
73
+ /**
74
+ * Takes one hub announcement into account.
75
+ * @param hub - What the hub announced.
76
+ */
77
+ observe(hub) {
78
+ const view = this._deps.view();
79
+ const decision = antiEntropyDecision(hub, view);
80
+ if (decision === "unknown") return;
81
+ const hubRef = hub.ref;
82
+ const hubPredecessors = hub.predecessors ?? [];
83
+ this._hubRef = hubRef;
84
+ this._localRef = view.currentRef;
85
+ if (decision === "in-sync") {
86
+ this._key = null;
87
+ this._divergedSince = null;
88
+ this._attempts = 0;
89
+ return;
90
+ }
91
+ const now = this._now();
92
+ const key = view.currentRef;
93
+ if (key !== this._key) {
94
+ this._key = key;
95
+ this._divergedSince ??= now;
96
+ this._attempts = 0;
97
+ this._nextRepairAt = now + this._options.graceMs;
98
+ return;
99
+ }
100
+ if (!this._options.enabled) return;
101
+ if (now < this._nextRepairAt) return;
102
+ if (this._deps.busy(hubRef)) return;
103
+ this._attempts++;
104
+ const backoff = Math.min(
105
+ this._options.graceMs * 2 ** (this._attempts - 1),
106
+ this._options.maxBackoffMs
107
+ );
108
+ this._nextRepairAt = now + backoff;
109
+ this._log(
110
+ `[FsAgent] anti-entropy: hub=${hubRef.slice(0, 8)}… local=${view.currentRef.slice(0, 8)}… diverged for ${Math.round((now - this._divergedSince) / 1e3)}s — ${decision} (attempt ${this._attempts})`
111
+ );
112
+ this._repairs++;
113
+ this._lastRepair = {
114
+ action: decision,
115
+ at: now,
116
+ hubRef,
117
+ localRef: view.currentRef,
118
+ attempt: this._attempts
119
+ };
120
+ this._deps.repair(decision, hubRef, [...hubPredecessors], this._attempts);
121
+ }
122
+ }
10
123
  class FsBlobAdapter {
11
124
  _bs;
12
125
  constructor(bs) {
@@ -1159,6 +1272,19 @@ class FsAgent {
1159
1272
  _stopSync;
1160
1273
  _stopSyncFromDb;
1161
1274
  _lastSentRef;
1275
+ /**
1276
+ * The ref this agent last pushed as its OWN work.
1277
+ *
1278
+ * Not the same as {@link _lastSentRef}, which an apply also sets when it
1279
+ * leaves the folder equal to — or short of — what it applied. Only a state
1280
+ * this agent authored may be re-announced by the anti-entropy: re-announcing
1281
+ * one it is still catching up to would roll its peers back.
1282
+ */
1283
+ _lastPushedRef;
1284
+ /** Tuning for the anti-entropy, as passed in. */
1285
+ _antiEntropyOptions;
1286
+ /** The running anti-entropy, while {@link syncFromDb} is active. */
1287
+ _antiEntropy;
1162
1288
  /**
1163
1289
  * The incoming ref most recently applied. Retired from the connector's dedup
1164
1290
  * sets when the next one supersedes it, so a peer returning the tree to that
@@ -1259,6 +1385,7 @@ class FsAgent {
1259
1385
  this._treeKey = options.treeKey;
1260
1386
  this._timeouts = { ...DEFAULT_TIMEOUTS, ...options.timeouts };
1261
1387
  this._resolveConflicts = options.resolveConflicts ?? false;
1388
+ this._antiEntropyOptions = options.antiEntropy;
1262
1389
  this._scanner = new FsScanner(rootPath, {
1263
1390
  ...options,
1264
1391
  ignore: [
@@ -1307,6 +1434,16 @@ class FsAgent {
1307
1434
  get timeouts() {
1308
1435
  return this._timeouts;
1309
1436
  }
1437
+ /**
1438
+ * Whether this node and the hub agree, and what the anti-entropy has done
1439
+ * about it when they did not. `null` until {@link syncFromDb} runs.
1440
+ *
1441
+ * A divergence that lasts is the one thing a lost message leaves behind, and
1442
+ * until now nothing reported it: this is what a diagnostics view should show.
1443
+ */
1444
+ get antiEntropyStatus() {
1445
+ return this._antiEntropy?.status ?? null;
1446
+ }
1310
1447
  /**
1311
1448
  * Records the ref this folder is now at, so a restart can still say what it
1312
1449
  * descends from.
@@ -2099,6 +2236,7 @@ ${err.stack}` : String(err);
2099
2236
  }
2100
2237
  if (initialRef && !isSilentJoiner) {
2101
2238
  this._lastSentRef = initialRef;
2239
+ this._lastPushedRef = initialRef;
2102
2240
  this._currentRef = initialRef;
2103
2241
  this._persistCurrentRef(initialRef);
2104
2242
  this._lastSentContentKey = this._contentKeyFromTree(initialTree);
@@ -2185,6 +2323,7 @@ ${err.stack}` : String(err);
2185
2323
  return;
2186
2324
  }
2187
2325
  this._lastSentRef = ref;
2326
+ this._lastPushedRef = ref;
2188
2327
  this._lastSentContentKey = contentKey;
2189
2328
  this._rememberAnnounced(tree);
2190
2329
  if (parentRef && parentRef !== ref) {
@@ -2557,6 +2696,7 @@ ${err.stack}` : String(err);
2557
2696
  const dbAdapter = new FsDbAdapter(db, treeKey);
2558
2697
  const ref = await dbAdapter.storeFsTree(tree, { previous });
2559
2698
  this._lastSentRef = ref;
2699
+ this._lastPushedRef = ref;
2560
2700
  this._lastSentContentKey = this._contentKeyFromTree(tree);
2561
2701
  this._rememberAnnounced(tree);
2562
2702
  this._currentRef = ref;
@@ -2582,6 +2722,7 @@ ${err.stack}` : String(err);
2582
2722
  let pendingRecoveryAttempt = 0;
2583
2723
  let pendingPredecessorRefs;
2584
2724
  let pendingIsNewest = true;
2725
+ let processing = false;
2585
2726
  const processRef = async (treeRef, recoveryAttempt = 0, predecessorRefs, isNewestFromSender = true) => {
2586
2727
  const maxAttempts = this._timeouts.processRefRetries + 1;
2587
2728
  for (let attempt = 1; attempt <= maxAttempts; attempt++) {
@@ -2776,7 +2917,12 @@ ${err.stack}` : String(err);
2776
2917
  const newest = pendingIsNewest;
2777
2918
  pendingRef = null;
2778
2919
  if (r) {
2779
- await processRef(r, ra, pr, newest);
2920
+ processing = true;
2921
+ try {
2922
+ await processRef(r, ra, pr, newest);
2923
+ } finally {
2924
+ processing = false;
2925
+ }
2780
2926
  }
2781
2927
  }, delayMs);
2782
2928
  };
@@ -2794,8 +2940,54 @@ ${err.stack}` : String(err);
2794
2940
  return Promise.resolve();
2795
2941
  };
2796
2942
  connector.listen(syncCallback);
2943
+ const antiEntropy = new FsAntiEntropy(this._antiEntropyOptions, {
2944
+ view: () => ({
2945
+ origin: connector.origin,
2946
+ currentRef: this._currentRef,
2947
+ lastAppliedRef: this._lastAppliedRef,
2948
+ lastPushedRef: this._lastPushedRef
2949
+ }),
2950
+ // A pending ref that IS the announced state does not count. The
2951
+ // connector hears the same heartbeat first, and after a failed apply it
2952
+ // queues every repeat of it — as "not newest", to be ignored. Counting
2953
+ // that as busy would block the repair on exactly the node that needs it,
2954
+ // on every heartbeat, forever. The repair takes over that pending slot.
2955
+ busy: (hubRef) => pendingRef !== null && pendingRef !== hubRef || processing || this._remoteApplyInFlight,
2956
+ repair: (action, hubRef, hubPredecessors, attempt) => {
2957
+ if (action === "push") {
2958
+ const ref = this._currentRef;
2959
+ this._lastSentRef = ref;
2960
+ this._sendRef(connector, ref, [hubRef]).catch(
2961
+ (err) => this._writeSyncError("antiEntropy/push", err)
2962
+ );
2963
+ return;
2964
+ }
2965
+ const predecessors = action === "pull" || attempt === 1 ? hubPredecessors : [];
2966
+ scheduleProcess(hubRef, 0, 0, predecessors, true);
2967
+ }
2968
+ });
2969
+ this._antiEntropy = antiEntropy;
2970
+ const onHubAnnouncement = (payload) => {
2971
+ if (typeof payload?.r !== "string") return;
2972
+ antiEntropy.observe({
2973
+ ref: payload.r,
2974
+ origin: payload.o,
2975
+ predecessors: Array.isArray(payload.p) ? payload.p : []
2976
+ });
2977
+ };
2978
+ const hubEvents = [
2979
+ connector.events.bootstrap,
2980
+ stateBeaconEvent(connector.route.flat)
2981
+ ];
2982
+ for (const event of hubEvents) {
2983
+ connector.socket.on(event, onHubAnnouncement);
2984
+ }
2797
2985
  return () => {
2798
2986
  if (fromDbTimer) clearTimeout(fromDbTimer);
2987
+ for (const event of hubEvents) {
2988
+ connector.socket.off(event, onHubAnnouncement);
2989
+ }
2990
+ if (this._antiEntropy === antiEntropy) this._antiEntropy = void 0;
2799
2991
  connector.tearDown();
2800
2992
  };
2801
2993
  }
@@ -2923,13 +3115,16 @@ async function runClientServerSetup(opts = {}) {
2923
3115
  return { baseDir, folderA, folderB, contentB, cleanup };
2924
3116
  }
2925
3117
  export {
3118
+ DEFAULT_ANTI_ENTROPY,
2926
3119
  DIR_MARKER,
2927
3120
  FsAgent,
3121
+ FsAntiEntropy,
2928
3122
  FsBlobAdapter,
2929
3123
  FsConflictResolver,
2930
3124
  FsDbAdapter,
2931
3125
  FsScanner,
2932
3126
  SYNC_ERROR_FILE,
3127
+ antiEntropyDecision,
2933
3128
  compareTips,
2934
3129
  conflictCopyName,
2935
3130
  decideWinner,
@@ -0,0 +1,146 @@
1
+ /** Tuning for {@link FsAntiEntropy}. */
2
+ export interface AntiEntropyOptions {
3
+ /** Whether divergence is repaired at all. Default: true. */
4
+ enabled?: boolean;
5
+ /**
6
+ * How long one divergence must persist before it is repaired, in ms.
7
+ *
8
+ * Live traffic produces short divergences constantly — a push in flight is
9
+ * one. Only a divergence that outlives it is a lost message. Default: 10 000.
10
+ */
11
+ graceMs?: number;
12
+ /**
13
+ * Upper bound of the backoff between repeated repairs of the SAME
14
+ * divergence, in ms. Each attempt doubles the wait from `graceMs`, so a
15
+ * repair that cannot succeed (a refusal, an unreachable blob) costs a
16
+ * message every few minutes rather than one per heartbeat. Default: 300 000.
17
+ */
18
+ maxBackoffMs?: number;
19
+ }
20
+ /** Defaults for {@link AntiEntropyOptions}. */
21
+ export declare const DEFAULT_ANTI_ENTROPY: Required<AntiEntropyOptions>;
22
+ /** What a repair does. See the header of this file. */
23
+ export type AntiEntropyAction = 'pull' | 'push' | 'merge';
24
+ /** What {@link antiEntropyDecision} concluded. */
25
+ export type AntiEntropyDecision = 'in-sync' | 'unknown' | AntiEntropyAction;
26
+ /** The part of an agent's state the decision reads. */
27
+ export interface AntiEntropyView {
28
+ /** The origin this agent's connector announces under. */
29
+ origin: string;
30
+ /** The state the folder is in. */
31
+ currentRef: string | undefined;
32
+ /** The incoming state most recently applied. */
33
+ lastAppliedRef: string | undefined;
34
+ /**
35
+ * The state this agent last pushed as its OWN work.
36
+ *
37
+ * Only such a state may be re-announced. An apply can leave the folder
38
+ * short of the tree it applied — a node still catching up — and announcing
39
+ * that is how a burst turns into a rollback.
40
+ */
41
+ lastPushedRef: string | undefined;
42
+ }
43
+ /** A hub announcement, as the heartbeat carries it. */
44
+ export interface HubAnnouncement {
45
+ /** The state the hub holds. */
46
+ ref: string;
47
+ /** Who produced that state. */
48
+ origin?: string;
49
+ /** What that state declares it descends from. */
50
+ predecessors?: readonly string[];
51
+ }
52
+ /**
53
+ * Decides who is behind, from the hub's announcement and our own state.
54
+ * @param hub - What the hub announced.
55
+ * @param view - This agent's state.
56
+ * @returns What to do about it.
57
+ */
58
+ export declare function antiEntropyDecision(hub: HubAnnouncement, view: AntiEntropyView): AntiEntropyDecision;
59
+ /** What {@link FsAntiEntropy} can report about itself. */
60
+ export interface AntiEntropyStatus {
61
+ /** Whether the last announcement differed from our state. */
62
+ diverged: boolean;
63
+ /** Since when the current divergence has lasted, epoch ms. */
64
+ divergedSince: number | null;
65
+ /** The state the hub last announced. */
66
+ hubRef: string | null;
67
+ /** Our state at that moment. */
68
+ localRef: string | null;
69
+ /** How many repairs were started over this agent's lifetime. */
70
+ repairs: number;
71
+ /** The most recent repair. */
72
+ lastRepair: {
73
+ action: AntiEntropyAction;
74
+ at: number;
75
+ hubRef: string;
76
+ localRef: string;
77
+ attempt: number;
78
+ } | null;
79
+ }
80
+ /** What {@link FsAntiEntropy} needs from the agent it runs in. */
81
+ export interface AntiEntropyDeps {
82
+ /** This agent's state, read fresh at every announcement. */
83
+ view: () => AntiEntropyView;
84
+ /**
85
+ * Whether anything is already applying or queued — a repair then waits.
86
+ * @param hubRef - The state the hub is announcing right now.
87
+ */
88
+ busy: (hubRef: string) => boolean;
89
+ /**
90
+ * Starts a repair.
91
+ * @param action - What to do.
92
+ * @param hubRef - The state the hub announced.
93
+ * @param hubPredecessors - What that state descends from.
94
+ * @param attempt - 1 for the first repair of this divergence, then 2, 3, …
95
+ */
96
+ repair: (action: AntiEntropyAction, hubRef: string, hubPredecessors: string[], attempt: number) => void;
97
+ /** Clock, for tests. */
98
+ now?: () => number;
99
+ /** Log sink. */
100
+ log?: (message: string) => void;
101
+ }
102
+ /**
103
+ * Notices a divergence between this agent and the hub, and repairs it.
104
+ *
105
+ * Fed with every hub announcement; decides nothing while this node's own state
106
+ * is still moving, only once it has sat still and out of step with the hub for
107
+ * {@link AntiEntropyOptions.graceMs} — however often the hub's state changed
108
+ * meanwhile.
109
+ */
110
+ export declare class FsAntiEntropy {
111
+ private readonly _deps;
112
+ private readonly _options;
113
+ private readonly _now;
114
+ private readonly _log;
115
+ /**
116
+ * Identifies the divergence being watched: OUR state, and only ours.
117
+ *
118
+ * It used to include the hub's state, so every change on the hub restarted
119
+ * the grace period — and a node that missed every forward while another
120
+ * machine wrote every few seconds never got a repair at all, showing "weicht
121
+ * ab, noch kein Reparaturversuch" for good (review, ONE-446). What makes a
122
+ * divergence a lost message is that THIS node is not moving: a node keeping
123
+ * up with the traffic changes its own state with every forward it applies.
124
+ * Which hub state the repair answers is read from the latest announcement.
125
+ */
126
+ private _key;
127
+ private _divergedSince;
128
+ /** Earliest moment the next repair of {@link _key} may start. */
129
+ private _nextRepairAt;
130
+ /** Repairs started for {@link _key}. */
131
+ private _attempts;
132
+ private _hubRef;
133
+ private _localRef;
134
+ private _repairs;
135
+ private _lastRepair;
136
+ constructor(options: AntiEntropyOptions | undefined, _deps: AntiEntropyDeps);
137
+ /** Whether repairs are switched on. */
138
+ get enabled(): boolean;
139
+ /** A snapshot of what this instance has seen and done. */
140
+ get status(): AntiEntropyStatus;
141
+ /**
142
+ * Takes one hub announcement into account.
143
+ * @param hub - What the hub announced.
144
+ */
145
+ observe(hub: HubAnnouncement): void;
146
+ }
package/dist/index.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  export { FsAgent, SYNC_ERROR_FILE, type FsAgentOptions, type RestoreOptions, type TimeoutConfig, } from './fs-agent.ts';
2
+ export { antiEntropyDecision, DEFAULT_ANTI_ENTROPY, FsAntiEntropy, type AntiEntropyAction, type AntiEntropyDecision, type AntiEntropyDeps, type AntiEntropyOptions, type AntiEntropyStatus, type AntiEntropyView, type HubAnnouncement, } from './fs-anti-entropy.ts';
2
3
  export { FsBlobAdapter, type BlobToFileOptions, type FileBlobMeta, type FileToBlobOptions, } from './fs-blob-adapter.ts';
3
4
  export { FsDbAdapter, type StoreFsTreeOptions } from './fs-db-adapter.ts';
4
5
  export { compareTips, conflictCopyName, decideWinner, DIR_MARKER, findCommonAncestor, formatConflictTimestamp, FsConflictResolver, fsTreeToContentMap, threeWayMerge, type BranchTip, type ConflictCopy, type ConflictResolverDeps, type ContentMap, type MergePlan, } from './fs-conflict-resolver.ts';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rljson/fs-agent",
3
- "version": "0.0.79",
3
+ "version": "0.0.81",
4
4
  "description": "Rljson fs-agent description",
5
5
  "homepage": "https://github.com/rljson/fs-agent",
6
6
  "bugs": "https://github.com/rljson/fs-agent/issues",
@@ -28,7 +28,7 @@
28
28
  "updateGoldens": "cross-env UPDATE_GOLDENS=true pnpm test"
29
29
  },
30
30
  "devDependencies": {
31
- "@rljson/server": "0.0.63",
31
+ "@rljson/server": "0.0.68",
32
32
  "@types/node": "^25.3.1",
33
33
  "@typescript-eslint/eslint-plugin": "^8.56.1",
34
34
  "@typescript-eslint/parser": "^8.56.1",
@@ -51,11 +51,11 @@
51
51
  },
52
52
  "dependencies": {
53
53
  "@rljson/bs": "0.0.26",
54
- "@rljson/db": "0.0.42",
54
+ "@rljson/db": "0.0.47",
55
55
  "@rljson/hash": "0.0.19",
56
- "@rljson/io": "0.0.78",
56
+ "@rljson/io": "0.0.80",
57
57
  "@rljson/json": "0.0.23",
58
- "@rljson/rljson": "0.0.81",
58
+ "@rljson/rljson": "0.0.83",
59
59
  "socket.io": "^4.8.3",
60
60
  "socket.io-client": "^4.8.3"
61
61
  },
@@ -64,7 +64,7 @@
64
64
  "esbuild"
65
65
  ],
66
66
  "overrides": {
67
- "@rljson/rljson": "0.0.81"
67
+ "@rljson/rljson": "0.0.83"
68
68
  }
69
69
  },
70
70
  "packageManager": "pnpm@10.11.0"