123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702(** Pager: page cache + allocator over a BLOCK backend.
Maintains:
- A bounded FIFO cache of pages (read from BLOCK). Capacity defaults to
[default_cache_capacity] and is overridable via [GRANARY_PAGE_CACHE].
- A dirty table of pages modified since the last flush.
- A pin table (#159): pages referenced by a live RO snapshot are pinned
so the writer's CoW churn can't FIFO out a reader's working set.
- An in-memory freelist for page allocation.
Dirty and pinned pages are never evicted from the cache; dirty pages are
written to BLOCK only on [flush]. *)(* Default if [GRANARY_PAGE_CACHE] is unset/invalid. Bumped from the
original 64 (#159): a bigger cache lets a reader's working set and a
writer's CoW churn coexist without immediate eviction pressure. *)letdefault_cache_capacity=1024letcache_capacity_from_env()=matchSys.getenv_opt"GRANARY_PAGE_CACHE"with|Somes->(matchint_of_string_optswith|Somenwhenn>0->n|_->default_cache_capacity)|None->default_cache_capacity;;typecache_key=int64*int(* (page_id, version); -1 = main DB *)letcache_key_mainpid:cache_key=pid,-1typewal_callbacks={wal_find_page:int64->intoption;wal_find_page_at:int64->max_frame:int->intoption;wal_read_frame:int->(Cstruct.t,string)resultLwt.t;wal_append_commit:(int64*Cstruct.t)list->(unit,string)resultLwt.t;wal_append_commit_no_sync:(int64*Cstruct.t)list->(unit,string)resultLwt.t;wal_sync:unit->(unit,string)resultLwt.t}typet={read_page:page_id:int64->Cstruct.t->(unit,string)resultLwt.t;write_page:page_id:int64->Cstruct.t->(unit,string)resultLwt.t;sync:unit->(unit,string)resultLwt.t;resize:n_pages:int64->(unit,string)resultLwt.t;mutablegeom:Geometry.t(** Page geometry for this file (#95): buffers are allocated at
[geom.page_size]; [btree]/[store] read [max_data_bytes] etc. from here.
Defaults to {!Geometry.default}; the open path calls {!set_geom} once
with the file's real geometry before any page op, after which it is
effectively immutable. *);cache:(cache_key,Cstruct.t)Hashtbl.t;dirty:(int64,Cstruct.t)Hashtbl.t;fifo:cache_keyQueue.t(* insertion order for FIFO eviction *);cache_capacity:int;pinned:(cache_key,int)Hashtbl.t;(* Refcount per cache key of live RO snapshots that have materialised it
(#159). [maybe_evict] never drops a key with refcount > 0. Multiple
concurrent snapshots referencing the same page share the count. *)mutablen_pages:int64;mutablefreelist:Freelist.t;mutablecurrent_txn_id:int64;mutablealloc_min_safe:int64;mutablen_pages_at_rw_begin:int64(** #297: page count captured at rw_begin; pages with id >= this
threshold were allocated by file extension in the current txn
and can be safely freed+reused within the same txn without
affecting snapshot readers or in-flight cursors. *);mutabletxn_owned_pool:int64list(** #297: pool of page-ids that were allocated above
[n_pages_at_rw_begin] during the current txn and have since
been freed. [alloc] consults this pool before the main
freelist. *);mutablewal:wal_callbacksoption;mutablewrite_tag:int32(** #174: schema-fingerprint stamp to write into the reserved header bytes
of the next Branch/Leaf page built. Set per tree-operation by the
store; 0 for system/untagged trees. Safe as shared state because
writes are serialised under the single RW transaction. *);mutableon_page_event:(Pager_event.t->unit)option(** #384: optional, synchronous, fire-and-forget observer for physical page
I/O (internals monitor). [None] = zero overhead: the per-kind [emit_*]
helpers construct the [Pager_event.t] only inside the [Some] branch, so
the [None] path neither allocates nor invokes anything.
[Store.set_event_callback] installs a translator here. *)}typeerror=|Block_errorofstring|Corruptionofstringletpp_errorfmt=function|Block_errormsg->Format.fprintffmt"Block_error: %s"msg|Corruptionmsg->Format.fprintffmt"Corruption: %s"msg;;letppfmtt=Format.fprintffmt"@[<hv>Pager.t { n_pages = %Ld;@ cached = %d;@ dirty = %d;@ txn_id = %Ld;@ txn_pool \
= %d }@]"t.n_pages(Hashtbl.lengtht.cache)(Hashtbl.lengtht.dirty)t.current_txn_id(List.lengtht.txn_owned_pool);;letcreate~read_page~write_page~sync~resize~n_pages~freelist={read_page;write_page;sync;resize;geom=Geometry.default;cache=Hashtbl.create64;dirty=Hashtbl.create16;fifo=Queue.create();cache_capacity=cache_capacity_from_env();pinned=Hashtbl.create16;n_pages;freelist;current_txn_id=0L;alloc_min_safe=0L;n_pages_at_rw_begin=0L;txn_owned_pool=[];wal=None;write_tag=0l;on_page_event=None};;(* #174: set the schema-fingerprint stamp for subsequently-built Branch/Leaf
pages. Reset to 0 before writing system-tree (e.g. meta) pages. *)letset_write_tagt(tag:int32)=t.write_tag<-tagletwrite_tagt=t.write_tagletset_page_event_callbacktcb=t.on_page_event<-cb(* #384: emit a [Page_read] iff an observer is attached. The event record is
constructed only inside the [Some] branch, so the [None] path allocates
nothing — keeping physical-read instrumentation truly zero-overhead when the
internals monitor is off. *)letemit_readtpage_id=matcht.on_page_eventwith|None->()|Somef->f(Pager_event.Page_read{page_id});;(* #392: emit a [Wal_read] iff an observer is attached — the WAL-overlay
counterpart of [emit_read]. Fires on a pager cache miss resolved from a WAL
frame (a backend resolution from the pager's viewpoint), with the same
zero-alloc guard as the other per-kind emit helpers. *)letemit_wal_readtpage_id=matcht.on_page_eventwith|None->()|Somef->f(Pager_event.Wal_read{page_id});;(* #384: emit a [Page_alloc]/[Page_free] iff an observer is attached; the record
is built only inside the [Some] branch (zero-alloc when the monitor is off). *)letemit_alloctpage_idreused=matcht.on_page_eventwith|None->()|Somef->f(Pager_event.Page_alloc{page_id;reused});;(* #384: same zero-alloc guard as emit_alloc. *)letemit_freetpage_id=matcht.on_page_eventwith|None->()|Somef->f(Pager_event.Page_free{page_id});;(* #384: emit one [Page_write] per dirty entry being flushed. Guard once, then
iterate — no allocation when no observer is attached (same zero-alloc
discipline as the per-kind emit helpers). *)letemit_writestentries=matcht.on_page_eventwith|None->()|Somef->List.iter(fun(pid,_)->f(Pager_event.Page_write{page_id=pid}))entries;;(* #384: emit a single [Page_write] iff an observer is attached (zero-alloc on
the [None] path, like the other per-kind emit helpers). *)letemit_writetpage_id=matcht.on_page_eventwith|None->()|Somef->f(Pager_event.Page_write{page_id});;(* #95: set the file's page geometry. Called once by the open path before any
page read/write, after peeking/deciding the geometry. *)letset_geomtgeom=t.geom<-geom(* #95: page geometry accessors (cheap field reads on the hot path). *)letgeomt=t.geomletpage_sizet=t.geom.page_sizeletreserved_bytest=t.geom.reserved_bytes_per_pageletmax_data_bytest=Geometry.max_data_bytest.geomletmax_overflow_payload_bytest=Geometry.max_overflow_payload_bytest.geomletmax_freelist_entries_per_paget=Geometry.max_freelist_entries_per_paget.geomletset_waltcb=(* Any cache entries built before the WAL hook was attached came from
the main DB only. If a WAL frame exists for those pages it is more
recent — so clear the cache when transitioning into WAL mode so a
subsequent [read] re-resolves through the WAL index. *)(matchcb,t.walwith|Some_,None->Hashtbl.resett.cache;Queue.cleart.fifo|_->());t.wal<-cb;;letwal_modet=t.wal<>None(** Evict the oldest cache entry if the cache is at capacity.
Never evicts dirty or pinned (#159) pages. *)letmaybe_evictt=(* Keep trying to evict until we find a clean page or the cache is small enough *)letcache_size=Hashtbl.lengtht.cacheinifcache_size<t.cache_capacitythen()else((* Scan the FIFO queue front-to-back looking for an evictable page
(neither dirty nor pinned). *)letevicted=reffalseinlettemp=Queue.create()inwhile(not!evicted)&¬(Queue.is_emptyt.fifo)doletkey=Queue.popt.fifoinifHashtbl.memt.dirty(fstkey)||Hashtbl.memt.pinnedkeythen(* dirty or pinned — put back at end so we don't lose track of it *)Queue.pushkeytempelse(Hashtbl.removet.cachekey;evicted:=true;(* push anything we moved to temp back into the real queue *)Queue.iter(funk->Queue.pushkt.fifo)temp;Queue.cleartemp)done;(* If we couldn't evict (all cached pages are dirty/pinned), keep them. *)ifnot!evictedthenQueue.iter(funk->Queue.pushkt.fifo)temp);;(* Largest number of distinct pages a set of live snapshots may pin. We
always keep a reserve of evictable slots so [maybe_evict] can make
progress and the cache stays bounded even under a giant scan. *)letmax_pinnedt=t.cache_capacity-max8(t.cache_capacity/8)(* Pin [page_id] for the snapshot whose pin set is [s], if budget allows.
Idempotent per snapshot: a page already in [s] is not double-counted.
When the pin budget is exhausted the page is simply left unpinned (it is
still cached normally and may be evicted). *)letpin_pagetpin_setpage_id=matchpin_setwith|None->()|Somes->if(not(Hashtbl.memspage_id))&&Hashtbl.lengtht.pinned<max_pinnedtthen(Hashtbl.replacespage_id();letkey=cache_key_mainpage_idinletc=Option.value~default:0(Hashtbl.find_optt.pinnedkey)inHashtbl.replacet.pinnedkey(c+1));;(** Release every pin held by a snapshot (called from [Store.ro_end]).
Decrements the shared refcount for each page the snapshot pinned. *)letunpin_alltpin_set=Hashtbl.iter(funpage_id()->letkey=cache_key_mainpage_idinmatchHashtbl.find_optt.pinnedkeywith|None|Some1->Hashtbl.removet.pinnedkey|Somen->Hashtbl.replacet.pinnedkey(n-1))pin_set;;(** Add a page to the cache, evicting if necessary. *)letcache_addtkeybuf=letalready_cached=Hashtbl.memt.cachekeyinmaybe_evictt;Hashtbl.replacet.cachekeybuf;ifnotalready_cachedthenQueue.pushkeyt.fifo;;(** Make a deep copy of a Cstruct. *)letcstruct_dupsrc=letlen=Cstruct.lengthsrcinletdst=Cstruct.createleninCstruct.blitsrc0dst0len;dst;;(* Resolve [page_id] from the WAL, if any. [finder] picks the relevant frame
(latest, or latest <= a snapshot bound). WAL frames are NOT cached: frame
indices are recycled after a WAL reset (checkpoint), so a cached
(page_id, frame_idx) entry could be served stale. Returns a fresh Cstruct.
#392: emits [Wal_read page_id] on the frame-served path (the WAL-overlay
counterpart of [emit_read] in [load_main_page]). *)letresolve_wal_paget~page_idfinder=letopenLwt.Syntaxinmatcht.walwith|None->Lwt.return_okNone|Somecb->(matchfindercbwith|None->Lwt.return_okNone|Someframe_idx->let*r=cb.wal_read_frameframe_idxin(matchrwith|Errors->Lwt.return_error(Block_errors)|Okpage->emit_wal_readtpage_id;Lwt.return_ok(Some(cstruct_duppage))));;(* Load [page_id] from the shared cache, or from the block device on a miss
(caching the result). The returned Cstruct is fresh. *)letload_main_page?(bypass_cache=false)tpin_setpage_id=letopenLwt.Syntaxinletkey=cache_key_mainpage_idinmatchHashtbl.find_optt.cachekeywith|Somebuf->pin_pagetpin_setpage_id;Lwt.return_ok(cstruct_dupbuf)|None->letbuf=Cstruct.createt.geom.page_sizeinlet*result=t.read_page~page_idbufin(matchresultwith|Errormsg->Lwt.return_error(Block_errormsg)|Ok()->emit_readtpage_id;ifnotbypass_cachethen(cache_addtkey(cstruct_dupbuf);pin_pagetpin_setpage_id);Lwt.return_okbuf);;letread?snapshot_frames?pin_set?(bypass_cache=false)tpage_id=letopenLwt.Syntaxinletload_after_walfinder=let*wal_r=resolve_wal_paget~page_idfinderinmatchwal_rwith|Errore->Lwt.return_errore|Ok(Somepage)->Lwt.return_okpage|OkNone->load_main_page~bypass_cachetpin_setpage_idinmatchsnapshot_frameswith|None->(* Writer / no-snapshot path: dirty wins. *)(matchHashtbl.find_optt.dirtypage_idwith|Somebuf->Lwt.return_ok(cstruct_dupbuf)|None->load_after_wal(funcb->cb.wal_find_pagepage_id))|Somemax_frame->(* Snapshot reader path: never consult [dirty]. *)load_after_wal(funcb->cb.wal_find_page_atpage_id~max_frame);;(* ---------------------------------------------------------------------- *)(* #244: scoped zero-copy borrow read path *)(* ---------------------------------------------------------------------- *)(* Like [resolve_wal_page] but hands back the frame buffer WITHOUT a defensive
copy. Memory-safe under the borrow contract: the page is decoded-and-
discarded inside the callback and never mutated or retained. NOTE (#246):
on a cache hit [Wal.read_frame] now returns a buffer the WAL RETAINS in its
decrypted-frame cache, shared across readers — so this no longer rests on the
old "fresh, unshared buffer per call" property. It is sound because that
cached buffer is immutable for the life of the WAL generation (frames are
append-only; the cache is dropped wholesale on [Wal.reset], never mutated in
place), exactly like the main page cache's borrow invariant above. A future
in-place mutation of a [Wal.read_frame] result would corrupt the cache and
every concurrent borrower — see [Wal.read_frame]'s contract. *)letresolve_wal_page_borrowt~page_idfinder=letopenLwt.Syntaxinmatcht.walwith|None->Lwt.return_okNone|Somecb->(matchfindercbwith|None->Lwt.return_okNone|Someframe_idx->let*r=cb.wal_read_frameframe_idxin(matchrwith|Errors->Lwt.return_error(Block_errors)|Okpage->emit_wal_readtpage_id;Lwt.return_ok(Somepage)));;(* Like [load_main_page] but returns the cache's own buffer WITHOUT a defensive
copy, and on a miss caches (and returns) the very buffer it read into rather
than caching a separate copy. Sound ONLY under the borrow contract: the
buffer is decoded-and-discarded inside the callback and never mutated or
retained. Cache/dirty buffers are immutable once stored (only ever replaced,
never written in place — see [write]/[write_owned]/[cache_add]), so a
concurrent writer dirtying the same page during a yielding callback installs
a NEW buffer and leaves this borrowed one untouched; eviction merely drops
the hashtbl entry, the buffer itself stays live while the callback holds it. *)letload_main_page_borrow?(bypass_cache=false)tpin_setpage_id=letopenLwt.Syntaxinletkey=cache_key_mainpage_idinmatchHashtbl.find_optt.cachekeywith|Somebuf->pin_pagetpin_setpage_id;Lwt.return_okbuf|None->letbuf=Cstruct.createt.geom.page_sizeinlet*result=t.read_page~page_idbufin(matchresultwith|Errormsg->Lwt.return_error(Block_errormsg)|Ok()->emit_readtpage_id;ifnotbypass_cachethen(cache_addtkeybuf;pin_pagetpin_setpage_id);Lwt.return_okbuf);;letread_borrow?snapshot_frames?pin_set?(bypass_cache=false)tpage_idf=letopenLwt.Syntaxinletborrowbuf=let*v=fbufinLwt.return_okvinletload_after_walfinder=let*wal_r=resolve_wal_page_borrowt~page_idfinderinmatchwal_rwith|Errore->Lwt.return_errore|Ok(Somepage)->borrowpage|OkNone->let*r=load_main_page_borrow~bypass_cachetpin_setpage_idin(matchrwith|Errore->Lwt.return_errore|Okbuf->borrowbuf)inmatchsnapshot_frameswith|None->(matchHashtbl.find_optt.dirtypage_idwith|Somebuf->borrowbuf|None->load_after_wal(funcb->cb.wal_find_pagepage_id))|Somemax_frame->load_after_wal(funcb->cb.wal_find_page_atpage_id~max_frame);;letwritetpage_idbuf=letcopy=cstruct_dupbufinHashtbl.replacet.dirtypage_idcopy;;(* #231: like [write], but takes OWNERSHIP of [buf] — no defensive copy. The
caller must never mutate [buf] after this call. Used by the B+-tree
build-and-write helpers, which create a fresh page buffer per write and drop
it immediately; the [write]-path [cstruct_dup] was a pure ~4KB alloc+memcpy
per page written (one per tree level per insert). Reads still hand out
copies of dirty pages, so stored buffers are never aliased to readers. *)letwrite_ownedtpage_idbuf=Hashtbl.replacet.dirtypage_idbuf(* #356: return the LIVE dirty buffer for [page_id] (NOT a copy), or [None] if
the page is not dirty in the current write txn. The caller MAY mutate the
returned buffer in place: a page in [dirty] was allocated or CoW-copied by
THIS txn, so no committed snapshot and no concurrent reader references it
(snapshot readers resolve through WAL frames, never [dirty]; the writer's own
read-your-own-writes via [read] returns a fresh [cstruct_dup]). The single
RW lock guarantees no other writer. Mutations must keep the page well-formed;
the CRC is resealed for every dirty page at flush time (see [seal_dirty]). *)letdirty_buffertpage_id:Cstruct.toption=Hashtbl.find_optt.dirtypage_id(* Previously also injected into the shared cache here for
read-after-write inside the same txn. Removed (#149): a concurrent
reader at an older snapshot would see uncommitted bytes. The
[dirty] table already covers writer read-after-write — [read]
consults [dirty] first on the no-snapshot path. *)letalloct=(* #297: consult the txn-owned pool first — pages that were allocated
above n_pages_at_rw_begin and have since been freed within this txn. *)matcht.txn_owned_poolwith|pid::rest->t.txn_owned_pool<-rest;emit_alloctpidtrue;Lwt.return_okpid|[]->(matchFreelist.popt.freelist~min_safe_txn_id:t.alloc_min_safewith|Some(pid32,fl')->t.freelist<-fl';letpid=Int64.of_int32pid32inemit_alloctpidtrue;Lwt.return_okpid|None->(* Extend the file by one page *)letnew_id=t.n_pagesinletnew_pages=Int64.addt.n_pages1LinletopenLwt.Syntaxinlet*result=t.resize~n_pages:new_pagesin(matchresultwith|Errormsg->Lwt.return_error(Block_errormsg)|Ok()->t.n_pages<-new_pages;emit_alloctnew_idfalse;Lwt.return_oknew_id));;letfreet~page_id~freed_at_txn_id=(* #297: pages allocated above n_pages_at_rw_begin are txn-owned and
can be safely reused within the current txn. Route them to the
txn_owned_pool instead of the main freelist so [alloc] returns them
immediately without risking cursor or snapshot corruption. *)ifInt64.comparepage_idt.n_pages_at_rw_begin>=0thent.txn_owned_pool<-page_id::t.txn_owned_poolelset.freelist<-Freelist.addt.freelist~page_id:(Int64.to_int32page_id)~freed_at_txn_id;emit_freetpage_id;;(* Seal all dirty pages' CRCs just before flushing to disk (#356).
B+-tree build helpers skip Page.seal per-page to avoid sealing pages
that will be immediately overwritten by the next insert (the
txn_owned_pool recycles page ids, so at commit only ~O(tree_size) pages
survive, not O(n_inserts) × pages_per_insert). Sealing at flush time
amortises the cost across the entire batch. *)letseal_dirtyt=Hashtbl.iter(fun_buf->Page.sealbuf)t.dirty(* Internal: drive the WAL append callback [append] with the dirty
entries; on success clear the dirty set. Used by both [flush] (sync)
and [flush_no_sync] (group commit) so the dirty-set management is
identical. *)letflush_via_walt~append=letopenLwt.Syntaxinletentries=Hashtbl.fold(funpidbufacc->(pid,buf)::acc)t.dirty[]inifentries=[]thenLwt.return_ok()else(seal_dirtyt;let*r=appendentriesinmatchrwith|Errormsg->Lwt.return_error(Block_errormsg)|Ok()->emit_writestentries;Hashtbl.cleart.dirty;Lwt.return_ok());;letflush_no_synct=matcht.walwith|Somecb->flush_via_walt~append:cb.wal_append_commit_no_sync|None->(* Non-WAL backends have no notion of deferred sync — fall through to
the regular [flush] which writes pages + syncs. *)letentries=Hashtbl.fold(funpidbufacc->(pid,buf)::acc)t.dirty[]inseal_dirtyt;letopenLwt.Syntaxinletrecwrite_all=function|[]->let*sync_result=t.sync()in(matchsync_resultwith|Errormsg->Lwt.return_error(Block_errormsg)|Ok()->Hashtbl.cleart.dirty;Lwt.return_ok())|(pid,buf)::rest->let*result=t.write_page~page_id:pidbufin(matchresultwith|Errormsg->Lwt.return_error(Block_errormsg)|Ok()->(* Update main-key cache so post-flush reads don't serve stale data.
[write] no longer injects into the shared cache (#149), so we must
update here after the block write is committed. *)cache_addt(cache_key_mainpid)(cstruct_dupbuf);emit_writetpid;write_allrest)inwrite_allentries;;letwal_synct=matcht.walwith|Somecb->letopenLwt.Syntaxinlet*r=cb.wal_sync()in(matchrwith|Errormsg->Lwt.return_error(Block_errormsg)|Ok()->Lwt.return_ok())|None->Lwt.return_ok();;letflusht=letopenLwt.Syntaxinletentries=Hashtbl.fold(funpidbufacc->(pid,buf)::acc)t.dirty[]inmatcht.walwith|Somecb->ifentries=[]thenLwt.return_ok()elselet*r=cb.wal_append_commitentriesin(matchrwith|Errormsg->Lwt.return_error(Block_errormsg)|Ok()->emit_writestentries;Hashtbl.cleart.dirty;Lwt.return_ok())|None->(* Legacy path: write every dirty page to the main DB and sync. *)letrecwrite_all=function|[]->let*sync_result=t.sync()in(matchsync_resultwith|Errormsg->Lwt.return_error(Block_errormsg)|Ok()->Hashtbl.cleart.dirty;Lwt.return_ok())|(pid,buf)::rest->let*result=t.write_page~page_id:pidbufin(matchresultwith|Errormsg->Lwt.return_error(Block_errormsg)|Ok()->(* Update main-key cache so post-flush reads don't serve stale data.
[write] no longer injects into the shared cache (#149), so we must
update here after the block write is committed. *)cache_addt(cache_key_mainpid)(cstruct_dupbuf);emit_writetpid;write_allrest)inwrite_allentries;;letn_pagest=t.n_pagesletfreelistt=t.freelistletset_txn_idtid=t.current_txn_id<-idletget_txn_idt=t.current_txn_idletset_alloc_min_safetv=t.alloc_min_safe<-vletset_n_pages_at_rw_begintv=t.n_pages_at_rw_begin<-vlettxn_owned_pool_gett=t.txn_owned_poollettxn_owned_pool_settv=t.txn_owned_pool<-v(* Number of distinct pages currently pinned by live RO snapshots (#159).
Exposed for #164 testing: lets a test assert pins return to 0 after a
snapshot ends — including when its reader closure raised. *)letpinned_countt=Hashtbl.lengtht.pinnedletset_freelisttfl=t.freelist<-flletset_n_pagestn=t.n_pages<-nletclear_dirtyt=letdirty_pids=Hashtbl.fold(funpid_acc->pid::acc)t.dirty[]inList.iter(funpid->Hashtbl.removet.dirtypid;Hashtbl.removet.cache(cache_key_mainpid))dirty_pids;letold_fifo=Queue.copyt.fifoinQueue.cleart.fifo;Queue.iter(funkey->ifHashtbl.memt.cachekeythenQueue.pushkeyt.fifo)old_fifo;(* #297: txn-owned pages are discarded on rollback (they were never
part of a committed tree). *)txn_owned_pool_sett[];;typedirty_snapshot=(int64,Cstruct.t)Hashtbl.t(* #356: DEEP-copy each page buffer when snapshotting/restoring the dirty set
for savepoints. In-place insert mutation (see [dirty_buffer]) mutates dirty
buffers in place, so a shallow [Hashtbl.copy] (which aliases the Cstructs)
would let a post-savepoint mutation corrupt the snapshot — ROLLBACK TO could
then not undo it. Deep copies make the snapshot immune; [dirty_restore]
likewise installs fresh copies so the snapshot stays pristine for a repeated
ROLLBACK TO the same savepoint. Savepoints are only taken on explicit
SAVEPOINT statements (never per-insert), so this copy is off the hot path. *)letdirty_clonet=letsnap=Hashtbl.create(Hashtbl.lengtht.dirty)inHashtbl.iter(funkv->Hashtbl.replacesnapk(cstruct_dupv))t.dirty;snap;;letdirty_restoretsnap=Hashtbl.resett.dirty;Hashtbl.iter(funkv->Hashtbl.replacet.dirtyk(cstruct_dupv))snap;;letflush_one_to_maint~page_id~buf=letopenLwt.Syntaxinlet*r=t.write_page~page_idbufinmatchrwith|Ok()->emit_writetpage_id;cache_addt(cache_key_mainpage_id)(cstruct_dupbuf);Lwt.return_ok()|Errors->Lwt.return_error(Block_errors);;letflush_sync_maint=letopenLwt.Syntaxinlet*r=t.sync()inmatchrwith|Ok()->Lwt.return_ok()|Errors->Lwt.return_error(Block_errors);;[@@@ai_disclosure"ai-generated"][@@@ai_model"claude-opus-4-7"][@@@ai_provider"Anthropic"]