utils/crdt_sync_dart
Krzysztof kuhy Rudnicki 6eef99d661
Some checks are pending
crdt-sync pre-commit / pre-commit (push) Waiting to run
crdt-sync tests / test (3.10) (push) Waiting to run
crdt-sync tests / test (3.11) (push) Waiting to run
crdt-sync tests / test (3.12) (push) Waiting to run
Add DeviceIdentity and a legacy device id for the uuid migration
Groundwork for moving diet-guard, screen-locker and wake-alarm off fixed
role ids ('pc'/'phone'/'desktop') onto per-install uuids, the scheme todo
and home_inventory already use. A role constant collides the moment a
second machine takes the same role, and a reinstall silently inherits the
previous install's CRDT identity.

The migration cannot rewrite history: the device id is baked into every HLC
stamp already written, is the record path segment and the revision key. So
a device that has just switched ids must still recognise its former id as
its own -- otherwise skip-own-writes stops matching the old path, and the
device pulls back and re-merges its own pre-migration log as though a peer
had written it. Idempotent under LWW, but pure wasted transfer on every
tick.

Both halves therefore take an optional legacy id and test set membership
(own_ids / ownIds) rather than equality against a single id:

- crdt-sync (Python) 0.5.1 -> 0.6.0: new crdt_sync._device with
  DeviceIdentity + load_device_identity (generate-or-load, persisted); the
  mkdir is deliberately unguarded, since handing back an unpersisted id
  would mint a fresh uuid every restart and strand a device dir each time.
  sync_log gains legacy_device_id.
- crdt_sync_dart 0.6.0 -> 0.7.0: DeviceIdentity value type; syncLog gains
  legacyDeviceId. Persistence stays app-side, where the existing uuid apps
  already keep it in SharedPreferences under 'crdt.nodeId'.

Both changes are backward compatible: the parameter defaults to null, which
reproduces the previous single-id behaviour exactly.

Each half has a positive test and a negative control proving the old path
*is* pulled when no legacy id is declared -- so the skip is verified to be
the parameter's doing, not an artifact of the fixture.

Python: 239 tests, 100% branch coverage. Dart: 248 tests, analyzer clean,
device.dart 11/11 and sync.dart 57/57 lines covered.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GZH89WEqAjuJT8WZdqc7AP
2026-08-09 16:54:33 +02:00
..
lib Add DeviceIdentity and a legacy device id for the uuid migration 2026-08-09 16:54:33 +02:00
test Add DeviceIdentity and a legacy device id for the uuid migration 2026-08-09 16:54:33 +02:00
tool crdt_sync: add a Firebase Realtime Database transport behind a RemoteStore seam 2026-08-03 18:14:25 +02:00
.gitignore Initial implementation: unified CRDT merge scheme + GitHub sync transport 2026-07-05 20:48:07 +02:00
analysis_options.yaml Initial implementation: unified CRDT merge scheme + GitHub sync transport 2026-07-05 20:48:07 +02:00
LICENSE Initial implementation: unified CRDT merge scheme + GitHub sync transport 2026-07-05 20:48:07 +02:00
pubspec.yaml Add DeviceIdentity and a legacy device id for the uuid migration 2026-08-09 16:54:33 +02:00
README.md Docs: correct stale 'not yet consumed' notes and old install URLs 2026-07-11 23:31:41 +02:00

crdt_sync

Shared CRDT merge scheme + GitHub-Contents-API sync transport, extracted for reuse across four personal apps that each need cross-device sync: todo, diet_guard's Flutter app, wake_alarm's phone_app, and screen-locker's workout_app. Pure Dart -- no Flutter SDK dependency (package:http only) -- so it works in both Flutter apps and plain Dart tooling. Mirrors the Python crdt-sync package module-for-module and test-for-test, so the merge algorithm canonically agrees on both sides of any sync between a Dart client and a Python one.

The merge scheme

See the Python package's README for the full rationale; in short, a generic LWW-map-with-sticky-remove:

  • Hlc -- a Hybrid Logical Clock (wallTimeMs, counter, nodeId), totally ordered, monotonic even across clock skew.
  • Record -- an id, a per-field last-writer-wins map (fieldName -> (value, Hlc)), and a sticky deleted flag (deleted = a.deleted || b.deleted, never the other way -- a delete can never be silently undone).
  • Log -- Map<String, Record>, merged by taking the union of ids and merging shared ones.

All three merges are commutative and idempotent -- see test/log_test.dart for the concrete convergence-property tests.

Install

Consume via a git dependency on the utils monorepo:

dependencies:
  crdt_sync:
    git:
      url: https://github.com/kuhyx/utils
      ref: crdt_sync_dart-v0.2.0
      path: crdt_sync_dart

Usage

import 'package:crdt_sync/crdt_sync.dart';

final nodeId = 'phone';
final clock = Hlc.newTick(nodeId);
final record = Record(
  id: 'abc123',
  fields: {'text': ('buy milk', clock)},
);

final client = GitHubClient(owner: 'kuhyx', repo: 'my-app-sync', token: token);
final merged = await syncLog(
  client: client,
  deviceId: nodeId,
  pathPrefix: 'devices',
  localLog: {record.id: record},
  encode: (log) => jsonEncode(log.map((k, r) => MapEntry(k, r.toJson()))),
  decode: (text) => (jsonDecode(text) as Map<String, dynamic>).map(
    (k, v) => MapEntry(k, Record.fromJson(v as Map<String, dynamic>)),
  ),
);

syncLog pulls every other device's last-pushed log from <pathPrefix>/<other-device-id>/..., merges each into the local log with mergeLogs, then pushes this device's own merged result back up.

Local persistence (LogStore)

The merge scheme above is in-memory only. For an app that needs to keep its Log on disk and drive a live UI off it, this package also ships a domain-agnostic LogStore:

import 'package:crdt_sync/crdt_sync.dart';
import 'package:crdt_sync/crdt_sync_io.dart'; // FileLogPersistence (dart:io)

final store = LogStore(
  persistence: FileLogPersistence(File('$docsDir/notes.json')),
  nodeId: 'phone',
);
await store.load();

// Reactive read: re-derive a domain view whenever anything changes. Filtering,
// sorting and search live here, in the app -- the store is field-agnostic.
final Stream<List<Record>> visible = store.changes.map(
  (_) => store.values.where((r) => !r.deleted).toList(),
);

await store.upsert(Record(id: 'n1', fields: {'text': ('hi', store.nextHlc())}));
await store.delete('n1'); // sticky tombstone, not a hard remove

// After a sync tick, swap in the merged result:
await store.replaceAll(await syncLog(/* ... */, localLog: store.snapshot()));

LogStore is pure Dart (import it from the main barrel); the filesystem-backed FileLogPersistence lives behind the separate crdt_sync_io.dart entrypoint so the core stays web-safe. Querying is deliberately not in the library — a Record's fields are an opaque map, so the app filters store.values itself. The Python side mirrors the on-disk format via crdt_sync.dump_log/read_log (load/save only; no reactive stream — that's a Dart/Flutter convenience).

Development

dart pub get
dart analyze
dart test