canontra-0.4.0.0: src/Canontra/Cache/SlabV7.hs
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DerivingStrategies #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE StrictData #-}
{- |
Module : Canontra.Cache.SlabV7
Description : Incremental zero-copy memory-mapped slab cache engine (CNTR\x07) for canontra v0.4.0.
Extends the CNTR\x06 4KB-paged, 64-byte cache-line-aligned slab architecture with:
- Full 9-tier 'FingerprintBundle' storage (including F_T).
- Compact binary per-file 'FileGraphSummary' payloads inside 4KB CRC-32C protected slabs
(with safe multi-page spanning for large modules), enabling warm and dirty incremental
whole-repository graph synthesis without re-parsing untouched source files.
- Persistent whole-repository bundle + unboxed CSR call/data-flow graph slabs.
- Transparent read-upgrade compatibility for CNTR\x06 and CNTR\x05 caches.
-}
module Canontra.Cache.SlabV7
( -- * Entry & Handle Types
SlabV7Entry (..)
, SlabV7Handle (..)
-- * Lifecycle
, openSlabV7
, closeSlabV7
-- * Lookups & Memory-Mapped Verification
, lookupSlabV7Warm
, lookupSlabV7BinaryBS
-- * Binary Encoding & Decoding
, encodeSlabV7Binary
, decodeSlabV7Binary
, decodeSlabV7Resilient
, verifySlabV7HeaderCRC
-- * FileGraphSummary Binary Serialization
, encodeFileGraphSummary
, decodeFileGraphSummary
-- * Disk File Operations
, writeSlabV7File
, readSlabV7File
, readSlabV7FileResilient
, readAnySlabCacheForV7
) where
import Control.DeepSeq (NFData (..))
import Control.Monad (replicateM)
import Data.Bits ((.&.), (.|.), shiftR)
import qualified Data.ByteString as BS
import qualified Data.ByteString.Builder as BB
import qualified Data.ByteString.Internal as BSI
import qualified Data.ByteString.Lazy as LBS
import qualified Data.List as List
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import Data.Ord (comparing)
import qualified Data.Text as T
import qualified Data.Text.Encoding as TE
import qualified Data.Vector.Unboxed as U
import Data.Word (Word16, Word32, Word64, Word8)
import Foreign.ForeignPtr (ForeignPtr, withForeignPtr)
import Foreign.Marshal.Utils (copyBytes)
import Foreign.Ptr (Ptr, castPtr, plusPtr)
import Foreign.Storable (peekByteOff)
import GHC.Generics (Generic)
import System.Directory (createDirectoryIfMissing, doesFileExist)
import System.FilePath (takeDirectory)
import System.Process (getCurrentPid)
import Canontra.Analysis.CSRGraph (CSRGraph (..))
import Canontra.Analysis.CallGraph (CallEdge (..), CalleeTarget (..), CallerNode (..))
import Canontra.Analysis.WholeRepoGraph (CallFlowSite (..), FileGraphSummary (..))
import Canontra.Cache.Common
( MerkleCache (..)
, MerkleCacheEntry (..)
, atomicSwapWithRetry_
, computeCRC32
, decodeDigest
, encodeBundle
, encodeDigest
, fastPathHash64
, normalizePathCanonical
, readWord16LE
, readWord32LE
, readWord64LE
)
import Canontra.Cache.Inode (FileMetadata (..))
import Canontra.Cache.PagedCache (decodeBinaryCacheV5)
import Canontra.Cache.SlabV6
( CacheRecordV6 (..)
, decodeCSRGraph
, decodeSlabV6Resilient
, encodeCSRGraph
)
import Canontra.Types
( DeclKind (..)
, Fingerprint (..)
, FingerprintBundle (..)
, GlobalSymbol (..)
, WholeRepoBundle (..)
)
-- | Cached entry in CNTR\x07 holding file metadata, 9-tier bundle, and optional graph summary.
data SlabV7Entry = SlabV7Entry
{ sv7Meta :: !FileMetadata
, sv7Bundle :: !FingerprintBundle
, sv7Summary :: !(Maybe FileGraphSummary)
} deriving stock (Eq, Show, Generic)
deriving anyclass (NFData)
-- | Handle to an active memory-mapped CNTR\x07 slab cache.
data SlabV7Handle = SlabV7Handle
{ sv7FilePath :: !FilePath
, sv7ByteString :: !BS.ByteString
, sv7BasePtr :: !(Ptr Word8)
, sv7ForeignPtr :: !(ForeignPtr Word8)
, sv7RecordCount :: !Word32
, sv7RecordCapacity :: !Word32
, sv7RadixTablePtr :: !(Ptr Word8)
, sv7FileTablePtr :: !(Ptr CacheRecordV6)
, sv7RepoBundle :: !(Maybe WholeRepoBundle)
, sv7RepoCallCSR :: !(Maybe CSRGraph)
, sv7RepoDataCSR :: !(Maybe CSRGraph)
} deriving stock (Show, Eq, Generic)
instance NFData SlabV7Handle where
rnf (SlabV7Handle fp bs _ _ rc cap _ _ rb rcg rdg) =
rnf fp `seq` rnf bs `seq` rnf rc `seq` rnf cap `seq` rnf rb `seq` rnf rcg `seq` rnf rdg
-- ============================================================================
-- Binary Encoding Helpers for FileGraphSummary
-- ============================================================================
encodeTextB :: T.Text -> BB.Builder
encodeTextB t =
let !bs = TE.encodeUtf8 t
in BB.word32LE (fromIntegral (BS.length bs)) <> BB.byteString bs
encodeFilePathB :: FilePath -> BB.Builder
encodeFilePathB = encodeTextB . T.pack
encodeListB :: (a -> BB.Builder) -> [a] -> BB.Builder
encodeListB f xs =
BB.word32LE (fromIntegral (length xs)) <> mconcat (map f xs)
encodeDeclKind :: DeclKind -> Word8
encodeDeclKind = \case
KindFunction -> 0
KindMethod -> 1
KindClass -> 2
KindStruct -> 3
KindInterface -> 4
KindTrait -> 5
KindImpl -> 6
KindVariable -> 7
KindTypeAlias -> 8
decodeDeclKind :: Word8 -> Maybe DeclKind
decodeDeclKind = \case
0 -> Just KindFunction
1 -> Just KindMethod
2 -> Just KindClass
3 -> Just KindStruct
4 -> Just KindInterface
5 -> Just KindTrait
6 -> Just KindImpl
7 -> Just KindVariable
8 -> Just KindTypeAlias
_ -> Nothing
encodeGlobalSymbolB :: GlobalSymbol -> BB.Builder
encodeGlobalSymbolB (GlobalSymbol fp m d k (Fingerprint t2)) =
encodeFilePathB fp
<> encodeTextB m
<> encodeTextB d
<> BB.word8 (encodeDeclKind k)
<> encodeTextB t2
encodeCallerNodeB :: CallerNode -> BB.Builder
encodeCallerNodeB = \case
CallTopLevel -> BB.word8 0
CallFunction fn -> BB.word8 1 <> encodeTextB fn
CallMethod cls m -> BB.word8 2 <> encodeTextB cls <> encodeTextB m
encodeCalleeTargetB :: CalleeTarget -> BB.Builder
encodeCalleeTargetB = \case
TargetLocal n -> BB.word8 0 <> encodeTextB n
TargetMethod c m -> BB.word8 1 <> encodeTextB c <> encodeTextB m
TargetImported m s -> BB.word8 2 <> encodeTextB m <> encodeTextB s
TargetDynamic _ -> BB.word8 3
encodeCallEdgeB :: CallEdge -> BB.Builder
encodeCallEdgeB (CallEdge caller callee cnt isAsync) =
encodeCallerNodeB caller
<> encodeCalleeTargetB callee
<> BB.word32LE (fromIntegral cnt)
<> BB.word8 (if isAsync then 1 else 0)
encodeCallFlowSiteB :: CallFlowSite -> BB.Builder
encodeCallFlowSiteB (CallFlowSite caller callee posArgs kwArgs) =
encodeCallerNodeB caller
<> encodeCalleeTargetB callee
<> encodeListB (encodeListB encodeTextB) posArgs
<> encodeListB (\(k, vs) -> encodeTextB k <> encodeListB encodeTextB vs) kwArgs
-- | Serialize a 'FileGraphSummary' to a compact binary 'BB.Builder'.
encodeFileGraphSummary :: FileGraphSummary -> BB.Builder
encodeFileGraphSummary (FileGraphSummary fp modN impMods reExps syms callEdges flowSites) =
encodeFilePathB fp
<> encodeTextB modN
<> encodeListB encodeTextB impMods
<> encodeListB (\(eN, sM, oN) -> encodeTextB eN <> encodeTextB sM <> encodeTextB oN) reExps
<> encodeListB encodeGlobalSymbolB syms
<> encodeListB encodeCallEdgeB callEdges
<> encodeListB encodeCallFlowSiteB flowSites
-- | Bounds-checked ByteString cursor decoder.
newtype Decoder a = Decoder { runDecoder :: BS.ByteString -> Int -> Maybe (a, Int) }
instance Functor Decoder where
fmap f (Decoder g) = Decoder $ \bs off -> do
(a, off') <- g bs off
pure (f a, off')
instance Applicative Decoder where
pure a = Decoder $ \_ off -> Just (a, off)
Decoder ff <*> Decoder fa = Decoder $ \bs off -> do
(f, off1) <- ff bs off
(a, off2) <- fa bs off1
pure (f a, off2)
instance Monad Decoder where
Decoder fa >>= k = Decoder $ \bs off -> do
(a, off1) <- fa bs off
runDecoder (k a) bs off1
decWord8 :: Decoder Word8
decWord8 = Decoder $ \bs off ->
if off + 1 > BS.length bs
then Nothing
else Just (BS.index bs off, off + 1)
decWord32 :: Decoder Word32
decWord32 = Decoder $ \bs off ->
if off + 4 > BS.length bs
then Nothing
else Just (readWord32LE bs off, off + 4)
decText :: Decoder T.Text
decText = do
lenW <- decWord32
let !len = fromIntegral lenW :: Int
Decoder $ \bs off ->
if off + len > BS.length bs
then Nothing
else
let !slice = BS.take len (BS.drop off bs)
in Just (TE.decodeUtf8Lenient slice, off + len)
decFilePath :: Decoder FilePath
decFilePath = T.unpack <$> decText
decList :: Decoder a -> Decoder [a]
decList itemDec = do
cnt <- decWord32
replicateM (fromIntegral cnt) itemDec
decGlobalSymbol :: Decoder GlobalSymbol
decGlobalSymbol = do
fp <- decFilePath
m <- decText
d <- decText
kb <- decWord8
k <- Decoder $ \_ off -> case decodeDeclKind kb of
Just dk -> Just (dk, off)
Nothing -> Nothing
t2 <- decText
pure (GlobalSymbol fp m d k (Fingerprint t2))
decCallerNode :: Decoder CallerNode
decCallerNode = do
t <- decWord8
case t of
0 -> pure CallTopLevel
1 -> CallFunction <$> decText
2 -> CallMethod <$> decText <*> decText
_ -> Decoder (\_ _ -> Nothing)
decCalleeTarget :: Decoder CalleeTarget
decCalleeTarget = do
t <- decWord8
case t of
0 -> TargetLocal <$> decText
1 -> TargetMethod <$> decText <*> decText
2 -> TargetImported <$> decText <*> decText
_ -> Decoder (\_ _ -> Nothing)
decCallEdge :: Decoder CallEdge
decCallEdge = do
caller <- decCallerNode
callee <- decCalleeTarget
cnt <- decWord32
ab <- decWord8
pure (CallEdge caller callee (fromIntegral cnt) (ab /= 0))
decCallFlowSite :: Decoder CallFlowSite
decCallFlowSite = do
caller <- decCallerNode
callee <- decCalleeTarget
posArgs <- decList (decList decText)
kwArgs <- decList ((,) <$> decText <*> decList decText)
pure (CallFlowSite caller callee posArgs kwArgs)
-- | Deserialize a 'FileGraphSummary' from a strict 'BS.ByteString' at the given offset.
decodeFileGraphSummary :: BS.ByteString -> Int -> Maybe (FileGraphSummary, Int)
decodeFileGraphSummary bs off = runDecoder decSummary bs off
where
decSummary = do
fp <- decFilePath
modN <- decText
impMods <- decList decText
reExps <- decList ((,,) <$> decText <*> decText <*> decText)
syms <- decList decGlobalSymbol
callEdges <- decList decCallEdge
flowSites <- decList decCallFlowSite
pure (FileGraphSummary fp modN impMods reExps syms callEdges flowSites)
-- ============================================================================
-- CNTR\x07 Layout & Encoding
-- ============================================================================
-- | Record flag indicating the payload spans multiple contiguous 4KB slab pages.
flagMultiPagePayload :: Word64
flagMultiPagePayload = 1
-- | Encodes entries and optional repository CSR graphs into CNTR\x07 binary format.
encodeSlabV7Binary
:: [SlabV7Entry]
-> Maybe (WholeRepoBundle, CSRGraph, CSRGraph)
-> BS.ByteString
encodeSlabV7Binary rawEntries mRepo =
let !numEntries = length rawEntries
!capacity = max 512 (fromIntegral numEntries :: Word32)
!fileTableBytes = fromIntegral capacity * 64 :: Int
!slabStartOffset = 2080 + fileTableBytes
prepEntry (SlabV7Entry meta bundle mSummary) =
let !norm = normalizePathCanonical (fmPath meta)
!pBS = TE.encodeUtf8 (T.pack norm)
!h = fastPathHash64 pBS
!b = fromIntegral (h `shiftR` 56) :: Int
in (b, h, norm, pBS, meta, bundle, mSummary)
sorted = List.sortBy (comparing (\(b, h, norm, _, _, _, _) -> (b, h, norm))) (map prepEntry rawEntries)
(records, slabDataBS) = buildSlabs slabStartOffset sorted
radixBS = buildRadixDirectory sorted (fromIntegral numEntries :: Word32)
(!repoOff, !repoLen, !repoSlabBS) = case mRepo of
Nothing -> (0 :: Word32, 0 :: Word32, BS.empty)
Just (wrb, cgCSR, dfCSR) ->
let !startOff = fromIntegral (slabStartOffset + BS.length slabDataBS) :: Word32
!body = encodeRepoBody wrb cgCSR dfCSR
!pageBS = buildMultiPageChunk body
in (startOff, fromIntegral (BS.length pageBS), pageBS)
fileTableBuilder =
mconcat [encodeRecord rec | rec <- records]
<> BB.byteString (BS.replicate (fromIntegral (capacity - fromIntegral numEntries) * 64) 0)
fileTableBS = LBS.toStrict (BB.toLazyByteString fileTableBuilder)
headerNoCRC =
BB.byteString "CNTR"
<> BB.word16LE 7
<> BB.word16LE (if repoOff > 0 then 1 else 0)
<> BB.word32LE (fromIntegral numEntries)
<> BB.word32LE capacity
<> BB.word32LE 0
<> BB.word32LE repoOff
<> BB.word32LE repoLen
<> BB.word32LE 0
headerNoCRC_BS = LBS.toStrict (BB.toLazyByteString headerNoCRC)
globalCRC = computeCRC32 (headerNoCRC_BS <> radixBS)
headerFinal =
BB.byteString "CNTR"
<> BB.word16LE 7
<> BB.word16LE (if repoOff > 0 then 1 else 0)
<> BB.word32LE (fromIntegral numEntries)
<> BB.word32LE capacity
<> BB.word32LE globalCRC
<> BB.word32LE repoOff
<> BB.word32LE repoLen
<> BB.word32LE 0
headerFinalBS = LBS.toStrict (BB.toLazyByteString headerFinal)
in headerFinalBS <> radixBS <> fileTableBS <> slabDataBS <> repoSlabBS
where
encodeRecord (CacheRecordV6 h mt nano sz off len f4 flg r1 r2) =
BB.word64LE h
<> BB.word64LE mt
<> BB.word32LE nano
<> BB.word32LE sz
<> BB.word32LE off
<> BB.word32LE len
<> BB.word64LE f4
<> BB.word64LE flg
<> BB.word64LE r1
<> BB.word64LE r2
-- O(N) single-pass 256-way L1 Radix directory builder
buildRadixDirectory sorted totalCount =
let countsMap = Map.fromListWith (+) [(b, 1 :: Word32) | (b, _, _, _, _, _, _) <- sorted]
(_, bucketEntries) = List.mapAccumL
(\ !accStart b ->
let !c = Map.findWithDefault 0 b countsMap
!entry = if c == 0
then BB.word32LE totalCount <> BB.word32LE 0
else BB.word32LE accStart <> BB.word32LE c
in (accStart + c, entry)
) 0 [0 .. 255 :: Int]
in LBS.toStrict (BB.toLazyByteString (mconcat bucketEntries))
buildSlabs baseOffset sorted =
let encodeItem (_, h, _, pBS, meta, bundle, mSummary) =
let !payloadBS = encodePayload pBS bundle mSummary
!f4Hex = unFingerprint (f4Composite bundle)
!f4Head = readWord64LE (TE.encodeUtf8 f4Hex) 0
in (h, fromIntegral (fmMtime meta) :: Word64, fromIntegral (fmSize meta) :: Word32, f4Head, payloadBS)
items = map encodeItem sorted
in packItemsIntoPages baseOffset items
packItemsIntoPages baseOffset items =
let (recs, pages) = go baseOffset 0 [] [] items
in (recs, BS.concat (reverse pages))
where
go _ _ accRecs accPages [] = (reverse accRecs, accPages)
go curBase pageIdx accRecs accPages (x@(_, _, _, _, p) : xs)
| BS.length p > 4088 =
-- Oversized payload spans k contiguous 4KB pages cleanly (never loops)
let !pageStart = curBase + pageIdx * 4096
!numPages = (BS.length p + 4087) `div` 4088
!chunkBS = buildMultiPageChunk p
!(h, mt, sz, f4Head, _) = x
!rec = CacheRecordV6 h mt 0 sz (fromIntegral pageStart) (fromIntegral (BS.length p)) f4Head flagMultiPagePayload 0 0
in go curBase (pageIdx + numPages) (rec : accRecs) (chunkBS : accPages) xs
| otherwise =
let (chunk, rest) = fitIntoPage 4088 (x : xs)
pagePayload = BS.concat [pl | (_, _, _, _, pl) <- chunk]
padding = 4088 - BS.length pagePayload
paddedBody = pagePayload <> BS.replicate padding 0
crc = computeCRC32 paddedBody
pageBS = LBS.toStrict $ BB.toLazyByteString $
BB.word32LE crc <> BB.word32LE 1 <> BB.byteString paddedBody
pageStart = curBase + pageIdx * 4096
assigned = assignOffsets (pageStart + 8) chunk
in go curBase (pageIdx + 1) (reverse assigned ++ accRecs) (pageBS : accPages) rest
fitIntoPage _ [] = ([], [])
fitIntoPage remSpace (y@(_, _, _, _, p) : ys)
| BS.length p <= remSpace =
let (fitted, rest) = fitIntoPage (remSpace - BS.length p) ys
in (y : fitted, rest)
| otherwise = ([], y : ys)
assignOffsets _ [] = []
assignOffsets off ((h, mt, sz, f4Head, p) : xs) =
let !len = fromIntegral (BS.length p) :: Word32
!rec = CacheRecordV6 h mt 0 sz (fromIntegral off) len f4Head 0 0 0
in rec : assignOffsets (off + fromIntegral len) xs
buildMultiPageChunk rawBody =
let !totalLen = BS.length rawBody
!numPages = max 1 ((totalLen + 4087) `div` 4088)
mkPage !idx =
let !slice = BS.take 4088 (BS.drop (idx * 4088) rawBody)
!padLen = 4088 - BS.length slice
!paddedBody = if padLen == 0 then slice else slice <> BS.replicate padLen 0
!crc = computeCRC32 paddedBody
!spanTag = if idx == 0 then fromIntegral numPages :: Word32 else 0
in BB.word32LE crc <> BB.word32LE spanTag <> BB.byteString paddedBody
in LBS.toStrict $ BB.toLazyByteString $ mconcat [mkPage i | i <- [0 .. numPages - 1]]
encodePayload pBS bundle mSummary =
let !normLen = fromIntegral (BS.length pBS) :: Word16
(!flags, !b0, !b1, !b2, !b3, !bcg, !bcf, !bdf, !b4) = encodeBundle bundle
(!isHexT, !bt) = encodeDigest (unFingerprint (fTTypeContract bundle))
!flagsFinal = flags .|. (if isHexT then 256 else 0)
!summaryPart = case mSummary of
Nothing -> BB.word32LE 0
Just s ->
let !sBS = LBS.toStrict (BB.toLazyByteString (encodeFileGraphSummary s))
in BB.word32LE (fromIntegral (BS.length sBS)) <> BB.byteString sBS
in LBS.toStrict $ BB.toLazyByteString $
BB.word16LE normLen
<> BB.byteString pBS
<> BB.word16LE flagsFinal
<> BB.byteString b0
<> BB.byteString b1
<> BB.byteString b2
<> BB.byteString b3
<> BB.byteString bcg
<> BB.byteString bcf
<> BB.byteString bdf
<> BB.byteString bt
<> BB.byteString b4
<> summaryPart
encodeRepoBody (WholeRepoBundle (Fingerprint fr) (Fingerprint fwcg) (Fingerprint fwdf) (Fingerprint fw4)) cgCSR dfCSR =
let (hxR, bR) = encodeDigest fr
(hxWCG, bWCG) = encodeDigest fwcg
(hxWDF, bWDF) = encodeDigest fwdf
(hxW4, bW4) = encodeDigest fw4
!rFlags = (if hxR then 1 else 0)
.|. (if hxWCG then 2 else 0)
.|. (if hxWDF then 4 else 0)
.|. (if hxW4 then 8 else 0) :: Word16
in LBS.toStrict $ BB.toLazyByteString $
BB.byteString "REPO"
<> BB.word16LE rFlags
<> BB.byteString bR
<> BB.byteString bWCG
<> BB.byteString bWDF
<> BB.byteString bW4
<> encodeCSRGraph cgCSR
<> encodeCSRGraph dfCSR
-- ============================================================================
-- Header & Page Verification
-- ============================================================================
-- | Verifies the integrity of the CNTR\x07 global header and 256-way radix directory.
verifySlabV7HeaderCRC :: BS.ByteString -> Bool
verifySlabV7HeaderCRC bs
| BS.length bs < 2080 = False
| BS.take 4 bs /= "CNTR" = False
| readWord16LE bs 4 /= 7 = False
| otherwise =
let !storedCRC = readWord32LE bs 16
!headerNoCRC = BS.take 16 bs <> BS.replicate 4 0 <> BS.take 12 (BS.drop 20 bs)
!radixBS = BS.take 2048 (BS.drop 32 bs)
!expectedCRC = computeCRC32 (headerNoCRC <> radixBS)
in storedCRC == expectedCRC
-- | Extract contiguous payload bytes for single-page or multi-page records.
extractPayloadBytes :: BS.ByteString -> Int -> Int -> Word64 -> BS.ByteString
extractPayloadBytes bs off len flags
| (flags .&. flagMultiPagePayload) == 0 =
BS.take len (BS.drop off bs)
| otherwise =
let !numPages = max 1 ((len + 4087) `div` 4088)
!raw = BS.concat
[ BS.take 4088 (BS.drop (off + p * 4096 + 8) bs)
| p <- [0 .. numPages - 1]
]
in BS.take len raw
decodeRepoBodyBytes :: BS.ByteString -> Maybe (WholeRepoBundle, CSRGraph, CSRGraph)
decodeRepoBodyBytes body
| BS.length body < 138 || BS.take 4 body /= "REPO" = Nothing
| otherwise =
let !rFlags = readWord16LE body 4
!bR = decodeDigest rFlags 0 (BS.take 32 (BS.drop 6 body))
!bWCG = decodeDigest rFlags 1 (BS.take 32 (BS.drop 38 body))
!bWDF = decodeDigest rFlags 2 (BS.take 32 (BS.drop 70 body))
!bW4 = decodeDigest rFlags 3 (BS.take 32 (BS.drop 102 body))
!bundle = WholeRepoBundle (Fingerprint bR) (Fingerprint bWCG) (Fingerprint bWDF) (Fingerprint bW4)
!cgRes = decodeCSRGraph body 134
(!cgCSR, !nextOff) = case cgRes of
Just (cg, n) -> (cg, n)
Nothing -> (CSRGraph 0 0 (U.singleton 0) U.empty U.empty, 134)
!dfRes = decodeCSRGraph body nextOff
!dfCSR = case dfRes of
Just (df, _) -> df
Nothing -> CSRGraph 0 0 (U.singleton 0) U.empty U.empty
in Just (bundle, cgCSR, dfCSR)
-- ============================================================================
-- Zero-Copy Memory-Mapped Handle & Lookups
-- ============================================================================
-- | Open a CNTR\x07 slab cache file into a memory-mapped handle.
openSlabV7 :: FilePath -> IO (Maybe SlabV7Handle)
openSlabV7 cachePath = do
exists <- doesFileExist cachePath
if not exists
then pure Nothing
else do
bs <- BS.readFile cachePath
if BS.length bs < 2080 || not (verifySlabV7HeaderCRC bs)
then pure Nothing
else do
let !numRecords = readWord32LE bs 8
!capacity = readWord32LE bs 12
!repoOff = readWord32LE bs 20
!repoLen = readWord32LE bs 24
(!fptr, !bsOff, _) = BSI.toForeignPtr bs
withForeignPtr fptr $ \rawPtr -> do
let !basePtr = rawPtr `plusPtr` bsOff
!radixPtr = basePtr `plusPtr` 32
!fileTablePtr = castPtr (basePtr `plusPtr` 2080) :: Ptr CacheRecordV6
(!mRepo, !mCgCSR, !mDfCSR) =
if repoOff == 0 || fromIntegral (repoOff + repoLen) > BS.length bs
then (Nothing, Nothing, Nothing)
else
let !repoBody = extractPayloadBytes bs (fromIntegral repoOff) (fromIntegral repoLen) flagMultiPagePayload
in case decodeRepoBodyBytes repoBody of
Just (wrb, cg, df) -> (Just wrb, Just cg, Just df)
Nothing -> (Nothing, Nothing, Nothing)
pure $ Just SlabV7Handle
{ sv7FilePath = cachePath
, sv7ByteString = bs
, sv7BasePtr = basePtr
, sv7ForeignPtr = fptr
, sv7RecordCount = numRecords
, sv7RecordCapacity = capacity
, sv7RadixTablePtr = radixPtr
, sv7FileTablePtr = fileTablePtr
, sv7RepoBundle = mRepo
, sv7RepoCallCSR = mCgCSR
, sv7RepoDataCSR = mDfCSR
}
-- | Close an active CNTR\x07 slab handle.
closeSlabV7 :: SlabV7Handle -> IO ()
closeSlabV7 _ = pure ()
-- | Sub-microsecond warm lookup directly from an open 'SlabV7Handle'.
lookupSlabV7Warm :: SlabV7Handle -> FilePath -> FileMetadata -> IO (Maybe (FingerprintBundle, Maybe FileGraphSummary))
lookupSlabV7Warm !handle !path !meta = do
let !norm = normalizePathCanonical path
!pBS = TE.encodeUtf8 (T.pack norm)
!h = fastPathHash64 pBS
!bucket = fromIntegral (h `shiftR` 56) :: Int
!radixPtr = sv7RadixTablePtr handle `plusPtr` (bucket * 8)
startIdx <- peekByteOff radixPtr 0 :: IO Word32
count <- peekByteOff radixPtr 4 :: IO Word32
if count == 0
then pure Nothing
else probeRec startIdx count 0 h
where
!mtTarget = fromIntegral (fmMtime meta) :: Word64
!szTarget = fromIntegral (fmSize meta) :: Word32
probeRec !startIdx !count !slot !h
| slot >= count = pure Nothing
| otherwise = do
let !recPtr = sv7FileTablePtr handle `plusPtr` (fromIntegral (startIdx + slot) * 64)
!recH <- peekByteOff (castPtr recPtr) 0 :: IO Word64
if recH /= h
then probeRec startIdx count (slot + 1) h
else do
!mt <- peekByteOff (castPtr recPtr) 8 :: IO Word64
!sz <- peekByteOff (castPtr recPtr) 20 :: IO Word32
if mt /= mtTarget || sz /= szTarget
then probeRec startIdx count (slot + 1) h
else do
!slabOff <- peekByteOff (castPtr recPtr) 24 :: IO Word32
!slabLen <- peekByteOff (castPtr recPtr) 28 :: IO Word32
!flags <- peekByteOff (castPtr recPtr) 40 :: IO Word64
if slabOff == 0 || slabLen == 0
then pure Nothing
else if (flags .&. flagMultiPagePayload) == 0
then do
let !payloadPtr = sv7BasePtr handle `plusPtr` fromIntegral slabOff
payloadBS <- BSI.create (fromIntegral slabLen) $ \buf ->
copyBytes buf payloadPtr (fromIntegral slabLen)
let (_, !bundle, !mSummary) = decodePayloadBS payloadBS
pure (Just (bundle, mSummary))
else do
let !payloadBS = extractPayloadBytes (sv7ByteString handle) (fromIntegral slabOff) (fromIntegral slabLen) flags
(_, !bundle, !mSummary) = decodePayloadBS payloadBS
pure (Just (bundle, mSummary))
-- | Pure zero-copy binary lookup directly in a CNTR\x07 ByteString.
lookupSlabV7BinaryBS :: FilePath -> FileMetadata -> BS.ByteString -> Maybe (FingerprintBundle, Maybe FileGraphSummary)
lookupSlabV7BinaryBS !path !meta !bs
| BS.length bs < 2080 = Nothing
| BS.take 4 bs /= "CNTR" = Nothing
| readWord16LE bs 4 /= 7 = Nothing
| otherwise =
let !norm = normalizePathCanonical path
!pBS = TE.encodeUtf8 (T.pack norm)
!h = fastPathHash64 pBS
!bucket = fromIntegral (h `shiftR` 56) :: Int
!radixOffset = 32 + bucket * 8
!startIdx = readWord32LE bs radixOffset
!count = readWord32LE bs (radixOffset + 4)
in if count == 0
then Nothing
else probe startIdx count 0 h
where
!mtTarget = fromIntegral (fmMtime meta) :: Word64
!szTarget = fromIntegral (fmSize meta) :: Word32
probe !startIdx !count !slot !h
| slot >= count = Nothing
| otherwise =
let !recOff = 2080 + fromIntegral (startIdx + slot) * 64
in if recOff + 64 > BS.length bs
then Nothing
else
let !recH = readWord64LE bs recOff
in if recH /= h
then probe startIdx count (slot + 1) h
else
let !mt = readWord64LE bs (recOff + 8)
!sz = readWord32LE bs (recOff + 20)
in if mt == mtTarget && sz == szTarget
then
let !slabOff = fromIntegral (readWord32LE bs (recOff + 24)) :: Int
!slabLen = fromIntegral (readWord32LE bs (recOff + 28)) :: Int
!recFlags = readWord64LE bs (recOff + 40)
in if slabOff == 0 || slabLen == 0 || slabOff >= BS.length bs
then Nothing
else
let !payloadBS = extractPayloadBytes bs slabOff slabLen recFlags
(_, !bundle, !mSummary) = decodePayloadBS payloadBS
in Just (bundle, mSummary)
else probe startIdx count (slot + 1) h
decodePayloadBS :: BS.ByteString -> (FilePath, FingerprintBundle, Maybe FileGraphSummary)
decodePayloadBS bs =
let !normLen = fromIntegral (readWord16LE bs 0) :: Int
!pBS = BS.take normLen (BS.drop 2 bs)
!path = T.unpack (TE.decodeUtf8Lenient pBS)
!off = 2 + normLen
!flags = readWord16LE bs off
!b0 = BS.take 32 (BS.drop (off + 2) bs)
!b1 = BS.take 32 (BS.drop (off + 34) bs)
!b2 = BS.take 32 (BS.drop (off + 66) bs)
!b3 = BS.take 32 (BS.drop (off + 98) bs)
!bcg = BS.take 32 (BS.drop (off + 130) bs)
!bcf = BS.take 32 (BS.drop (off + 162) bs)
!bdf = BS.take 32 (BS.drop (off + 194) bs)
!bt = BS.take 32 (BS.drop (off + 226) bs)
!b4 = BS.take 32 (BS.drop (off + 258) bs)
!f0 = decodeDigest flags 0 b0
!f1 = decodeDigest flags 1 b1
!f2 = decodeDigest flags 2 b2
!f3 = decodeDigest flags 3 b3
!fcg = decodeDigest flags 4 bcg
!fcf = decodeDigest flags 5 bcf
!fdf = decodeDigest flags 6 bdf
!ft = decodeDigest flags 8 bt
!f4 = decodeDigest flags 7 b4
!bundle = FingerprintBundle (Fingerprint f0) (Fingerprint f1) (Fingerprint f2) (Fingerprint f3)
(Fingerprint fcg) (Fingerprint fcf) (Fingerprint fdf) (Fingerprint ft)
(Fingerprint f4)
!sumLenOff = off + 290
!mSummary =
if sumLenOff + 4 > BS.length bs
then Nothing
else
let !sumLen = fromIntegral (readWord32LE bs sumLenOff) :: Int
in if sumLen == 0 || sumLenOff + 4 + sumLen > BS.length bs
then Nothing
else fmap fst (decodeFileGraphSummary bs (sumLenOff + 4))
in (path, bundle, mSummary)
-- ============================================================================
-- Full Binary Decoding & Resilient 4KB Bit-Rot Recovery
-- ============================================================================
-- | Decode all entries from a CNTR\x07 ByteString (strictly requiring 0 corrupted pages).
decodeSlabV7Binary
:: BS.ByteString
-> Maybe (Map FilePath SlabV7Entry, Maybe (WholeRepoBundle, CSRGraph, CSRGraph))
decodeSlabV7Binary bs
| BS.length bs < 2080 || not (verifySlabV7HeaderCRC bs) = Nothing
| otherwise =
let (entries, mRepo, corrupted) = decodeSlabV7Resilient bs
in if null corrupted then Just (entries, mRepo) else Nothing
-- | Decode a CNTR\x07 slab cache with isolated 4KB page bit-rot recovery.
decodeSlabV7Resilient
:: BS.ByteString
-> (Map FilePath SlabV7Entry, Maybe (WholeRepoBundle, CSRGraph, CSRGraph), [Word32])
decodeSlabV7Resilient bs
| BS.length bs < 2080 || not (verifySlabV7HeaderCRC bs) = (Map.empty, Nothing, [0])
| otherwise =
let !numRecords = readWord32LE bs 8
!capacity = readWord32LE bs 12
!repoOff = readWord32LE bs 20
!repoLen = readWord32LE bs 24
!totalBytes = BS.length bs
!slabStart = 2080 + fromIntegral capacity * 64 :: Int
!totalSlabPages = if totalBytes > slabStart then (totalBytes - slabStart + 4095) `div` 4096 else 0
checkPage p =
let !pageOff = slabStart + p * 4096
in if pageOff + 4096 > totalBytes
then False
else
let !storedCRC = readWord32LE bs pageOff
!body = BS.take 4088 (BS.drop (pageOff + 8) bs)
in storedCRC == computeCRC32 body
corruptedPages =
[ fromIntegral p
| p <- [0 .. totalSlabPages - 1]
, not (checkPage p)
]
corruptedSet = Map.fromList [(p, ()) | p <- corruptedPages]
anyPageCorrupt startPage numP =
any (\dp -> Map.member (startPage + dp) corruptedSet) [0 .. numP - 1]
decodeRecord slot
| slot >= fromIntegral numRecords = Nothing
| otherwise =
let !recOff = 2080 + slot * 64
!mt = readWord64LE bs (recOff + 8)
!sz = readWord32LE bs (recOff + 20)
!off = fromIntegral (readWord32LE bs (recOff + 24)) :: Int
!len = fromIntegral (readWord32LE bs (recOff + 28)) :: Int
!recFlags = readWord64LE bs (recOff + 40)
!startPage = fromIntegral ((off - slabStart) `div` 4096) :: Word32
!numP = if (recFlags .&. flagMultiPagePayload) == 0
then 1
else fromIntegral (max 1 ((len + 4087) `div` 4088))
in if off < slabStart || len == 0 || off + 4 > totalBytes || anyPageCorrupt startPage numP
then Nothing
else
let !payloadBS = extractPayloadBytes bs off len recFlags
!(path, bundle, mSummary) = decodePayloadBS payloadBS
!meta = FileMetadata path (fromIntegral sz) (fromIntegral mt)
in Just (path, SlabV7Entry meta bundle mSummary)
validEntries = Map.fromList
[ item
| slot <- [0 .. fromIntegral numRecords - 1]
, Just item <- [decodeRecord slot]
]
mRepo =
if repoOff == 0 || fromIntegral repoOff < slabStart || fromIntegral repoOff >= totalBytes
then Nothing
else
let !repoStartPage = fromIntegral ((fromIntegral repoOff - slabStart) `div` 4096) :: Word32
!repoSpan = max 1 (readWord32LE bs (fromIntegral repoOff + 4)) :: Word32
in if anyPageCorrupt repoStartPage repoSpan
then Nothing
else
let !repoBody = extractPayloadBytes bs (fromIntegral repoOff) (fromIntegral repoLen) flagMultiPagePayload
in decodeRepoBodyBytes repoBody
in (validEntries, mRepo, corruptedPages)
-- ============================================================================
-- Disk File Operations & Transparent Cache Migration
-- ============================================================================
-- | Write CNTR\x07 entries and optional repository graphs atomically to disk.
writeSlabV7File
:: FilePath
-> [SlabV7Entry]
-> Maybe (WholeRepoBundle, CSRGraph, CSRGraph)
-> IO ()
writeSlabV7File cachePath entries mRepo = do
createDirectoryIfMissing True (takeDirectory cachePath)
pid <- getCurrentPid
let !encoded = encodeSlabV7Binary entries mRepo
!tmpPath = cachePath ++ ".tmp." ++ show pid
BS.writeFile tmpPath encoded
atomicSwapWithRetry_ tmpPath cachePath
-- | Read a CNTR\x07 slab cache file from disk.
readSlabV7File
:: FilePath
-> IO (Maybe (Map FilePath SlabV7Entry, Maybe (WholeRepoBundle, CSRGraph, CSRGraph)))
readSlabV7File cachePath = do
exists <- doesFileExist cachePath
if not exists
then pure Nothing
else do
bs <- BS.readFile cachePath
case decodeSlabV7Binary bs of
Just res -> pure (Just res)
Nothing -> do
let (validEntries, mRepo, corruptedPages) = decodeSlabV7Resilient bs
if Map.null validEntries && null corruptedPages
then pure Nothing
else pure (Just (validEntries, mRepo))
-- | Read a CNTR\x07 slab cache file with isolated 4KB page bit-rot recovery.
readSlabV7FileResilient
:: FilePath
-> IO (Map FilePath SlabV7Entry, Maybe (WholeRepoBundle, CSRGraph, CSRGraph), [Word32])
readSlabV7FileResilient cachePath = do
exists <- doesFileExist cachePath
if not exists
then pure (Map.empty, Nothing, [])
else do
bs <- BS.readFile cachePath
pure (decodeSlabV7Resilient bs)
-- | Read CNTR\x07, CNTR\x06, or CNTR\x05 binary buffers transparently into 'SlabV7Entry' maps.
-- Returns 'Nothing' for older versions (<= 4 or legacy JSON) so callers can fall back cleanly.
readAnySlabCacheForV7
:: BS.ByteString
-> Maybe (Map FilePath SlabV7Entry, Maybe (WholeRepoBundle, CSRGraph, CSRGraph))
readAnySlabCacheForV7 bs
| BS.length bs < 32 || BS.take 4 bs /= "CNTR" = Nothing
| otherwise = case readWord16LE bs 4 of
7 ->
let (entries, mRepo, corrupted) = decodeSlabV7Resilient bs
in if Map.null entries && not (null corrupted) && corrupted == [0]
then Nothing
else Just (entries, mRepo)
6 ->
let (entries, mRepo, corrupted) = decodeSlabV6Resilient bs
in if Map.null entries && not (null corrupted) && corrupted == [0]
then Nothing
else Just (Map.map (\(m, b) -> SlabV7Entry m b Nothing) entries, mRepo)
5 -> case decodeBinaryCacheV5 bs of
Nothing -> Nothing
Just (MerkleCache mc) ->
Just (Map.mapWithKey (\p (MerkleCacheEntry sz mt b) -> SlabV7Entry (FileMetadata p sz mt) b Nothing) mc, Nothing)
_ -> Nothing