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
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
open Lwt.Syntax
let = 24
let frame_meta_bytes = 24
let frame_size_bytes = frame_meta_bytes + Geometry.default.page_size
let wal_magic = 0x57414C35_00000000L
type frame =
{ frame_idx : int
; page_id : int64
; is_commit : bool
; page : Cstruct.t
}
type error =
| Block_error of string
| Corrupt_frame of int
let pp_error fmt = function
| Block_error s -> Format.fprintf fmt "Block_error(%s)" s
| Corrupt_frame i -> Format.fprintf fmt "Corrupt_frame(idx=%d)" i
;;
type t =
{ read_at : offset:int64 -> Cstruct.t -> (unit, string) result Lwt.t
; write_at : offset:int64 -> Cstruct.t -> (unit, string) result Lwt.t
; sync : unit -> (unit, string) result Lwt.t
; page_size : int (** page bytes per frame (#95); matches the main DB geometry *)
; frame_size : int (** [frame_meta_bytes + page_size + cipher_overhead] *)
; cipher : Crypto.t option
(** When [Some c], frame payloads are AES-256-GCM encrypted. *)
; cipher_overhead : int (** 0 or [Crypto.overhead] depending on [cipher]. *)
; mutable size_bytes : int64
;
salt : int64
; seed : int64
; mutable committed_frames : int
; index : (int64, int list) Hashtbl.t
;
mutable sync_count : int
;
mutable epoch : int64
; frame_cache : (int, Cstruct.t) Hashtbl.t
;
frame_cache_fifo : int Queue.t
; frame_cache_capacity : int
}
let default_frame_cache_capacity =
match Sys.getenv_opt "GRANARY_WAL_FRAME_CACHE" with
| Some s ->
(match int_of_string_opt s with
| Some n when n >= 0 -> n
| _ -> 1024)
| None -> 1024
;;
let committed_frames t = t.committed_frames
let sync_count t = t.sync_count
let epoch t = t.epoch
let salt t = t.salt
let seed t = t.seed
let pp fmt t =
Format.fprintf
fmt
"@[<hv>Wal.t { committed_frames = %d;@ size_bytes = %Ld }@]"
t.committed_frames
t.size_bytes
;;
let find_page t pid =
match Hashtbl.find_opt t.index pid with
| None | Some [] -> None
| Some (idx :: _) -> Some idx
;;
let find_page_at t pid ~max_frame =
match Hashtbl.find_opt t.index pid with
| None -> None
| Some lst ->
let rec scan = function
| [] -> None
| idx :: rest -> if idx < max_frame then Some idx else scan rest
in
scan lst
;;
let iter_index t f =
Hashtbl.iter
(fun pid lst ->
match lst with
| [] -> ()
| idx :: _ -> f pid idx)
t.index
;;
let fnv64_offset = 0xCBF29CE484222325L
let fnv64_prime = 0x00000100000001B3L
let fnv64_update_byte h b =
let h' = Int64.logxor h (Int64.of_int (b land 0xff)) in
Int64.mul h' fnv64_prime
;;
let fnv64_update_int64 h x =
let h = ref h in
for i = 7 downto 0 do
h := fnv64_update_byte !h (Int64.to_int (Int64.shift_right_logical x (i * 8)))
done;
!h
;;
let fnv64_update_cstruct h c =
let len = Cstruct.length c in
let h = ref h in
for i = 0 to len - 1 do
h := fnv64_update_byte !h (Char.code (Cstruct.get_char c i))
done;
!h
;;
let frame_checksum ~salt ~seed ~page_id ~flags ~page =
let h = fnv64_offset in
let h = fnv64_update_int64 h salt in
let h = fnv64_update_int64 h seed in
let h = fnv64_update_int64 h page_id in
let h = fnv64_update_int64 h flags in
fnv64_update_cstruct h page
;;
let ~write_at ~sync =
let salt = Random.int64 Int64.max_int in
let seed = Random.int64 Int64.max_int in
let hdr = Cstruct.create header_size_bytes in
Cstruct.BE.set_uint64 hdr 0 wal_magic;
Cstruct.BE.set_uint64 hdr 8 salt;
Cstruct.BE.set_uint64 hdr 16 seed;
let* r = write_at ~offset:0L hdr in
match r with
| Error s -> Lwt.return_error (Block_error s)
| Ok () ->
let* s = sync () in
(match s with
| Error s -> Lwt.return_error (Block_error s)
| Ok () -> Lwt.return_ok (salt, seed))
;;
let ~read_at =
let hdr = Cstruct.create header_size_bytes in
let* r = read_at ~offset:0L hdr in
match r with
| Error s -> Lwt.return_error (Block_error s)
| Ok () ->
let magic = Cstruct.BE.get_uint64 hdr 0 in
if Int64.equal magic wal_magic
then (
let salt = Cstruct.BE.get_uint64 hdr 8 in
let seed = Cstruct.BE.get_uint64 hdr 16 in
Lwt.return_ok (Some (salt, seed)))
else Lwt.return_ok None
;;
let frame_offset t idx =
Int64.add
(Int64.of_int header_size_bytes)
(Int64.mul (Int64.of_int idx) (Int64.of_int t.frame_size))
;;
let read_frame_raw ?(verify = true) t idx =
let off = frame_offset t idx in
let last_byte = Int64.add off (Int64.of_int t.frame_size) in
if Int64.compare last_byte t.size_bytes > 0
then Lwt.return_ok None
else (
let buf = Cstruct.create t.frame_size in
let* r = t.read_at ~offset:off buf in
match r with
| Error s -> Lwt.return_error (Block_error s)
| Ok () ->
let page_id = Cstruct.BE.get_uint64 buf 0 in
let flags = Cstruct.BE.get_uint64 buf 8 in
let payload_len = t.page_size + t.cipher_overhead in
let payload = Cstruct.sub buf frame_meta_bytes payload_len in
let ok =
if verify
then (
let ck_have = Cstruct.BE.get_uint64 buf 16 in
let ck_want =
frame_checksum ~salt:t.salt ~seed:t.seed ~page_id ~flags ~page:payload
in
Int64.equal ck_have ck_want)
else true
in
if ok
then (
let is_commit = Int64.logand flags 1L <> 0L in
match t.cipher with
| None ->
let page_copy = Cstruct.create t.page_size in
Cstruct.blit payload 0 page_copy 0 t.page_size;
Lwt.return_ok (Some { frame_idx = idx; page_id; is_commit; page = page_copy })
| Some c ->
(match Crypto.decrypt_frame c ~page_id payload with
| Error `Tag_mismatch ->
Lwt.return_error (Corrupt_frame idx)
| Ok page_copy ->
Lwt.return_ok
(Some { frame_idx = idx; page_id; is_commit; page = page_copy })))
else Lwt.return_ok None)
;;
let recover_index t =
let pending : (int64, int) Hashtbl.t = Hashtbl.create 16 in
let last_commit_idx = ref (-1) in
let stop = ref false in
let idx = ref 0 in
let rec loop () =
if !stop
then Lwt.return_ok ()
else
let* r = read_frame_raw t !idx in
match r with
| Error e -> Lwt.return_error e
| Ok None ->
stop := true;
Lwt.return_ok ()
| Ok (Some f) ->
Hashtbl.replace pending f.page_id !idx;
if f.is_commit
then (
Hashtbl.iter
(fun k v ->
let prev = Option.value ~default:[] (Hashtbl.find_opt t.index k) in
Hashtbl.replace t.index k (v :: prev))
pending;
Hashtbl.reset pending;
last_commit_idx := !idx);
incr idx;
loop ()
in
let* r = loop () in
match r with
| Error e -> Lwt.return_error e
| Ok () ->
t.committed_frames <- !last_commit_idx + 1;
Lwt.return_ok ()
;;
let open_
?(cipher = None)
?(page_size = Geometry.default.page_size)
?(frame_cache_capacity = default_frame_cache_capacity)
~read_at
~write_at
~sync
~size_bytes
()
=
let cipher_overhead =
match cipher with
| Some _ -> Crypto.overhead
| None -> 0
in
let frame_size = frame_meta_bytes + page_size + cipher_overhead in
if Int64.compare size_bytes (Int64.of_int header_size_bytes) < 0
then
let* r = init_header ~write_at ~sync in
match r with
| Error e -> Lwt.return_error e
| Ok (salt, seed) ->
Lwt.return_ok
{ read_at
; write_at
; sync
; page_size
; frame_size
; cipher
; cipher_overhead
; size_bytes
; salt
; seed
; committed_frames = 0
; sync_count = 0
; epoch = 0L
; index = Hashtbl.create 64
; frame_cache = Hashtbl.create 64
; frame_cache_fifo = Queue.create ()
; frame_cache_capacity
}
else
let* hr = read_header ~read_at in
match hr with
| Error e -> Lwt.return_error e
| Ok None ->
let* r = init_header ~write_at ~sync in
(match r with
| Error e -> Lwt.return_error e
| Ok (salt, seed) ->
Lwt.return_ok
{ read_at
; write_at
; sync
; page_size
; frame_size
; cipher
; cipher_overhead
; size_bytes
; salt
; seed
; committed_frames = 0
; sync_count = 0
; epoch = 0L
; index = Hashtbl.create 64
; frame_cache = Hashtbl.create 64
; frame_cache_fifo = Queue.create ()
; frame_cache_capacity
})
| Ok (Some (salt, seed)) ->
let t =
{ read_at
; write_at
; sync
; page_size
; frame_size
; cipher
; cipher_overhead
; size_bytes
; salt
; seed
; committed_frames = 0
; sync_count = 0
; epoch = 0L
; index = Hashtbl.create 64
; frame_cache = Hashtbl.create 64
; frame_cache_fifo = Queue.create ()
; frame_cache_capacity
}
in
let* r = recover_index t in
(match r with
| Error e -> Lwt.return_error e
| Ok () -> Lwt.return_ok t)
;;
let cache_frame t ~expected_epoch idx page =
if
Int64.equal t.epoch expected_epoch
&& t.frame_cache_capacity > 0
&& not (Hashtbl.mem t.frame_cache idx)
then (
while
Hashtbl.length t.frame_cache >= t.frame_cache_capacity
&& not (Queue.is_empty t.frame_cache_fifo)
do
Hashtbl.remove t.frame_cache (Queue.pop t.frame_cache_fifo)
done;
Hashtbl.replace t.frame_cache idx page;
Queue.push idx t.frame_cache_fifo)
;;
let read_frame t idx =
if idx < 0 || idx >= t.committed_frames
then Lwt.return_error (Corrupt_frame idx)
else (
match Hashtbl.find_opt t.frame_cache idx with
| Some page ->
Lwt.return_ok page
| None ->
let epoch_before = t.epoch in
let* r = read_frame_raw ~verify:false t idx in
(match r with
| Error e -> Lwt.return_error e
| Ok None -> Lwt.return_error (Corrupt_frame idx)
| Ok (Some f) ->
cache_frame t ~expected_epoch:epoch_before idx f.page;
Lwt.return_ok f.page))
;;
let read_committed_frame t idx =
if idx < 0 || idx >= t.committed_frames
then Lwt.return_error (Corrupt_frame idx)
else
let* r = read_frame_raw ~verify:false t idx in
match r with
| Error e -> Lwt.return_error e
| Ok None -> Lwt.return_error (Corrupt_frame idx)
| Ok (Some f) ->
Lwt.return_ok f
;;
let write_frame t ~idx ~page_id ~is_commit ~page =
let buf = Cstruct.create t.frame_size in
Cstruct.BE.set_uint64 buf 0 page_id;
let flags = if is_commit then 1L else 0L in
Cstruct.BE.set_uint64 buf 8 flags;
let payload_len = t.page_size + t.cipher_overhead in
(match t.cipher with
| None -> Cstruct.blit page 0 buf frame_meta_bytes t.page_size
| Some c ->
let enc = Crypto.encrypt_frame c ~page_id ~plaintext:page in
Cstruct.blit enc 0 buf frame_meta_bytes payload_len);
let ck =
frame_checksum
~salt:t.salt
~seed:t.seed
~page_id
~flags
~page:(Cstruct.sub buf frame_meta_bytes payload_len)
in
Cstruct.BE.set_uint64 buf 16 ck;
let off = frame_offset t idx in
t.write_at ~offset:off buf
;;
let write_pages_at t ~base pages =
let n = List.length pages in
let last = n - 1 in
let rec write_all i = function
| [] -> Lwt.return_ok n
| (page_id, page) :: rest ->
let is_commit = i = last in
let* r = write_frame t ~idx:(base + i) ~page_id ~is_commit ~page in
(match r with
| Error s -> Lwt.return_error (Block_error s)
| Ok () -> write_all (i + 1) rest)
in
write_all 0 pages
;;
let publish_pages t ~base pages =
let n = List.length pages in
List.iteri
(fun i (page_id, _) ->
let prev = Option.value ~default:[] (Hashtbl.find_opt t.index page_id) in
Hashtbl.replace t.index page_id ((base + i) :: prev))
pages;
t.committed_frames <- base + n;
let new_end =
Int64.add
(Int64.of_int header_size_bytes)
(Int64.mul (Int64.of_int (base + n)) (Int64.of_int t.frame_size))
in
if Int64.compare new_end t.size_bytes > 0 then t.size_bytes <- new_end
;;
let flush_sync t =
let* r = t.sync () in
match r with
| Error s -> Lwt.return_error (Block_error s)
| Ok () ->
t.sync_count <- t.sync_count + 1;
Lwt.return_ok ()
;;
let append_commit_no_sync t pages =
match pages with
| [] -> Lwt.return_ok ()
| _ ->
let base = t.committed_frames in
let* r = write_pages_at t ~base pages in
(match r with
| Error e -> Lwt.return_error e
| Ok _ ->
publish_pages t ~base pages;
Lwt.return_ok ())
;;
let append_commit t pages =
match pages with
| [] -> Lwt.return_ok ()
| _ ->
let base = t.committed_frames in
let* r = write_pages_at t ~base pages in
(match r with
| Error e -> Lwt.return_error e
| Ok _ ->
let* sr = flush_sync t in
(match sr with
| Error e -> Lwt.return_error e
| Ok () ->
publish_pages t ~base pages;
Lwt.return_ok ()))
;;
let reset t =
Hashtbl.reset t.index;
Hashtbl.reset t.frame_cache;
Queue.clear t.frame_cache_fifo;
t.committed_frames <- 0;
t.epoch <- Int64.succ t.epoch
;;
[@@@ai_disclosure "ai-generated"]
[@@@ai_model "claude-opus-4-7"]
[@@@ai_provider "Anthropic"]