Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Add canonicalize level merge to replace sqlite merge in Rust core (#2159)
Leendert de Borst075aaf5f6086
diff --git a/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts b/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.tsindex f9ed2c36b..7a0322c65 100644--- a/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts+++ b/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts@@ -51,7 +51,7 @@ import { clearDirtyScopes, getDirtyScopes } from '@/utils/VaultDirtyState';import { VaultKeyService } from '@/utils/VaultKeyService';import { vaultRequiresManifestMigration, VaultMigrationKind, type VaultMigrationStatus } from '@/utils/VaultManifestMigration';import { vaultMergeService } from '@/utils/VaultMergeService';-import { vaultSyncService, invalidateCanonicalizeCache } from '@/utils/VaultSyncService';+import { type PullAndMergeResult, vaultSyncService, invalidateCanonicalizeCache } from '@/utils/VaultSyncService';import { WebApiService } from '@/utils/WebApiService';import { t } from '@/i18n/StandaloneI18n';@@ -1794,129 +1794,168 @@ async function applyServerDirectedChanges(webApi: WebApiService, statusResponse:}/**- * Pull the server's latest vault and merge any local changes onto it.+ * Pull the server's latest vault and merge it with what is stored locally (if needed).** @param syncState - the sync state the pull runs against* @param encryptionKey - the key the local and server vaults are encrypted with* @param grantSyncChangedVault - whether an earlier step already changed the stored vault*/async function pullAndMaterializeServerVault(syncState: VaultSyncState, encryptionKey: string, grantSyncChangedVault: boolean): Promise<FullVaultSyncResult> {- const vaultResponseJson = await fetchLatestVaultFromServer();+ const strategy = await choosePullStrategy(syncState, encryptionKey);+ switch (strategy.kind) {+ case 'canonical':+ return await canonicalPullAndMerge(strategy.localClient, syncState, encryptionKey, grantSyncChangedVault);+ case 'legacy-sqlite':+ return await legacyStatementPullAndMerge(syncState, encryptionKey, grantSyncChangedVault);+ case 'server-only':+ return await adoptServerVault(await fetchLatestVaultFromServer(), syncState);+ case 'abort':+ return strategy.result;+ }+}++/**+ * How a pull reconciles the server's vault with the local one.+ */+type PullStrategy =+ /** Merge onto the server's vault at canonical level, per manifest, in Rust: the manifest-v1 path. */+ | { kind: 'canonical'; localClient: SqliteClient }+ /** LEGACY: merge at the SQLite statement level, for a local vault still on the pre-manifest-v1 storage model. */+ | { kind: 'legacy-sqlite' }+ /** Nothing to merge onto: the server's vault is taken as-is. */+ | { kind: 'server-only' }+ /** The local vault could not be opened; the sync reports this result instead of pulling. */+ | { kind: 'abort'; result: FullVaultSyncResult };++/**+ * Decide how the pull reconciles with the local vault, before anything is fetched.+ *+ * @param syncState - the sync state the pull runs against+ * @param encryptionKey - the key the local vault is encrypted with+ */+async function choosePullStrategy(syncState: VaultSyncState, encryptionKey: string): Promise<PullStrategy> {+ if (!syncState.isDirty) {+ return { kind: 'server-only' };+ }++ const localEncryptedVault = await storage.getItem(StorageKeys.ENCRYPTED_VAULT) as string | null;+ if (!localEncryptedVault) {+ devLog('[VaultSync] No stored local vault to merge onto; taking the server vault as-is.');+ return { kind: 'server-only' };+ }++ // Create a fresh client decrypted from the stored blob for the merge input.+ const localClient = new SqliteClient();try {- if (syncState.isDirty) {- await pruneRowsOfManifestsNoLongerServed(encryptionKey);- const mergedResult = await mergeAndPushLocalChanges(vaultResponseJson, syncState, encryptionKey, grantSyncChangedVault);- if (mergedResult) {- return mergedResult;- }- }+ await localClient.initializeFromBase64(await EncryptionUtility.symmetricDecrypt(localEncryptedVault, encryptionKey));/*- * No local changes (or merge failed) - just use server vault.- * Use expectedMutationSeq to detect concurrent mutations.+ * Both checks matter: requiresSchemaMigration deliberately answers false for a vault still on the+ * legacy sqlite-blob chain, but such a vault cannot canonicalize (unstamped rows) and must merge+ * via the legacy statement path.*/- const storeResult = await handleStoreEncryptedVault({- vaultBlob: vaultResponseJson.vault.blob,- expectedMutationSeq: syncState.mutationSequence- });-- if (!storeResult.success) {- devLog('[VaultSync] Mutation detected during sync, re-syncing...');- return handleFullVaultSync();+ if (await localClient.requiresLegacySqliteBlobMigration() || await localClient.requiresSchemaMigration()) {+ devLog('[VaultSync] Local vault is on a legacy or stale schema; merging via the legacy statement path.');+ localClient.close();+ return { kind: 'legacy-sqlite' };}-- await storeVaultMetadata(vaultResponseJson);-- return await materializedVaultResult();} catch (error) {- if (error instanceof VaultVersionIncompatibleError) {- return syncResult({ success: false, requiresLogout: true, error: error.message });- }- // E-501: Vault decryption failed- throw new Error(formatErrorWithCode(- 'Vault could not be decrypted, if the problem persists please logout and login again.',- AppErrorCode.VAULT_DECRYPT_FAILED- ));+ localClient.close();+ return { kind: 'abort', result: mapVaultOpenError(error) };}++ return { kind: 'canonical', localClient };}/**- * Drop the rows of every manifest the snapshot just pulled no longer serves this account.- * @param encryptionKey - the key the stored vault is sealed with+ * Turn a failure to open a vault into the sync result to report: an incompatible vault version forces a+ * logout, anything else is rethrown as a reportable decryption failure.+ *+ * @param error - the error the decrypt or open threw*/-async function pruneRowsOfManifestsNoLongerServed(encryptionKey: string): Promise<void> {- const sqliteClient = await createVaultSqliteClient();- const dropped = await vaultSyncService.dropRowsOfManifestsNoLongerServed(sqliteClient, vaultSyncService.manifestIdsServedByLastSnapshot());- if (dropped.length === 0) {- return;+function mapVaultOpenError(error: unknown): FullVaultSyncResult {+ if (error instanceof VaultVersionIncompatibleError) {+ return syncResult({ success: false, requiresLogout: true, error: error.message });}- // Not a local change of the user's making, so it is stored without touching the dirty state or its sequence.- await handleStoreEncryptedVault({ vaultBlob: await EncryptionUtility.symmetricEncrypt(sqliteClient.exportToBase64(), encryptionKey) });- invalidateCanonicalizeCache();+ // E-501: Vault decryption failed+ throw new Error(formatErrorWithCode('Vault could not be decrypted, if the problem persists please logout and login again.', AppErrorCode.VAULT_DECRYPT_FAILED));}/**- * Merge the local vault onto the server's latest vault and upload the result.+ * Store the server's vault as the local vault, replacing whatever was there.** @param vaultResponse - the vault just pulled from the server- * @param syncState - the sync state the merge runs against- * @param encryptionKey - the key both vaults are encrypted with- * @param grantSyncChangedVault - whether an earlier step already changed the stored vault- * @returns The sync result, or null when there is nothing to merge onto and the caller should take the- * server vault as-is (no local vault stored, or the merge itself failed).+ * @param syncState - the sync state the pull runs against, whose mutation sequence detects a concurrent local change*/-async function mergeAndPushLocalChanges(- vaultResponse: VaultResponse,- syncState: VaultSyncState,- encryptionKey: string,- grantSyncChangedVault: boolean-): Promise<FullVaultSyncResult | null> {- const localEncryptedVault = await storage.getItem(StorageKeys.ENCRYPTED_VAULT) as string | null;- if (!localEncryptedVault) {- return null;+async function adoptServerVault(vaultResponse: VaultResponse, syncState: VaultSyncState): Promise<FullVaultSyncResult> {+ const storeResult = await handleStoreEncryptedVault({ vaultBlob: vaultResponse.vault.blob, expectedMutationSeq: syncState.mutationSequence });+ if (!storeResult.success) {+ devLog('[VaultSync] Mutation detected during sync, re-syncing...');+ return handleFullVaultSync();}- const localDecrypted = await EncryptionUtility.symmetricDecrypt(localEncryptedVault, encryptionKey);- const serverDecrypted = await EncryptionUtility.symmetricDecrypt(vaultResponse.vault.blob, encryptionKey);+ await storeVaultMetadata(vaultResponse);- /*- * Guard for the sqlite-blob to manifest-v1 migration window: this device has already migrated its vault onto the current- * schema but the push has not landed yet, while another (not-yet-updated) device advanced the server's- * legacy sqlite-blob. The two databases have different column sets, so merging them would throw an error.- * We assume here the migrated local vault is newer, so it's pushed as-is.- */- if (await isLegacyStorageVault(serverDecrypted) && !await isLegacyStorageVault(localDecrypted)) {- devWarn('[VaultSync] Server vault is still on the legacy storage format while the local vault is migrated; skipping the merge and pushing the local vault.');- return await pushOverLegacyServerVault(grantSyncChangedVault);+ try {+ return await materializedVaultResult();+ } catch (error) {+ return mapVaultOpenError(error);}+}- const mergeResult = await vaultMergeService.merge(localDecrypted, serverDecrypted);-- if (!mergeResult.success) {- console.error('Vault merge failed during sync, using server vault');- return null;+/**+ * Canonical-merge path of a dirty pull: fetch the snapshot, merge the local vault onto it at canonical+ * level (per manifest, in Rust), store the result, and push.+ *+ * @param localClient - the local vault, freshly decrypted from storage+ * @param syncState - the sync state the pull runs against+ * @param encryptionKey - the key the local vault and the snapshot are encrypted with+ * @param grantSyncChangedVault - whether an earlier step already changed the stored vault+ */+async function canonicalPullAndMerge(localClient: SqliteClient, syncState: VaultSyncState, encryptionKey: string, grantSyncChangedVault: boolean): Promise<FullVaultSyncResult> {+ // Network and vault-processing errors propagate unchanged, exactly like the plain pull path.+ let result: PullAndMergeResult;+ try {+ result = await vaultSyncService.pullAndMerge(encryptionKey, localClient);+ } finally {+ // The merge is the only reader of this client and its result is fully materialized, so the sql.js database can go.+ localClient.close();}- devLog('[VaultSync] Vault merge during sync completed:', mergeResult.stats);-- const mergedEncryptedVault = await EncryptionUtility.symmetricEncrypt(mergeResult.mergedVaultBase64, encryptionKey);+ if (result.kind === 'legacy-server') {+ devWarn('[VaultSync] Server vault is still on the legacy storage format while the local vault is migrated; skipping the merge and pushing the local vault.');+ return await pushOverLegacyServerVault(grantSyncChangedVault);+ }- // Store merged vault. Use expectedMutationSeq to detect if a local mutation happened during merge.- const storeResult = await handleStoreEncryptedVault({- vaultBlob: mergedEncryptedVault,- expectedMutationSeq: syncState.mutationSequence- });+ if (result.kind === 'merged') {+ if (result.fallbackManifestIds.length > 0) {+ devWarn(`[VaultSync] Canonical merge fell back to the server's rows for manifest(s) ${result.fallbackManifestIds.join(', ')}; local changes to them were dropped.`);+ }+ devLog('[VaultSync] Canonical vault merge completed:', result.stats);+ }+ // Store the merged (or server-only) vault; expectedMutationSeq detects a mutation racing the merge.+ const storeResult = await handleStoreEncryptedVault({ vaultBlob: result.response.vault.blob, expectedMutationSeq: syncState.mutationSequence });if (!storeResult.success) {- devLog('[VaultSync] Mutation detected during merge, re-syncing...');+ devLog('[VaultSync] Mutation detected during canonical merge, re-syncing...');return handleFullVaultSync();}- // Upload merged vault to server- const uploadResponse = await handleUploadVault();+ /*+ * Only now do the pulled revisions become the local truth: committing them before a raced store would+ * clear needsPull while the merged content was never kept, and the resync would push the unmerged local+ * vault over the other device's rows.+ */+ await result.commitRevisions();+ if (result.kind === 'server-only') {+ await storeVaultMetadata(result.response);+ return await materializedVaultResult();+ }++ const uploadResponse = await handleUploadVault();if (uploadResponse.success && uploadResponse.status === 0) {await handleMarkVaultClean({ mutationSeqAtStart: uploadResponse.mutationSeqAtStart! });} else if (uploadResponse.status === 2) {@@ -1927,11 +1966,78 @@ async function mergeAndPushLocalChanges(return syncResult({ success: false, error: uploadResponse.error });}- await storeVaultMetadata(vaultResponse);-+ await storeVaultMetadata(result.response);return await materializedVaultResult();}+/**+ * LEGACY: pull that merges the local vault onto the server's at the SQLite statement level and uploads the+ * result. A merge that cannot run or fails degrades to taking the server vault as-is.+ *+ * @param syncState - the sync state the merge runs against+ * @param encryptionKey - the key both vaults are encrypted with+ * @param grantSyncChangedVault - whether an earlier step already changed the stored vault+ */+async function legacyStatementPullAndMerge(syncState: VaultSyncState, encryptionKey: string, grantSyncChangedVault: boolean): Promise<FullVaultSyncResult> {+ const vaultResponse = await fetchLatestVaultFromServer();++ try {+ const localEncryptedVault = await storage.getItem(StorageKeys.ENCRYPTED_VAULT) as string | null;+ if (!localEncryptedVault) {+ return await adoptServerVault(vaultResponse, syncState);+ }++ const localDecrypted = await EncryptionUtility.symmetricDecrypt(localEncryptedVault, encryptionKey);+ const serverDecrypted = await EncryptionUtility.symmetricDecrypt(vaultResponse.vault.blob, encryptionKey);++ /*+ * Guard for the sqlite-blob to manifest-v1 migration window: this device has already migrated its vault onto the current+ * schema but the push has not landed yet, while another (not-yet-updated) device advanced the server's+ * legacy sqlite-blob. The two databases have different column sets, so merging them would throw an error.+ * We assume here the migrated local vault is newer, so it's pushed as-is.+ */+ if (await isLegacyStorageVault(serverDecrypted) && !await isLegacyStorageVault(localDecrypted)) {+ devWarn('[VaultSync] Server vault is still on the legacy storage format while the local vault is migrated; skipping the merge and pushing the local vault.');+ return await pushOverLegacyServerVault(grantSyncChangedVault);+ }++ const mergeResult = await vaultMergeService.merge(localDecrypted, serverDecrypted);+ if (!mergeResult.success) {+ console.error('Vault merge failed during sync, using server vault');+ return await adoptServerVault(vaultResponse, syncState);+ }++ devLog('[VaultSync] Vault merge during sync completed:', mergeResult.stats);++ // Store merged vault. Use expectedMutationSeq to detect if a local mutation happened during merge.+ const mergedEncryptedVault = await EncryptionUtility.symmetricEncrypt(mergeResult.mergedVaultBase64, encryptionKey);+ const storeResult = await handleStoreEncryptedVault({ vaultBlob: mergedEncryptedVault, expectedMutationSeq: syncState.mutationSequence });+ if (!storeResult.success) {+ devLog('[VaultSync] Mutation detected during merge, re-syncing...');+ return handleFullVaultSync();+ }++ // Upload merged vault to server+ const uploadResponse = await handleUploadVault();++ if (uploadResponse.success && uploadResponse.status === 0) {+ await handleMarkVaultClean({ mutationSeqAtStart: uploadResponse.mutationSeqAtStart! });+ } else if (uploadResponse.status === 2) {+ // Outdated: another device uploaded first, or the merged vault is not one this session may write whole.+ return resyncAfterOutdatedPush('the merged vault');+ } else {+ console.error('Failed to upload merged vault:', uploadResponse.error);+ return syncResult({ success: false, error: uploadResponse.error });+ }++ await storeVaultMetadata(vaultResponse);++ return await materializedVaultResult();+ } catch (error) {+ return mapVaultOpenError(error);+ }+}+/*** Push the local vault over a server vault that is still on the legacy sqlite-blob format, replacing it whole instead of merging two incompatible schemas.*diff --git a/apps/browser-extension/src/utils/VaultMergeService.ts b/apps/browser-extension/src/utils/VaultMergeService.tsindex 4c19b8421..e533230d4 100644--- a/apps/browser-extension/src/utils/VaultMergeService.ts+++ b/apps/browser-extension/src/utils/VaultMergeService.ts@@ -152,7 +152,9 @@ export class VaultMergeService {}/**- * Merge local vault changes with server vault using LWW strategy.+ * LEGACY: SQLite statement-level merge, kept only for the frozen sqlite-blob storage format (a+ * not-yet-migrated local vault). Manifest-v1 vaults merge at canonical level instead, see+ * `VaultSyncService.pullAndMerge`. TODO: delete this function once all users have migrated to manifest-v1.** Uses Rust WASM for the merge logic. The merge base is the SERVER vault (it is freshly* materialized with the newest schema and the newest codec overflow carrier), and the localdiff --git a/apps/browser-extension/src/utils/VaultSyncService.ts b/apps/browser-extension/src/utils/VaultSyncService.tsindex 62ac3bd1f..560d8c258 100644--- a/apps/browser-extension/src/utils/VaultSyncService.ts+++ b/apps/browser-extension/src/utils/VaultSyncService.ts@@ -16,7 +16,7 @@ import { EncryptionUtility } from '@/utils/EncryptionUtility';import { completeLegacyAccountKeyMigration, isLegacySqliteBlobSnapshot, legacyUnstampedRowAdoption, openLegacySqliteBlobSnapshot, prepareLegacyAccountKeyMigration, withOutdatedServerGuard, type LegacyAccountKeyMigration, type LegacySqliteBlobSnapshot } from '@/utils/legacy/LegacyStorageModelMigration';import { getManifestRevisions, getPersonalManifestId, recordManifestRevisions, replaceManifestRevisions, toManifestRevisionMap } from '@/utils/ManifestRevisions';import { multiManifestRendering } from '@/utils/MultiManifestRendering';-import {vaultCodecComputeCiphertextHash, vaultCodecComputeContentFingerprint, vaultCodecCanonicalizeFromSqlite, vaultCodecExtractEncryptionKeyForPublicKey, vaultCodecGenerateManifestSalt, vaultCodecUnpackPayload, vaultCodecMaterializeAsSqlite, vaultCodecPackPayload, vaultCodecValidateManifest, vaultCodecValidateDataBucket, type CodecBlobEntry, type CodecCanonicalized, type CodecManifest, type CodecManifestSpec, vaultSharingPartitionManifestAccess, vaultSharingResolveManifestWriteSet, type SharingAccessPartition} from '@/utils/RustCore';+import {vaultCodecComputeCiphertextHash, vaultCodecComputeContentFingerprint, vaultCodecCanonicalizeFromSqlite, vaultCodecExtractEncryptionKeyForPublicKey, vaultCodecGenerateManifestSalt, vaultCodecMergeCanonical, vaultCodecUnpackPayload, vaultCodecMaterializeAsSqlite, vaultCodecPackPayload, vaultCodecValidateManifest, vaultCodecValidateDataBucket, type CodecBlobEntry, type CodecCanonicalized, type CodecCanonicalManifestMerge, type CodecManifest, type CodecManifestSpec, vaultSharingPartitionManifestAccess, vaultSharingResolveManifestWriteSet, type SharingAccessPartition} from '@/utils/RustCore';import { SharingService, type ManifestVekGrant, type SharedManifestRecord } from '@/utils/SharingService';import { SqliteClient } from '@/utils/SqliteClient';import { getStorageItem } from '@/utils/StorageUtility';@@ -161,6 +161,45 @@ type PullResult = {manifestRevision: number;};+/**+ * What {@link VaultSyncService.openManifestsAndAdoptSyncState} produces: every manifest of one snapshot,+ * decrypted and ready to materialize or merge, with the local sync state already adopted from it.+ */+type OpenedManifestSet = {+ resolved: ResolvedManifest[];+ dataBuckets: VaultDataBucket[];+ blobMap: Map<string, Uint8Array>;+ contentlessManifestIds: string[];+ personalRevision: number;+ commitManifestRevisions: () => Promise<void>;+};++/** Aggregate canonical-merge statistics across all manifests. */+export type MergeSummary = {+ tablesProcessed: number;+ recordsFromLocal: number;+ recordsFromServer: number;+ recordsCreatedLocally: number;+ conflicts: number;+ recordsInserted: number;+};++/**+ * Result of {@link VaultSyncService.pullAndMerge}: what the fetched snapshot turned out to be and, for the+ * manifest-v1 outcomes, the merged (or server-only) vault plus the deferred revision commit.+ */+export type PullAndMergeResult =+ | { kind: 'legacy-server'; response: VaultResponse }+ | {+ kind: 'merged';+ response: VaultResponse;+ stats: MergeSummary;+ fallbackManifestIds: string[];+ droppedLocalManifestIds: string[];+ commitRevisions: () => Promise<void>;+ }+ | { kind: 'server-only'; response: VaultResponse; commitRevisions: () => Promise<void> };+/*** Result of a push. The revisions of every manifest the write carried are recorded in the per-manifest revision* map ({@link recordManifestRevisions}) as part of the push itself; callers only act on the status.@@ -383,6 +422,178 @@ export class VaultSyncService {}}+ /**+ * Pull the latest snapshot and merge the local vault onto it at canonical level, one manifest at a time.+ * The server side is the base; the local side is canonicalized from `localClient`.+ * @param encryptionKey - the personal manifest's symmetric key+ * @param localClient - the local vault, freshly decrypted from storage+ */+ public async pullAndMerge(encryptionKey: string, localClient: SqliteClient): Promise<PullAndMergeResult> {+ devLog('[V2Merge] Fetching vault snapshot for canonical merge (GET /v2/Vault)...');+ const snapshot = await this.fetchSnapshot();+ this.lastServedManifestIds = (snapshot.manifests ?? []).map(m => m.manifestId);++ // LEGACY: a server still on the sqlite-blob format cannot merge with a manifest-v1 vault; the caller pushes over it.+ if (isLegacySqliteBlobSnapshot(snapshot)) {+ const legacy = await openLegacySqliteBlobSnapshot(snapshot);+ return { kind: 'legacy-server', response: this.buildResponse(legacy.encryptedBlob, legacy.version, legacy.revision, snapshot) };+ }++ try {+ const opened = await this.openManifestsAndAdoptSyncState(snapshot, encryptionKey, { deferRevisionCommit: true });++ try {+ return await this.mergeOntoOpenedManifests(opened, snapshot, encryptionKey, localClient);+ } catch (mergeError) {+ // Today's merge-failure fallback, from the same snapshot: the server vault stands, local changes are dropped.+ devError('[V2Merge] Canonical merge failed, falling back to the server vault:', mergeError);+ const sqliteBase64 = await this.materializeToSqlite(opened.resolved.map(m => m.manifest), opened.dataBuckets, opened.blobMap);+ const encryptedVault = await EncryptionUtility.symmetricEncrypt(sqliteBase64, encryptionKey);+ return { kind: 'server-only', response: this.buildResponse(encryptedVault, '2.0.0', opened.personalRevision, snapshot), commitRevisions: opened.commitManifestRevisions };+ }+ } catch (error) {+ devError('[V2Merge] FAILED: the last logged step above is where it broke:', error);+ throw new VaultProcessingError('vault-pull', error);+ }+ }++ /**+ * The merge core of {@link pullAndMerge}: canonicalize the local vault, run the Rust canonical merge+ * against the manifests just opened, validate the result per manifest, and materialize it.+ * @param opened - the opened server manifests (the merge base)+ * @param snapshot - the raw snapshot (for the email-routing block of the response)+ * @param encryptionKey - the personal manifest's symmetric key+ * @param localClient - the local vault, freshly decrypted from storage+ */+ private async mergeOntoOpenedManifests(opened: OpenedManifestSet, snapshot: GetResponseDto, encryptionKey: string, localClient: SqliteClient): Promise<PullAndMergeResult> {+ const { canonicalized } = await this.canonicalizeVault(localClient);++ const schemaColumns = await VaultCodec.getSchemaColumns(new VaultSqlGenerator().getCompleteSchemaSql());+ devLog(`[V2Merge] Merging ${canonicalized.manifests.length} local manifest(s) onto ${opened.resolved.length} server manifest(s)...`);+ const mergeOutput = await vaultCodecMergeCanonical({+ serverManifests: opened.resolved.map(m => m.manifest),+ serverBuckets: opened.dataBuckets,+ contentlessServerManifestIds: opened.contentlessManifestIds,+ localManifests: canonicalized.manifests.map(m => m.manifest),+ localBuckets: canonicalized.dataBuckets,+ schemaColumns,+ });++ // Validation gate, per manifest: the server's version of a failing manifest stands.+ const serverManifestById = new Map(opened.resolved.map(m => [m.manifestId.toLowerCase(), m.manifest]));+ const serverBucketsById = new Map<string, VaultDataBucket[]>();+ for (const bucket of opened.dataBuckets) {+ const key = bucket.manifestId.toLowerCase();+ serverBucketsById.set(key, [...(serverBucketsById.get(key) ?? []), bucket]);+ }+ const contentlessIds = new Set(opened.contentlessManifestIds.map(id => id.toLowerCase()));++ const manifests: VaultManifest[] = [];+ const dataBuckets: VaultDataBucket[] = [];+ const fallbackManifestIds: string[] = [];+ const stats: MergeSummary = { tablesProcessed: 0, recordsFromLocal: 0, recordsFromServer: 0, recordsCreatedLocally: 0, conflicts: 0, recordsInserted: 0 };+ for (const entry of mergeOutput.manifests) {+ const failure = await this.validateMergedManifest(entry);+ if (failure !== null && !contentlessIds.has(entry.manifestId.toLowerCase())) {+ devWarn(`[V2Merge] Merged manifest ${entry.manifestId} failed validation (${failure}); the server's version stands and local changes to it are dropped.`);+ fallbackManifestIds.push(entry.manifestId);+ const serverManifest = serverManifestById.get(entry.manifestId.toLowerCase());+ if (serverManifest) {+ manifests.push(serverManifest);+ dataBuckets.push(...(serverBucketsById.get(entry.manifestId.toLowerCase()) ?? []));+ }+ continue;+ }+ if (failure !== null) {+ // A contentless pass-through has no server base to fall back to; keep the local rows, the push gate decides.+ devWarn(`[V2Merge] Pass-through manifest ${entry.manifestId} failed validation (${failure}); keeping its local rows.`);+ }+ manifests.push(entry.manifest);+ dataBuckets.push(...entry.buckets);+ stats.tablesProcessed += entry.stats.tables_processed;+ stats.recordsFromLocal += entry.stats.records_from_local;+ stats.recordsFromServer += entry.stats.records_from_server;+ stats.recordsCreatedLocally += entry.stats.records_created_locally;+ stats.conflicts += entry.stats.conflicts;+ stats.recordsInserted += entry.stats.records_inserted;+ }+ for (const dropped of mergeOutput.droppedLocalManifestIds) {+ devWarn(`[V2Merge] Local manifest ${dropped} is no longer served; its rows are dropped from the merged vault.`);+ }++ // Blob bytes for materialize: the server download plus everything the local canonicalize extracted.+ const blobMap = opened.blobMap;+ for (const { blobs } of canonicalized.manifests) {+ for (const [hash, blob] of Object.entries(blobs)) {+ if (!blobMap.has(hash)) {+ blobMap.set(hash, VaultCodec.base64ToBytes(blob.bytesBase64));+ }+ }+ }+ this.assertMergedBlobRefsResolve(manifests, blobMap, opened.resolved[0]?.manifestId ?? '');++ const sqliteBase64 = await this.materializeToSqlite(manifests, dataBuckets, blobMap);+ const encryptedVault = await EncryptionUtility.symmetricEncrypt(sqliteBase64, encryptionKey);+ devLog(`[V2Merge] Canonical merge complete: ${stats.conflicts} conflict(s), ${stats.recordsInserted} offline row(s) kept, ${fallbackManifestIds.length} validation fallback(s), ${mergeOutput.droppedLocalManifestIds.length} dropped local manifest(s).`);++ return {+ kind: 'merged',+ response: this.buildResponse(encryptedVault, '2.0.0', opened.personalRevision, snapshot),+ stats,+ fallbackManifestIds,+ droppedLocalManifestIds: mergeOutput.droppedLocalManifestIds,+ commitRevisions: opened.commitManifestRevisions,+ };+ }++ /**+ * Validate one merged manifest and its buckets. Returns the failed rules, or null when valid.+ * @param entry - one manifest's merge result+ */+ private async validateMergedManifest(entry: CodecCanonicalManifestMerge): Promise<string | null> {+ const validation = await vaultCodecValidateManifest(entry.manifest);+ if (!validation.ok) {+ return validation.failedRules.join(', ');+ }+ for (const bucket of entry.buckets) {+ const bucketValidation = await vaultCodecValidateDataBucket(bucket);+ if (!bucketValidation.ok) {+ return `bucket "${bucket.category}": ${bucketValidation.failedRules.join(', ')}`;+ }+ }+ return null;+ }++ /**+ * Every blob marker in the merged manifests must resolve to bytes, or materialize would silently insert+ * NULL.+ * @param manifests - the manifests about to materialize+ * @param blobMap - the bytes available by hash+ * @param personalManifestId - the personal manifest's id+ */+ private assertMergedBlobRefsResolve(manifests: VaultManifest[], blobMap: Map<string, Uint8Array>, personalManifestId: string): void {+ for (const manifest of manifests) {+ const isPersonal = manifestIdsEqual(manifest.manifestId, personalManifestId);+ for (const rows of Object.values(manifest.tables)) {+ for (const row of rows) {+ for (const value of Object.values(row)) {+ if (typeof value !== 'object' || value === null || !('__blobRef' in value)) {+ continue;+ }+ const ref = value as { __blobRef: string; __blobKind?: string };+ if (blobMap.has(ref.__blobRef)) {+ continue;+ }+ if (ref.__blobKind === 'attachment' && isPersonal) {+ throw new Error(`VaultSyncService: merged vault references attachment blob ${ref.__blobRef} with no bytes available, refusing to materialize an incomplete vault.`);+ }+ devWarn(`[V2Merge] Merged ${ref.__blobKind ?? 'blob'} ${ref.__blobRef} has no bytes available; it will materialize as empty.`);+ }+ }+ }+ }+ }+/*** Migrate the local vault onto the current full schema, entirely locally: canonicalize the database into* manifest-v1 form and materialize it straight back out again so it works offline too.@@ -439,8 +650,20 @@ export class VaultSyncService {* @param vek - the personal manifest's symmetric key (from the unlock chain); decrypts the personal manifest and the data buckets*/private async materializeFromSnapshot(snapshot: GetResponseDto, vek: string): Promise<PullResult> {- const webApi = new WebApiService();+ const opened = await this.openManifestsAndAdoptSyncState(snapshot, vek);+ const sqliteBase64 = await this.materializeToSqlite(opened.resolved.map(m => m.manifest), opened.dataBuckets, opened.blobMap);+ return { sqliteBase64, manifestRevision: opened.personalRevision };+ }+ /**+ * Open every manifest a snapshot carries (the personal one plus each shared one) and adopt the snapshot as+ * this device's sync state.+ * @param snapshot - the raw GET /v2/Vault response+ * @param vek - the personal manifest's symmetric key (from the unlock chain); every other manifest key resolves from it+ * @param options - set deferRevisionCommit to hand the revision write back to the caller as `commitManifestRevisions`,+ * for when the pulled revisions may only become local truth once a later step has succeeded+ */+ private async openManifestsAndAdoptSyncState(snapshot: GetResponseDto, vek: string, options?: { deferRevisionCommit?: boolean }): Promise<OpenedManifestSet> {const personalDto = selectPersonalManifest(snapshot);if (!personalDto) {throw new Error('VaultSyncService: server returned no personal manifest, refusing to assemble.');@@ -454,8 +677,8 @@ export class VaultSyncService {const pulledFingerprints: Record<string, string> = {};/*- * Open every manifest in the snapshot through one path, personal manifest first. Every failure to resolve a- * key or open a blob throws on purpose.+ * 1) Open every manifest in the snapshot through one path, personal manifest first. Every failure to resolve+ * a key or open a blob throws on purpose.*/const accountKeyVeks = new Map<string, string>([[personalDto.manifestId, vek]]);const resolved: ResolvedManifest[] = [];@@ -488,11 +711,6 @@ export class VaultSyncService {devLog(`[V2Pull] Manifest ${entry.manifestId} opened (content hash verified, ${isPersonal ? 'personal' : `shared "${entry.manifest.name ?? 'unnamed'}"`}): tables: ${Object.entries(entry.manifest.tables).map(([t, rows]) => `${t}=${rows.length}`).join(', ')}`);if (isPersonal) {- /*- * Persist the personal manifest's blob salt locally so subsequent canonicalizes hash blobs the same way, and the- * personal manifest id, which is the sole record of it: it is server-reported client state, not vault content, so- * it stays out of the vault (`SqliteClient` hydrates it from here whenever the database is opened).- */await storage.setItem(StorageKeys.VAULT_MANIFEST_SALT, entry.manifest.manifestSalt);await storage.setItem(StorageKeys.VAULT_PERSONAL_MANIFEST_ID, entry.manifestId);continue;@@ -515,7 +733,55 @@ export class VaultSyncService {const personal = resolved[0];- // Decrypt every data bucket in the snapshot.+ // 2) Open the data buckets belonging to those manifests.+ const { dataBuckets, bucketFingerprints } = await this.openDataBuckets(snapshot, resolved);+ Object.assign(pulledFingerprints, bucketFingerprints);++ // 3) Revision baselines: what the next status check compares this device against.+ const manifestRevisions = { ...Object.fromEntries(resolved.map(m => [m.manifestId, m.revision])), ...contentlessRevisions };+ /**+ * Commit the snapshot's revision map as the local believed-current revisions.+ */+ const commitManifestRevisions = async (): Promise<void> => {+ await replaceManifestRevisions(manifestRevisions);+ devLog(`[V2Pull] Stored local manifest revisions from snapshot: ${Object.entries(manifestRevisions).map(([id, rev]) => `${id}=${rev}`).join(', ')}. Next status check compares against these.`);+ };+ if (options?.deferRevisionCommit !== true) {+ await commitManifestRevisions();+ }++ // 4) Fetch and decrypt every blob the opened manifests reference.+ const blobMap = await this.downloadReferencedBlobs(resolved, vek);++ /*+ * 5) Fingerprint baselines: what the next push diffs against. Replace rather than merge, the record must+ * mirror exactly the manifests and buckets the server holds right now, so entries of revoked/removed+ * manifests drop out. One entry per opened manifest, the personal one included.+ */+ for (const entry of resolved) {+ pulledFingerprints[fingerprintManifestKey(entry.manifestId)] = entry.contentFingerprint;+ }+ await storage.setItem(StorageKeys.VAULT_CONTENT_FINGERPRINTS, pulledFingerprints);+ devLog(`[V2Pull] Stored ${Object.keys(pulledFingerprints).length} content fingerprint baseline(s) for push-side change detection.`);++ return {+ resolved,+ dataBuckets,+ blobMap,+ contentlessManifestIds: Object.keys(contentlessRevisions),+ personalRevision: personal.revision,+ commitManifestRevisions,+ };+ }++ /**+ * Open the data buckets a snapshot carries and record their revisions as the local baseline.+ * @param snapshot - the raw GET /v2/Vault response+ * @param resolved - the manifests already opened; a bucket addressed to any other manifest is refused+ * @returns The decrypted buckets plus one content fingerprint per bucket, for the push-side change detection+ */+ private async openDataBuckets(snapshot: GetResponseDto, resolved: ResolvedManifest[]): Promise<{ dataBuckets: VaultDataBucket[]; bucketFingerprints: Record<string, string> }> {+ const bucketFingerprints: Record<string, string> = {};const keyByManifestId = new Map(resolved.map(entry => [entry.manifestId, entry.vek]));const dataBuckets: VaultDataBucket[] = [];const pulledBucketRevisions: Record<string, number> = {};@@ -537,7 +803,7 @@ export class VaultSyncService {}dataBuckets.push(bucket);- pulledFingerprints[fingerprintBucketKey(bucketDto.manifestId, bucketDto.category)] = await vaultCodecComputeContentFingerprint(bucketJson);+ bucketFingerprints[fingerprintBucketKey(bucketDto.manifestId, bucketDto.category)] = await vaultCodecComputeContentFingerprint(bucketJson);const rowCount = Object.values(bucket.tables ?? {}).reduce((n, rows) => n + rows.length, 0);devLog(`[V2Pull] Data bucket ${label} opened: ${rowCount} rows (revision ${bucketDto.revision}).`);if (typeof bucketDto.revision === 'number') {@@ -550,16 +816,18 @@ export class VaultSyncService {devLog('[V2Pull] No data buckets in snapshot.');}- // One fingerprint baseline per opened manifest, addressed by manifest id (the personal manifest included).- for (const entry of resolved) {- pulledFingerprints[fingerprintManifestKey(entry.manifestId)] = entry.contentFingerprint;- }-- const manifestRevisions = { ...Object.fromEntries(resolved.map(m => [m.manifestId, m.revision])), ...contentlessRevisions };- await replaceManifestRevisions(manifestRevisions);- devLog(`[V2Pull] Stored local manifest revisions from snapshot: ${Object.entries(manifestRevisions).map(([id, rev]) => `${id}=${rev}`).join(', ')}. Next status check compares against these.`);+ return { dataBuckets, bucketFingerprints };+ }- // Fetch any referenced blobs that aren't already in the local (encrypted) cache.+ /**+ * Fetch every blob the opened manifests reference that is not already cached locally, decrypt it, and prune+ * the persisted cache to exactly that referenced set, so the cache stays bounded by the current vault size.+ * @param resolved - the opened manifests, whose references decide what is downloaded and which key opens it+ * @param vek - fallback key for a reference whose owning manifest cannot be determined+ * @returns Plaintext bytes per blob hash, for the codec to re-embed+ */+ private async downloadReferencedBlobs(resolved: ResolvedManifest[], vek: string): Promise<Map<string, Uint8Array>> {+ const webApi = new WebApiService();const refOwners = new Map<string, ResolvedManifest>();const refs: StoredBlobRefDto[] = [];for (const entry of resolved) {@@ -586,29 +854,14 @@ export class VaultSyncService {}}- /*- * Decrypt referenced blobs for reassembly and prune the persisted cache to exactly the referenced set, so- * the cache stays bounded by the current vault size. A blob that can't be reconstituted: the server couldn't- * serve it (missing) or its ciphertext won't decrypt with the current key (stale key / corruption): is fatal- * for attachments (silently dropping bytes would propagate permanent data loss on the next push); a favicon- * only degrades cosmetically, so it's logged and skipped. The codec inserts NULL for any skipped blob ref.- */+ // Decrypt the referenced blobs and prune the cache to exactly the referenced set, so the cache stays bounded by the current vault size.const prunedCache: Record<string, string> = {};const blobMap = new Map<string, Uint8Array>();for (const r of refs) {const ciphertext = cache[r.hash];const owner = refOwners.get(r.hash);const blobKey = owner?.vek ?? vek;- /*- * Personal-manifest attachments are load-bearing (a NULL insert would propagate data loss on the next push);- * shared-manifest blob gaps only degrade that folder, so they are logged and skipped. TODO: revisit once- * cross-member blob availability is guaranteed (shared attachment gaps currently degrade like favicons).- */- const strict = r.category === 'attachment' && owner?.isPersonal === true;if (!ciphertext) {- if (strict) {- throw new Error(`VaultSyncService: attachment blob ${r.hash} is referenced by the manifest but missing on the server, refusing to assemble an incomplete vault.`);- }devWarn(`[V2Sync] Referenced ${r.category} blob ${r.hash} missing on server, continuing without it.`);continue;}@@ -616,10 +869,6 @@ export class VaultSyncService {blobMap.set(r.hash, await this.decryptBlobToBytes(ciphertext, blobKey));prunedCache[r.hash] = ciphertext;} catch (e) {- // Present on the server but undecryptable with the current key. Apply the same policy as a missing blob.- if (strict) {- throw new Error(`VaultSyncService: attachment blob ${r.hash} is referenced by the manifest but could not be decrypted with the current key (stale key or corrupt ciphertext), refusing to assemble an incomplete vault. Underlying: ${e instanceof Error ? e.message : String(e)}`);- }devWarn(`[V2Sync] Referenced ${r.category} blob ${r.hash} failed to decrypt with the current key, continuing without it.`);}}@@ -628,24 +877,23 @@ export class VaultSyncService {// The server demonstrably has every blob it just served or referenced, seed the upload diff with them.await storage.setItem(StorageKeys.VAULT_SERVER_BLOB_HASHES, refs.map(r => r.hash));- /*- * Replace (not merge) the content-fingerprint baselines: the record must mirror exactly the manifests and- * buckets the server holds right now, so entries of revoked/removed manifests drop out.- */- await storage.setItem(StorageKeys.VAULT_CONTENT_FINGERPRINTS, pulledFingerprints);- devLog(`[V2Pull] Stored ${Object.keys(pulledFingerprints).length} content fingerprint baseline(s) for push-side change detection.`);+ return blobMap;+ }- devLog(`[V2Pull] ${blobMap.size} blobs decrypted; running codec reassembly into a fresh SQLite (${resolved.length} manifest(s) combined)...`);+ /**+ * Materialize manifests + data buckets into a fresh SQLite database via the codec.+ * @param manifests - the manifests to combine, the caller's own first+ * @param dataBuckets - the data buckets belonging to those manifests+ * @param blobMap - plaintext bytes for every blob hash the manifests reference+ * @returns Base64 of the materialized SQLite database (plaintext)+ */+ private async materializeToSqlite(manifests: VaultManifest[], dataBuckets: VaultDataBucket[], blobMap: Map<string, Uint8Array>): Promise<string> {+ devLog(`[V2Pull] ${blobMap.size} blobs decrypted; running codec reassembly into a fresh SQLite (${manifests.length} manifest(s) combined)...`);const sqlGen = new VaultSqlGenerator();const schemaSql = sqlGen.getCompleteSchemaSql();const schemaColumns = await VaultCodec.getSchemaColumns(schemaSql);- const materialized = await vaultCodecMaterializeAsSqlite(resolved.map(m => m.manifest), dataBuckets, schemaColumns);+ const materialized = await vaultCodecMaterializeAsSqlite(manifests, dataBuckets, schemaColumns);- /*- * Anything a newer client wrote that our schema can't hold was split off the insert set into the- * CodecOverflows carrier row (part of the tables inserted below, so it lives inside the encrypted- * vault DB). Canonicalize re-merges it on push, so this client never deletes a newer writer's data.- */const overflowTableCount = Object.keys(materialized.overflow.tables).length + Object.values(materialized.overflow.bucketTables).reduce((n, t) => n + Object.keys(t).length, 0);const overflowColumnTables = Object.keys(materialized.overflow.columns);if (overflowTableCount > 0 || overflowColumnTables.length > 0) {@@ -655,7 +903,7 @@ export class VaultSyncService {const sqliteBase64 = await VaultCodec.insertTables(materialized, blobMap, schemaSql);devLog('[V2Pull] Codec reassembly complete.');- return { sqliteBase64, manifestRevision: personal.revision };+ return sqliteBase64;}/**diff --git a/core/rust/src/lib.rs b/core/rust/src/lib.rsindex 54ee30d50..9d33796db 100644--- a/core/rust/src/lib.rs+++ b/core/rust/src/lib.rs@@ -30,7 +30,8 @@ pub mod argon2;pub use error::VaultError;pub use vault_merge::{- merge_vaults, MergeInput, MergeOutput, MergeStats, SqlStatement, TableData,+ merge_canonical, merge_canonical_json, merge_vaults, CanonicalManifestMerge, CanonicalMergeInput,+ CanonicalMergeOutput, MergeInput, MergeOutput, MergeStats, SqlStatement, TableData,SYNCABLE_TABLE_NAMES,};pub use vault_codec::{diff --git a/core/rust/src/vault_merge/canonical.rs b/core/rust/src/vault_merge/canonical.rsnew file mode 100644index 000000000..877a75e8c--- /dev/null+++ b/core/rust/src/vault_merge/canonical.rs@@ -0,0 +1,632 @@+//! Canonical-level vault merge: LWW over manifest JSON + data buckets, rows in, rows out.+//!+//! This is the merge for the manifest-v1 storage format (used since 0.31.0+). It runs one layer above any concrete+//! materialization (SQLite or otherwise): both sides arrive in canonical form and the output is+//! the merged canonical form, which the platform then materializes once.+//!+//! Each manifest is merged independently (the server manifest set is the universe), so a broken+//! manifest can never affect another manifest's rows, and blob columns carry `__blobRef` markers+//! rather than bytes, so no byte payload ever crosses the merge.++use std::collections::{BTreeSet, HashMap, HashSet};++use serde::{Deserialize, Serialize};++use super::{get_key, get_updated_at, MergeStats, TableConfig, SYNCABLE_TABLES};+use crate::error::VaultResult;+use crate::vault_codec::{bucket_categories, is_bucketed_table, tables_for_category, CodecRecord, DataBucket, Manifest};++/// Input of the canonical merge. The server side is the base (kept on ties); the local side is the+/// incoming set produced by `canonicalize_from_sqlite`.+#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct CanonicalMergeInput {+ pub server_manifests: Vec<Manifest>,+ pub server_buckets: Vec<DataBucket>,+ #[serde(default)]+ pub contentless_server_manifest_ids: Vec<String>,+ pub local_manifests: Vec<Manifest>,+ pub local_buckets: Vec<DataBucket>,+ pub schema_columns: HashMap<String, Vec<String>>,+}++/// One manifest's merged result.+#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct CanonicalManifestMerge {+ pub manifest_id: String,+ pub manifest: Manifest,+ pub buckets: Vec<DataBucket>,+ pub stats: MergeStats,+}++/// Output of the canonical merge.+#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct CanonicalMergeOutput {+ pub manifests: Vec<CanonicalManifestMerge>,+ pub dropped_local_manifest_ids: Vec<String>,+}++/// Merge the local canonical vault onto the server canonical vault (the base), per manifest.+pub fn merge_canonical(input: CanonicalMergeInput) -> VaultResult<CanonicalMergeOutput> {+ let CanonicalMergeInput { server_manifests, server_buckets, contentless_server_manifest_ids, local_manifests, local_buckets, schema_columns } = input;++ let mut local_by_id: HashMap<String, Manifest> = local_manifests.into_iter().map(|m| (m.manifest_id.to_lowercase(), m)).collect();+ let mut local_buckets_by_id = group_buckets(local_buckets);+ let mut server_buckets_by_id = group_buckets(server_buckets);++ let mut manifests: Vec<CanonicalManifestMerge> = Vec::new();+ for server_manifest in server_manifests {+ let key = server_manifest.manifest_id.to_lowercase();+ let local = local_by_id.remove(&key);+ let local_buckets = local_buckets_by_id.remove(&key).unwrap_or_default();+ let server_buckets = server_buckets_by_id.remove(&key).unwrap_or_default();+ manifests.push(merge_manifest_pair(server_manifest, server_buckets, local, local_buckets, &schema_columns));+ }++ // A contentless server manifest has no base; the local counterpart passes through whole.+ for manifest_id in contentless_server_manifest_ids {+ let key = manifest_id.to_lowercase();+ if let Some(local) = local_by_id.remove(&key) {+ manifests.push(pass_through(local, local_buckets_by_id.remove(&key).unwrap_or_default()));+ }+ }++ let mut dropped_local_manifest_ids: Vec<String> = local_by_id.into_values().map(|m| m.manifest_id).collect();+ dropped_local_manifest_ids.sort();++ Ok(CanonicalMergeOutput { manifests, dropped_local_manifest_ids })+}++/// JSON convenience wrapper for FFI.+pub fn merge_canonical_json(input_json: &str) -> VaultResult<String> {+ let input: CanonicalMergeInput = serde_json::from_str(input_json)?;+ Ok(serde_json::to_string(&merge_canonical(input)?)?)+}++/// Group buckets by their manifest id (lowercased).+fn group_buckets(buckets: Vec<DataBucket>) -> HashMap<String, Vec<DataBucket>> {+ let mut grouped: HashMap<String, Vec<DataBucket>> = HashMap::new();+ for bucket in buckets {+ grouped.entry(bucket.manifest_id.to_lowercase()).or_default().push(bucket);+ }+ grouped+}++/// Merge one manifest: LWW over the flattened table view of both sides, then split the bucketed+/// tables back out. The merged `Manifest` is the server one with only its tables replaced.+fn merge_manifest_pair(+ server: Manifest,+ server_buckets: Vec<DataBucket>,+ local: Option<Manifest>,+ local_buckets: Vec<DataBucket>,+ schema_columns: &HashMap<String, Vec<String>>,+) -> CanonicalManifestMerge {+ let manifest_id = server.manifest_id.clone();+ let mut stats = MergeStats::default();++ // A bucket of a category this build does not know cannot be flattened without losing its+ // category; the server's ride through as-is and the local ones are dropped with the rest of+ // the local carrier, exactly as the base-wins rule treats every unknown table.+ let (server_bucket_tables, unknown_server_buckets) = split_known_buckets(server_buckets);+ let (local_bucket_tables, _) = split_known_buckets(local_buckets);++ let mut base_tables = server.tables.clone();+ base_tables.extend(server_bucket_tables);+ let mut incoming_tables = local.map(|m| m.tables).unwrap_or_default();+ incoming_tables.extend(local_bucket_tables);++ let table_names: BTreeSet<String> = base_tables.keys().chain(incoming_tables.keys()).cloned().collect();++ let mut merged: HashMap<String, Vec<CodecRecord>> = HashMap::new();+ for name in table_names {+ let base_rows = base_tables.remove(&name).unwrap_or_default();+ let incoming_rows = incoming_tables.remove(&name).unwrap_or_default();+ let merged_rows = match SYNCABLE_TABLES.iter().find(|t| t.name == name) {+ Some(config) => {+ stats.tables_processed += 1;+ merge_rows(config, base_rows, incoming_rows, schema_columns, &mut stats)+ }+ // Not a syncable table (a skip table, or one from a newer writer): the base wins as-is.+ None => base_rows,+ };+ if !merged_rows.is_empty() {+ merged.insert(name, merged_rows);+ }+ }++ let mut buckets = unknown_server_buckets;+ for category in bucket_categories() {+ let mut bucket_tables: HashMap<String, Vec<CodecRecord>> = HashMap::new();+ for table in tables_for_category(category) {+ if let Some(rows) = merged.remove(table) {+ bucket_tables.insert(table.to_string(), rows);+ }+ }+ if !bucket_tables.is_empty() {+ buckets.push(DataBucket::new(manifest_id.clone(), category.to_string(), bucket_tables));+ }+ }++ let manifest = Manifest { tables: merged, ..server };+ CanonicalManifestMerge { manifest_id, manifest, buckets, stats }+}++/// Split buckets into the flattened rows of the tables this build buckets itself, and leftover+/// buckets holding every other table (a newer writer's), kept under their served category.+fn split_known_buckets(buckets: Vec<DataBucket>) -> (HashMap<String, Vec<CodecRecord>>, Vec<DataBucket>) {+ let mut tables: HashMap<String, Vec<CodecRecord>> = HashMap::new();+ let mut unknown: Vec<DataBucket> = Vec::new();+ for bucket in buckets {+ let mut unknown_tables: HashMap<String, Vec<CodecRecord>> = HashMap::new();+ for (name, rows) in bucket.tables {+ if is_bucketed_table(&name) {+ tables.entry(name).or_default().extend(rows);+ } else {+ unknown_tables.insert(name, rows);+ }+ }+ if !unknown_tables.is_empty() {+ unknown.push(DataBucket::new(bucket.manifest_id, bucket.category, unknown_tables));+ }+ }+ (tables, unknown)+}++/// A contentless server manifest's local counterpart passes through whole: every row is an+/// offline-kept row.+fn pass_through(local: Manifest, local_buckets: Vec<DataBucket>) -> CanonicalManifestMerge {+ let mut stats = MergeStats::default();+ let row_count = |tables: &HashMap<String, Vec<CodecRecord>>| tables.values().map(|rows| rows.len() as u32).sum::<u32>();+ stats.records_inserted = row_count(&local.tables) + local_buckets.iter().map(|b| row_count(&b.tables)).sum::<u32>();++ CanonicalManifestMerge { manifest_id: local.manifest_id.clone(), manifest: local.clone(), buckets: local_buckets, stats }+}++/// LWW one table, rows out: base rows in order (replaced where the incoming row is strictly+/// newer), then incoming-only rows in first-occurrence order.+fn merge_rows(+ config: &TableConfig,+ base_rows: Vec<CodecRecord>,+ incoming_rows: Vec<CodecRecord>,+ schema_columns: &HashMap<String, Vec<String>>,+ stats: &mut MergeStats,+) -> Vec<CodecRecord> {+ let identity_columns = config.identity_columns();+ let match_columns: &[&str] = if config.uses_composite_key() { config.composite_key_columns } else { &identity_columns };+ let known_columns: Option<HashSet<&str>> = schema_columns.get(config.name).map(|cols| cols.iter().map(String::as_str).collect());++ // Winner per match key among incoming rows; on duplicates the latest UpdatedAt wins.+ let mut incoming_map: HashMap<String, &CodecRecord> = HashMap::new();+ for record in &incoming_rows {+ let key = get_key(record, match_columns);+ match incoming_map.get(&key) {+ Some(existing) if get_updated_at(record) <= get_updated_at(existing) => {}+ _ => {+ incoming_map.insert(key, record);+ }+ }+ }++ let mut merged: Vec<CodecRecord> = Vec::with_capacity(base_rows.len());+ for base_record in base_rows {+ let key = get_key(&base_record, match_columns);+ match incoming_map.remove(&key) {+ Some(incoming) => {+ let (incoming_ts, base_ts) = (get_updated_at(incoming), get_updated_at(&base_record));+ match (incoming_ts, base_ts) {+ (Some(i_ts), Some(b_ts)) if i_ts > b_ts => {+ stats.conflicts += 1;+ stats.records_from_server += 1;+ merged.push(overlay_winner(incoming.clone(), &base_record, &identity_columns, known_columns.as_ref()));+ }+ _ => {+ stats.records_from_local += 1;+ merged.push(base_record);+ }+ }+ }+ None => {+ stats.records_created_locally += 1;+ merged.push(base_record);+ }+ }+ }++ for record in &incoming_rows {+ if let Some(winner) = incoming_map.remove(&get_key(record, match_columns)) {+ stats.records_inserted += 1;+ merged.push(winner.clone());+ }+ }++ merged+}++/// A winning incoming row.+fn overlay_winner(mut winner: CodecRecord, base: &CodecRecord, identity_columns: &[&str], known_columns: Option<&HashSet<&str>>) -> CodecRecord {+ for (column, value) in base {+ let base_wins = identity_columns.contains(&column.as_str()) || known_columns.is_some_and(|known| !known.contains(column.as_str()));+ if base_wins {+ winner.insert(column.clone(), value.clone());+ }+ }+ winner+}++#[cfg(test)]+mod tests {+ use super::*;+ use serde_json::json;++ const PERSONAL: &str = "m-personal";+ const SHARED: &str = "m-shared";+ const SALT: &str = "0123456789abcdef0123456789abcdef";++ fn manifest(manifest_id: &str, tables: HashMap<String, Vec<CodecRecord>>) -> Manifest {+ Manifest {+ schema_version: 1,+ manifest_salt: SALT.to_string(),+ canonicalized_at: "2024-01-01T00:00:00Z".to_string(),+ manifest_id: manifest_id.to_string(),+ name: None,+ tables,+ extra: HashMap::new(),+ }+ }++ fn item(manifest_id: &str, id: &str, name: &str, updated_at: &str) -> CodecRecord {+ [+ ("ManifestId".to_string(), json!(manifest_id)),+ ("Id".to_string(), json!(id)),+ ("Name".to_string(), json!(name)),+ ("UpdatedAt".to_string(), json!(updated_at)),+ ]+ .into_iter()+ .collect()+ }++ fn items_manifest(manifest_id: &str, rows: Vec<CodecRecord>) -> Manifest {+ manifest(manifest_id, [("Items".to_string(), rows)].into_iter().collect())+ }++ fn schema() -> HashMap<String, Vec<String>> {+ [+ ("Items".to_string(), vec!["ManifestId".to_string(), "Id".to_string(), "Name".to_string(), "UpdatedAt".to_string()]),+ ("Settings".to_string(), vec!["ManifestId".to_string(), "Key".to_string(), "Value".to_string(), "UpdatedAt".to_string()]),+ ("ItemStats".to_string(), vec!["ManifestId".to_string(), "Id".to_string(), "LastUsedAt".to_string(), "UpdatedAt".to_string()]),+ ("FieldValues".to_string(), vec!["ManifestId".to_string(), "Id".to_string(), "ItemId".to_string(), "FieldKey".to_string(), "Value".to_string(), "UpdatedAt".to_string()]),+ ("Attachments".to_string(), vec!["ManifestId".to_string(), "Id".to_string(), "Blob".to_string(), "UpdatedAt".to_string()]),+ ]+ .into_iter()+ .collect()+ }++ fn merge_single(server_rows: Vec<CodecRecord>, local_rows: Vec<CodecRecord>) -> CanonicalManifestMerge {+ let output = merge_canonical(CanonicalMergeInput {+ server_manifests: vec![items_manifest(PERSONAL, server_rows)],+ server_buckets: vec![],+ contentless_server_manifest_ids: vec![],+ local_manifests: vec![items_manifest(PERSONAL, local_rows)],+ local_buckets: vec![],+ schema_columns: schema(),+ })+ .unwrap();+ assert_eq!(output.manifests.len(), 1);+ output.manifests.into_iter().next().unwrap()+ }++ fn names_of(manifest: &Manifest) -> Vec<String> {+ manifest.tables.get("Items").map(|rows| rows.iter().map(|r| r["Name"].as_str().unwrap().to_string()).collect()).unwrap_or_default()+ }++ #[test]+ fn local_newer_wins_server_newer_and_tie_keep_base() {+ let merged = merge_single(+ vec![+ item(PERSONAL, "local-wins", "server-old", "2024-01-01T00:00:00Z"),+ item(PERSONAL, "server-wins", "server-new", "2024-01-09T00:00:00Z"),+ item(PERSONAL, "tie", "server-tie", "2024-01-05T00:00:00Z"),+ ],+ vec![+ item(PERSONAL, "local-wins", "local-new", "2024-01-09T00:00:00Z"),+ item(PERSONAL, "server-wins", "local-old", "2024-01-01T00:00:00Z"),+ item(PERSONAL, "tie", "local-tie", "2024-01-05T00:00:00Z"),+ ],+ );++ assert_eq!(names_of(&merged.manifest), vec!["local-new", "server-new", "server-tie"], "ties and newer base rows keep the server version");+ assert_eq!(merged.stats.conflicts, 1);+ assert_eq!(merged.stats.records_from_server, 1);+ assert_eq!(merged.stats.records_from_local, 2);+ }++ #[test]+ fn one_sided_rows_are_kept_on_both_sides() {+ let merged = merge_single(+ vec![item(PERSONAL, "server-only", "on-server", "2024-01-01T00:00:00Z")],+ vec![item(PERSONAL, "local-only", "made-offline", "2024-01-02T00:00:00Z")],+ );++ assert_eq!(names_of(&merged.manifest), vec!["on-server", "made-offline"], "base rows first, then offline-created rows");+ assert_eq!(merged.stats.records_created_locally, 1);+ assert_eq!(merged.stats.records_inserted, 1);+ }++ #[test]+ fn manifests_merge_independently_same_id_never_crosses() {+ // The structural guarantee of the canonical merge: manifests are the partition, so the+ // same row id in two manifests can never interact, whatever the timestamps say.+ let output = merge_canonical(CanonicalMergeInput {+ server_manifests: vec![+ items_manifest(PERSONAL, vec![item(PERSONAL, "same-id", "mine", "2024-01-01T00:00:00Z")]),+ items_manifest(SHARED, vec![item(SHARED, "same-id", "theirs-old", "2024-01-01T00:00:00Z")]),+ ],+ server_buckets: vec![],+ contentless_server_manifest_ids: vec![],+ local_manifests: vec![+ items_manifest(PERSONAL, vec![item(PERSONAL, "same-id", "mine", "2024-01-01T00:00:00Z")]),+ items_manifest(SHARED, vec![item(SHARED, "same-id", "theirs-new", "2024-01-09T00:00:00Z")]),+ ],+ local_buckets: vec![],+ schema_columns: schema(),+ })+ .unwrap();++ let by_id: HashMap<&str, &CanonicalManifestMerge> = output.manifests.iter().map(|m| (m.manifest_id.as_str(), m)).collect();+ assert_eq!(names_of(&by_id[PERSONAL].manifest), vec!["mine"], "the personal row is untouched by the shared manifest's newer row");+ assert_eq!(names_of(&by_id[SHARED].manifest), vec!["theirs-new"]);+ assert_eq!(by_id[PERSONAL].stats.conflicts, 0);+ }++ #[test]+ fn field_values_keep_the_base_identity_on_a_semantic_match() {+ // FieldValues match on (ManifestId, ItemId, FieldKey): a winning local row minted under a+ // different Id updates the base row, which keeps its own Id.+ let field_value = |id: &str, value: &str, updated_at: &str| -> CodecRecord {+ [+ ("ManifestId".to_string(), json!(PERSONAL)),+ ("Id".to_string(), json!(id)),+ ("ItemId".to_string(), json!("item-1")),+ ("FieldKey".to_string(), json!("username")),+ ("Value".to_string(), json!(value)),+ ("UpdatedAt".to_string(), json!(updated_at)),+ ]+ .into_iter()+ .collect()+ };++ let output = merge_canonical(CanonicalMergeInput {+ server_manifests: vec![manifest(PERSONAL, [("FieldValues".to_string(), vec![field_value("fv-base", "old", "2024-01-01T00:00:00Z")])].into_iter().collect())],+ server_buckets: vec![],+ contentless_server_manifest_ids: vec![],+ local_manifests: vec![manifest(PERSONAL, [("FieldValues".to_string(), vec![field_value("fv-local", "new", "2024-01-09T00:00:00Z")])].into_iter().collect())],+ local_buckets: vec![],+ schema_columns: schema(),+ })+ .unwrap();++ let rows = &output.manifests[0].manifest.tables["FieldValues"];+ assert_eq!(rows.len(), 1);+ assert_eq!(rows[0]["Id"], json!("fv-base"), "the base row keeps its own Id");+ assert_eq!(rows[0]["Value"], json!("new"), "but carries the winning value");+ }++ #[test]+ fn bucketed_tables_merge_and_come_back_as_buckets() {+ let setting = |value: &str, updated_at: &str| -> CodecRecord {+ [+ ("ManifestId".to_string(), json!(PERSONAL)),+ ("Key".to_string(), json!("theme")),+ ("Value".to_string(), json!(value)),+ ("UpdatedAt".to_string(), json!(updated_at)),+ ]+ .into_iter()+ .collect()+ };++ let output = merge_canonical(CanonicalMergeInput {+ server_manifests: vec![items_manifest(PERSONAL, vec![])],+ server_buckets: vec![DataBucket::new(PERSONAL, "Settings", [("Settings".to_string(), vec![setting("light", "2024-01-01T00:00:00Z")])].into_iter().collect())],+ contentless_server_manifest_ids: vec![],+ local_manifests: vec![items_manifest(PERSONAL, vec![])],+ local_buckets: vec![DataBucket::new(PERSONAL, "Settings", [("Settings".to_string(), vec![setting("dark", "2024-01-09T00:00:00Z")])].into_iter().collect())],+ schema_columns: schema(),+ })+ .unwrap();++ let merged = &output.manifests[0];+ assert!(!merged.manifest.tables.contains_key("Settings"), "bucketed tables never surface in manifest.tables");+ assert_eq!(merged.buckets.len(), 1);+ assert_eq!(merged.buckets[0].category, "Settings");+ assert_eq!(merged.buckets[0].tables["Settings"][0]["Value"], json!("dark"), "the newer local setting wins inside the bucket");+ assert!(crate::vault_codec::validate_data_bucket(&merged.buckets[0]).ok);+ }++ #[test]+ fn unknown_columns_keep_the_server_value_when_local_wins() {+ // A newer client added Items.NewColumn; this client's schema does not know it. The local+ // row winning the LWW must not regress that column.+ let mut base = item(PERSONAL, "row", "server-old", "2024-01-01T00:00:00Z");+ base.insert("NewColumn".to_string(), json!("newer-client-value"));+ let mut incoming = item(PERSONAL, "row", "local-new", "2024-01-09T00:00:00Z");+ incoming.insert("NewColumn".to_string(), json!("stale-carried-value"));++ let merged = merge_single(vec![base], vec![incoming]);++ let row = &merged.manifest.tables["Items"][0];+ assert_eq!(row["Name"], json!("local-new"), "known columns follow the winner");+ assert_eq!(row["NewColumn"], json!("newer-client-value"), "unknown columns keep the base value");+ }++ #[test]+ fn unknown_tables_are_taken_from_the_server_wholesale() {+ let future_row = |payload: &str| -> CodecRecord {+ [("ManifestId".to_string(), json!(PERSONAL)), ("Id".to_string(), json!("f-1")), ("Payload".to_string(), json!(payload))].into_iter().collect()+ };+ let with_future = |payload: Option<&str>| -> Manifest {+ let mut tables: HashMap<String, Vec<CodecRecord>> = [("Items".to_string(), vec![])].into_iter().collect();+ if let Some(p) = payload {+ tables.insert("FutureTable".to_string(), vec![future_row(p)]);+ }+ manifest(PERSONAL, tables)+ };++ let output = merge_canonical(CanonicalMergeInput {+ server_manifests: vec![with_future(Some("server-version"))],+ server_buckets: vec![],+ contentless_server_manifest_ids: vec![],+ local_manifests: vec![with_future(Some("local-carried-version"))],+ local_buckets: vec![],+ schema_columns: schema(),+ })+ .unwrap();+ assert_eq!(output.manifests[0].manifest.tables["FutureTable"][0]["Payload"], json!("server-version"));++ // And a local-only unknown table is dropped, matching the discarded local carrier of today.+ let output = merge_canonical(CanonicalMergeInput {+ server_manifests: vec![with_future(None)],+ server_buckets: vec![],+ contentless_server_manifest_ids: vec![],+ local_manifests: vec![with_future(Some("local-only"))],+ local_buckets: vec![],+ schema_columns: schema(),+ })+ .unwrap();+ assert!(!output.manifests[0].manifest.tables.contains_key("FutureTable"));+ }++ #[test]+ fn local_manifest_no_longer_served_is_dropped_and_reported() {+ let output = merge_canonical(CanonicalMergeInput {+ server_manifests: vec![items_manifest(PERSONAL, vec![])],+ server_buckets: vec![],+ contentless_server_manifest_ids: vec![],+ local_manifests: vec![items_manifest(PERSONAL, vec![]), items_manifest(SHARED, vec![item(SHARED, "x", "gone", "2024-01-01T00:00:00Z")])],+ local_buckets: vec![],+ schema_columns: schema(),+ })+ .unwrap();++ assert_eq!(output.manifests.len(), 1);+ assert_eq!(output.dropped_local_manifest_ids, vec![SHARED.to_string()]);+ }++ #[test]+ fn contentless_server_manifest_passes_the_local_one_through() {+ let output = merge_canonical(CanonicalMergeInput {+ server_manifests: vec![items_manifest(PERSONAL, vec![])],+ server_buckets: vec![],+ contentless_server_manifest_ids: vec![SHARED.to_string()],+ local_manifests: vec![items_manifest(PERSONAL, vec![]), items_manifest(SHARED, vec![item(SHARED, "x", "kept-offline", "2024-01-01T00:00:00Z")])],+ local_buckets: vec![],+ schema_columns: schema(),+ })+ .unwrap();++ assert!(output.dropped_local_manifest_ids.is_empty());+ let shared = output.manifests.iter().find(|m| m.manifest_id == SHARED).unwrap();+ assert_eq!(names_of(&shared.manifest), vec!["kept-offline"]);+ assert_eq!(shared.stats.records_inserted, 1);+ }++ #[test]+ fn blob_refs_ride_through_as_opaque_values() {+ let attachment = |blob_ref: &str, updated_at: &str| -> CodecRecord {+ [+ ("ManifestId".to_string(), json!(PERSONAL)),+ ("Id".to_string(), json!("att-1")),+ ("Blob".to_string(), json!({ "__blobRef": blob_ref, "__blobKind": "attachment" })),+ ("UpdatedAt".to_string(), json!(updated_at)),+ ]+ .into_iter()+ .collect()+ };++ let output = merge_canonical(CanonicalMergeInput {+ server_manifests: vec![manifest(PERSONAL, [("Attachments".to_string(), vec![attachment("hash-old", "2024-01-01T00:00:00Z")])].into_iter().collect())],+ server_buckets: vec![],+ contentless_server_manifest_ids: vec![],+ local_manifests: vec![manifest(PERSONAL, [("Attachments".to_string(), vec![attachment("hash-new", "2024-01-09T00:00:00Z")])].into_iter().collect())],+ local_buckets: vec![],+ schema_columns: schema(),+ })+ .unwrap();++ assert_eq!(output.manifests[0].manifest.tables["Attachments"][0]["Blob"], json!({ "__blobRef": "hash-new", "__blobKind": "attachment" }));+ }++ #[test]+ fn merged_manifest_keeps_server_metadata_and_validates() {+ let mut server = items_manifest(PERSONAL, vec![item(PERSONAL, "a", "server", "2024-01-01T00:00:00Z")]);+ server.name = Some("Family".to_string());+ let local = items_manifest(PERSONAL, vec![item(PERSONAL, "b", "local", "2024-01-02T00:00:00Z")]);++ let output = merge_canonical(CanonicalMergeInput {+ server_manifests: vec![server],+ server_buckets: vec![],+ contentless_server_manifest_ids: vec![],+ local_manifests: vec![local],+ local_buckets: vec![],+ schema_columns: schema(),+ })+ .unwrap();++ let merged = &output.manifests[0].manifest;+ assert_eq!(merged.manifest_salt, SALT, "salt comes from the server manifest");+ assert_eq!(merged.name.as_deref(), Some("Family"), "name comes from the server manifest");+ let validation = crate::vault_codec::validate_manifest(merged);+ assert!(validation.ok, "merged manifest must validate: {:?}", validation.failed_rules);+ }++ #[test]+ fn manifest_pairing_is_case_insensitive() {+ let output = merge_canonical(CanonicalMergeInput {+ server_manifests: vec![items_manifest("M-PERSONAL", vec![item("M-PERSONAL", "a", "server", "2024-01-01T00:00:00Z")])],+ server_buckets: vec![],+ contentless_server_manifest_ids: vec![],+ local_manifests: vec![items_manifest("m-personal", vec![item("m-personal", "b", "local", "2024-01-02T00:00:00Z")])],+ local_buckets: vec![],+ schema_columns: schema(),+ })+ .unwrap();++ assert!(output.dropped_local_manifest_ids.is_empty(), "differently-cased ids are the same manifest");+ assert_eq!(output.manifests[0].manifest.tables["Items"].len(), 2);+ }++ #[test]+ fn unknown_category_bucket_tables_ride_through_from_the_server() {+ // A newer writer added a table inside the Settings bucket and a whole new category. The+ // known Settings rows still merge; the unknown tables ride through from the server only.+ let unknown_row: CodecRecord = [("ManifestId".to_string(), json!(PERSONAL)), ("Id".to_string(), json!("u-1"))].into_iter().collect();+ let server_settings = DataBucket::new(+ PERSONAL,+ "Settings",+ [+ ("Settings".to_string(), vec![[("ManifestId".to_string(), json!(PERSONAL)), ("Key".to_string(), json!("theme")), ("Value".to_string(), json!("light")), ("UpdatedAt".to_string(), json!("2024-01-01T00:00:00Z"))].into_iter().collect()]),+ ("SettingsExtras".to_string(), vec![unknown_row.clone()]),+ ]+ .into_iter()+ .collect(),+ );+ let local_future = DataBucket::new(PERSONAL, "FutureCategory", [("FutureRows".to_string(), vec![unknown_row])].into_iter().collect());++ let output = merge_canonical(CanonicalMergeInput {+ server_manifests: vec![items_manifest(PERSONAL, vec![])],+ server_buckets: vec![server_settings],+ contentless_server_manifest_ids: vec![],+ local_manifests: vec![items_manifest(PERSONAL, vec![])],+ local_buckets: vec![local_future],+ schema_columns: schema(),+ })+ .unwrap();++ let buckets = &output.manifests[0].buckets;+ let categories: Vec<&str> = buckets.iter().map(|b| b.category.as_str()).collect();+ assert!(categories.contains(&"Settings"), "the known Settings rows still come back as a bucket");+ assert!(buckets.iter().any(|b| b.category == "Settings" && b.tables.contains_key("SettingsExtras")), "the server's unknown bucket table rides through under its category");+ assert!(!categories.contains(&"FutureCategory"), "a local-only unknown bucket is dropped with the rest of the local carrier");+ }+}diff --git a/core/rust/src/vault_merge/mod.rs b/core/rust/src/vault_merge/mod.rsindex 35b87bfbf..6eac0ed0e 100644--- a/core/rust/src/vault_merge/mod.rs+++ b/core/rust/src/vault_merge/mod.rs@@ -3,6 +3,7 @@//! This module provides the core merge functionality that works on JSON table data.//! It generates SQL statements that clients can execute directly on their local database.+mod canonical;mod types;use chrono::{DateTime, Utc};@@ -10,6 +11,7 @@ use serde::{Deserialize, Serialize};use std::collections::HashMap;use crate::error::VaultResult;+pub use canonical::{merge_canonical, merge_canonical_json, CanonicalManifestMerge, CanonicalMergeInput, CanonicalMergeOutput};pub use types::SYNCABLE_TABLE_NAMES;pub use types::{merge_table_names, SYNCABLE_TABLES, TableConfig};diff --git a/core/rust/src/wasm.rs b/core/rust/src/wasm.rsindex 9c06d9516..ec40c925a 100644--- a/core/rust/src/wasm.rs+++ b/core/rust/src/wasm.rs@@ -10,7 +10,7 @@ use crate::password_generator::{available_languages, generate_password};use crate::vault_codec::{self, CanonicalizeInput, DataBucket, ExtractBucketsInput, Manifest, MaterializeInput,};-use crate::vault_merge::{merge_vaults, MergeInput, MergeOutput};+use crate::vault_merge::{merge_canonical, merge_vaults, CanonicalMergeInput, CanonicalMergeOutput, MergeInput, MergeOutput};use crate::vault_sharing::{self, ManifestAccessRequest, ManifestWriteSetRequest};use crate::vault_pruner::{prune_vault, PruneInput, PruneOutput};@@ -48,7 +48,9 @@ pub fn get_syncable_table_names() -> Vec<String> {/// Merge vaults using LWW strategy.///-/// Takes a JsValue (MergeInput) and returns a JsValue (MergeOutput).+/// Takes a JsValue (MergeInput) and returns a JsValue (MergeOutput). Serialized via `codec_to_js`+/// so `{ __b64 }` byte params survive as plain objects (the default serializer would render them+/// as JS Maps) and null params reach sql.js as null.#[wasm_bindgen(js_name = mergeVaults)]pub fn merge_vaults_js(input: JsValue) -> Result<JsValue, JsValue> {let input: MergeInput = serde_wasm_bindgen::from_value(input)@@ -57,8 +59,7 @@ pub fn merge_vaults_js(input: JsValue) -> Result<JsValue, JsValue> {let output: MergeOutput = merge_vaults(input).map_err(|e| JsValue::from_str(&format!("Merge failed: {}", e)))?;- serde_wasm_bindgen::to_value(&output)- .map_err(|e| JsValue::from_str(&format!("Failed to serialize output: {}", e)))+ codec_to_js(&output)}/// Merge vaults using JSON strings (alternative API).@@ -70,6 +71,21 @@ pub fn merge_vaults_json_js(input_json: &str) -> Result<String, JsValue> {.map_err(|e| JsValue::from_str(&format!("Merge failed: {}", e)))}+/// Merge the local canonical vault onto the server canonical vault (manifest-v1 format).+///+/// Takes a JsValue (CanonicalMergeInput) and returns a JsValue (CanonicalMergeOutput): the merged+/// manifests + data buckets, one entry per server manifest, rows out instead of SQL statements.+#[wasm_bindgen(js_name = mergeCanonical)]+pub fn merge_canonical_js(input: JsValue) -> Result<JsValue, JsValue> {+ let input: CanonicalMergeInput = serde_wasm_bindgen::from_value(input)+ .map_err(|e| JsValue::from_str(&format!("Failed to parse canonical merge input: {}", e)))?;++ let output: CanonicalMergeOutput = merge_canonical(input)+ .map_err(|e| JsValue::from_str(&format!("Canonical merge failed: {}", e)))?;++ codec_to_js(&output)+}+// ═══════════════════════════════════════════════════════════════════════════════// Vault Pruner WASM Bindings// ═══════════════════════════════════════════════════════════════════════════════