hakodb 0.21.2

Embedded & Cloud-native Document Engine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
//! sync_core: transport-independent sync primitives (0.9.0).
//!
//! `net_sync` (TCP mesh) and `cloud_sync` (WS star) duplicated this logic
//! op-by-op; `socket_sync` is the third consumer. Anything here must stay
//! free of transport, timers, and I/O — pure functions over WAL ops plus
//! the shared echo-cache discipline. Behavioral changes here ripple to
//! every topology, so keep it boring and tested.
//!
//! Deliberately NOT extracted (yet): the tail loops themselves (offset
//! bookkeeping differs: DB-persisted vs in-memory), blob inflation
//! (resolve paths differ), and cloud framing (msgpack over WS — a different
//! wire). Length-prefix framing IS shared below (`frame_bytes`, `MAX_FRAME`)
//! by the TCP mesh and unix-socket planes; the async send/recv halves live
//! in `sync_frame` (tokio-gated) so this module stays tokio-free and
//! compilable in minimal builds.

use std::collections::HashMap;
use std::sync::{Arc, Mutex, RwLock};
use std::sync::atomic::Ordering;

use crate::document::hako_doc::HakoDoc;
use crate::document::value::Value;
use crate::engine::engine::IndexList;
use crate::engine::{ChangeEvent, ChangeKind, Hako};
use crate::storage::blob::BlobWork;
use crate::storage::engine::{Pointer, StorageEngine};
use crate::storage::wal::WalOp;

/// Logical timestamp carried by a WAL op: the `_time` prefix of inlined
/// values (Version 3 layout: magic(1) ver(1) time(8)) or the delete marker.
/// Anything else (tx markers, segment/blob pointers, short/corrupt values)
/// carries none → 0 and is never echo-matched. One deliberate deviation
/// from the three inlined copies it replaces: they sliced `value[2..10]`
/// directly (panic on a short value, killing the tailer thread); this
/// falls through to 0 instead — the op still replicates, only the echo
/// match is skipped. Fail-open on corrupt tails, never thread death.
pub fn op_logical_time(op: &WalOp) -> i64 {
    match op {
        WalOp::PutInlined { value, .. } => value
            .get(2..10)
            .and_then(|s| s.try_into().ok())
            .map(i64::from_le_bytes)
            .unwrap_or(0),
        WalOp::Delete { timestamp, .. } => *timestamp,
        _ => 0,
    }
}

/// Fail-closed frame cap for the length-prefix planes (mesh TCP, unix
/// socket): a corrupt length prefix fails the connection, never allocates
/// the box. Snapshots bigger than this fail the peer, not the process.
pub const MAX_FRAME: usize = 256 * 1024 * 1024;

/// Frame already-serialized bytes (u32-LE length + payload), pure and
/// transport-free; the caller serializes (bincode on both planes today).
/// Rejects empty and over-cap payloads — the mesh previously sent/received
/// uncapped, so a corrupt prefix could allocate gigabytes.
pub fn frame_bytes(data: &[u8]) -> std::io::Result<Vec<u8>> {
    if data.is_empty() || data.len() > MAX_FRAME {
        return Err(std::io::Error::new(
            std::io::ErrorKind::InvalidData,
            "bad frame length",
        ));
    }
    let mut frame = Vec::with_capacity(4 + data.len());
    frame.extend_from_slice(&(data.len() as u32).to_le_bytes());
    frame.extend_from_slice(data);
    Ok(frame)
}

/// Echo discipline, shared: an op we just ingested from a peer must not
/// bounce straight back out. Check-and-REMOVE on hit (a lingering entry
/// would swallow a later legitimate same-timestamp write). The caller
/// computes the cache key (raw key on mesh, room-prefixed on cloud) —
/// the take itself is identical everywhere.
pub fn echo_take(cache: &Mutex<HashMap<String, i64>>, key: &str, ts: i64) -> bool {
    let mut cache = cache.lock().unwrap();
    if let Some(&cached_ts) = cache.get(key) {
        if cached_ts == ts {
            cache.remove(key);
            return true;
        }
    }
    false
}

