Killing O(N^2) Commits and the 64 MiB Snapshot Cliff: GoodCRM Wave 5 Storage
Commit eb26a6a in Wave 5 fixed three storage bottlenecks across Apple and HarmonyOS: O(N^2) sequential commits from full-state JSON re-encoding, HarmonyOS protection snapshots silently dropped past 64 MiB, and 25 MB attachments crossing Worker IPC as Base64 strings.
GoodCRM (1.0) is live on the US App Store (id6837223780) for iPhone, iPad, and Mac, with the native HarmonyOS version in preparation. With no developer CRM servers, every entity, immutable revision, change event, index invalidation, and receipt sits inside one canonical local state blob that gets hashed and persisted on every commit.
Everything felt fast with ten customers. With a couple hundred sequential commits, latency fell off a cliff. Commit eb26a6a on November 14 (Wave 5, covering T6-P1-01, T6-P1-02, and T2-P1-06 in TAB_AUDIT_AND_REMEDIATION.md) rebuilt three hot paths together.
Why 200 Sequential Commits Degraded to $O(N^2)$
Every local commit appends to four arrays: local_commits, change_events, index_invalidations, and receipts. Previously, each commit re-encoded the entire State4 / CoreState4 graph into canonical JSON, hashed the full buffer, and re-decoded the whole state to validate it; HarmonyOS also ran recursive prefix deep-equality scans and a second service.read() after commit.
As the history arrays grew, each commit did $O(N)$ redundant work, turning $N$ sequential commits into $O(N^2)$.
Both platforms kept byte-identical canonical JSON and SHA-256 verification while caching untouched subtrees:
- Apple (
Model4CommandTransaction.swift,Model4LocalService.swift): Added@TaskLocal static var cachedBaseRootandIncrementalObjectBytesCache. Transactions trackmutatedObjectKeys,touchedArrayIndices, andappendedArrayStart, then callLibraryJSON.encodeIncremental(orencodeIncrementalSplit) to re-encode only dirty keys and appended tail elements, paired withJSONDeltaReuseContextforModel4Wire.decodeValidatedValue.Model4LocalServicealso cachescachedInitProofandcachedDailySnapshotTag(utcDayKey), and scanslocal_commits/receiptsviareversed()/last(where:)instead of scanning from index0. - HarmonyOS (
Model4LocalService.ts,Model4LibraryWorker.ets,NativeModel4Rdb.ets): MergedprepareandcommitPreparedinto a single transaction, reusedcachedShaandcachedState, deleted redundantdecodeCoreState4Shapeand prefix deep-equality scans, moved hot-path hashing to native@kit.CryptoArchitectureKitSHA-256, and switchedModel4LibraryWorker.etstoservice.peekCachedSnapshot()instead of issuing a secondservice.read().
CHG-20261114-REM-W5.json records the post-fix host benchmarks: 220 sequential commits on Apple completed in 3766.35 ms (-O, well under the 30-second ceiling), and 200 sequential entity commits on HarmonyOS completed in 5644.1 ms (under the 15-second ceiling).
Splitting model4_snapshots_v1.json Past the 64 MiB Cliff
The second landmine was HarmonyOS’s protection snapshot store (T6-P1-02 / R08).
Previously, NativeModel4Rdb.ets packed every daily and pre-restore protection snapshot into a single model4_snapshots_v1.json file. Reading was capped at 64 MiB (SNAPSHOT_MAX_SINGLE_FILE_BYTES4 = 64 * 1024 * 1024). Two valid 25 MiB capture attachments plus Base64 expansion pushed the single file past 64 MiB — and on restart, the valid protection snapshot was silently dropped.
SnapshotStore4.ts splits the single blob into three layers:
- Lightweight index (
index.json,version: 2): Stores only snapshot metadata (id,kind,created_at,byte_size,file, andassets). - Content-addressed per-snapshot files (
snapshot_<sha256>.json): Unchanged snapshots are reused across saves instead of rewriting all historical snapshots on every save. - 512 KiB sidecar extraction (
SIDECAR_THRESHOLD4 = 512 * 1024): Any byte payload or capture file at or above512 KiBis written once asasset_<sha256>.binand referenced inside JSON as@asset_<sha256>.bin:<byteLength>, with length and SHA-256 verified on every load.
Cutovers use a two-phase protocol: stageSnapshotPrivacy4 writes privacy_<digest>.json (and privacy_capture_<digest>.json) first; only after SQLite commits that digest does publishSnapshotPrivacy4 swap index.json atomically and unlink obsolete files and legacy model4_snapshots_v1.json. If a protection snapshot cannot be written within limits, GoodCRM rejects the overwrite (PROTECTION_SNAPSHOT_TOO_LARGE) rather than replacing the live library without a valid rollback point.
Streaming Attachments Across Worker IPC via Sandbox Paths
Wave 5 also removed large Base64 blobs from HarmonyOS Worker IPC (T2-P1-06).
In Model4WorkerClient.ets, AttachmentDownload4, ExportBuildResult4, and BackupDumpResult4 previously carried bytes_base64: string. A 25 MB attachment expanded into a 33+ MB JS string, straining memory and structured cloning on every transfer.
Those payloads now pass sandbox file paths (file_path: string, or preview_path for previews). Inside the Worker, NativeAttachmentFiles4.ets allocates paths under context.filesDir + '/ipc_tmp' (guarded by assertSandboxPath against .., \x00, and \), streams in 1 MiB chunks via readBlobSlice, copyStream, preparePreviewFile, openBackupByteSink, and openBackupByteSource with incremental Sha256Hasher4, and sweeps leftover files older than 24 hours via sweepStaleIpcTmp.
Verification Scope
At eb26a6a, CHG-20261114-REM-W5.json logged passing host runs across both platforms: 464/0 on Apple (including the 220-commit benchmark), tsc --noEmit exit 0 and 549/0 on HarmonyOS (including the 200-commit benchmark and SnapshotStore4 migration tests), plus unsigned Apple Debug builds and hvigorw assembleHap. Physical tablet hardware remained not_run at this checkpoint and moved to later native device verification.
Comments