/// Shared ingest: apply one batch of replicated ops (any transport) with
/// LWW conflict resolution, echo-cache insert, WAL commit (remote: skip
/// fsync), index + watcher notification. Ported verbatim from the mesh
/// ingest — `net_sync` calls this now, `socket_sync` reuses it, cloud
/// keeps its own (different batching/flush architecture, out of scope).
/// Transport differences live ABOVE (framing) and BELOW (none) this fn.
pub async fn apply_replicated_batch(
    db: Arc<Hako>,
    collection: String,
    ops: Vec<WalOp>,
    echo_cache: Arc<Mutex<HashMap<String, i64>>>,
) {
    // Local-only signal (inbound): a locally-scoped collection refuses
    // everything offered. Per-key marks do NOT filter inbound — a
    // genuinely newer remote put still resurrects (documented rule).
    if db.is_collection_local(&collection) {
        return;
    }
    let shard_arc = match db.get_shard(&collection) {
        Ok(s) => s,
        Err(e) => {
            // Serious: data arrived but the local shard is unreadable.
            eprintln!("[sync] CRITICAL: Cannot apply replication to {}. Shard error: {}", collection, e);
            return;
        }
    };
    let threshold = db.config.value_blob_threshold_bytes;

    let mut accepted_ops = Vec::new();
    let mut affected_keys = Vec::new();
    let mut index_puts = Vec::new();
    let mut blob_work_items = Vec::new();

    // 1. PHASE 1: PREPARE AND CONFLICT RESOLUTION
    {
        // Read lock first to check timestamps (LWW).
        let shard_read = shard_arc.read().unwrap();
        let echo_cache_clone = echo_cache.clone();

        for op in ops {
            let (key, mut doc, is_delete, remote_ts) = match op {
                WalOp::PutInlined { ref key, ref value } => {
                    if let Some(d) = HakoDoc::decode(value) {
                        let ts = d.get_logical_time();
                        (key.clone(), d, false, ts)
                    } else { continue; }
                }
                WalOp::Delete { ref key, timestamp } => {
                    (key.clone(), HakoDoc::default(), true, timestamp)
                }
                _ => continue,
            };

            // LWW: only apply when strictly newer than local.
            if let Some(local_ptr) = shard_read.index.get(&key) {
                let local_ts = match local_ptr {
                    Pointer::Deleted { timestamp } => *timestamp,
                    Pointer::Inlined(bytes) => i64::from_le_bytes(bytes[2..10].try_into().unwrap_or([0; 8])),
                    _ => {
                        shard_read.read_pointer_internal(local_ptr, false)
                            .ok().flatten()
                            .and_then(|b| HakoDoc::decode(&b))
                            .map(|d| d.get_logical_time())
                            .unwrap_or(0)
                    }
                };
                if remote_ts <= local_ts { continue; }
            }

            if is_delete {
                {
                    let mut cache = echo_cache_clone.lock().unwrap();
                    cache.insert(key.clone(), remote_ts);
                }
                accepted_ops.push(WalOp::Delete { key: key.clone(), timestamp: remote_ts });
                index_puts.push((key.clone(), None)); // None signals delete below
                // Deletes bump versions too: Hako::get serves from doc_cache
                // on version match, so an unbumped delete leaves the live
                // doc cached FOREVER (stale reads after replicated deletes).
                affected_keys.push(key.into());
                // Hybrid-clock watermark (issue #80): accepted remote ts
                // raises the floor so local stamps never go backwards.
                db.observe_remote_ts(remote_ts);
            } else {
                let ts = doc.get_logical_time();
                {
                    let mut cache = echo_cache_clone.lock().unwrap();
                    cache.insert(key.clone(), ts);
                }
                // RE-EXTRACT BLOBS: sender sent a full doc but it's large —
                // extract locally on the receiver to save segment space.
                if let Some(bm) = &shard_read.blob_manager {
                    let extracted = bm.extract_blobs_raw(&collection, &key, &mut doc, threshold);
                    for b in extracted {
                        blob_work_items.push(b);
                    }
                }

                let skeleton_bytes = doc.encode();
                accepted_ops.push(WalOp::PutInlined { key: key.clone(), value: skeleton_bytes });
                index_puts.push((key.clone(), Some(doc)));
                affected_keys.push(key.into());
                // Hybrid-clock watermark (issue #80): see the delete arm.
                db.observe_remote_ts(ts);
            }
        }
    } // Read lock dropped.

    if accepted_ops.is_empty() { return; }

    // 2. PHASE 2: PHYSICAL COMMIT (receiver shard).
    {
        let mut shard = shard_arc.write().unwrap();

        // A. WAL commit (remote: skip fsync).
        let tx_id = shard.next_tx_id;
        shard.next_tx_id += 1;
        let _ = shard.wal.append_batch_fast(tx_id, &accepted_ops, true);

        // B. Index update.
        // ponytail (#151): batched sorted-view maintenance, flushed before
        // the shard write lock drops at the end of this block.
        let mut pending_sorted = Vec::new();
        for (key, doc_opt) in index_puts {
            if let Some(doc) = doc_opt {
                // Blob-extracted docs stay pending.
                let has_blob = blob_work_items.iter().any(|b| {
                    if let BlobWork::PutRaw { key: k, .. } = b { k == &key } else { false }
                });

                if has_blob {
                    shard.update_index_entry_deferred(key, Some(Pointer::BlobPending(Arc::new(doc))), &mut pending_sorted);
                } else {
                    shard.update_index_entry_deferred(key, Some(Pointer::Inlined(Arc::new(doc.encode()))), &mut pending_sorted);
                }
            } else {
                // Delete: find its timestamp from the accepted batch.
                let ts = accepted_ops.iter().find_map(|o| {
                    if let WalOp::Delete { key: k, timestamp } = o {
                        if k == &key { return Some(*timestamp); }
                    }
                    None
                }).unwrap_or(0);
                shard.update_index_entry_deferred(key, Some(Pointer::Deleted { timestamp: ts }), &mut pending_sorted);
            }
        }
        shard.flush_pending_sorted(&mut pending_sorted);

        // C. Queue blobs for the receiver's blob worker.
        let mut total_bytes = 0;
        for b in blob_work_items {
            if let BlobWork::PutRaw { len, .. } = &b { total_bytes += *len as usize; }
            shard.blob_flush_queue.push_back(b);
        }
        shard.total_pending_blob_bytes.fetch_add(total_bytes, Ordering::Relaxed);

        // Wake the receiver's blob worker.
        db.trigger_blob_flush.store(true, Ordering::Release);
    }

    // 3. PHASE 3: NOTIFY LOCAL SYSTEM.
    db.bump_versions_by_keys(affected_keys);

    // 4. PHASE 4: hand to the indexer.
    let index_docs: Vec<(String, Arc<HakoDoc>)> = accepted_ops.iter().filter_map(|op| {
        if let WalOp::PutInlined { key, value } = op {
            // Naked ID from "col:id" form, else the key as-is.
            let doc_id = key.split_once(':')
                .map(|(_, id)| id.to_string())
                .unwrap_or_else(|| key.clone());

            // Decode and wrap in Arc immediately.
            HakoDoc::decode(value).map(|d| (doc_id, Arc::new(d)))
        } else {
            None
        }
    }).collect();

    if !index_docs.is_empty() {
        // Send the batch to the persistent index worker.
        db.enqueue_index_update(collection.clone(), Arc::new(index_docs), vec![]);
    }

    // 5. PHASE 5: notify watchers (the tailer skips re-broadcast:
    // key/timestamp sits in the echo cache now).
    for op in &accepted_ops {
        let kind = match op {
            WalOp::PutInlined { .. } => ChangeKind::Put,
            WalOp::Delete { .. } => ChangeKind::Delete,
            _ => continue,
        };

        let event = ChangeEvent {
            path: Arc::from(op.get_key()),
            kind,
        };

        db.notify_watchers(&collection, event);
    }
}

/// Apply a peer's advertised index defs locally (issue #51). Shared by
/// every plane that carries defs (mesh Ping, socket IndexDefs, cloud
/// VersionPing): secondary/FTS/composite create arms plus vector.
/// Vector defs travel; graphs rebuild locally via the create backfill
/// (never on the wire, by design). The vector arm is guarded —
/// re-creating on every packet would restart backfills + invalidate the
/// plan cache network-wide for zero benefit. Pure (no sockets): the mesh
/// unit test covers the logic for all planes.
pub(crate) fn apply_peer_index_defs(db: &Arc<Hako>, indexes: &IndexList) {
    for (col, fields) in &indexes.secondary {
        for field in fields {
            // db.create_index is internal-idempotent (it won't recreate if exists)
            let _ = db.create_index(col, field);
        }
    }

    for (col, fields) in &indexes.fts {
        for field in fields {
            let _ = db.create_fts_index(col, field);
        }
    }

    use crate::index::composite::definition::SortDirection;
    for comp in &indexes.composite {
        let fields: Vec<(String, SortDirection)> = comp.fields.iter().map(|f| {
            let dir = if f.direction == "desc" { SortDirection::Desc } else { SortDirection::Asc };
            (f.field.clone(), dir)
        }).collect();

        // This registers the index and starts background backfilling
        let _ = db.create_composite_index(&comp.collection, fields);
    }

    {
        let known: std::collections::HashSet<(String, String, u32, String)> = db
            .list_indexes(None)
            .vector
            .into_iter()
            .flat_map(|(col, defs)| {
                defs.into_iter().map(move |d| (col.clone(), d.field, d.dim, d.metric))
            })
            .collect();
        for (col, defs) in &indexes.vector {
            for def in defs {
                if known.contains(&(col.clone(), def.field.clone(), def.dim, def.metric.clone())) {
                    continue;
                }
                let metric = match def.metric.as_str() {
                    "l2" => crate::index::vector::Metric::L2,
                    _ => crate::index::vector::Metric::Cosine,
                };
                let _ = db.create_vector_index(col, &def.field, def.dim, metric);
            }
        }
    }

    // 5. Sync traverse targets (issue #53): tracked sets converge;
    // backlink edges rebuild locally through hooks (never on the wire).
    // Idempotent by construction (track is a set insert — repeated Pings
    // cost one lookup, never a backfill storm; creation backfill runs
    // only on first track).
    for col in &indexes.traverse {
        let _ = db.create_traverse_index(col);
    }
}

/// Send-side blob inflation, shared: turn any WAL op into full wire bytes.
/// Segment/blob pointers resolve from disk; skeleton docs with BlobLinks
/// inflate via the blob manager (receivers can't use our file offsets).
/// Returns None when the bytes can't be materialized (caller skips, except
/// deletes which pass through). Ported from the mesh resolver — `net_sync`
/// calls this now, `socket_sync` reuses it.
pub fn resolve_send_bytes(
    shard_arc: &Arc<RwLock<StorageEngine>>,
    db: &Arc<Hako>,
    op: &WalOp,
) -> Option<Vec<u8>> {
    // 1. Raw bytes (skeleton) from the WAL op.
    let bytes = match op {
        WalOp::PutInlined { value, .. } => value.clone(),
        WalOp::Put { segment_id, segment_offset, len, .. } => {
            let ptr = Pointer::Segment { segment_id: *segment_id, offset: *segment_offset, len: *len };
            shard_arc.read().unwrap().read_pointer_internal(&ptr, false).ok().flatten()?
        }
        WalOp::PutBlob { offset, len, .. } => {
            let ptr = Pointer::Blob { offset: *offset, len: *len };
            shard_arc.read().unwrap().read_pointer_internal(&ptr, false).ok().flatten()?
        }
        _ => return None,
    };

    // 2. Decode to check for BlobLinks.
    if let Some(mut doc) = HakoDoc::decode(&bytes) {
        let has_links = doc.fields.iter().any(|(_, v)| matches!(v, Value::BlobLink { .. }));

        if has_links {
            // INFLATE: file offsets become real bytes on the wire.
            let encryption_key = db.config.encryption_key.as_deref();
            if crate::engine::engine::resolve_doc_static(&mut doc, shard_arc, encryption_key).is_ok() {
                return Some(doc.encode_buffered());
            }
            return None;
        }
    }

    Some(bytes)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn op_time_decode_matches_tailers() {
        // PutInlined: magic, ver, LE time.
        let mut v = vec![3u8, 3u8];
        v.extend_from_slice(&12345678i64.to_le_bytes());
        v.extend_from_slice(&[9u8; 4]);
        let op = WalOp::PutInlined { key: "k".into(), value: v };
        assert_eq!(op_logical_time(&op), 12345678);
        // Short values fall through to 0 (never echo-matched).
        let op = WalOp::PutInlined { key: "k".into(), value: vec![1, 2, 3] };
        assert_eq!(op_logical_time(&op), 0);
        // Deletes carry their marker.
        let op = WalOp::Delete { key: "k".into(), timestamp: 999 };
        assert_eq!(op_logical_time(&op), 999);
        // Markers carry nothing.
        let op = WalOp::BeginTx { tx_id: 7 };
        assert_eq!(op_logical_time(&op), 0);
    }

    #[test]
    fn frame_bytes_roundtrip_and_caps() {
        // Layout: u32-LE length + payload.
        let f = frame_bytes(&[7u8, 8, 9]).unwrap();
        assert_eq!(&f[..4], &3u32.to_le_bytes());
        assert_eq!(&f[4..], &[7u8, 8, 9]);
        // Fail closed: empty and over-cap never frame (mesh previously
        // received uncapped — a corrupt prefix could allocate gigabytes).
        assert!(frame_bytes(&[]).is_err());
        assert!(frame_bytes(&vec![0u8; MAX_FRAME + 1]).is_err());
        assert!(frame_bytes(&vec![0u8; MAX_FRAME]).is_ok());
    }

    #[test]
    fn echo_take_removes_on_hit_only() {
        let cache = Mutex::new(HashMap::from([("k".to_string(), 42i64)]));
        assert!(echo_take(&cache, "k", 42));
        // Removed: second take misses.
        assert!(!echo_take(&cache, "k", 42));
        // Wrong timestamp: kept, misses.
        cache.lock().unwrap().insert("j".into(), 7);
        assert!(!echo_take(&cache, "j", 8));
        assert!(cache.lock().unwrap().contains_key("j"));
        // Unknown key: miss.
        assert!(!echo_take(&cache, "?", 0));
    }

    /// Shared ingest contract (guards net_sync's rewire + socket_sync):
    /// stale remote loses, newer wins, deletes tombstone, echo fills.
    #[tokio::test]
    async fn ingest_lww_delete_echo() {
        use crate::config::{DurabilityMode, HakoConfig};
        use crate::document::value::Value;

        let nanos = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_nanos();
        let dir = std::env::temp_dir().join(format!("hako-ingest-{nanos}"));
        let mut cfg = HakoConfig::default();
        cfg.durability_mode = DurabilityMode::Manual;
        let db = std::sync::Arc::new(Hako::open(&dir, cfg).expect("open"));

        fn doc_with_time(v: &str, ts: i64) -> Vec<u8> {
            let mut d = HakoDoc::default();
            d.insert("v", Value::String(v.into()));
            d._time = ts;
            d.encode()
        }

        // Local baseline via the normal path.
        let mut local = HakoDoc::default();
        local.insert("v", Value::String("local".into()));
        db.put_owned("c", "k", local).expect("put");
        let t0 = db.get("c", "k").expect("get").expect("doc").get_logical_time();

        let echo = Arc::new(Mutex::new(HashMap::new()));

        // Stale remote put loses (older than local).
        apply_replicated_batch(
            db.clone(),
            "c".into(),
            vec![WalOp::PutInlined { key: "k".into(), value: doc_with_time("stale", 1) }],
            echo.clone(),
        )
        .await;
        assert_eq!(db.get("c", "k").expect("get2").expect("doc2").get("v"), Some(&Value::String("local".into())));

        // Newer remote put wins.
        apply_replicated_batch(
            db.clone(),
            "c".into(),
            vec![WalOp::PutInlined { key: "k".into(), value: doc_with_time("new", i64::MAX) }],
            echo.clone(),
        )
        .await;
        let doc = db.get("c", "k").expect("get3").expect("doc3");
        assert_eq!(doc.get("v"), Some(&Value::String("new".into())));
        // Winner lands in the echo cache (tailers won't rebroadcast it).
        assert!(echo.lock().unwrap().contains_key("k"));

        // Stale delete loses to the live newer doc.
        apply_replicated_batch(
            db.clone(),
            "c".into(),
            vec![WalOp::Delete { key: "k".into(), timestamp: t0 }],
            echo.clone(),
        )
        .await;
        assert!(db.get("c", "k").expect("get4").is_some());

        // Newer delete tombstones (fresh key: local time is real, delete is MAX).
        let mut local2 = HakoDoc::default();
        local2.insert("v", Value::String("two".into()));
        db.put_owned("c", "k2", local2).expect("put2");
        apply_replicated_batch(
            db.clone(),
            "c".into(),
            vec![WalOp::Delete { key: "k2".into(), timestamp: i64::MAX }],
            echo.clone(),
        )
        .await;
        assert!(db.get("c", "k2").expect("get5").is_none());

        std::fs::remove_dir_all(&dir).ok();
    }

    /// Blob regression for the shared send/receive primitives: the sender
    /// inflates its BlobLink, the receiver re-extracts it (never trusting
    /// the sender's file offsets), and both point reads and get_json resolve
    /// the same bytes after a restart.
    #[tokio::test]
    async fn replicated_blob_round_trips_and_resolves() {
        use crate::config::{DurabilityMode, HakoConfig};
        use crate::document::value::Value;

        let nanos = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_nanos();
        let src_dir = std::env::temp_dir().join(format!("hako-sync-blob-src-{nanos}"));
        let dst_dir = std::env::temp_dir().join(format!("hako-sync-blob-dst-{nanos}"));
        let cfg = HakoConfig {
            durability_mode: DurabilityMode::Manual,
            value_blob_threshold_bytes: 1024,
            ..Default::default()
        };
        let src = Arc::new(Hako::open(&src_dir, cfg.clone()).expect("open src"));
        let dst = Arc::new(Hako::open(&dst_dir, cfg.clone()).expect("open dst"));

        let payload = "x".repeat(4096);
        let mut doc = HakoDoc::default();
        doc.insert("small", Value::String("ok".into()));
        doc.insert("payload", Value::String(payload.clone()));
        src.put_owned("c", "k", doc).expect("put");

        // Source stores a skeleton + blob; the wire copy must carry bytes.
        let view = src.get_view("c", "k").expect("view").expect("doc");
        assert!(view.has_blob_links(), "source must store a BlobLink");
        let expected = src.get("c", "k").expect("get").expect("doc");
        assert_eq!(expected.get("payload"), Some(&Value::String(payload.clone())));

        let shard = src.get_shard("c").expect("shard");
        let op = WalOp::PutInlined { key: "k".into(), value: view.as_bytes().to_vec() };
        let wire = resolve_send_bytes(&shard, &src, &op).expect("inflate source blob");
        let wire_doc = HakoDoc::decode(&wire).expect("wire decodes");
        assert_eq!(wire_doc.get("payload"), Some(&Value::String(payload)));

        apply_replicated_batch(
            dst.clone(),
            "c".into(),
            vec![WalOp::PutInlined { key: "k".into(), value: wire }],
            Arc::new(Mutex::new(HashMap::new())),
        )
        .await;

        // Receiver must re-extract locally, not keep the sender's link.
        let dst_view = dst.get_view("c", "k").expect("dst view").expect("dst doc");
        assert!(dst_view.has_blob_links(), "receiver must re-extract the blob");

        let expected_json = expected.to_json_bytes();
        let (time, json) = dst.get_json("c", "k").expect("dst get_json").expect("dst json");
        assert_eq!(time, expected._time);
        assert_eq!(json, expected_json);

        // Graceful close drains the queue; reopen proves the WAL skeleton and
        // blob file survived together.
        drop(dst);
        let dst = Arc::new(Hako::open(&dst_dir, cfg).expect("reopen dst"));
        let reopened = dst.get("c", "k").expect("reopened get").expect("reopened doc");
        assert_eq!(reopened.to_json_bytes(), expected_json);
        let (time, json) = dst.get_json("c", "k").expect("reopened get_json").expect("reopened json");
        assert_eq!(time, expected._time);
        assert_eq!(json, expected_json);

        std::fs::remove_dir_all(&src_dir).ok();
        std::fs::remove_dir_all(&dst_dir).ok();
    }
}