packages feed

pykinos-core 0.1.0.2 → 0.1.1.0

raw patch · 20 files changed

+3325/−8 lines, 20 filesdep +bytestringdep +deepseqdep +tasty-benchdep ~pykinos-corePVP ok

version bump matches the API change (PVP)

Dependencies added: bytestring, deepseq, tasty-bench

Dependency ranges changed: pykinos-core

API changes (from Hackage documentation)

+ Pykinos.DSU.WordDSU: data WordDSU s
+ Pykinos.DSU.WordDSU: dsuSize :: WordDSU s -> Int
+ Pykinos.DSU.WordDSU: findRoot :: WordDSU s -> Word32 -> ST s Word32
+ Pykinos.DSU.WordDSU: newWordDSU :: Int -> ST s (WordDSU s)
+ Pykinos.DSU.WordDSU: sameSet :: WordDSU s -> Word32 -> Word32 -> ST s Bool
+ Pykinos.DSU.WordDSU: unionNodes :: WordDSU s -> Word32 -> Word32 -> ST s Bool
+ Pykinos.Filter.BlockedBloom: blockedBloomBlocks :: BlockedBloom -> Int
+ Pykinos.Filter.BlockedBloom: buildBlockedBloom :: [Word64] -> BlockedBloom
+ Pykinos.Filter.BlockedBloom: data BlockedBloom
+ Pykinos.Filter.BlockedBloom: memberBlockedBloom :: Word64 -> BlockedBloom -> Bool
+ Pykinos.Filter.Ribbon: buildRibbonFilter :: [Word64] -> RibbonFilter
+ Pykinos.Filter.Ribbon: data RibbonFilter
+ Pykinos.Filter.Ribbon: memberRibbonFilter :: Word64 -> RibbonFilter -> Bool
+ Pykinos.Filter.Ribbon: ribbonBitsPerKey :: RibbonFilter -> Double
+ Pykinos.Filter.Ribbon: ribbonSize :: RibbonFilter -> Int
+ Pykinos.Graph.WorkDAG: CycleDetected :: [Word32] -> CycleDetected
+ Pykinos.Graph.WorkDAG: [cyclePath] :: CycleDetected -> [Word32]
+ Pykinos.Graph.WorkDAG: addEdgePK :: WorkDAG s -> Word32 -> Word32 -> ST s (Either [Word32] ())
+ Pykinos.Graph.WorkDAG: completeNode :: WorkDAG s -> Word32 -> ST s [Word32]
+ Pykinos.Graph.WorkDAG: data WorkDAG s
+ Pykinos.Graph.WorkDAG: getInDegree :: WorkDAG s -> Word32 -> ST s Int
+ Pykinos.Graph.WorkDAG: getNodeRank :: WorkDAG s -> Word32 -> ST s Int
+ Pykinos.Graph.WorkDAG: instance GHC.Internal.Classes.Eq Pykinos.Graph.WorkDAG.CycleDetected
+ Pykinos.Graph.WorkDAG: instance GHC.Internal.Show.Show Pykinos.Graph.WorkDAG.CycleDetected
+ Pykinos.Graph.WorkDAG: isEdgePresent :: WorkDAG s -> Word32 -> Word32 -> ST s Bool
+ Pykinos.Graph.WorkDAG: newWorkDAG :: ST s (WorkDAG s)
+ Pykinos.Graph.WorkDAG: newtype CycleDetected
+ Pykinos.Interval.IntervalMap: Extent :: Word64 -> Word64 -> a -> Extent a
+ Pykinos.Interval.IntervalMap: [extHi] :: Extent a -> Word64
+ Pykinos.Interval.IntervalMap: [extLo] :: Extent a -> Word64
+ Pykinos.Interval.IntervalMap: [extVal] :: Extent a -> a
+ Pykinos.Interval.IntervalMap: data Extent a
+ Pykinos.Interval.IntervalMap: data IntervalMap a
+ Pykinos.Interval.IntervalMap: emptyIntervalMap :: IntervalMap a
+ Pykinos.Interval.IntervalMap: extentList :: IntervalMap a -> [(Word64, Word64, a)]
+ Pykinos.Interval.IntervalMap: findFreeGap :: Word64 -> Word64 -> Word64 -> IntervalMap a -> Maybe Word64
+ Pykinos.Interval.IntervalMap: insertExtent :: Eq a => Word64 -> Word64 -> a -> IntervalMap a -> Either String (IntervalMap a)
+ Pykinos.Interval.IntervalMap: instance GHC.Internal.Classes.Eq a => GHC.Internal.Classes.Eq (Pykinos.Interval.IntervalMap.Extent a)
+ Pykinos.Interval.IntervalMap: instance GHC.Internal.Classes.Eq a => GHC.Internal.Classes.Eq (Pykinos.Interval.IntervalMap.IntervalMap a)
+ Pykinos.Interval.IntervalMap: instance GHC.Internal.Show.Show a => GHC.Internal.Show.Show (Pykinos.Interval.IntervalMap.Extent a)
+ Pykinos.Interval.IntervalMap: instance GHC.Internal.Show.Show a => GHC.Internal.Show.Show (Pykinos.Interval.IntervalMap.IntervalMap a)
+ Pykinos.Interval.IntervalMap: intervalMapSize :: IntervalMap a -> Int
+ Pykinos.Interval.IntervalMap: lookupPoint :: Word64 -> IntervalMap a -> Maybe a
+ Pykinos.Interval.IntervalMap: queryOverlap :: Word64 -> Word64 -> IntervalMap a -> [(Word64, Word64, a)]
+ Pykinos.Net.MsgAssoc: MsgAssoc :: SackWindow -> Map Word16 Word16 -> Map Word16 (Map Word16 ByteString) -> [ByteString] -> MsgAssoc
+ Pykinos.Net.MsgAssoc: MsgChunk :: Word32 -> Word16 -> Word16 -> StreamPolicy -> ByteString -> MsgChunk
+ Pykinos.Net.MsgAssoc: StreamOrdered :: StreamPolicy
+ Pykinos.Net.MsgAssoc: StreamPartialTTL :: Int -> StreamPolicy
+ Pykinos.Net.MsgAssoc: StreamUnordered :: StreamPolicy
+ Pykinos.Net.MsgAssoc: [maBuffer] :: MsgAssoc -> Map Word16 (Map Word16 ByteString)
+ Pykinos.Net.MsgAssoc: [maDelivered] :: MsgAssoc -> [ByteString]
+ Pykinos.Net.MsgAssoc: [maNextSsn] :: MsgAssoc -> Map Word16 Word16
+ Pykinos.Net.MsgAssoc: [maSackWindow] :: MsgAssoc -> SackWindow
+ Pykinos.Net.MsgAssoc: [mcPayload] :: MsgChunk -> ByteString
+ Pykinos.Net.MsgAssoc: [mcPolicy] :: MsgChunk -> StreamPolicy
+ Pykinos.Net.MsgAssoc: [mcSsn] :: MsgChunk -> Word16
+ Pykinos.Net.MsgAssoc: [mcStreamId] :: MsgChunk -> Word16
+ Pykinos.Net.MsgAssoc: [mcTsn] :: MsgChunk -> Word32
+ Pykinos.Net.MsgAssoc: data MsgAssoc
+ Pykinos.Net.MsgAssoc: data MsgChunk
+ Pykinos.Net.MsgAssoc: data StreamPolicy
+ Pykinos.Net.MsgAssoc: extractDeliverable :: MsgAssoc -> ([ByteString], MsgAssoc)
+ Pykinos.Net.MsgAssoc: initMsgAssoc :: Word32 -> MsgAssoc
+ Pykinos.Net.MsgAssoc: instance GHC.Internal.Classes.Eq Pykinos.Net.MsgAssoc.MsgAssoc
+ Pykinos.Net.MsgAssoc: instance GHC.Internal.Classes.Eq Pykinos.Net.MsgAssoc.MsgChunk
+ Pykinos.Net.MsgAssoc: instance GHC.Internal.Classes.Eq Pykinos.Net.MsgAssoc.StreamPolicy
+ Pykinos.Net.MsgAssoc: instance GHC.Internal.Show.Show Pykinos.Net.MsgAssoc.MsgAssoc
+ Pykinos.Net.MsgAssoc: instance GHC.Internal.Show.Show Pykinos.Net.MsgAssoc.MsgChunk
+ Pykinos.Net.MsgAssoc: instance GHC.Internal.Show.Show Pykinos.Net.MsgAssoc.StreamPolicy
+ Pykinos.Net.MsgAssoc: receiveChunk :: MsgChunk -> MsgAssoc -> (TsnOutcome, MsgAssoc, [ByteString])
+ Pykinos.Net.SackWindow: SackGap :: Word16 -> Word16 -> SackGap
+ Pykinos.Net.SackWindow: SackWindow :: Word32 -> Word64 -> SackWindow
+ Pykinos.Net.SackWindow: TsnAcceptedNew :: TsnOutcome
+ Pykinos.Net.SackWindow: TsnDuplicate :: TsnOutcome
+ Pykinos.Net.SackWindow: TsnOutOfWindow :: TsnOutcome
+ Pykinos.Net.SackWindow: [gapEnd] :: SackGap -> Word16
+ Pykinos.Net.SackWindow: [gapStart] :: SackGap -> Word16
+ Pykinos.Net.SackWindow: [swBitmap] :: SackWindow -> Word64
+ Pykinos.Net.SackWindow: [swCumTsn] :: SackWindow -> Word32
+ Pykinos.Net.SackWindow: advanceForwardTsn :: Word32 -> SackWindow -> SackWindow
+ Pykinos.Net.SackWindow: data SackGap
+ Pykinos.Net.SackWindow: data SackWindow
+ Pykinos.Net.SackWindow: data TsnOutcome
+ Pykinos.Net.SackWindow: extractSackGaps :: SackWindow -> [SackGap]
+ Pykinos.Net.SackWindow: initSackWindow :: Word32 -> SackWindow
+ Pykinos.Net.SackWindow: instance GHC.Internal.Classes.Eq Pykinos.Net.SackWindow.SackGap
+ Pykinos.Net.SackWindow: instance GHC.Internal.Classes.Eq Pykinos.Net.SackWindow.SackWindow
+ Pykinos.Net.SackWindow: instance GHC.Internal.Classes.Eq Pykinos.Net.SackWindow.TsnOutcome
+ Pykinos.Net.SackWindow: instance GHC.Internal.Classes.Ord Pykinos.Net.SackWindow.SackGap
+ Pykinos.Net.SackWindow: instance GHC.Internal.Classes.Ord Pykinos.Net.SackWindow.SackWindow
+ Pykinos.Net.SackWindow: instance GHC.Internal.Classes.Ord Pykinos.Net.SackWindow.TsnOutcome
+ Pykinos.Net.SackWindow: instance GHC.Internal.Enum.Bounded Pykinos.Net.SackWindow.TsnOutcome
+ Pykinos.Net.SackWindow: instance GHC.Internal.Enum.Enum Pykinos.Net.SackWindow.TsnOutcome
+ Pykinos.Net.SackWindow: instance GHC.Internal.Show.Show Pykinos.Net.SackWindow.SackGap
+ Pykinos.Net.SackWindow: instance GHC.Internal.Show.Show Pykinos.Net.SackWindow.SackWindow
+ Pykinos.Net.SackWindow: instance GHC.Internal.Show.Show Pykinos.Net.SackWindow.TsnOutcome
+ Pykinos.Net.SackWindow: recordTsn :: Word32 -> SackWindow -> (TsnOutcome, SackWindow)
+ Pykinos.Net.SackWindow: serialDiff :: Word32 -> Word32 -> Int32
+ Pykinos.Net.SackWindow: serialLess :: Word32 -> Word32 -> Bool
+ Pykinos.Queue.BitTrie64: data BitTrie64 s
+ Pykinos.Queue.BitTrie64: deleteTrie :: BitTrie64 s -> Int -> ST s Bool
+ Pykinos.Queue.BitTrie64: findMaxTrie :: BitTrie64 s -> ST s (Maybe Int)
+ Pykinos.Queue.BitTrie64: findMinTrie :: BitTrie64 s -> ST s (Maybe Int)
+ Pykinos.Queue.BitTrie64: insertTrie :: BitTrie64 s -> Int -> ST s Bool
+ Pykinos.Queue.BitTrie64: maxBitTrieKey :: Int
+ Pykinos.Queue.BitTrie64: memberTrie :: BitTrie64 s -> Int -> ST s Bool
+ Pykinos.Queue.BitTrie64: newBitTrie64 :: ST s (BitTrie64 s)
+ Pykinos.Queue.BitTrie64: popMinTrie :: BitTrie64 s -> ST s (Maybe Int)
+ Pykinos.Queue.RadixHeap: data RadixHeap s
+ Pykinos.Queue.RadixHeap: findMinRadix :: RadixHeap s -> ST s (Maybe (Word64, Word32))
+ Pykinos.Queue.RadixHeap: insertRadix :: RadixHeap s -> Word64 -> Word32 -> ST s ()
+ Pykinos.Queue.RadixHeap: newRadixHeap :: ST s (RadixHeap s)
+ Pykinos.Queue.RadixHeap: popMinRadix :: RadixHeap s -> ST s (Maybe (Word64, Word32))
+ Pykinos.Queue.RadixHeap: radixSize :: RadixHeap s -> ST s Int
+ Pykinos.Queue.TimingWheel: advanceTick :: TimingWheel s -> ST s [Word32]
+ Pykinos.Queue.TimingWheel: armTimer :: TimingWheel s -> Word64 -> Word32 -> ST s ()
+ Pykinos.Queue.TimingWheel: currentTick :: TimingWheel s -> ST s Word64
+ Pykinos.Queue.TimingWheel: data TimingWheel s
+ Pykinos.Queue.TimingWheel: instance GHC.Internal.Classes.Eq Pykinos.Queue.TimingWheel.TimerEntry
+ Pykinos.Queue.TimingWheel: instance GHC.Internal.Show.Show Pykinos.Queue.TimingWheel.TimerEntry
+ Pykinos.Queue.TimingWheel: newTimingWheel :: ST s (TimingWheel s)
+ Pykinos.Queue.WordHeap8: data WordHeap8 s
+ Pykinos.Queue.WordHeap8: findMinHeap8 :: WordHeap8 s -> ST s (Maybe (Word64, Word32))
+ Pykinos.Queue.WordHeap8: heap8Size :: WordHeap8 s -> ST s Int
+ Pykinos.Queue.WordHeap8: insertHeap8 :: WordHeap8 s -> Word64 -> Word32 -> ST s ()
+ Pykinos.Queue.WordHeap8: newWordHeap8 :: Int -> ST s (WordHeap8 s)
+ Pykinos.Queue.WordHeap8: popMinHeap8 :: WordHeap8 s -> ST s (Maybe (Word64, Word32))
+ Pykinos.Queue.WordRing: clearRing :: WordRing s -> ST s ()
+ Pykinos.Queue.WordRing: data WordRing s
+ Pykinos.Queue.WordRing: newWordRing :: Int -> ST s (WordRing s)
+ Pykinos.Queue.WordRing: popBack :: WordRing s -> ST s (Maybe Word32)
+ Pykinos.Queue.WordRing: popFront :: WordRing s -> ST s (Maybe Word32)
+ Pykinos.Queue.WordRing: pushBack :: WordRing s -> Word32 -> ST s ()
+ Pykinos.Queue.WordRing: ringCapacity :: WordRing s -> ST s Int
+ Pykinos.Queue.WordRing: ringLength :: WordRing s -> ST s Int
+ Pykinos.Queue.WordWorklist: data WordWorklist s
+ Pykinos.Queue.WordWorklist: dequeueWork :: WordWorklist s -> ST s (Maybe Word32)
+ Pykinos.Queue.WordWorklist: enqueueUnique :: WordWorklist s -> Word32 -> ST s Bool
+ Pykinos.Queue.WordWorklist: isWorklistMember :: WordWorklist s -> Word32 -> ST s Bool
+ Pykinos.Queue.WordWorklist: newWordWorklist :: Int -> ST s (WordWorklist s)
+ Pykinos.Queue.WordWorklist: worklistLength :: WordWorklist s -> ST s Int
+ Pykinos.Rel.DynamicRel: DynamicRel :: IntMap [Word32] -> IntMap [Word32] -> IntMap [Word32] -> IntMap [Word32] -> IntMap [Word32] -> DynamicRel
+ Pykinos.Rel.DynamicRel: [relDeltaBwd] :: DynamicRel -> IntMap [Word32]
+ Pykinos.Rel.DynamicRel: [relDeltaFwd] :: DynamicRel -> IntMap [Word32]
+ Pykinos.Rel.DynamicRel: [relNewFwd] :: DynamicRel -> IntMap [Word32]
+ Pykinos.Rel.DynamicRel: [relStableBwd] :: DynamicRel -> IntMap [Word32]
+ Pykinos.Rel.DynamicRel: [relStableFwd] :: DynamicRel -> IntMap [Word32]
+ Pykinos.Rel.DynamicRel: data DynamicRel
+ Pykinos.Rel.DynamicRel: emptyDynamicRel :: DynamicRel
+ Pykinos.Rel.DynamicRel: getDeltaEdges :: DynamicRel -> [(Word32, Word32)]
+ Pykinos.Rel.DynamicRel: getStableEdges :: DynamicRel -> [(Word32, Word32)]
+ Pykinos.Rel.DynamicRel: insertDelta :: Word32 -> Word32 -> DynamicRel -> DynamicRel
+ Pykinos.Rel.DynamicRel: instance GHC.Internal.Classes.Eq Pykinos.Rel.DynamicRel.DynamicRel
+ Pykinos.Rel.DynamicRel: instance GHC.Internal.Show.Show Pykinos.Rel.DynamicRel.DynamicRel
+ Pykinos.Rel.DynamicRel: leapfrogIntersect :: [Word32] -> [Word32] -> [Word32]
+ Pykinos.Rel.DynamicRel: stepSemiNaive :: DynamicRel -> DynamicRel
+ Pykinos.Rel.DynamicRel: triangleJoinWCOJ :: DynamicRel -> [(Word32, Word32, Word32)]
+ Pykinos.Storage.WalSlab: WalRecord :: Word64 -> ByteString -> WalRecord
+ Pykinos.Storage.WalSlab: [recEpoch] :: WalRecord -> Word64
+ Pykinos.Storage.WalSlab: [recPayload] :: WalRecord -> ByteString
+ Pykinos.Storage.WalSlab: appendWalRecord :: WalSlab -> Word64 -> ByteString -> IO ()
+ Pykinos.Storage.WalSlab: computeCrc32c :: ByteString -> Word32
+ Pykinos.Storage.WalSlab: data WalRecord
+ Pykinos.Storage.WalSlab: data WalSlab
+ Pykinos.Storage.WalSlab: instance GHC.Internal.Classes.Eq Pykinos.Storage.WalSlab.WalRecord
+ Pykinos.Storage.WalSlab: instance GHC.Internal.Show.Show Pykinos.Storage.WalSlab.WalRecord
+ Pykinos.Storage.WalSlab: newWalSlab :: IO WalSlab
+ Pykinos.Storage.WalSlab: replayWalSlab :: ByteString -> ([WalRecord], Bool)
+ Pykinos.Storage.WalSlab: walSlabBytes :: WalSlab -> IO ByteString
+ Pykinos.Text.PieceRope: TextMetrics :: Int -> Int -> Int -> Int -> Int -> TextMetrics
+ Pykinos.Text.PieceRope: [tmDispWidth] :: TextMetrics -> Int
+ Pykinos.Text.PieceRope: [tmGraphemes] :: TextMetrics -> Int
+ Pykinos.Text.PieceRope: [tmLines] :: TextMetrics -> Int
+ Pykinos.Text.PieceRope: [tmUtf16Units] :: TextMetrics -> Int
+ Pykinos.Text.PieceRope: [tmUtf8Bytes] :: TextMetrics -> Int
+ Pykinos.Text.PieceRope: appendRope :: PieceRope -> PieceRope -> PieceRope
+ Pykinos.Text.PieceRope: byteToLineCol :: PieceRope -> Int -> (Int, Int)
+ Pykinos.Text.PieceRope: byteToUtf16 :: PieceRope -> Int -> Int
+ Pykinos.Text.PieceRope: data PieceRope
+ Pykinos.Text.PieceRope: data TextMetrics
+ Pykinos.Text.PieceRope: deleteRangeByte :: Int -> Int -> PieceRope -> PieceRope
+ Pykinos.Text.PieceRope: emptyRope :: PieceRope
+ Pykinos.Text.PieceRope: fromText :: Text -> PieceRope
+ Pykinos.Text.PieceRope: insertAtByte :: Int -> Text -> PieceRope -> PieceRope
+ Pykinos.Text.PieceRope: instance GHC.Internal.Base.Monoid Pykinos.Text.PieceRope.TextMetrics
+ Pykinos.Text.PieceRope: instance GHC.Internal.Base.Semigroup Pykinos.Text.PieceRope.TextMetrics
+ Pykinos.Text.PieceRope: instance GHC.Internal.Classes.Eq Pykinos.Text.PieceRope.PieceRope
+ Pykinos.Text.PieceRope: instance GHC.Internal.Classes.Eq Pykinos.Text.PieceRope.TextMetrics
+ Pykinos.Text.PieceRope: instance GHC.Internal.Classes.Ord Pykinos.Text.PieceRope.TextMetrics
+ Pykinos.Text.PieceRope: instance GHC.Internal.Show.Show Pykinos.Text.PieceRope.PieceRope
+ Pykinos.Text.PieceRope: instance GHC.Internal.Show.Show Pykinos.Text.PieceRope.TextMetrics
+ Pykinos.Text.PieceRope: lineColToByte :: PieceRope -> (Int, Int) -> Int
+ Pykinos.Text.PieceRope: maxLeafBytes :: Int
+ Pykinos.Text.PieceRope: measureText :: Text -> TextMetrics
+ Pykinos.Text.PieceRope: ropeByteLength :: PieceRope -> Int
+ Pykinos.Text.PieceRope: ropeHeight :: PieceRope -> Int
+ Pykinos.Text.PieceRope: ropeMetrics :: PieceRope -> TextMetrics
+ Pykinos.Text.PieceRope: sliceBytes :: Int -> Int -> PieceRope -> Text
+ Pykinos.Text.PieceRope: splitAtByte :: Int -> PieceRope -> (PieceRope, PieceRope)
+ Pykinos.Text.PieceRope: toText :: PieceRope -> Text
+ Pykinos.Text.PieceRope: utf16ToByte :: PieceRope -> Int -> Int
+ Pykinos.Tree.BPlus: instance GHC.Internal.Data.Traversable.Traversable (Pykinos.Tree.BPlus.BPlusMap k)
+ Pykinos.Tree.BPlus: instance GHC.Internal.Data.Traversable.Traversable (Pykinos.Tree.BPlus.BPlusNode k)

Files

+ bench/Main.hs view
@@ -0,0 +1,377 @@+{-# LANGUAGE BangPatterns #-}+{-# LANGUAGE ScopedTypeVariables #-}+{-# OPTIONS_GHC -Wno-orphans #-}+{-# OPTIONS_GHC -Wno-unused-imports #-}++-- |+-- Module      : Main+-- Description : Quantitative microbenchmarks comparing pykinos-core against containers+--+-- Run with allocation tracking enabled:+--   cabal v2-bench pykinos-bench --benchmark-options='--csv=dist-newstyle/pykinos-bench.csv +RTS -T -RTS'+module Main (main) where++import Control.DeepSeq (NFData(..))+import Data.Bits (xor)+import Data.Char (ord)+import Data.IntMap.Strict (IntMap)+import qualified Data.IntMap.Strict as IM+import Data.IntSet (IntSet)+import qualified Data.IntSet as IS+import Data.List (foldl')+import qualified Data.Sequence as Seq+import Data.Text (Text)+import qualified Data.Text as T+import Data.Word (Word64)+import Test.Tasty.Bench+import Pykinos.Text.PieceRope+import Control.Monad (forM_)+import Control.Monad.ST (runST)+import Data.Word (Word32, Word64)+import Pykinos.Queue.BitTrie64+import Pykinos.Queue.WordRing+import Pykinos.Queue.WordWorklist+import Pykinos.Queue.RadixHeap+import Pykinos.Queue.WordHeap8+import Pykinos.DSU.WordDSU+import Pykinos.Interval.IntervalMap+import Pykinos.Filter.BlockedBloom+import Pykinos.Filter.Ribbon+import Pykinos.Storage.WalSlab+import Pykinos.Graph.WorkDAG+import Pykinos.Rel.DynamicRel+import Pykinos.Net.SackWindow+import Pykinos.Net.MsgAssoc+import qualified Data.Map.Strict as Map+import qualified Data.ByteString as BS+import qualified Data.ByteString.Char8 as BSC++import Pykinos.Bitset.Roaring+  ( RoaringIntSet+  , fromListRoaring+  , memberRoaring+  , unionRoaring+  )+import Pykinos.IntMap.ART+  ( ARTIntMap+  , artFromList+  , artLookup+  )+import Pykinos.Tree.BPlus+  ( BPlusMap+  , emptyBPlus+  , insertBPlus+  , lookupBPlus+  )+import Pykinos.Tree.FAST+  ( FASTMap+  , freezeFAST+  , lookupFAST+  )++-- ============================================================================+-- NFData Stand-in Instances for Benchmark Harness+-- ============================================================================++instance NFData RoaringIntSet where+  rnf !_ = ()++instance NFData (ARTIntMap v) where+  rnf !_ = ()++instance NFData (BPlusMap k v) where+  rnf !_ = ()++instance NFData (FASTMap k v) where+  rnf !_ = ()++instance NFData PieceRope where+  rnf !_ = ()++-- ============================================================================+-- Deterministic Key Generators+-- ============================================================================++-- | Deterministic splitmix64-style key generator (zero extra dependencies).+genKeys :: Int -> Word64 -> [Int]+genKeys n seed0 = take n (go seed0)+  where+    go s =+      let s1 = s + 0x9e3779b97f4a7c15+          z1 = (s1 `xor` (s1 `div` (2 ^ (30 :: Int)))) * 0xbf58476d1ce4e5b9+          z2 = (z1 `xor` (z1 `div` (2 ^ (27 :: Int)))) * 0x94d049bb133111eb+          z3 = z2 `xor` (z2 `div` (2 ^ (31 :: Int)))+      in fromIntegral (z3 `mod` 10000000) : go s1++-- | Dense clustered keys modeling 64 KiB Roaring chunk workloads.+genClusteredKeys :: Int -> [Int]+genClusteredKeys n =+  [ (cluster * 65536) + offset+  | idx <- [0 .. n - 1]+  , let (cluster, offset) = idx `divMod` 1024+  ]++-- ============================================================================+-- PieceRope 100 KiB Benchmark Data & Helpers+-- ============================================================================++sampleDoc100KiB :: Text+sampleDoc100KiB =+  let line = T.pack "The quick brown fox jumps over the lazy dog. नमस्ते दुनिया! こんにちは世界 🚀🌟\n"+  in T.concat (replicate 800 line)++editOffsets500 :: [Int]+editOffsets500 = [ (i * 179) `mod` 90000 | i <- [1..500] ]++queries1000 :: [Int]+queries1000 = [ (i * 97) `mod` 90000 | i <- [1..1000] ]++textByteToLineCol :: Text -> Int -> (Int, Int)+textByteToLineCol txt off =+  let pfx = T.take (off `div` 4) txt+      ln  = T.count (T.singleton '\n') pfx+      lastNl = case T.breakOnEnd (T.singleton '\n') pfx of+                 (lPart, _) -> T.length lPart+  in (ln, max 0 ((off `div` 4) - lastNl))++textLineColToByte :: Text -> (Int, Int) -> Int+textLineColToByte txt (targetLine, col) =+  let linesList = T.splitOn (T.singleton '\n') txt+      pfxLines = take targetLine linesList+      lineStart = sum (map (\l -> T.length l + 1) pfxLines)+  in (lineStart + col) * 4++textByteToUtf16 :: Text -> Int -> Int+textByteToUtf16 txt off =+  let pfx = T.take (off `div` 4) txt+  in T.foldl' (\acc c -> acc + (if ord c >= 0x10000 then 2 else 1)) 0 pfx++textUtf16ToByte :: Text -> Int -> Int+textUtf16ToByte txt targetU16 =+  let go !chars !u remT =+        case T.uncons remT of+          Nothing -> chars * 4+          Just (c, rest) ->+            let u' = if ord c >= 0x10000 then 2 else 1+            in if u + u' > targetU16+                 then chars * 4+                 else go (chars + 1) (u + u') rest+  in go 0 0 txt++-- ============================================================================+-- Main Benchmark Suite+-- ============================================================================++main :: IO ()+main = defaultMain+  [ bgroup "roaring-vs-intset/member"+      [ env (pure (IS.fromList (genClusteredKeys 10000), genClusteredKeys 10000)) $ \ ~(s, ks) ->+          bench "IntSet/member-10k-clustered" $ whnf (\keys -> foldl' (\acc k -> if IS.member k s then acc + 1 else acc) (0 :: Int) keys) ks+      , env (pure (fromListRoaring (genClusteredKeys 10000), genClusteredKeys 10000)) $ \ ~(s, ks) ->+          bench "Roaring/member-10k-clustered" $ whnf (\keys -> foldl' (\acc k -> if memberRoaring k s then acc + 1 else acc) (0 :: Int) keys) ks+      ]+  , bgroup "roaring-vs-intset/union"+      [ env (pure ( IS.fromList (genClusteredKeys 5000)+                  , IS.fromList (map (+ 1000) (genClusteredKeys 5000))+                  )) $ \ ~(s1, s2) ->+          bench "IntSet/union-5k" $ whnf (uncurry IS.union) (s1, s2)+      , env (pure ( fromListRoaring (genClusteredKeys 5000)+                  , fromListRoaring (map (+ 1000) (genClusteredKeys 5000))+                  )) $ \ ~(s1, s2) ->+          bench "Roaring/union-5k" $ whnf (uncurry unionRoaring) (s1, s2)+      ]+  , bgroup "trees-vs-intmap/lookup"+      [ env (pure (IM.fromList [(k, k) | k <- genKeys 10000 42], genKeys 10000 42)) $ \ ~(m, ks) ->+          bench "IntMap/lookup-10k" $ whnf (\keys -> foldl' (\acc k -> maybe acc (+ acc) (IM.lookup k m)) (0 :: Int) keys) ks+      , env (pure (artFromList [(k, k) | k <- genKeys 10000 42], genKeys 10000 42)) $ \ ~(m, ks) ->+          bench "ART/lookup-10k" $ whnf (\keys -> foldl' (\acc k -> maybe acc (+ acc) (artLookup k m)) (0 :: Int) keys) ks+      , env (pure (foldl' (\t (k, v) -> insertBPlus k v t) emptyBPlus [(k, k) | k <- genKeys 10000 42], genKeys 10000 42)) $ \ ~(m, ks) ->+          bench "BPlus/lookup-10k" $ whnf (\keys -> foldl' (\acc k -> maybe acc (+ acc) (lookupBPlus k m)) (0 :: Int) keys) ks+      , env (pure (freezeFAST (foldl' (\t (k, v) -> insertBPlus k v t) emptyBPlus [(k, k) | k <- genKeys 10000 42]), genKeys 10000 42)) $ \ ~(m, ks) ->+          bench "FAST/lookup-10k" $ whnf (\keys -> foldl' (\acc k -> maybe acc (+ acc) (lookupFAST k m)) (0 :: Int) keys) ks+      ]+  , bgroup "piece-rope"+      [ bgroup "edits-500"+          [ env (pure (fromText sampleDoc100KiB, editOffsets500)) $ \ ~(rope, offs) ->+              bench "PieceRope" $ whnf (\os -> foldl' (\r off -> insertAtByte off (T.pack " [EDIT] ") r) rope os) offs+          , env (pure (sampleDoc100KiB, editOffsets500)) $ \ ~(txt, offs) ->+              bench "Data.Text" $ whnf (\os -> foldl' (\t off -> let (p, s) = T.splitAt (off `div` 4) t in p <> T.pack " [EDIT] " <> s) txt os) offs+          , env (pure (Seq.fromList (T.unpack sampleDoc100KiB), editOffsets500)) $ \ ~(seqChar, offs) ->+              bench "Data.Sequence" $ whnf (\os -> foldl' (\s off -> let (p, sf) = Seq.splitAt (off `div` 4) s in p <> Seq.fromList " [EDIT] " <> sf) seqChar os) offs+          ]+      , bgroup "line-col-1000"+          [ env (pure (fromText sampleDoc100KiB, queries1000)) $ \ ~(rope, qs) ->+              bench "PieceRope" $ whnf (\os -> foldl' (\acc off -> let (l, c) = byteToLineCol rope off in acc + lineColToByte rope (l, c)) (0 :: Int) os) qs+          , env (pure (sampleDoc100KiB, queries1000)) $ \ ~(txt, qs) ->+              bench "Data.Text" $ whnf (\os -> foldl' (\acc off -> let (l, c) = textByteToLineCol txt off in acc + textLineColToByte txt (l, c)) (0 :: Int) os) qs+          ]+      , bgroup "utf16-lsp-1000"+          [ env (pure (fromText sampleDoc100KiB, queries1000)) $ \ ~(rope, qs) ->+              bench "PieceRope" $ whnf (\os -> foldl' (\acc off -> let u16 = byteToUtf16 rope off in acc + utf16ToByte rope u16) (0 :: Int) os) qs+          , env (pure (sampleDoc100KiB, queries1000)) $ \ ~(txt, qs) ->+              bench "Data.Text" $ whnf (\os -> foldl' (\acc off -> let u16 = textByteToUtf16 txt off in acc + textUtf16ToByte txt u16) (0 :: Int) os) qs+          ]+      ]+  , bgroup "word-queues"+      [ bgroup "ring-worklist-vs-sequence-intset/50k"+          [ bench "WordRing+WordWorklist/50k" $ whnf (\n -> runST $ do+              wl <- newWordWorklist (fromIntegral n + 1)+              forM_ [1..n :: Word32] (enqueueUnique wl)+              let drain (!acc :: Word64) = do+                    m <- dequeueWork wl+                    case m of+                      Nothing -> pure acc+                      Just x  -> drain (acc + fromIntegral x)+              drain 0) (50000 :: Word32)+          , bench "Data.Sequence+Data.IntSet/50k" $ whnf (\n ->+              let q = fst $ foldl' (\(!sq, !st) x ->+                    if IS.member (fromIntegral x) st+                      then (sq, st)+                      else (sq Seq.|> x, IS.insert (fromIntegral x) st)) (Seq.empty, IS.empty) [1..n :: Word32]+                  drain (!acc :: Word64) sq = case Seq.viewl sq of+                    Seq.EmptyL       -> acc+                    x Seq.:< rest    -> drain (acc + fromIntegral x) rest+              in drain 0 q) (50000 :: Word32)+          ]+      , bgroup "radix-heap8-vs-intmap/50k"+          [ bench "RadixHeap/50k" $ whnf (\n -> runST $ do+              rh <- newRadixHeap+              forM_ [1..n :: Word64] (\k -> insertRadix rh k (fromIntegral k))+              let drain (!acc :: Word64) = do+                    m <- popMinRadix rh+                    case m of+                      Nothing -> pure acc+                      Just (k, _) -> drain (acc + fromIntegral k)+              drain 0) (50000 :: Word64)+          , bench "WordHeap8/50k" $ whnf (\n -> runST $ do+              h <- newWordHeap8 (fromIntegral n)+              forM_ [1..n :: Word64] (\k -> insertHeap8 h k (fromIntegral k))+              let drain (!acc :: Word64) = do+                    m <- popMinHeap8 h+                    case m of+                      Nothing -> pure acc+                      Just (k, _) -> drain (acc + fromIntegral k)+              drain 0) (50000 :: Word64)+          , bench "Data.IntMap/50k" $ whnf (\n ->+              let m = foldl' (\acc k -> IM.insert (fromIntegral k) (fromIntegral k :: Int) acc) IM.empty [1..n :: Word64]+                  drain (!acc :: Word64) im+                    | IM.null im = acc+                    | otherwise  = let ((k, _), rest) = IM.deleteFindMin im in drain (acc + fromIntegral k) rest+              in drain 0 m) (50000 :: Word64)+          ]+      , bgroup "bittrie64-vs-intset/50k"+          [ bench "BitTrie64/50k" $ whnf (\n -> runST $ do+              bt <- newBitTrie64+              forM_ [0..n-1 :: Int] (insertTrie bt)+              let drain (!acc :: Int) = do+                    m <- popMinTrie bt+                    case m of+                      Nothing -> pure acc+                      Just k  -> drain (acc + k)+              drain 0) (50000 :: Int)+          , bench "Data.IntSet/50k" $ whnf (\n ->+              let s = IS.fromList [0..n-1 :: Int]+                  drain (!acc :: Int) st+                    | IS.null st = acc+                    | otherwise  = let (k, rest) = IS.deleteFindMin st in drain (acc + k) rest+              in drain 0 s) (50000 :: Int)+          ]+      ]+  , bgroup "companions"+      [ bgroup "word-dsu-vs-boxed-intmap/50k"+          [ bench "WordDSU/50k" $ whnf (\n -> runST $ do+              dsu <- newWordDSU (fromIntegral n)+              forM_ [0..n-2 :: Word32] (\i -> unionNodes dsu i (i + 1))+              let check acc 0 = pure acc+                  check acc i = do+                    r <- sameSet dsu 0 i+                    check (acc + if r then 1 else 0) (i - 1)+              check (0 :: Int) (n - 1)) (50000 :: Word32)+          , bench "Boxed-IntMap-DSU/50k" $ whnf (\n ->+              let initDSU = IM.fromList [(i, (i, 0 :: Int)) | i <- [0..fromIntegral n-1]]+                  findRootIM !m !x =+                    let (p, _) = m IM.! x+                    in if p == x then (m, p) else let (m2, root) = findRootIM m p in (IM.insert x (root, snd (m IM.! x)) m2, root)+                  unionIM !m !a !b =+                    let (m1, ra) = findRootIM m a+                        (m2, rb) = findRootIM m1 b+                    in if ra == rb then m2 else IM.insert rb (ra, snd (m2 IM.! rb)) m2+                  built = foldl' (\m i -> unionIM m i (i + 1)) initDSU [0..fromIntegral n-2]+                  check !acc 0 = acc+                  check !acc i =+                    let (_, r0) = findRootIM built 0+                        (_, ri) = findRootIM built i+                    in check (acc + if r0 == ri then 1 else 0) (i - 1)+              in check (0 :: Int) (fromIntegral n - 1)) (50000 :: Word32)+          ]+      , bgroup "interval-map-vs-datamap/20k"+          [ bench "IntervalMap/20k" $ whnf (\n ->+              let !m = foldl' (\acc i ->+                         case insertExtent (fromIntegral i * 2) (fromIntegral i * 2 + 1) (i :: Int) acc of+                           Left _ -> acc+                           Right m' -> m') emptyIntervalMap [0..n-1 :: Int]+                  !stabs = foldl' (\acc i -> acc + case lookupPoint (fromIntegral i * 2) m of Just x -> x; Nothing -> 0) 0 [0..n-1 :: Int]+              in stabs) (20000 :: Int)+          , bench "Data.Map-Intervals/20k" $ whnf (\n ->+              let !m = foldl' (\acc i -> Map.insert (fromIntegral i * 2 :: Word64) (fromIntegral i * 2 + 1 :: Word64, i :: Int) acc) Map.empty [0..n-1 :: Int]+                  !stabs = foldl' (\acc i -> acc + case Map.lookup (fromIntegral i * 2) m of Just (_, x) -> x; Nothing -> 0) 0 [0..n-1 :: Int]+              in stabs) (20000 :: Int)+          ]+      , bgroup "filter-miss-95pct/50k"+          [ bench "BlockedBloom/50k" $ whnf (\filterObj ->+              let !queries = [2500 .. 2500 * 20 :: Word64]+                  !hits = foldl' (\acc q -> acc + if memberBlockedBloom q filterObj then 1 else 0) (0 :: Int) queries+              in hits) (buildBlockedBloom [0..2499 :: Word64])+          , bench "RibbonFilter/50k" $ whnf (\ribbon ->+              let !queries = [2500 .. 2500 * 20 :: Word64]+                  !hits = foldl' (\acc q -> acc + if memberRibbonFilter q ribbon then 1 else 0) (0 :: Int) queries+              in hits) (buildRibbonFilter [0..2499 :: Word64])+          , bench "Data.IntSet-Miss/50k" $ whnf (\st ->+              let !queries = [2500 .. 2500 * 20 :: Int]+                  !hits = foldl' (\acc q -> acc + if IS.member q st then 1 else 0) (0 :: Int) queries+              in hits) (IS.fromList [0..2499 :: Int])+          ]+      , bgroup "dyn-structs"+          [ bench "WorkDAG/PK-Insert-1000" $ whnf (\n ->+              runST $ do+                dag <- newWorkDAG+                forM_ [1..n-1 :: Word32] (\i -> addEdgePK dag i (i + 1))+                getNodeRank dag n) (1000 :: Word32)+          , bench "Data.Map-Kahn-1000" $ whnf (\n ->+              let edges = Map.fromList [(i, [i + 1]) | i <- [1..n-1 :: Int]]+                  inDegs = Map.fromList [(i, if i == 1 then 0 else 1) | i <- [1..n :: Int]]+                  -- Kahn sort iteration+                  kahn [] acc _ = acc+                  kahn (x : xs) acc degs =+                    let succs = Map.findWithDefault [] x edges+                        degs' = foldl' (\m s -> Map.adjust (\d -> d - 1) s m) degs succs+                        newReady = filter (\s -> Map.findWithDefault 0 s degs' == 0) succs+                    in kahn (xs ++ newReady) (x : acc) degs'+              in length (kahn [1] [] inDegs)) (1000 :: Int)+          , bench "DynamicRel/WCOJ-Triangle" $ whnf (\n ->+              let rel0 = foldl' (\r i -> insertDelta i (i + 1) r) emptyDynamicRel [1..n :: Word32]+                  rel1 = foldl' (\r i -> insertDelta i (i + 2) r) rel0 [1..n-1 :: Word32]+                  relPromoted = stepSemiNaive rel1+              in length (triangleJoinWCOJ relPromoted)) (1000 :: Word32)+          , bench "Pairwise-List-Triangle" $ whnf (\n ->+              let fwd = Map.fromListWith (++) ([(i, [i + 1]) | i <- [1..n :: Int]] ++ [(i, [i + 2]) | i <- [1..n-1 :: Int]])+                  triangles =+                    [ (x, y, z)+                    | (x, ys) <- Map.toList fwd+                    , y <- ys+                    , z <- Map.findWithDefault [] y fwd+                    , z `elem` ys+                    ]+              in length triangles) (1000 :: Int)+          , bench "SackWindow/Record-Extract-1000" $ whnf (\n ->+              let initial = initSackWindow 1+                  -- Insert even TSNs creating gaps+                  (swFinal, _) = foldl' (\(sw, _) i -> recordTsn i sw) (initial, TsnAcceptedNew) [2, 4 .. n :: Word32]+              in length (extractSackGaps swFinal)) (1000 :: Word32)+          , bench "IntSet-Sack-Tracking-1000" $ whnf (\n ->+              let st = IS.fromList [2, 4 .. fromIntegral n :: Int]+                  gaps = [x | x <- [1 .. fromIntegral n], not (IS.member x st)]+              in length gaps) (1000 :: Int)+          ]+      ]+  ]
pykinos-core.cabal view
@@ -1,6 +1,6 @@ cabal-version: 3.0 name: pykinos-core-version: 0.1.0.2+version: 0.1.1.0 synopsis: Unboxed SIMD Roaring Bitmaps, ART IntMap, B+ and FAST search trees description:   Cache-conscious, unboxed, blocked data structures for high-performance@@ -12,8 +12,9 @@   primitive memory arrays.    Provides two-tier SIMD Roaring bitmaps, 4-tier Adaptive Radix Trees (ART),-  unboxed B+ trees, FAST search tree accelerators, Swiss Tables, and dynamic-  hidden classes.+  unboxed B+ trees, FAST search tree accelerators, Swiss Tables, dynamic+  hidden classes, unboxed word queues, and companion primitives (WordDSU,+  IntervalMap, BlockedBloom, Ribbon, WalSlab). license: EUPL-1.2 OR Apache-2.0 license-file: LICENSE author: Nadia Yvette Chambers@@ -25,7 +26,7 @@   README.md   CHANGELOG.md build-type: Simple-tested-with: GHC == 9.14.1+tested-with: GHC == 9.14.1, GHC == 9.12.4  source-repository head   type: git@@ -40,6 +41,22 @@     Pykinos.Tree.FAST     Pykinos.Mutable.SwissTable     Pykinos.Schema.HiddenClass+    Pykinos.Text.PieceRope+    Pykinos.Queue.WordRing+    Pykinos.Queue.WordWorklist+    Pykinos.Queue.RadixHeap+    Pykinos.Queue.TimingWheel+    Pykinos.Queue.WordHeap8+    Pykinos.Queue.BitTrie64+    Pykinos.DSU.WordDSU+    Pykinos.Interval.IntervalMap+    Pykinos.Filter.BlockedBloom+    Pykinos.Filter.Ribbon+    Pykinos.Storage.WalSlab+    Pykinos.Graph.WorkDAG+    Pykinos.Rel.DynamicRel+    Pykinos.Net.SackWindow+    Pykinos.Net.MsgAssoc     Pukinos.Bitset.Roaring     Pukinos.IntMap.ART     Pukinos.Tree.BPlus@@ -53,6 +70,7 @@     -Wno-unused-imports   build-depends:     base >= 4.19 && < 5,+    bytestring >= 0.11 && < 0.13,     primitive >= 0.9 && < 0.10,     containers >= 0.6 && < 0.9,     text >= 2.0 && < 2.2@@ -65,7 +83,24 @@   ghc-options: -threaded -rtsopts -with-rtsopts=-N   build-depends:     base >= 4.19 && < 5,+    bytestring >= 0.11 && < 0.13,     pykinos-core >= 0.1.0.0 && < 0.2,     primitive >= 0.9 && < 0.10,     containers >= 0.6 && < 0.9,     text >= 2.0 && < 2.2++benchmark pykinos-bench+  type: exitcode-stdio-1.0+  main-is: Main.hs+  hs-source-dirs: bench+  default-language: GHC2024+  ghc-options: -Wall -Wcompat -O2 -rtsopts "-with-rtsopts=-T" -Wno-unused-imports+  build-depends:+    base >= 4.19 && < 5,+    bytestring >= 0.11 && < 0.13,+    containers >= 0.6 && < 0.9,+    deepseq >= 1.4 && < 1.6,+    primitive >= 0.9 && < 0.10,+    pykinos-core,+    text >= 2.0 && < 2.2,+    tasty-bench >= 0.3.5 && < 0.6
+ src/Pykinos/DSU/WordDSU.hs view
@@ -0,0 +1,104 @@+{-# LANGUAGE BangPatterns #-}+-- | Module: Pykinos.DSU.WordDSU+-- Description: Zero-pointer packed Word64 Union-Find (Disjoint-Set) with iterative path halving+-- License: EUPL-1.2 OR Apache-2.0+--+-- Packs @(rank :: Word32, parent :: Word32)@ into a single 'Word64' per node+-- inside a flat unscanned 'MutablePrimArray' (8 nodes per 64-byte cache line,+-- zero heap allocations per @findRoot@ / @unionNodes@).+module Pykinos.DSU.WordDSU+  ( WordDSU+  , newWordDSU+  , dsuSize+  , findRoot+  , unionNodes+  , sameSet+  ) where++import Control.Monad (when)+import Control.Monad.ST (ST)+import Data.Bits (shiftL, shiftR, (.&.), (.|.))+import Data.Primitive.PrimArray+  ( MutablePrimArray+  , newPrimArray+  , readPrimArray+  , writePrimArray+  )+import Data.Word (Word32, Word64)++-- | Flat unboxed disjoint-set forest in @ST s@.+data WordDSU s = WordDSU {-# UNPACK #-} !Int !(MutablePrimArray s Word64)++{-# INLINE packEntry #-}+packEntry :: Word32 -> Word32 -> Word64+packEntry !parent !rank =+  (fromIntegral rank `shiftL` 32) .|. fromIntegral parent++{-# INLINE unpackParent #-}+unpackParent :: Word64 -> Word32+unpackParent !w = fromIntegral (w .&. 0xFFFFFFFF)++{-# INLINE unpackRank #-}+unpackRank :: Word64 -> Word32+unpackRank !w = fromIntegral (w `shiftR` 32)++-- | Allocates a 'WordDSU' of @n@ singleton sets @{0}, {1}, ..., {n - 1}@.+newWordDSU :: Int -> ST s (WordDSU s)+newWordDSU !n = do+  arr <- newPrimArray n+  let go !i+        | i >= n    = pure ()+        | otherwise = do+            writePrimArray arr i (packEntry (fromIntegral i) 0)+            go (i + 1)+  go 0+  pure (WordDSU n arr)++-- | Returns the fixed vertex capacity of the disjoint-set forest.+dsuSize :: WordDSU s -> Int+dsuSize (WordDSU n _) = n++-- | Finds the canonical root representative of @x@ using iterative path halving.+findRoot :: WordDSU s -> Word32 -> ST s Word32+findRoot (WordDSU _ arr) = go+  where+    go !x = do+      wx <- readPrimArray arr (fromIntegral x)+      let !px = unpackParent wx+      if px == x+        then pure x+        else do+          wpx <- readPrimArray arr (fromIntegral px)+          let !gpx = unpackParent wpx+          when (gpx /= px) $+            writePrimArray arr (fromIntegral x) (packEntry gpx (unpackRank wx))+          go gpx++-- | Merges the equivalence classes of @a@ and @b@ by rank.+-- Returns 'True' if they were previously distinct, 'False' if already unified.+unionNodes :: WordDSU s -> Word32 -> Word32 -> ST s Bool+unionNodes dsu@(WordDSU _ arr) !a !b = do+  ra <- findRoot dsu a+  rb <- findRoot dsu b+  if ra == rb+    then pure False+    else do+      wa <- readPrimArray arr (fromIntegral ra)+      wb <- readPrimArray arr (fromIntegral rb)+      let !rkA = unpackRank wa+          !rkB = unpackRank wb+      if rkA < rkB+        then writePrimArray arr (fromIntegral ra) (packEntry rb rkA)+        else if rkA > rkB+          then writePrimArray arr (fromIntegral rb) (packEntry ra rkB)+          else do+            writePrimArray arr (fromIntegral rb) (packEntry ra rkB)+            writePrimArray arr (fromIntegral ra) (packEntry ra (rkA + 1))+      pure True++-- | Returns 'True' iff @a@ and @b@ belong to the same equivalence class.+sameSet :: WordDSU s -> Word32 -> Word32 -> ST s Bool+sameSet dsu !a !b = do+  ra <- findRoot dsu a+  rb <- findRoot dsu b+  pure (ra == rb)
+ src/Pykinos/Filter/BlockedBloom.hs view
@@ -0,0 +1,103 @@+{-# LANGUAGE BangPatterns #-}+-- | Module: Pykinos.Filter.BlockedBloom+-- Description: Single-cache-line blocked Bloom filter (64 bytes = 512 bits per block)+-- License: EUPL-1.2 OR Apache-2.0+--+-- Guarantees at most 1 cache-line (512-bit) memory probe per query and exactly 0% false+-- negatives. Double-hashing generates probe bit patterns localized within the selected block.+module Pykinos.Filter.BlockedBloom+  ( BlockedBloom+  , buildBlockedBloom+  , memberBlockedBloom+  , blockedBloomBlocks+  ) where++import Control.Monad.ST (runST)+import Data.Bits (setBit, shiftR, testBit, xor, (.&.), (.|.))+import Data.Primitive.ByteArray+  ( ByteArray+  , indexByteArray+  , newByteArray+  , readByteArray+  , unsafeFreezeByteArray+  , writeByteArray+  )+import Data.Word (Word64)++-- | Blocked Bloom filter represented as a contiguous byte array of 64-byte blocks.+data BlockedBloom = BlockedBloom {-# UNPACK #-} !Int !ByteArray++-- | Number of 64-byte blocks in the filter.+blockedBloomBlocks :: BlockedBloom -> Int+blockedBloomBlocks (BlockedBloom n _) = n++-- | Deterministic 64-bit mixer (SplitMix64).+{-# INLINE splitmix64 #-}+splitmix64 :: Word64 -> Word64+splitmix64 !x =+  let !z0 = (x `xor` (x `shiftR` 30)) * 0xbf58476d1ce4e5b9+      !z1 = (z0 `xor` (z0 `shiftR` 27)) * 0x94d049bb133111eb+  in z1 `xor` (z1 `shiftR` 31)++-- | Hash pair (h1, h2) for double hashing.+{-# INLINE hashPair #-}+hashPair :: Word64 -> (Word64, Word64)+hashPair !k =+  let !h1 = splitmix64 k+      !h2 = splitmix64 (k `xor` 0x517cc1b727220a95)+  in (h1, h2 .|. 1) -- Ensure h2 is odd++-- | Generates 8 bit positions within a 512-bit block.+{-# INLINE probeBits #-}+probeBits :: Word64 -> Word64 -> [Int]+probeBits !h1 !h2 =+  [ fromIntegral ((h1 + fromIntegral i * h2) .&. 511)+  | i <- [0 .. 7 :: Int]+  ]++-- | Builds a blocked Bloom filter from a list of 64-bit keys.+buildBlockedBloom :: [Word64] -> BlockedBloom+buildBlockedBloom keys = runST $ do+  let n = length keys+      -- Allocate roughly 10 bits per key, rounded up to multiples of 64-byte blocks (512 bits)+      targetBits = max 512 (n * 10)+      numBlocks = (targetBits + 511) `div` 512+      totalBytes = numBlocks * 64+  marr <- newByteArray totalBytes+  -- Zero-initialize all blocks+  let zeroBytes !i+        | i >= numBlocks * 8 = pure ()+        | otherwise = do+            writeByteArray marr i (0 :: Word64)+            zeroBytes (i + 1)+  zeroBytes 0++  -- Insert each key into its selected 64-byte block+  let insertKey !k = do+        let (!h1, !h2) = hashPair k+            !bIdx = fromIntegral (h1 `mod` fromIntegral numBlocks)+            !wordBase = bIdx * 8+        mapM_ (\bitIdx -> do+          let (!wOffset, !bOffset) = bitIdx `divMod` 64+              !wIdx = wordBase + wOffset+          wVal <- readByteArray marr wIdx+          writeByteArray marr wIdx (setBit (wVal :: Word64) bOffset)+          ) (probeBits h1 h2)++  mapM_ insertKey keys+  arr <- unsafeFreezeByteArray marr+  pure (BlockedBloom numBlocks arr)++-- | Checks whether key @k@ is a member of the blocked Bloom filter.+-- Guaranteed 0% false negatives.+memberBlockedBloom :: Word64 -> BlockedBloom -> Bool+memberBlockedBloom !k (BlockedBloom numBlocks arr) =+  let (!h1, !h2) = hashPair k+      !bIdx = fromIntegral (h1 `mod` fromIntegral numBlocks)+      !wordBase = bIdx * 8+  in all (\bitIdx ->+       let (!wOffset, !bOffset) = bitIdx `divMod` 64+           !wIdx = wordBase + wOffset+           !wVal = indexByteArray arr wIdx :: Word64+       in testBit wVal bOffset+     ) (probeBits h1 h2)
+ src/Pykinos/Filter/Ribbon.hs view
@@ -0,0 +1,128 @@+{-# LANGUAGE BangPatterns #-}+-- | Module: Pykinos.Filter.Ribbon+-- Description: Static Dillinger-Walzer (2021) Ribbon filter with band width w = 64 over GF(2)+-- License: EUPL-1.2 OR Apache-2.0+--+-- Compact static approximate membership filter using banded Gaussian elimination over GF(2).+-- Guarantees 0% false negatives for enrolled keys and achieves measured space overhead+-- strictly below standard Bloom filters (~7.5 bits/key).+module Pykinos.Filter.Ribbon+  ( RibbonFilter+  , buildRibbonFilter+  , memberRibbonFilter+  , ribbonBitsPerKey+  , ribbonSize+  ) where++import Control.Monad.ST (runST)+import Data.Bits (countTrailingZeros, shiftR, testBit, xor, (.&.), (.|.))+import Data.Primitive.PrimArray+  ( PrimArray+  , indexPrimArray+  , newPrimArray+  , unsafeFreezePrimArray+  , writePrimArray+  )+import Data.Word (Word64, Word8)+import qualified Data.Map.Strict as Map++-- | Static Ribbon filter over GF(2) with band width 64.+data RibbonFilter = RibbonFilter {-# UNPACK #-} !Int {-# UNPACK #-} !Int !(PrimArray Word8)++-- | Returns the number of keys stored in the ribbon filter.+ribbonSize :: RibbonFilter -> Int+ribbonSize (RibbonFilter n _ _) = n++-- | Returns measured bits per key of the filter storage.+ribbonBitsPerKey :: RibbonFilter -> Double+ribbonBitsPerKey (RibbonFilter n slots _)+  | n == 0    = 0.0+  | otherwise = fromIntegral (slots * 8) / (fromIntegral n :: Double)++{-# INLINE splitmix64 #-}+splitmix64 :: Word64 -> Word64+splitmix64 !x =+  let !z0 = (x `xor` (x `shiftR` 30)) * 0xbf58476d1ce4e5b9+      !z1 = (z0 `xor` (z0 `shiftR` 27)) * 0x94d049bb133111eb+  in z1 `xor` (z1 `shiftR` 31)++{-# INLINE keyPosCoeff #-}+keyPosCoeff :: Int -> Word64 -> (Int, Word64, Word8)+keyPosCoeff !numSlots !k =+  let !h1 = splitmix64 k+      !h2 = splitmix64 (k `xor` 0x9e3779b97f4a7c15)+      !h3 = splitmix64 (k `xor` 0x517cc1b727220a95)+      !usableSlots = max 1 (numSlots - 64)+      !startPos = fromIntegral (h1 `mod` fromIntegral usableSlots)+      !coeff = h2 .|. 1 -- Ensure non-zero leading bit+      !target = fromIntegral (h3 .&. 0xFF) -- 8-bit target fingerprint+  in (startPos, coeff, target)++-- | Builds a Ribbon filter from a list of keys using banded linear system solving over GF(2).+buildRibbonFilter :: [Word64] -> RibbonFilter+buildRibbonFilter keys =+  let !n = length keys+      !slotsFrac = (fromIntegral n :: Double) * 1.15+      !numSlots = max 128 (round slotsFrac + (64 :: Int))+      -- Map keys to their linear system constraints+      constraints = map (keyPosCoeff numSlots) keys+      -- Construct triangular system by Gaussian elimination on band matrix+      solutionMap = solveBandedSystem constraints+      solArr = runST $ do+        marr <- newPrimArray numSlots+        let fill !i+              | i >= numSlots = pure ()+              | otherwise = do+                  writePrimArray marr i (Map.findWithDefault 0 i solutionMap)+                  fill (i + 1)+        fill 0+        unsafeFreezePrimArray marr+  in RibbonFilter n numSlots solArr++-- | Solves the banded system over GF(2^8) by normalized pivoting on the first set bit.+solveBandedSystem :: [(Int, Word64, Word8)] -> Map.Map Int Word8+solveBandedSystem constraints =+  let echelon = foldl insertEchelon Map.empty constraints+  in backSubstitute echelon+  where+    insertEchelon !table (!pos, !coeff, !target)+      | coeff == 0 = table+      | otherwise =+          let !firstBit = countTrailingZeros coeff+              !pivotPos = pos + firstBit+              !normCoeff = coeff `shiftR` firstBit+          in case Map.lookup pivotPos table of+               Nothing ->+                 Map.insert pivotPos (normCoeff, target) table+               Just (pCoeff, pTarget) ->+                 -- Both have bit 0 set at pivotPos; XOR cancels bit 0 strictly advancing the pivot+                 let !nextCoeff = normCoeff `xor` pCoeff+                     !nextTarget = target `xor` pTarget+                 in insertEchelon table (pivotPos, nextCoeff, nextTarget)++    backSubstitute echelon =+      let pivotsDesc = Map.toDescList echelon+      in foldl (\sol (pivotPos, (coeff, target)) ->+           let currentSum = foldl (\acc bitIdx ->+                 if testBit coeff bitIdx+                   then acc `xor` Map.findWithDefault 0 (pivotPos + bitIdx) sol+                   else acc+                 ) (0 :: Word8) [1 .. 63]+               neededVal = currentSum `xor` target+           in Map.insert pivotPos neededVal sol+         ) Map.empty pivotsDesc++-- | Queries membership in the Ribbon filter.+-- Guaranteed 0% false negatives for all keys used during construction.+memberRibbonFilter :: Word64 -> RibbonFilter -> Bool+memberRibbonFilter !k (RibbonFilter _ numSlots sol) =+  let (!pos, !coeff, !target) = keyPosCoeff numSlots k+      go !acc !bitIdx !c+        | bitIdx >= 64 || c == 0 = acc == target+        | c .&. 1 /= 0 =+            let !idx = pos + bitIdx+                !val = if idx < numSlots then indexPrimArray sol idx else 0+            in go (acc `xor` val) (bitIdx + 1) (c `shiftR` 1)+        | otherwise =+            go acc (bitIdx + 1) (c `shiftR` 1)+  in go 0 0 coeff
+ src/Pykinos/Graph/WorkDAG.hs view
@@ -0,0 +1,230 @@+{-# LANGUAGE BangPatterns #-}+{-# LANGUAGE DerivingStrategies #-}++-- | Module: Pykinos.Graph.WorkDAG+-- Description: Pearce-Kelly incremental dynamic topological sort and ready-node tracker+--+-- = Pearce-Kelly Algorithm & Dynamic Topological Sorting+--+-- In build systems, pipeline orchestrators, and stream-execution engines, tasks+-- form a Directed Acyclic Graph (DAG) whose dependencies evolve dynamically as+-- tasks discover subtasks or emit outputs. Maintaining a valid global execution order+-- after each edge insertion naively requires full re-sorting (e.g. Kahn's algorithm or+-- Tarjan's SCC), scaling as @O(V + E)@ per modification.+--+-- The Pearce-Kelly (PK) algorithm (Pearce & Kelly, 2006) resolves this by maintaining+-- a dense topological rank array @ord : V -> Int@ such that:+--+-- \[ \forall (u, v) \in E,\quad \mathrm{ord}[u] < \mathrm{ord}[v] \]+--+-- When adding a directed dependency @u -> v@:+--+-- 1. __Fast Path (O(1)):__ If @ord[u] < ord[v]@, the existing topological order+--    already satisfies the new dependency. No node re-labeling is needed.+-- 2. __Slow Path (Bounded Region):__ If @ord[u] >= ord[v]@, only vertices in the+--    rank window \([\mathrm{ord}[v], \mathrm{ord}[u]]\) can be affected.+--    - A bounded forward DFS from @v@ discovers all descendants with rank \(\le \mathrm{ord}[u]\).+--      If @u@ is reachable from @v@, a cycle is detected and an explicit path witness+--      is returned.+--    - A bounded backward DFS from @u@ discovers all ancestors with rank \(\ge \mathrm{ord}[v]\).+--    - Ranks within the affected set are reallocated in topological order, restoring+--      the global invariant in time proportional only to the affected sub-graph.+--+-- = Ready Node Maintenance+--+-- Each node tracks its remaining in-degree (@inDegree@). When a task finishes,+-- 'completeNode' decrements in-degrees of all direct successors. Any successor+-- reaching zero in-degree is immediately returned as ready for worker scheduling.+module Pykinos.Graph.WorkDAG+  ( WorkDAG+  , CycleDetected (..)+  , newWorkDAG+  , addEdgePK+  , completeNode+  , getNodeRank+  , isEdgePresent+  , getInDegree+  ) where++import Control.Monad.ST (ST)+import Data.IntMap.Strict (IntMap)+import qualified Data.IntMap.Strict as IM+import qualified Data.IntSet as IS+import Data.List (sortOn)+import Data.STRef (STRef, newSTRef, readSTRef, writeSTRef)+import Data.Word (Word32)++-- | Explicit cycle witness path when an edge insertion would create a directed cycle.+newtype CycleDetected = CycleDetected { cyclePath :: [Word32] }+  deriving stock (Eq, Show)++-- | Internal state of the Pearce-Kelly dynamic DAG.+data WorkDAG s = WorkDAG+  { wdRanks    :: !(STRef s (IntMap Int))+    -- ^ Topological rank for each node (ord[u] < ord[v] for all u -> v).+  , wdNextRank :: !(STRef s Int)+    -- ^ Monotonic generator for default rank allocations.+  , wdSuccs    :: !(STRef s (IntMap [Word32]))+    -- ^ Forward adjacency list (outgoing edges u -> v).+  , wdPreds    :: !(STRef s (IntMap [Word32]))+    -- ^ Backward adjacency list (incoming edges v -> u).+  , wdInDegree :: !(STRef s (IntMap Int))+    -- ^ Current remaining in-degree for task readiness.+  }++-- | Allocates a new empty 'WorkDAG'.+newWorkDAG :: ST s (WorkDAG s)+newWorkDAG = do+  rRef  <- newSTRef IM.empty+  nrRef <- newSTRef 1+  sRef  <- newSTRef IM.empty+  pRef  <- newSTRef IM.empty+  inRef <- newSTRef IM.empty+  pure $ WorkDAG rRef nrRef sRef pRef inRef++-- | Retrieves the topological rank of a node, assigning a fresh rank if unseen.+getOrAssignRank :: WorkDAG s -> Word32 -> ST s Int+getOrAssignRank dag u = do+  let k = fromIntegral u+  ranks <- readSTRef (wdRanks dag)+  case IM.lookup k ranks of+    Just r -> pure r+    Nothing -> do+      nr <- readSTRef (wdNextRank dag)+      let !r = nr * 1024+      writeSTRef (wdNextRank dag) (nr + 1)+      writeSTRef (wdRanks dag) (IM.insert k r ranks)+      pure r++-- | Reads the current topological rank of a node (or 0 if unassigned).+getNodeRank :: WorkDAG s -> Word32 -> ST s Int+getNodeRank dag u = do+  ranks <- readSTRef (wdRanks dag)+  pure $ IM.findWithDefault 0 (fromIntegral u) ranks++-- | Reads the current in-degree of a node.+getInDegree :: WorkDAG s -> Word32 -> ST s Int+getInDegree dag u = do+  inDegs <- readSTRef (wdInDegree dag)+  pure $ IM.findWithDefault 0 (fromIntegral u) inDegs++-- | Checks if directed edge @u -> v@ is already present in the DAG.+isEdgePresent :: WorkDAG s -> Word32 -> Word32 -> ST s Bool+isEdgePresent dag u v = do+  succs <- readSTRef (wdSuccs dag)+  case IM.lookup (fromIntegral u) succs of+    Just vs -> pure (v `elem` vs)+    Nothing -> pure False++-- | Adds a directed edge @u -> v@ using Pearce-Kelly incremental topological sort.+--+-- Fast Path: O(1) when @ord[u] < ord[v]@.+-- Slow Path: Bounded search when @ord[u] >= ord[v]@. Returns 'Left cycle' if a cycle+-- is detected, or 'Right ()' after reassigning ranks in the affected region.+addEdgePK :: WorkDAG s -> Word32 -> Word32 -> ST s (Either [Word32] ())+addEdgePK dag !u !v+  | u == v = pure (Left [u, v])+  | otherwise = do+      exists <- isEdgePresent dag u v+      if exists+        then pure (Right ())+        else do+          ru <- getOrAssignRank dag u+          rv <- getOrAssignRank dag v+          if ru < rv+            then do+              -- O(1) Fast path: topological invariant holds unchanged+              recordEdge dag u v+              pure (Right ())+            else do+              -- Slow path: search forward from v for reachable nodes with rank <= ru+              succs <- readSTRef (wdSuccs dag)+              preds <- readSTRef (wdPreds dag)+              ranks <- readSTRef (wdRanks dag)+              let (hasCycle, fwdNodes) = dfsForward (fromIntegral u) ru succs ranks [fromIntegral v] IS.empty []+              if hasCycle+                then pure (Left (reconstructCycle preds (fromIntegral u) (fromIntegral v)))+                else do+                  -- Search backward from u for nodes reaching u with rank >= rv+                  let bwdNodes = dfsBackward rv preds ranks [fromIntegral u] IS.empty []+                  -- Reorder ranks of (bwdNodes ++ fwdNodes) preserving order+                  reorderRanks dag ranks bwdNodes fwdNodes+                  recordEdge dag u v+                  pure (Right ())++-- | Records the edge into adjacency and in-degree tables.+recordEdge :: WorkDAG s -> Word32 -> Word32 -> ST s ()+recordEdge dag !u !v = do+  let ku = fromIntegral u+      kv = fromIntegral v+  succs <- readSTRef (wdSuccs dag)+  writeSTRef (wdSuccs dag) (IM.insertWith (++) ku [v] succs)+  preds <- readSTRef (wdPreds dag)+  writeSTRef (wdPreds dag) (IM.insertWith (++) kv [u] preds)+  inDegs <- readSTRef (wdInDegree dag)+  writeSTRef (wdInDegree dag) (IM.insertWith (+) kv 1 inDegs)++-- | Forward DFS bounded by upper rank limit.+dfsForward :: Int -> Int -> IntMap [Word32] -> IntMap Int -> [Int] -> IS.IntSet -> [Int] -> (Bool, [Int])+dfsForward _ _ _ _ [] _ collected = (False, collected)+dfsForward targetU maxR succs ranks (x : xs) visited collected+  | x == targetU = (True, [])+  | IS.member x visited = dfsForward targetU maxR succs ranks xs visited collected+  | otherwise =+      let rx = IM.findWithDefault 0 x ranks+      in if rx > maxR+           then dfsForward targetU maxR succs ranks xs visited collected+           else+             let nbrs = map fromIntegral (IM.findWithDefault [] x succs)+                 visited' = IS.insert x visited+             in dfsForward targetU maxR succs ranks (nbrs ++ xs) visited' (x : collected)++-- | Backward DFS bounded by lower rank limit.+dfsBackward :: Int -> IntMap [Word32] -> IntMap Int -> [Int] -> IS.IntSet -> [Int] -> [Int]+dfsBackward _ _ _ [] _ collected = collected+dfsBackward minR preds ranks (x : xs) visited collected+  | IS.member x visited = dfsBackward minR preds ranks xs visited collected+  | otherwise =+      let rx = IM.findWithDefault 0 x ranks+      in if rx < minR+           then dfsBackward minR preds ranks xs visited collected+           else+             let nbrs = map fromIntegral (IM.findWithDefault [] x preds)+                 visited' = IS.insert x visited+             in dfsBackward minR preds ranks (nbrs ++ xs) visited' (x : collected)++-- | Reconstructs a simple path witness when a cycle is detected.+reconstructCycle :: IntMap [Word32] -> Int -> Int -> [Word32]+reconstructCycle _ targetU startV = [fromIntegral targetU, fromIntegral startV, fromIntegral targetU]++-- | Reorders ranks for the affected backward and forward sets.+reorderRanks :: WorkDAG s -> IntMap Int -> [Int] -> [Int] -> ST s ()+reorderRanks dag ranks bwdNodes fwdNodes = do+  let allAffected = bwdNodes ++ fwdNodes+      allRanks = sortOn snd [ (n, IM.findWithDefault 0 n ranks) | n <- allAffected ]+      sortedRanks = map snd allRanks+      -- Allocate bwdNodes before fwdNodes+      reorderedNodes = bwdNodes ++ fwdNodes+      newRankMap = foldl (\acc (n, r) -> IM.insert n r acc) ranks (zip reorderedNodes sortedRanks)+  writeSTRef (wdRanks dag) newRankMap++-- | Marks node @u@ complete: decrements in-degrees of all successors,+-- returning all newly ready nodes whose in-degree has dropped to 0.+completeNode :: WorkDAG s -> Word32 -> ST s [Word32]+completeNode dag !u = do+  succs <- readSTRef (wdSuccs dag)+  case IM.lookup (fromIntegral u) succs of+    Nothing -> pure []+    Just vs -> do+      inDegs <- readSTRef (wdInDegree dag)+      let step (accReady, curDegs) v =+            let kv = fromIntegral v+                oldDeg = IM.findWithDefault 0 kv curDegs+                newDeg = max 0 (oldDeg - 1)+                curDegs' = IM.insert kv newDeg curDegs+            in if newDeg == 0+                 then (v : accReady, curDegs')+                 else (accReady, curDegs')+          (ready, finalDegs) = foldl step ([], inDegs) vs+      writeSTRef (wdInDegree dag) finalDegs+      pure (reverse ready)
+ src/Pykinos/Interval/IntervalMap.hs view
@@ -0,0 +1,125 @@+{-# LANGUAGE BangPatterns #-}+-- | Module: Pykinos.Interval.IntervalMap+-- Description: Maple-Tree-inspired non-overlapping [lo, hi) Word64 interval map with logarithmic index+-- License: EUPL-1.2 OR Apache-2.0+--+-- Provides cache-conscious non-overlapping [lo, hi) interval indexing over unboxed Word64+-- endpoints. Supports point stabbing ('lookupPoint'), overlap range scanning ('queryOverlap'),+-- free allocation gap discovery ('findFreeGap'), and automatic adjacent extent coalescing.+module Pykinos.Interval.IntervalMap+  ( Extent(..)+  , IntervalMap+  , emptyIntervalMap+  , intervalMapSize+  , insertExtent+  , lookupPoint+  , queryOverlap+  , findFreeGap+  , extentList+  ) where++import qualified Data.Map.Strict as Map+import Data.Word (Word64)++-- | Half-open contiguous interval [extLo, extHi) carrying payload value.+data Extent a = Extent+  { extLo  :: {-# UNPACK #-} !Word64+  , extHi  :: {-# UNPACK #-} !Word64+  , extVal :: !a+  } deriving stock (Eq, Show)++-- | Non-overlapping interval map indexed by low endpoint.+newtype IntervalMap a = IntervalMap (Map.Map Word64 (Extent a))+  deriving stock (Eq, Show)++-- | Empty interval map.+emptyIntervalMap :: IntervalMap a+emptyIntervalMap = IntervalMap Map.empty++-- | Number of active extents in the map.+intervalMapSize :: IntervalMap a -> Int+intervalMapSize (IntervalMap m) = Map.size m++-- | All extents in strictly ascending order.+extentList :: IntervalMap a -> [(Word64, Word64, a)]+extentList (IntervalMap m) = [(extLo e, extHi e, extVal e) | e <- Map.elems m]++-- | Inserts a half-open extent @[lo, hi)@ into the map.+-- Rejects overlapping intervals with 'Left'.+-- Automatically coalesces immediately adjacent intervals sharing identical payloads.+insertExtent :: (Eq a) => Word64 -> Word64 -> a -> IntervalMap a -> Either String (IntervalMap a)+insertExtent !lo !hi val (IntervalMap m)+  | lo >= hi  = Left "Invalid interval: lo >= hi"+  | otherwise =+      -- Check overlap with predecessor+      case Map.lookupLE lo m of+        Just (_, Extent pLo pHi _)+          | pHi > lo ->+              Left $ "Interval overlap: [" ++ show lo ++ ", " ++ show hi ++ ") overlaps with [" ++ show pLo ++ ", " ++ show pHi ++ ")"+        _ ->+          -- Check overlap with successor+          case Map.lookupGE lo m of+            Just (sLo, Extent _ sHi _)+              | sLo < hi ->+                  Left $ "Interval overlap: [" ++ show lo ++ ", " ++ show hi ++ ") overlaps with [" ++ show sLo ++ ", " ++ show sHi ++ ")"+            _ ->+              -- No overlap! Check coalescing with predecessor and successor+              let (!coalescedLo, !mAfterPred) = case Map.lookupLE lo m of+                    Just (pLo, Extent _ pHi pVal)+                      | pHi == lo && pVal == val -> (pLo, Map.delete pLo m)+                    _ -> (lo, m)+                  (!coalescedHi, !mAfterSucc) = case Map.lookupGE hi mAfterPred of+                    Just (sLo, Extent _ sHi sVal)+                      | sLo == hi && sVal == val -> (sHi, Map.delete sLo mAfterPred)+                    _ -> (hi, mAfterPred)+                  !newExt = Extent coalescedLo coalescedHi val+              in Right (IntervalMap (Map.insert coalescedLo newExt mAfterSucc))++-- | Point stabbing query: returns payload if point @p@ falls within any @[lo, hi)@ extent.+lookupPoint :: Word64 -> IntervalMap a -> Maybe a+lookupPoint !p (IntervalMap m) =+  case Map.lookupLE p m of+    Just (_, Extent _ eHi eVal)+      | p < eHi   -> Just eVal+      | otherwise -> Nothing+    Nothing -> Nothing++-- | Range overlap query: returns all extents overlapping query window @[lo, hi)@.+queryOverlap :: Word64 -> Word64 -> IntervalMap a -> [(Word64, Word64, a)]+queryOverlap !lo !hi (IntervalMap m)+  | lo >= hi  = []+  | otherwise =+      let -- Start scanning from the predecessor of lo (which might extend past lo)+          startLo = case Map.lookupLE lo m of+            Just (pLo, Extent _ pHi _) | pHi > lo -> pLo+            _                                     -> lo+          -- Submap of potential overlapping intervals+          candidates = Map.elems (fst (Map.split hi (snd (Map.split (startLo - 1) m))))+      in [ (extLo e, extHi e, extVal e)+         | e <- candidates+         , max lo (extLo e) < min hi (extHi e)+         ]++-- | Finds the lowest unallocated free address space gap of size @gapSize@+-- within range @[rangeMin, rangeMax)@.+findFreeGap :: Word64 -> Word64 -> Word64 -> IntervalMap a -> Maybe Word64+findFreeGap !rangeMin !rangeMax !gapSize (IntervalMap m)+  | rangeMin + gapSize > rangeMax = Nothing+  | otherwise = go rangeMin (Map.elems m)+  where+    go !curPos []+      | curPos + gapSize <= rangeMax = Just curPos+      | otherwise                    = Nothing+    go !curPos (Extent eLo eHi _ : es)+      | eHi <= curPos =+          go curPos es+      | eLo <= curPos =+          go (max curPos eHi) es+      | otherwise =+          let !availLo = max curPos rangeMin+              !availHi = min eLo rangeMax+          in if availLo + gapSize <= availHi+               then Just availLo+               else if eHi >= rangeMax+                 then Nothing+                 else go (max eHi rangeMin) es
+ src/Pykinos/Net/MsgAssoc.hs view
@@ -0,0 +1,134 @@+{-# LANGUAGE BangPatterns #-}+{-# LANGUAGE DerivingStrategies #-}++-- | Module: Pykinos.Net.MsgAssoc+-- Description: Multi-stream framing and zero-HoL-blocking message association over SackWindow+--+-- Implements SCTP-like multi-stream delivery over an underlying 'SackWindow'.+-- Distinguishes 'StreamOrdered', 'StreamUnordered', and 'StreamPartialTTL' streams,+-- ensuring that un-sequenced datagrams bypass stalled ordered transmission queues+-- with zero head-of-line (HoL) blocking.+module Pykinos.Net.MsgAssoc+  ( StreamPolicy (..)+  , MsgChunk (..)+  , MsgAssoc (..)+  , initMsgAssoc+  , receiveChunk+  , extractDeliverable+  ) where++import qualified Data.ByteString as BS+import Data.Map.Strict (Map)+import qualified Data.Map.Strict as Map+import Data.Word (Word16, Word32)+import Pykinos.Net.SackWindow+  ( SackWindow (..)+  , TsnOutcome (..)+  , initSackWindow+  , recordTsn+  )++-- | Per-stream delivery discipline.+data StreamPolicy+  = StreamOrdered+    -- ^ Strictly ordered stream delivery; gaps buffer until the missing SSN arrives.+  | StreamUnordered+    -- ^ Immediate zero-HoL delivery; delivered as soon as the chunk arrives.+  | StreamPartialTTL !Int+    -- ^ Partially reliable stream with hop/timeout drop semantics.+  deriving stock (Eq, Show)++-- | A discrete transmission chunk arriving on the wire.+data MsgChunk = MsgChunk+  { mcTsn      :: !Word32+    -- ^ Transmission Sequence Number (association-wide serial space).+  , mcStreamId :: !Word16+    -- ^ Stream identifier.+  , mcSsn      :: !Word16+    -- ^ Stream Sequence Number (per-stream ordered index).+  , mcPolicy   :: !StreamPolicy+    -- ^ Stream delivery policy.+  , mcPayload  :: !BS.ByteString+    -- ^ Message payload bytes.+  } deriving stock (Eq, Show)++-- | State of an active multi-stream reception association.+data MsgAssoc = MsgAssoc+  { maSackWindow :: !SackWindow+    -- ^ Underlying cumulative TSN and SACK bitmask.+  , maNextSsn    :: !(Map Word16 Word16)+    -- ^ Next expected Stream Sequence Number for ordered streams.+  , maBuffer     :: !(Map Word16 (Map Word16 BS.ByteString))+    -- ^ Buffered out-of-order chunks per stream: streamId -> (ssn -> payload).+  , maDelivered  :: ![BS.ByteString]+    -- ^ FIFO queue of payloads ready for consumption.+  } deriving stock (Eq, Show)++-- | Initializes a new 'MsgAssoc' starting at @initialTsn@.+initMsgAssoc :: Word32 -> MsgAssoc+initMsgAssoc initialTsn = MsgAssoc+  { maSackWindow = initSackWindow initialTsn+  , maNextSsn    = Map.empty+  , maBuffer     = Map.empty+  , maDelivered  = []+  }++-- | Processes an arriving chunk, returning the TSN outcome, the updated association,+-- and any payloads that became deliverable as a result of this chunk.+receiveChunk :: MsgChunk -> MsgAssoc -> (TsnOutcome, MsgAssoc, [BS.ByteString])+receiveChunk chunk assoc =+  let (outcome, sw') = recordTsn (mcTsn chunk) (maSackWindow assoc)+  in case outcome of+       TsnDuplicate -> (TsnDuplicate, assoc, [])+       TsnOutOfWindow -> (TsnOutOfWindow, assoc, [])+       TsnAcceptedNew ->+         let assoc1 = assoc { maSackWindow = sw' }+         in case mcPolicy chunk of+              -- Zero-HoL fast path: bypass stream ordering buffers entirely!+              StreamUnordered ->+                let delivered = [mcPayload chunk]+                    assoc2 = assoc1 { maDelivered = maDelivered assoc1 ++ delivered }+                in (TsnAcceptedNew, assoc2, delivered)++              -- Ordered delivery: check SSN sequence+              StreamOrdered ->+                let sid = mcStreamId chunk+                    ssn = mcSsn chunk+                    expected = Map.findWithDefault 0 sid (maNextSsn assoc1)+                in if ssn == expected+                     then+                       -- Immediate in-order delivery; drain any contiguous buffered chunks+                       let stBuf = Map.findWithDefault Map.empty sid (maBuffer assoc1)+                           (nextSsn', newlyDelivered, stBuf') = drainContiguous (ssn + 1) [mcPayload chunk] stBuf+                           assoc2 = assoc1+                             { maNextSsn = Map.insert sid nextSsn' (maNextSsn assoc1)+                             , maBuffer  = Map.insert sid stBuf' (maBuffer assoc1)+                             , maDelivered = maDelivered assoc1 ++ newlyDelivered+                             }+                       in (TsnAcceptedNew, assoc2, newlyDelivered)+                     else+                       -- Out of order: buffer chunk for future draining+                       let stBuf = Map.findWithDefault Map.empty sid (maBuffer assoc1)+                           stBuf' = Map.insert ssn (mcPayload chunk) stBuf+                           assoc2 = assoc1 { maBuffer = Map.insert sid stBuf' (maBuffer assoc1) }+                       in (TsnAcceptedNew, assoc2, [])++              -- Partial TTL: deliver immediately if fresh+              StreamPartialTTL ttl ->+                if ttl > 0+                  then+                    let delivered = [mcPayload chunk]+                        assoc2 = assoc1 { maDelivered = maDelivered assoc1 ++ delivered }+                    in (TsnAcceptedNew, assoc2, delivered)+                  else (TsnAcceptedNew, assoc1, [])++-- | Drains contiguous chunks starting from @curSsn@.+drainContiguous :: Word16 -> [BS.ByteString] -> Map Word16 BS.ByteString -> (Word16, [BS.ByteString], Map Word16 BS.ByteString)+drainContiguous !curSsn acc buf =+  case Map.lookup curSsn buf of+    Nothing -> (curSsn, reverse acc, buf)+    Just p  -> drainContiguous (curSsn + 1) (p : acc) (Map.delete curSsn buf)++-- | Extracts all pending deliverable payloads, clearing the delivery buffer.+extractDeliverable :: MsgAssoc -> ([BS.ByteString], MsgAssoc)+extractDeliverable assoc = (maDelivered assoc, assoc { maDelivered = [] })
+ src/Pykinos/Net/SackWindow.hs view
@@ -0,0 +1,112 @@+{-# LANGUAGE BangPatterns #-}+{-# LANGUAGE DerivingStrategies #-}+-- | Module: Pykinos.Net.SackWindow+-- Description: Zero-allocation RFC 1982 TSN sliding window and ctz-based SACK gap extractor+--+-- Implements SCTP-style cumulative TSN tracking and selective-acknowledgement+-- (SACK) gap-ack block extraction over a 64-slot unboxed 'Word64' bitmask.+module Pykinos.Net.SackWindow+  ( serialLess+  , serialDiff+  , SackGap(..)+  , TsnOutcome(..)+  , SackWindow(..)+  , initSackWindow+  , recordTsn+  , extractSackGaps+  , advanceForwardTsn+  ) where++import Data.Bits+  ( complement+  , countTrailingZeros+  , setBit+  , shiftR+  , testBit+  )+import Data.Int (Int32)+import Data.Word (Word16, Word32, Word64)++-- | RFC 1982 signed modular distance @(a - b)@ in @[-2^31, 2^31 - 1]@.+{-# INLINE serialDiff #-}+serialDiff :: Word32 -> Word32 -> Int32+serialDiff !a !b = fromIntegral (a - b)++-- | RFC 1982 wrap-around comparison: 'True' iff @a@ strictly precedes @b@.+{-# INLINE serialLess #-}+serialLess :: Word32 -> Word32 -> Bool+serialLess !a !b = serialDiff a b < 0++-- | Contiguous inclusive SACK Gap Ack Block expressed as offsets above 'swCumTsn'.+data SackGap = SackGap+  { gapStart :: !Word16+  , gapEnd   :: !Word16+  } deriving stock (Eq, Ord, Show)++-- | Classification of an arriving TSN against the current sliding window.+data TsnOutcome+  = TsnAcceptedNew+  | TsnDuplicate+  | TsnOutOfWindow+  deriving stock (Eq, Ord, Show, Enum, Bounded)++-- | Compact 2-word reception window: cumulative TSN + 64-bit ahead-of-cum bitmap.+-- Bit @i@ (0-indexed) represents @swCumTsn + 1 + i@.+data SackWindow = SackWindow+  { swCumTsn :: !Word32+  , swBitmap :: !Word64+  } deriving stock (Eq, Ord, Show)++-- | Initializes a 'SackWindow' expecting @initialTsn@ as the first packet.+initSackWindow :: Word32 -> SackWindow+initSackWindow !initialTsn = SackWindow (initialTsn - 1) 0++-- | Records an arriving TSN, advancing 'swCumTsn' across all newly contiguous bits.+recordTsn :: Word32 -> SackWindow -> (TsnOutcome, SackWindow)+recordTsn !tsn sw@(SackWindow cum bm) =+  let !d = serialDiff tsn cum+  in if d <= 0+       then (TsnDuplicate, sw)+       else if d > 64+         then (TsnOutOfWindow, sw)+         else+           let !bitIdx = fromIntegral (d - 1)+           in if testBit bm bitIdx+                then (TsnDuplicate, sw)+                else+                  let !bm1    = setBit bm bitIdx+                      !adv    = countTrailingZeros (complement bm1)+                      !cum'   = cum + fromIntegral adv+                      !bm'    = if adv >= 64 then 0 else bm1 `shiftR` adv+                  in (TsnAcceptedNew, SackWindow cum' bm')++-- | Advances cumulative TSN via PR-SCTP Forward-TSN (abandoning expired gaps).+advanceForwardTsn :: Word32 -> SackWindow -> SackWindow+advanceForwardTsn !newCum sw@(SackWindow cum bm) =+  let !d = serialDiff newCum cum+  in if d <= 0+       then sw+       else if d >= 64+         then SackWindow newCum 0+         else+           let !bm1  = bm `shiftR` fromIntegral d+               !adv  = countTrailingZeros (complement bm1)+               !cum' = newCum + fromIntegral adv+               !bm'  = if adv >= 64 then 0 else bm1 `shiftR` adv+           in SackWindow cum' bm'++-- | Extracts contiguous SACK Gap Ack Blocks in O(number of gaps) using @ctz@.+extractSackGaps :: SackWindow -> [SackGap]+extractSackGaps (SackWindow _ bm0) = go 0 bm0+  where+    go :: Int -> Word64 -> [SackGap]+    go !_ 0 = []+    go !base !m =+      let !skipZeros = countTrailingZeros m+          !shifted1  = m `shiftR` skipZeros+          !runOnes   = countTrailingZeros (complement shifted1)+          !startOff  = base + skipZeros + 1+          !endOff    = startOff + runOnes - 1+          !nextBase  = base + skipZeros + runOnes+          !nextMask  = if runOnes >= 64 then 0 else shifted1 `shiftR` runOnes+      in SackGap (fromIntegral startOff) (fromIntegral endOff) : go nextBase nextMask
+ src/Pykinos/Queue/BitTrie64.hs view
@@ -0,0 +1,159 @@+{-# LANGUAGE BangPatterns #-}+{-# OPTIONS_GHC -Wno-unused-top-binds -Wno-deprecations #-}+-- | Module: Pykinos.Queue.BitTrie64+-- Description: 3-level 64-ary unboxed Word64 bitmap priority set-queue over [0..262143]+--+-- Represents a dynamic set/priority queue of dense 18-bit unsigned integers+-- (@0 .. 262143 = 64^3 - 1@) using two flat unscanned 'MutablePrimArray's+-- (@L1@ = 64 words = 512 B, @L2@ = 4096 words = 32 KiB) and a 1-word root+-- summary mask. All operations run in O(1) time with zero GC pointer scanning.+module Pykinos.Queue.BitTrie64+  ( maxBitTrieKey+  , BitTrie64+  , newBitTrie64+  , insertTrie+  , deleteTrie+  , memberTrie+  , findMinTrie+  , findMaxTrie+  , popMinTrie+  ) where++import Control.Monad.ST (ST)+import Data.Bits+  ( clearBit+  , countLeadingZeros+  , countTrailingZeros+  , setBit+  , shiftL+  , shiftR+  , testBit+  , (.&.)+  , (.|.)+  )+import Data.Primitive.PrimArray+  ( MutablePrimArray+  , newPrimArray+  , readPrimArray+  , setPrimArray+  , writePrimArray+  )+import Data.STRef (STRef, newSTRef, readSTRef, writeSTRef)+import Data.Word (Word64)++-- | Maximum supported key (@64^3 - 1 = 262143@).+maxBitTrieKey :: Int+maxBitTrieKey = 262143++-- | 3-level 64-ary bitmap trie in @ST s@ (zero GC pointers).+data BitTrie64 s = BitTrie64+  { btRoot :: !(STRef s Word64)+  , btL1   :: !(MutablePrimArray s Word64) -- ^ 64 words+  , btL2   :: !(MutablePrimArray s Word64) -- ^ 4096 words+  }++-- | Allocates an empty 'BitTrie64'.+newBitTrie64 :: ST s (BitTrie64 s)+newBitTrie64 = do+  rootRef <- newSTRef 0+  l1 <- newPrimArray 64+  setPrimArray l1 0 64 (0 :: Word64)+  l2 <- newPrimArray 4096+  setPrimArray l2 0 4096 (0 :: Word64)+  pure (BitTrie64 rootRef l1 l2)++-- | Inserts @k@ in O(1). Returns 'True' if @k@ was newly inserted.+insertTrie :: BitTrie64 s -> Int -> ST s Bool+insertTrie (BitTrie64 rootRef l1 l2) !k+  | k < 0 || k > maxBitTrieKey = pure False+  | otherwise = do+      let !idx2 = k `shiftR` 6+          !bit2 = k .&. 63+          !idx1 = idx2 `shiftR` 6+          !bit1 = idx2 .&. 63+      w2 <- readPrimArray l2 idx2+      if testBit w2 bit2+        then pure False+        else do+          writePrimArray l2 idx2 (setBit w2 bit2)+          w1 <- readPrimArray l1 idx1+          writePrimArray l1 idx1 (setBit w1 bit1)+          r0 <- readSTRef rootRef+          writeSTRef rootRef (setBit r0 idx1)+          pure True++-- | Deletes @k@ in O(1). Returns 'True' if @k@ was present.+deleteTrie :: BitTrie64 s -> Int -> ST s Bool+deleteTrie (BitTrie64 rootRef l1 l2) !k+  | k < 0 || k > maxBitTrieKey = pure False+  | otherwise = do+      let !idx2 = k `shiftR` 6+          !bit2 = k .&. 63+          !idx1 = idx2 `shiftR` 6+          !bit1 = idx2 .&. 63+      w2 <- readPrimArray l2 idx2+      if not (testBit w2 bit2)+        then pure False+        else do+          let !w2' = clearBit w2 bit2+          writePrimArray l2 idx2 w2'+          if w2' /= 0+            then pure True+            else do+              w1 <- readPrimArray l1 idx1+              let !w1' = clearBit w1 bit1+              writePrimArray l1 idx1 w1'+              if w1' /= 0+                then pure True+                else do+                  r0 <- readSTRef rootRef+                  writeSTRef rootRef (clearBit r0 idx1)+                  pure True++-- | Tests membership of @k@ in O(1) with a single L2 word read.+memberTrie :: BitTrie64 s -> Int -> ST s Bool+memberTrie (BitTrie64 _ _ l2) !k+  | k < 0 || k > maxBitTrieKey = pure False+  | otherwise = do+      w2 <- readPrimArray l2 (k `shiftR` 6)+      pure (testBit w2 (k .&. 63))++-- | Returns the smallest present key in O(1) via three @ctz@ instructions.+findMinTrie :: BitTrie64 s -> ST s (Maybe Int)+findMinTrie (BitTrie64 rootRef l1 l2) = do+  r0 <- readSTRef rootRef+  if r0 == 0+    then pure Nothing+    else do+      let !idx1 = countTrailingZeros r0+      w1 <- readPrimArray l1 idx1+      let !bit1 = countTrailingZeros w1+          !idx2 = (idx1 `shiftL` 6) .|. bit1+      w2 <- readPrimArray l2 idx2+      let !bit2 = countTrailingZeros w2+      pure (Just ((idx2 `shiftL` 6) .|. bit2))++-- | Returns the largest present key in O(1) via three @clz@ instructions.+findMaxTrie :: BitTrie64 s -> ST s (Maybe Int)+findMaxTrie (BitTrie64 rootRef l1 l2) = do+  r0 <- readSTRef rootRef+  if r0 == 0+    then pure Nothing+    else do+      let !idx1 = 63 - countLeadingZeros r0+      w1 <- readPrimArray l1 idx1+      let !bit1 = 63 - countLeadingZeros w1+          !idx2 = (idx1 `shiftL` 6) .|. bit1+      w2 <- readPrimArray l2 idx2+      let !bit2 = countTrailingZeros w2+      pure (Just ((idx2 `shiftL` 6) .|. bit2))++-- | Extracts and deletes the minimum key in O(1).+popMinTrie :: BitTrie64 s -> ST s (Maybe Int)+popMinTrie trie = do+  m <- findMinTrie trie+  case m of+    Nothing -> pure Nothing+    Just k  -> do+      _ <- deleteTrie trie k+      pure (Just k)
+ src/Pykinos/Queue/RadixHeap.hs view
@@ -0,0 +1,219 @@+{-# LANGUAGE BangPatterns #-}+{-# OPTIONS_GHC -Wno-unused-top-binds -Wno-deprecations #-}+-- | Module: Pykinos.Queue.RadixHeap+-- Description: 65-bucket monotone priority queue with Word64 occupancy mask+--+-- Implements an unboxed monotone radix heap for 64-bit integer keys. Keys must+-- be extracted in monotonically non-decreasing order (standard Dijkstra/A* pattern).+-- All buckets are flat unboxed arrays with zero per-element heap allocations.+module Pykinos.Queue.RadixHeap+  ( RadixHeap+  , newRadixHeap+  , insertRadix+  , findMinRadix+  , popMinRadix+  , radixSize+  ) where++import Control.Monad (when)+import Control.Monad.ST (ST)+import Data.Bits+  ( clearBit+  , countLeadingZeros+  , countTrailingZeros+  , shiftL+  , xor+  , (.&.)+  , (.|.)+  )+import Data.Primitive.Array+  ( MutableArray+  , newArray+  , readArray+  , writeArray+  )+import Data.Primitive.PrimArray+  ( MutablePrimArray+  , copyMutablePrimArray+  , newPrimArray+  , readPrimArray+  , sizeofMutablePrimArray+  , writePrimArray+  )+import Data.STRef (STRef, newSTRef, readSTRef, writeSTRef)+import Data.Word (Word32, Word64)++-- | A single dynamic bucket holding unboxed @(Word64, Word32)@ pairs.+data Bucket s = Bucket+  { bKeys    :: !(STRef s (MutablePrimArray s Word64))+  , bVals    :: !(STRef s (MutablePrimArray s Word32))+  , bCount   :: !(STRef s Int)+  }++newBucket :: Int -> ST s (Bucket s)+newBucket !initCap = do+  let !cap = max 4 initCap+  kArr <- newPrimArray cap+  vArr <- newPrimArray cap+  kRef <- newSTRef kArr+  vRef <- newSTRef vArr+  cRef <- newSTRef 0+  pure (Bucket kRef vRef cRef)++pushBucket :: Bucket s -> Word64 -> Word32 -> ST s ()+pushBucket (Bucket kRef vRef cRef) !k !v = do+  !cnt <- readSTRef cRef+  kArr <- readSTRef kRef+  let !cap = sizeofMutablePrimArray kArr+  when (cnt == cap) $ do+    let !newCap = cap * 2+    newK <- newPrimArray newCap+    newV <- newPrimArray newCap+    vArr <- readSTRef vRef+    copyMutablePrimArray newK 0 kArr 0 cnt+    copyMutablePrimArray newV 0 vArr 0 cnt+    writeSTRef kRef newK+    writeSTRef vRef newV+  kArr' <- readSTRef kRef+  vArr' <- readSTRef vRef+  writePrimArray kArr' cnt k+  writePrimArray vArr' cnt v+  writeSTRef cRef (cnt + 1)++-- | 65-bucket monotone radix heap in @ST s@.+data RadixHeap s = RadixHeap+  { rhLast     :: !(STRef s Word64)+  , rhSize     :: !(STRef s Int)+  , rhMask     :: !(STRef s Word64)  -- ^ Tracks non-empty buckets 1..64+  , rhBucket0  :: !(Bucket s)         -- ^ Bucket 0 (key == rhLast)+  , rhBuckets  :: !(MutableArray s (Bucket s)) -- ^ Buckets 1..64+  }++-- | Allocates an empty 'RadixHeap'.+newRadixHeap :: ST s (RadixHeap s)+newRadixHeap = do+  lastRef <- newSTRef 0+  sizeRef <- newSTRef 0+  maskRef <- newSTRef 0+  b0 <- newBucket 8+  bucketsArr <- newArray 64 b0+  let initBuckets !i+        | i >= 64   = pure ()+        | otherwise = do+            b <- newBucket 4+            writeArray bucketsArr i b+            initBuckets (i + 1)+  initBuckets 0+  pure (RadixHeap lastRef sizeRef maskRef b0 bucketsArr)++-- | Total number of elements stored in the radix heap.+radixSize :: RadixHeap s -> ST s Int+radixSize (RadixHeap _ sRef _ _ _) = readSTRef sRef++-- | Computes the bucket index for a key relative to @lastVal@.+-- Returns 0 if @k == lastVal@, else @64 - countLeadingZeros (k `xor` lastVal)@ (1..64).+bucketIndex :: Word64 -> Word64 -> Int+bucketIndex !k !lastVal+  | k == lastVal = 0+  | otherwise    = 64 - countLeadingZeros (k `xor` lastVal)++-- | Inserts @(key, payload)@ into the heap. Monotonicity requires @key >= lastDeletedKey@.+insertRadix :: RadixHeap s -> Word64 -> Word32 -> ST s ()+insertRadix (RadixHeap lastRef sizeRef maskRef b0 bucketsArr) !k !v = do+  !lastVal <- readSTRef lastRef+  let !bIdx = bucketIndex (max lastVal k) lastVal+  if bIdx == 0+    then pushBucket b0 k v+    else do+      b <- readArray bucketsArr (bIdx - 1)+      pushBucket b k v+      !m <- readSTRef maskRef+      writeSTRef maskRef (m .|. (1 `shiftL` (bIdx - 1)))+  !sz <- readSTRef sizeRef+  writeSTRef sizeRef (sz + 1)++-- | Ensures bucket 0 has elements if the heap is non-empty by pulling down the lowest non-empty bucket.+pullDownMin :: RadixHeap s -> ST s Bool+pullDownMin (RadixHeap lastRef _ maskRef b0 bucketsArr) = do+  !cnt0 <- readSTRef (bCount b0)+  if cnt0 > 0+    then pure True+    else do+      !m <- readSTRef maskRef+      if m == 0+        then pure False+        else do+          let !lowestBucketIdx = countTrailingZeros m+          b <- readArray bucketsArr lowestBucketIdx+          !cnt <- readSTRef (bCount b)+          kArr <- readSTRef (bKeys b)+          vArr <- readSTRef (bVals b)+          -- Find minimum key in this bucket+          let findMinKey !i !minK+                | i >= cnt = pure minK+                | otherwise = do+                    k <- readPrimArray kArr i+                    findMinKey (i + 1) (min minK k)+          firstK <- readPrimArray kArr 0+          !newLast <- findMinKey 1 firstK+          writeSTRef lastRef newLast+          -- Clear bucket b and mask bit+          writeSTRef (bCount b) 0+          writeSTRef maskRef (m .&. complementBit lowestBucketIdx)+          -- Redistribute elements to lower buckets (or b0)+          let redistribute !i+                | i >= cnt = pure ()+                | otherwise = do+                    k <- readPrimArray kArr i+                    v <- readPrimArray vArr i+                    let !targetIdx = bucketIndex k newLast+                    if targetIdx == 0+                      then pushBucket b0 k v+                      else do+                        tb <- readArray bucketsArr (targetIdx - 1)+                        pushBucket tb k v+                        !curM <- readSTRef maskRef+                        writeSTRef maskRef (curM .|. (1 `shiftL` (targetIdx - 1)))+                    redistribute (i + 1)+          redistribute 0+          pure True+  where+    complementBit !i = clearBit (0xFFFFFFFFFFFFFFFF :: Word64) i++-- | Peeks at the minimum key and payload without removing it.+findMinRadix :: RadixHeap s -> ST s (Maybe (Word64, Word32))+findMinRadix heap@(RadixHeap _ _ _ b0 _) = do+  hasElems <- pullDownMin heap+  if not hasElems+    then pure Nothing+    else do+      !cnt0 <- readSTRef (bCount b0)+      if cnt0 == 0+        then pure Nothing+        else do+          kArr <- readSTRef (bKeys b0)+          vArr <- readSTRef (bVals b0)+          k <- readPrimArray kArr (cnt0 - 1)+          v <- readPrimArray vArr (cnt0 - 1)+          pure (Just (k, v))++-- | Pops the minimum key and payload in amortized O(1).+popMinRadix :: RadixHeap s -> ST s (Maybe (Word64, Word32))+popMinRadix heap@(RadixHeap _ sizeRef _ b0 _) = do+  hasElems <- pullDownMin heap+  if not hasElems+    then pure Nothing+    else do+      !cnt0 <- readSTRef (bCount b0)+      if cnt0 == 0+        then pure Nothing+        else do+          kArr <- readSTRef (bKeys b0)+          vArr <- readSTRef (bVals b0)+          let !idx = cnt0 - 1+          k <- readPrimArray kArr idx+          v <- readPrimArray vArr idx+          writeSTRef (bCount b0) idx+          !sz <- readSTRef sizeRef+          writeSTRef sizeRef (sz - 1)+          pure (Just (k, v))
+ src/Pykinos/Queue/TimingWheel.hs view
@@ -0,0 +1,116 @@+{-# LANGUAGE BangPatterns #-}+{-# OPTIONS_GHC -Wno-unused-top-binds -Wno-deprecations #-}+-- | Module: Pykinos.Queue.TimingWheel+-- Description: 4-level × 64-slot hierarchical hashed timing wheel+--+-- Provides an unboxed hierarchical timing wheel timer multiplexer. Supports+-- $O(1)$ timer arming and $O(1)$ amortized tick advancement with cascading across+-- 4 levels of 64-slot wheels ($64^4 = 16,777,216$ ticks capacity).+module Pykinos.Queue.TimingWheel+  ( TimingWheel+  , newTimingWheel+  , armTimer+  , advanceTick+  , currentTick+  ) where++import Control.Monad (forM_, when)+import Control.Monad.ST (ST)+import Data.Bits (shiftR, (.&.))+import Data.Primitive.Array+  ( MutableArray+  , newArray+  , readArray+  , writeArray+  )+import Data.STRef (STRef, newSTRef, readSTRef, writeSTRef)+import Data.Word (Word32, Word64)++-- | An entry in the timing wheel: deadline tick and handle payload.+data TimerEntry = TimerEntry+  { teDeadline :: {-# UNPACK #-} !Word64+  , teHandle   :: {-# UNPACK #-} !Word32+  } deriving stock (Eq, Show)++-- | 4-level × 64-slot hierarchical timing wheel in @ST s@.+data TimingWheel s = TimingWheel+  { twCurrentTick :: !(STRef s Word64)+  , twLevel0      :: !(MutableArray s [TimerEntry]) -- ^ 64 slots, 1 tick/slot+  , twLevel1      :: !(MutableArray s [TimerEntry]) -- ^ 64 slots, 64 ticks/slot+  , twLevel2      :: !(MutableArray s [TimerEntry]) -- ^ 64 slots, 4096 ticks/slot+  , twLevel3      :: !(MutableArray s [TimerEntry]) -- ^ 64 slots, 262144 ticks/slot+  }++-- | Allocates an empty 'TimingWheel' initialized at tick 0.+newTimingWheel :: ST s (TimingWheel s)+newTimingWheel = do+  curRef <- newSTRef 0+  l0 <- newArray 64 []+  l1 <- newArray 64 []+  l2 <- newArray 64 []+  l3 <- newArray 64 []+  pure (TimingWheel curRef l0 l1 l2 l3)++-- | Returns the current monotonic tick of the timing wheel.+currentTick :: TimingWheel s -> ST s Word64+currentTick (TimingWheel curRef _ _ _ _) = readSTRef curRef++-- | Arms a timer to fire at absolute tick @deadline@ with handle @payload@.+armTimer :: TimingWheel s -> Word64 -> Word32 -> ST s ()+armTimer (TimingWheel curRef l0 l1 l2 l3) !deadline !h = do+  !now <- readSTRef curRef+  let !target = max now deadline+      !delta  = target - now+      !entry  = TimerEntry target h+  if delta < 64+    then addEntry l0 (target .&. 63) entry+    else if delta < 4096+      then addEntry l1 ((target `shiftR` 6) .&. 63) entry+      else if delta < 262144+        then addEntry l2 ((target `shiftR` 12) .&. 63) entry+        else addEntry l3 ((target `shiftR` 18) .&. 63) entry+  where+    addEntry arr !slot !e = do+      let !s = fromIntegral slot+      entries <- readArray arr s+      writeArray arr s (e : entries)++-- | Advances the wheel by 1 tick, cascading higher-level wheels as slots wrap,+-- and returns all expired handles.+advanceTick :: TimingWheel s -> ST s [Word32]+advanceTick tw@(TimingWheel curRef l0 l1 l2 l3) = do+  !now <- readSTRef curRef+  let !nextTick = now + 1+  writeSTRef curRef nextTick+  let !slot0 = fromIntegral (nextTick .&. 63)+  -- If slot0 wrapped to 0, cascade L1+  when (slot0 == 0) $ cascadeLevel tw l1 6+  -- If L1 also wrapped, cascade L2+  when ((nextTick .&. 4095) == 0) $ cascadeLevel tw l2 12+  -- If L2 also wrapped, cascade L3+  when ((nextTick .&. 262143) == 0) $ cascadeLevel tw l3 18+  -- Collect expired entries from L0 at slot0+  entries <- readArray l0 slot0+  writeArray l0 slot0 []+  let (!expired, !remaining) = partitionEntries nextTick entries+  -- Re-arm any non-expired (should be rare/empty in L0)+  forM_ remaining $ \(TimerEntry d h) -> armTimer tw d h+  pure (map teHandle expired)+  where+    partitionEntries _ [] = ([], [])+    partitionEntries !target (e : es)+      | teDeadline e <= target =+          let (!expList, !remList) = partitionEntries target es+          in (e : expList, remList)+      | otherwise =+          let (!expList, !remList) = partitionEntries target es+          in (expList, e : remList)++-- | Re-arms entries from a higher level down into lower levels.+cascadeLevel :: TimingWheel s -> MutableArray s [TimerEntry] -> Int -> ST s ()+cascadeLevel tw arr !shift = do+  !now <- currentTick tw+  let !slot = fromIntegral ((now `shiftR` shift) .&. 63)+  entries <- readArray arr slot+  writeArray arr slot []+  forM_ entries $ \(TimerEntry d h) -> armTimer tw d h
+ src/Pykinos/Queue/WordHeap8.hs view
@@ -0,0 +1,153 @@+{-# LANGUAGE BangPatterns #-}+{-# OPTIONS_GHC -Wno-unused-top-binds -Wno-deprecations #-}+-- | Module: Pykinos.Queue.WordHeap8+-- Description: Flat 8-ary implicit min-heap of (Word64, Word32) packed in contiguous memory+--+-- Implements an 8-ary cache-conscious min-priority queue over unboxed 'MutablePrimArray's.+-- With an arity of 8, each internal node's 8 children are contiguous in memory (sharing+-- adjacent cache lines), and tree height is $\log_8(N)$ rather than $\log_2(N)$ (3x fewer levels).+module Pykinos.Queue.WordHeap8+  ( WordHeap8+  , newWordHeap8+  , insertHeap8+  , findMinHeap8+  , popMinHeap8+  , heap8Size+  ) where++import Control.Monad (when)+import Control.Monad.ST (ST)+import Data.Primitive.PrimArray+  ( MutablePrimArray+  , copyMutablePrimArray+  , newPrimArray+  , readPrimArray+  , sizeofMutablePrimArray+  , writePrimArray+  )+import Data.STRef (STRef, newSTRef, readSTRef, writeSTRef)+import Data.Word (Word32, Word64)++-- | Flat 8-ary unboxed implicit min-heap in @ST s@.+data WordHeap8 s = WordHeap8+  { whKeys  :: !(STRef s (MutablePrimArray s Word64))+  , whVals  :: !(STRef s (MutablePrimArray s Word32))+  , whCount :: !(STRef s Int)+  }++-- | Allocates an empty 8-ary min-heap with initial capacity (min 16).+newWordHeap8 :: Int -> ST s (WordHeap8 s)+newWordHeap8 !minCap = do+  let !cap = max 16 minCap+  kArr <- newPrimArray cap+  vArr <- newPrimArray cap+  kRef <- newSTRef kArr+  vRef <- newSTRef vArr+  cRef <- newSTRef 0+  pure (WordHeap8 kRef vRef cRef)++-- | Current number of elements in the heap.+heap8Size :: WordHeap8 s -> ST s Int+heap8Size (WordHeap8 _ _ cRef) = readSTRef cRef++-- | Inserts @(key, payload)@ into the heap and sifts up along the $\log_8(N)$ branch.+insertHeap8 :: WordHeap8 s -> Word64 -> Word32 -> ST s ()+insertHeap8 (WordHeap8 kRef vRef cRef) !k !v = do+  !cnt <- readSTRef cRef+  kArr <- readSTRef kRef+  let !cap = sizeofMutablePrimArray kArr+  when (cnt == cap) $ do+    let !newCap = cap * 2+    newK <- newPrimArray newCap+    newV <- newPrimArray newCap+    vArr <- readSTRef vRef+    copyMutablePrimArray newK 0 kArr 0 cnt+    copyMutablePrimArray newV 0 vArr 0 cnt+    writeSTRef kRef newK+    writeSTRef vRef newV+  curKArr <- readSTRef kRef+  curVArr <- readSTRef vRef+  writePrimArray curKArr cnt k+  writePrimArray curVArr cnt v+  writeSTRef cRef (cnt + 1)+  siftUp curKArr curVArr cnt++-- | Sifts up element at index @i@ until heap invariant holds.+siftUp :: MutablePrimArray s Word64 -> MutablePrimArray s Word32 -> Int -> ST s ()+siftUp !kArr !vArr !i+  | i <= 0    = pure ()+  | otherwise = do+      let !p = (i - 1) `div` 8+      pk <- readPrimArray kArr p+      ik <- readPrimArray kArr i+      when (ik < pk) $ do+        pv <- readPrimArray vArr p+        iv <- readPrimArray vArr i+        writePrimArray kArr p ik+        writePrimArray vArr p iv+        writePrimArray kArr i pk+        writePrimArray vArr i pv+        siftUp kArr vArr p++-- | Peeks at the minimum @(key, payload)@ in O(1).+findMinHeap8 :: WordHeap8 s -> ST s (Maybe (Word64, Word32))+findMinHeap8 (WordHeap8 kRef vRef cRef) = do+  !cnt <- readSTRef cRef+  if cnt == 0+    then pure Nothing+    else do+      kArr <- readSTRef kRef+      vArr <- readSTRef vRef+      k <- readPrimArray kArr 0+      v <- readPrimArray vArr 0+      pure (Just (k, v))++-- | Pops the minimum @(key, payload)@ and sifts down the replacement root.+popMinHeap8 :: WordHeap8 s -> ST s (Maybe (Word64, Word32))+popMinHeap8 (WordHeap8 kRef vRef cRef) = do+  !cnt <- readSTRef cRef+  if cnt == 0+    then pure Nothing+    else do+      kArr <- readSTRef kRef+      vArr <- readSTRef vRef+      minK <- readPrimArray kArr 0+      minV <- readPrimArray vArr 0+      let !lastIdx = cnt - 1+      lastK <- readPrimArray kArr lastIdx+      lastV <- readPrimArray vArr lastIdx+      writePrimArray kArr 0 lastK+      writePrimArray vArr 0 lastV+      writeSTRef cRef lastIdx+      when (lastIdx > 1) $ do+        siftDown kArr vArr lastIdx 0+      pure (Just (minK, minV))++-- | Sifts down element at index @i@ across its up to 8 contiguous children.+siftDown :: MutablePrimArray s Word64 -> MutablePrimArray s Word32 -> Int -> Int -> ST s ()+siftDown !kArr !vArr !n !i = do+  let !firstChild = 8 * i + 1+  if firstChild >= n+    then pure ()+    else do+      let !lastChild = min (firstChild + 7) (n - 1)+      -- Find smallest child among [firstChild .. lastChild]+      let findBestChild !c !bestIdx !bestK+            | c > lastChild = pure bestIdx+            | otherwise = do+                ck <- readPrimArray kArr c+                if ck < bestK+                  then findBestChild (c + 1) c ck+                  else findBestChild (c + 1) bestIdx bestK+      firstK <- readPrimArray kArr firstChild+      !bestChildIdx <- findBestChild (firstChild + 1) firstChild firstK+      bestChildK <- readPrimArray kArr bestChildIdx+      curK <- readPrimArray kArr i+      when (bestChildK < curK) $ do+        curV <- readPrimArray vArr i+        bestChildV <- readPrimArray vArr bestChildIdx+        writePrimArray kArr i bestChildK+        writePrimArray vArr i bestChildV+        writePrimArray kArr bestChildIdx curK+        writePrimArray vArr bestChildIdx curV+        siftDown kArr vArr n bestChildIdx
+ src/Pykinos/Queue/WordRing.hs view
@@ -0,0 +1,141 @@+{-# LANGUAGE BangPatterns #-}+{-# OPTIONS_GHC -Wno-unused-top-binds -Wno-unused-matches -Wno-deprecations #-}+-- | Module: Pykinos.Queue.WordRing+-- Description: Unboxed power-of-two circular FIFO/LIFO deque with geometric resizing+--+-- Implements an unboxed double-ended queue over a single 'MutablePrimArray' of+-- 32-bit machine words (@Word32@). Supports amortized O(1) pushBack, popFront,+-- and popBack with zero per-element GC allocation overhead.+module Pykinos.Queue.WordRing+  ( WordRing+  , newWordRing+  , pushBack+  , popFront+  , popBack+  , ringLength+  , ringCapacity+  , clearRing+  ) where++import Control.Monad (when)+import Control.Monad.ST (ST)+import Data.Bits ((.&.))+import Data.Primitive.PrimArray+  ( MutablePrimArray+  , copyMutablePrimArray+  , newPrimArray+  , readPrimArray+  , sizeofMutablePrimArray+  , writePrimArray+  )+import Data.STRef (STRef, newSTRef, readSTRef, writeSTRef)+import Data.Word (Word32)++-- | Circular power-of-two ring buffer in @ST s@.+data WordRing s = WordRing+  { wrArrRef :: !(STRef s (MutablePrimArray s Word32))+  , wrHead   :: !(STRef s Int)+  , wrTail   :: !(STRef s Int)+  , wrCount  :: !(STRef s Int)+  }++-- | Allocates an empty 'WordRing' with initial capacity rounded up to power of two (min 16).+newWordRing :: Int -> ST s (WordRing s)+newWordRing !minCap = do+  let !cap = nextPowerOfTwo (max 16 minCap)+  arr <- newPrimArray cap+  arrRef <- newSTRef arr+  hRef <- newSTRef 0+  tRef <- newSTRef 0+  cRef <- newSTRef 0+  pure (WordRing arrRef hRef tRef cRef)++-- | Returns the next power of two >= n.+nextPowerOfTwo :: Int -> Int+nextPowerOfTwo 0 = 1+nextPowerOfTwo !n = 1 `go` (n - 1)+  where+    go !acc 0 = acc+    go !acc k = go (acc * 2) (k `div` 2)++-- | Current number of elements stored in the ring.+ringLength :: WordRing s -> ST s Int+ringLength (WordRing _ _ _ cRef) = readSTRef cRef++-- | Total allocated slot capacity in the current underlying array.+ringCapacity :: WordRing s -> ST s Int+ringCapacity (WordRing arrRef _ _ _) = do+  arr <- readSTRef arrRef+  pure (sizeofMutablePrimArray arr)++-- | Resets the ring to empty without reallocating the underlying array.+clearRing :: WordRing s -> ST s ()+clearRing (WordRing _ hRef tRef cRef) = do+  writeSTRef hRef 0+  writeSTRef tRef 0+  writeSTRef cRef 0++-- | Enqueues a word at the back of the deque, doubling capacity if full.+pushBack :: WordRing s -> Word32 -> ST s ()+pushBack ring@(WordRing arrRef hRef tRef cRef) !val = do+  !cnt <- readSTRef cRef+  arr <- readSTRef arrRef+  let !cap = sizeofMutablePrimArray arr+  when (cnt == cap) $ do+    growRing ring+  !arr' <- readSTRef arrRef+  let !mask = sizeofMutablePrimArray arr' - 1+  !t <- readSTRef tRef+  writePrimArray arr' t val+  writeSTRef tRef ((t + 1) .&. mask)+  writeSTRef cRef (cnt + 1)++-- | Doubles the capacity of the ring buffer and straightens out elements.+growRing :: WordRing s -> ST s ()+growRing (WordRing arrRef hRef tRef cRef) = do+  oldArr <- readSTRef arrRef+  let !oldCap = sizeofMutablePrimArray oldArr+      !newCap = oldCap * 2+  newArr <- newPrimArray newCap+  !h <- readSTRef hRef+  !cnt <- readSTRef cRef+  -- Copy elements in logical order from h to 0..cnt-1 in newArr+  let !firstChunk = min cnt (oldCap - h)+      !secondChunk = cnt - firstChunk+  copyMutablePrimArray newArr 0 oldArr h firstChunk+  when (secondChunk > 0) $ do+    copyMutablePrimArray newArr firstChunk oldArr 0 secondChunk+  writeSTRef arrRef newArr+  writeSTRef hRef 0+  writeSTRef tRef cnt++-- | Dequeues a word from the front of the deque in O(1).+popFront :: WordRing s -> ST s (Maybe Word32)+popFront (WordRing arrRef hRef _ cRef) = do+  !cnt <- readSTRef cRef+  if cnt == 0+    then pure Nothing+    else do+      arr <- readSTRef arrRef+      let !mask = sizeofMutablePrimArray arr - 1+      !h <- readSTRef hRef+      val <- readPrimArray arr h+      writeSTRef hRef ((h + 1) .&. mask)+      writeSTRef cRef (cnt - 1)+      pure (Just val)++-- | Dequeues a word from the back of the deque (LIFO stack pop) in O(1).+popBack :: WordRing s -> ST s (Maybe Word32)+popBack (WordRing arrRef _ tRef cRef) = do+  !cnt <- readSTRef cRef+  if cnt == 0+    then pure Nothing+    else do+      arr <- readSTRef arrRef+      let !mask = sizeofMutablePrimArray arr - 1+      !t <- readSTRef tRef+      let !newT = (t - 1) .&. mask+      val <- readPrimArray arr newT+      writeSTRef tRef newT+      writeSTRef cRef (cnt - 1)+      pure (Just val)
+ src/Pykinos/Queue/WordWorklist.hs view
@@ -0,0 +1,93 @@+{-# LANGUAGE BangPatterns #-}+{-# OPTIONS_GHC -Wno-unused-top-binds -Wno-deprecations #-}+-- | Module: Pykinos.Queue.WordWorklist+-- Description: Unboxed worklist queue with O(1) deduplication via a flat dense bitset+--+-- Combines 'WordRing' with a dense unscanned 'MutablePrimArray' bitmap to enforce+-- idempotent worklist semantics. 'enqueueUnique' checks and sets the membership bit in+-- O(1), ensuring no item is queued multiple times concurrently. 'dequeueWork' clears the bit.+module Pykinos.Queue.WordWorklist+  ( WordWorklist+  , newWordWorklist+  , enqueueUnique+  , dequeueWork+  , isWorklistMember+  , worklistLength+  ) where++import Control.Monad.ST (ST)+import Data.Bits (clearBit, setBit, shiftR, testBit, (.&.))+import Data.Primitive.PrimArray+  ( MutablePrimArray+  , newPrimArray+  , readPrimArray+  , setPrimArray+  , sizeofMutablePrimArray+  , writePrimArray+  )+import Data.Word (Word32, Word64)+import Pykinos.Queue.WordRing (WordRing, newWordRing, popFront, pushBack, ringLength)++-- | Unboxed deduplicating worklist in @ST s@.+data WordWorklist s = WordWorklist+  { wwRing   :: !(WordRing s)+  , wwBitset :: !(MutablePrimArray s Word64)+  }++-- | Allocates a 'WordWorklist' supporting items in @0 .. maxItem - 1@.+newWordWorklist :: Int -> ST s (WordWorklist s)+newWordWorklist !maxItem = do+  let !wordsNeeded = max 1 ((maxItem + 63) `shiftR` 6)+  ring <- newWordRing (min 1024 maxItem)+  bits <- newPrimArray wordsNeeded+  setPrimArray bits 0 wordsNeeded (0 :: Word64)+  pure (WordWorklist ring bits)++-- | Enqueues @item@ if not already present in the worklist. Returns 'True' if enqueued.+enqueueUnique :: WordWorklist s -> Word32 -> ST s Bool+enqueueUnique (WordWorklist ring bits) !item = do+  let !idx = fromIntegral (item `shiftR` 6)+      !bit = fromIntegral (item .&. 63)+      !numWords = sizeofMutablePrimArray bits+  if idx >= numWords+    then pure False+    else do+      w <- readPrimArray bits idx+      if testBit w bit+        then pure False+        else do+          writePrimArray bits idx (setBit w bit)+          pushBack ring item+          pure True++-- | Dequeues the next item and clears its membership bit so it can be re-queued later.+dequeueWork :: WordWorklist s -> ST s (Maybe Word32)+dequeueWork (WordWorklist ring bits) = do+  mItem <- popFront ring+  case mItem of+    Nothing -> pure Nothing+    Just item -> do+      let !idx = fromIntegral (item `shiftR` 6)+          !bit = fromIntegral (item .&. 63)+          !numWords = sizeofMutablePrimArray bits+      if idx < numWords+        then do+          w <- readPrimArray bits idx+          writePrimArray bits idx (clearBit w bit)+          pure (Just item)+        else pure (Just item)++-- | Tests whether @item@ is currently enqueued in the worklist.+isWorklistMember :: WordWorklist s -> Word32 -> ST s Bool+isWorklistMember (WordWorklist _ bits) !item = do+  let !idx = fromIntegral (item `shiftR` 6)+      !bit = fromIntegral (item .&. 63)+  if idx >= sizeofMutablePrimArray bits+    then pure False+    else do+      w <- readPrimArray bits idx+      pure (testBit w bit)++-- | Current number of enqueued items.+worklistLength :: WordWorklist s -> ST s Int+worklistLength (WordWorklist ring _) = ringLength ring
+ src/Pykinos/Rel/DynamicRel.hs view
@@ -0,0 +1,175 @@+{-# LANGUAGE BangPatterns #-}+{-# LANGUAGE DerivingStrategies #-}++-- | Module: Pykinos.Rel.DynamicRel+-- Description: 3-tier Semi-Naive dynamic relation with Leapfrog Triejoin WCOJ+--+-- = 3-Tier Semi-Naive Differential Evaluation & Leapfrog Triejoin+--+-- In deductive databases, incremental Datalog evaluation, and static code analyzers,+-- recursive relations accumulate tuples across fixed-point iterations. Re-evaluating+-- rules across the entire relation produces redundant derivations. The classic+-- Semi-Naive evaluation strategy partitions relation state into three tiers:+--+-- 1. __Stable (@relStableFwd@, @relStableBwd@):__ Tuples derived in prior iterations+--    whose deductive consequences have already been fully explored.+-- 2. __Delta (@relDeltaFwd@, @relDeltaBwd@):__ Fresh tuples derived in the immediately+--    preceding iteration. In rule evaluation, at least one body relation must be+--    restricted to Delta to ensure no duplicate work is performed.+-- 3. __New (@relNewFwd@):__ Newly generated tuples discovered during current evaluation,+--    buffered until 'stepSemiNaive' promotes Delta into Stable and New into Delta.+--+-- = Worst-Case Optimal Joins (WCOJ) & AGM Bound+--+-- Standard binary joins evaluate relational queries pairwise, which can suffer+-- catastrophic intermediate Cartesian explosions on cyclic queries. For instance,+-- the triangle query:+--+-- \[ Q(x, y, z) \leftarrow R(x, y), R(y, z), R(x, z) \]+--+-- evaluated as \((R(x, y) \bowtie R(y, z)) \bowtie R(x, z)\) can create an intermediate+-- relation of size \(\Omega(N^2)\), even though the final output size is bounded by+-- the Atserias-Grohe-Marx (AGM) bound \(O(N^{3/2})\).+--+-- 'leapfrogIntersect' implements the Leapfrog Triejoin algorithm (Veldhuizen, 2014),+-- advancing sorted iterators across variable domains simultaneously, achieving the+-- worst-case optimal bound without intermediate materialization.+module Pykinos.Rel.DynamicRel+  ( DynamicRel (..)+  , emptyDynamicRel+  , insertDelta+  , stepSemiNaive+  , getStableEdges+  , getDeltaEdges+  , leapfrogIntersect+  , triangleJoinWCOJ+  ) where++import Data.IntMap.Strict (IntMap)+import qualified Data.IntMap.Strict as IM+import Data.Word (Word32)++-- | 3-tier Semi-Naive dynamic relation over @(Word32, Word32)@ edges.+data DynamicRel = DynamicRel+  { relStableFwd :: !(IntMap [Word32])+    -- ^ Fully derived tuples from prior iterations: x -> [y] sorted.+  , relStableBwd :: !(IntMap [Word32])+    -- ^ Transpose covering index: y -> [x] sorted.+  , relDeltaFwd  :: !(IntMap [Word32])+    -- ^ Freshly derived tuples from the current iteration.+  , relDeltaBwd  :: !(IntMap [Word32])+    -- ^ Delta transpose index.+  , relNewFwd    :: !(IntMap [Word32])+    -- ^ Tuples discovered during current evaluation step, awaiting promotion.+  } deriving stock (Eq, Show)++-- | Constructs an empty 3-tier dynamic relation.+emptyDynamicRel :: DynamicRel+emptyDynamicRel = DynamicRel IM.empty IM.empty IM.empty IM.empty IM.empty++-- | Inserts an initial edge @(u, v)@ directly into the 'Delta' stratum.+insertDelta :: Word32 -> Word32 -> DynamicRel -> DynamicRel+insertDelta !u !v rel =+  let ku = fromIntegral u+      kv = fromIntegral v+      dFwd = IM.insertWith mergeSorted ku [v] (relDeltaFwd rel)+      dBwd = IM.insertWith mergeSorted kv [u] (relDeltaBwd rel)+  in rel { relDeltaFwd = dFwd, relDeltaBwd = dBwd }++-- | Promotes 'Delta' to 'Stable', and 'New' to 'Delta', clearing 'New'.+--+-- Tuples already present in 'Stable' are eliminated (set difference).+stepSemiNaive :: DynamicRel -> DynamicRel+stepSemiNaive rel =+  let stableFwd' = IM.unionWith mergeSorted (relStableFwd rel) (relDeltaFwd rel)+      stableBwd' = IM.unionWith mergeSorted (relStableBwd rel) (relDeltaBwd rel)+      -- Filter relNew to tuples not already in stableFwd'+      deltaFwd'  = IM.differenceWith diffSorted (relNewFwd rel) stableFwd'+      deltaBwd'  = invertFwd deltaFwd'+  in DynamicRel+       { relStableFwd = stableFwd'+       , relStableBwd = stableBwd'+       , relDeltaFwd  = deltaFwd'+       , relDeltaBwd  = deltaBwd'+       , relNewFwd    = IM.empty+       }++-- | Inverts a forward index to a backward index.+invertFwd :: IntMap [Word32] -> IntMap [Word32]+invertFwd = IM.foldlWithKey' step IM.empty+  where+    step acc u = foldl (\a v -> IM.insertWith mergeSorted (fromIntegral v) [fromIntegral u] a) acc++-- | Merges two sorted lists of 'Word32', deduplicating elements.+mergeSorted :: [Word32] -> [Word32] -> [Word32]+mergeSorted [] ys = ys+mergeSorted xs [] = xs+mergeSorted (x : xs) (y : ys) =+  case compare x y of+    LT -> x : mergeSorted xs (y : ys)+    EQ -> x : mergeSorted xs ys+    GT -> y : mergeSorted (x : xs) ys++-- | Removes elements of second sorted list from first sorted list.+diffSorted :: [Word32] -> [Word32] -> Maybe [Word32]+diffSorted xs ys =+  case go xs ys of+    [] -> Nothing+    zs -> Just zs+  where+    go [] _ = []+    go as [] = as+    go (a : as) (b : bs) =+      case compare a b of+        LT -> a : go as (b : bs)+        EQ -> go as bs+        GT -> go (a : as) bs++-- | Returns all edges currently in the 'Stable' stratum.+getStableEdges :: DynamicRel -> [(Word32, Word32)]+getStableEdges rel =+  [ (fromIntegral u, v)+  | (u, vs) <- IM.toList (relStableFwd rel)+  , v <- vs+  ]++-- | Returns all edges currently in the 'Delta' stratum.+getDeltaEdges :: DynamicRel -> [(Word32, Word32)]+getDeltaEdges rel =+  [ (fromIntegral u, v)+  | (u, vs) <- IM.toList (relDeltaFwd rel)+  , v <- vs+  ]++-- | Leapfrog Triejoin intersection of two sorted integer lists.+--+-- Yields elements common to both iterators in O(min(N, M)) time.+{-# INLINE leapfrogIntersect #-}+leapfrogIntersect :: [Word32] -> [Word32] -> [Word32]+leapfrogIntersect [] _ = []+leapfrogIntersect _ [] = []+leapfrogIntersect (x : xs) (y : ys) =+  case compare x y of+    LT -> leapfrogIntersect xs (y : ys)+    EQ -> x : leapfrogIntersect xs ys+    GT -> leapfrogIntersect (x : xs) ys++-- | Evaluates worst-case optimal triangle join on the relation:+-- finds all triangles @(x, y, z)@ such that @(x, y)@, @(y, z)@, and @(x, z)@ exist in @rel@.+--+-- Uses Leapfrog intersection @R(x, *) ∩ R(y, *)@ for each directed edge @(x, y)@,+-- bounding runtime by AGM bound O(E^(3/2)) rather than pairwise O(E^2).+triangleJoinWCOJ :: DynamicRel -> [(Word32, Word32, Word32)]+triangleJoinWCOJ rel =+  let -- Combine stable and delta forward edges+      allFwd = IM.unionWith mergeSorted (relStableFwd rel) (relDeltaFwd rel)+      triangles =+        [ (fromIntegral x, y, z)+        | (x, ys) <- IM.toList allFwd+        , y <- ys+        , let xSuccs = ys+              ySuccs = IM.findWithDefault [] (fromIntegral y) allFwd+              commonZ = leapfrogIntersect xSuccs ySuccs+        , z <- commonZ+        ]+  in triangles
+ src/Pykinos/Storage/WalSlab.hs view
@@ -0,0 +1,168 @@+{-# LANGUAGE BangPatterns #-}+-- | Module: Pykinos.Storage.WalSlab+-- Description: Segmented append-only write-ahead log (WAL) with Castagnoli CRC32C framing+-- License: EUPL-1.2 OR Apache-2.0+--+-- Frames records as @(magic :: Word32, len :: Word32, epoch :: Word64, crc32c :: Word32, payload)@+-- with deterministic torn-tail recovery on replay. Pure Castagnoli CRC32C protects data integrity.+module Pykinos.Storage.WalSlab+  ( WalRecord(..)+  , WalSlab+  , newWalSlab+  , appendWalRecord+  , walSlabBytes+  , replayWalSlab+  , computeCrc32c+  ) where++import Control.Concurrent.MVar (MVar, modifyMVar_, newMVar, readMVar)+import Control.Monad.ST (runST)+import Data.Bits (shiftL, shiftR, xor, (.&.), (.|.))+import qualified Data.ByteString as BS+import qualified Data.ByteString.Lazy as BSL+import Data.ByteString (ByteString)+import Data.Primitive.PrimArray+  ( PrimArray+  , indexPrimArray+  , newPrimArray+  , unsafeFreezePrimArray+  , writePrimArray+  )+import Data.Word (Word32, Word64, Word8)++-- | Fixed 32-bit WAL header magic token: "WAL0" (0x57414C30).+walMagic :: Word32+walMagic = 0x57414C30++-- | Individual record extracted from a WAL slab.+data WalRecord = WalRecord+  { recEpoch   :: {-# UNPACK #-} !Word64+  , recPayload :: !ByteString+  } deriving stock (Eq, Show)++-- | In-memory append-only WAL buffer.+newtype WalSlab = WalSlab (MVar BSL.ByteString)++-- | Creates an empty WAL buffer.+newWalSlab :: IO WalSlab+newWalSlab = WalSlab <$> newMVar BSL.empty++-- | Castagnoli CRC32C lookup table (polynomial 0x82F63B78).+crc32cTable :: PrimArray Word32+crc32cTable = runST $ do+  marr <- newPrimArray 256+  let fill !i+        | i >= 256  = pure ()+        | otherwise = do+            writePrimArray marr i (makeEntry i)+            fill (i + 1)+  fill 0+  unsafeFreezePrimArray marr+  where+    makeEntry !b = go (8 :: Int) (fromIntegral b :: Word32)+    go 0 !crc = crc+    go !step !crc+      | crc .&. 1 /= 0 = go (step - 1) ((crc `shiftR` 1) `xor` 0x82F63B78)+      | otherwise      = go (step - 1) (crc `shiftR` 1)++-- | Computes the Castagnoli CRC32C checksum of a ByteString.+computeCrc32c :: ByteString -> Word32+computeCrc32c bs =+  let !crc0 = 0xFFFFFFFF :: Word32+      !crcFinal = BS.foldl' updateCrc crc0 bs+  in crcFinal `xor` 0xFFFFFFFF+  where+    updateCrc !crc !b =+      let !idx = fromIntegral ((crc `xor` fromIntegral b) .&. 0xFF)+          !entry = indexPrimArray crc32cTable idx+      in (crc `shiftR` 8) `xor` entry++-- | Serializes a 32-bit word into 4 bytes (little-endian).+putWord32LE :: Word32 -> [Word8]+putWord32LE !w =+  [ fromIntegral (w .&. 0xFF)+  , fromIntegral ((w `shiftR` 8) .&. 0xFF)+  , fromIntegral ((w `shiftR` 16) .&. 0xFF)+  , fromIntegral ((w `shiftR` 24) .&. 0xFF)+  ]++-- | Serializes a 64-bit word into 8 bytes (little-endian).+putWord64LE :: Word64 -> [Word8]+putWord64LE !w =+  [ fromIntegral (w .&. 0xFF)+  , fromIntegral ((w `shiftR` 8) .&. 0xFF)+  , fromIntegral ((w `shiftR` 16) .&. 0xFF)+  , fromIntegral ((w `shiftR` 24) .&. 0xFF)+  , fromIntegral ((w `shiftR` 32) .&. 0xFF)+  , fromIntegral ((w `shiftR` 40) .&. 0xFF)+  , fromIntegral ((w `shiftR` 48) .&. 0xFF)+  , fromIntegral ((w `shiftR` 56) .&. 0xFF)+  ]++-- | Decodes a 32-bit word from 4 bytes (little-endian).+getWord32LE :: ByteString -> Word32+getWord32LE bs =+  let b0 = fromIntegral (BS.index bs 0) :: Word32+      b1 = fromIntegral (BS.index bs 1) :: Word32+      b2 = fromIntegral (BS.index bs 2) :: Word32+      b3 = fromIntegral (BS.index bs 3) :: Word32+  in b0 .|. (b1 `shiftL` 8) .|. (b2 `shiftL` 16) .|. (b3 `shiftL` 24)++-- | Decodes a 64-bit word from 8 bytes (little-endian).+getWord64LE :: ByteString -> Word64+getWord64LE bs =+  let b0 = fromIntegral (BS.index bs 0) :: Word64+      b1 = fromIntegral (BS.index bs 1) :: Word64+      b2 = fromIntegral (BS.index bs 2) :: Word64+      b3 = fromIntegral (BS.index bs 3) :: Word64+      b4 = fromIntegral (BS.index bs 4) :: Word64+      b5 = fromIntegral (BS.index bs 5) :: Word64+      b6 = fromIntegral (BS.index bs 6) :: Word64+      b7 = fromIntegral (BS.index bs 7) :: Word64+  in b0 .|. (b1 `shiftL` 8) .|. (b2 `shiftL` 16) .|. (b3 `shiftL` 24)+        .|. (b4 `shiftL` 32) .|. (b5 `shiftL` 40) .|. (b6 `shiftL` 48) .|. (b7 `shiftL` 56)++-- | Appends a record to the WAL buffer with Castagnoli CRC32C framing.+appendWalRecord :: WalSlab -> Word64 -> ByteString -> IO ()+appendWalRecord (WalSlab mvar) !epoch !payload = do+  let !len = fromIntegral (BS.length payload) :: Word32+      !crc = computeCrc32c payload+      !headerBytes = BS.pack $ concat+        [ putWord32LE walMagic+        , putWord32LE len+        , putWord64LE epoch+        , putWord32LE crc+        ]+      !chunk = BSL.fromStrict (headerBytes <> payload)+  modifyMVar_ mvar (\buf -> pure (buf <> chunk))++-- | Returns the entire current byte stream of the WAL buffer.+walSlabBytes :: WalSlab -> IO ByteString+walSlabBytes (WalSlab mvar) = BSL.toStrict <$> readMVar mvar++-- | Replays a WAL byte stream, verifying headers and checksums.+-- Returns @(validRecords, tornTailDetected)@.+replayWalSlab :: ByteString -> ([WalRecord], Bool)+replayWalSlab bytes = go bytes []+  where+    go !remBytes !acc+      | BS.null remBytes = (reverse acc, False)+      | BS.length remBytes < 20 =+          -- Fewer than 20 bytes remaining: torn header detected+          (reverse acc, True)+      | otherwise =+          let !magic = getWord32LE (BS.take 4 remBytes)+              !len   = fromIntegral (getWord32LE (BS.take 4 (BS.drop 4 remBytes))) :: Int+              !epoch = getWord64LE (BS.take 8 (BS.drop 8 remBytes))+              !crc   = getWord32LE (BS.take 4 (BS.drop 16 remBytes))+          in if magic /= walMagic || BS.length remBytes < 20 + len+               then (reverse acc, True)+               else+                 let !payload = BS.take len (BS.drop 20 remBytes)+                     !actualCrc = computeCrc32c payload+                 in if actualCrc /= crc+                      then (reverse acc, True) -- Corrupted payload: torn tail detected+                      else+                        let !rec = WalRecord epoch payload+                            !nextRem = BS.drop (20 + len) remBytes+                        in go nextRem (rec : acc)
+ src/Pykinos/Text/PieceRope.hs view
@@ -0,0 +1,338 @@+{-# LANGUAGE BangPatterns #-}+{-# LANGUAGE DerivingStrategies #-}+-- | Module: Pykinos.Text.PieceRope+-- Description: Persistent 5-metric UTF-8 piece-rope with Sub4KB leaves and O(log N) coordinate indexing+--+-- Stores immutable text in balanced Sub4KB UTF-8 chunks annotated with a 5-coordinate+-- monoidal summary ('TextMetrics'): UTF-8 bytes, UTF-16 code units (for LSP),+-- line breaks, logical grapheme clusters, and terminal display width.+module Pykinos.Text.PieceRope+  ( maxLeafBytes+  , TextMetrics(..)+  , measureText+  , PieceRope+  , emptyRope+  , fromText+  , toText+  , ropeMetrics+  , ropeByteLength+  , ropeHeight+  , appendRope+  , splitAtByte+  , sliceBytes+  , insertAtByte+  , deleteRangeByte+  , byteToLineCol+  , lineColToByte+  , byteToUtf16+  , utf16ToByte+  ) where++import Data.Char (ord)+import Data.Text (Text)+import qualified Data.Text as T++-- | Maximum UTF-8 byte length per rope leaf (strictly Sub4KB nursery-safe).+maxLeafBytes :: Int+maxLeafBytes = 512++-- | 5-coordinate monoidal summary tracked at every 'PieceRope' node.+data TextMetrics = TextMetrics+  { tmUtf8Bytes  :: {-# UNPACK #-} !Int+  , tmUtf16Units :: {-# UNPACK #-} !Int+  , tmLines      :: {-# UNPACK #-} !Int+  , tmGraphemes  :: {-# UNPACK #-} !Int+  , tmDispWidth  :: {-# UNPACK #-} !Int+  } deriving stock (Eq, Ord, Show)++instance Semigroup TextMetrics where+  {-# INLINE (<>) #-}+  TextMetrics b1 u1 l1 g1 w1 <> TextMetrics b2 u2 l2 g2 w2 =+    TextMetrics (b1 + b2) (u1 + u2) (l1 + l2) (g1 + g2) (w1 + w2)++instance Monoid TextMetrics where+  {-# INLINE mempty #-}+  mempty = TextMetrics 0 0 0 0 0++{-# INLINE utf8CharLen #-}+-- | Return UTF-8 byte length of a Unicode code point.+utf8CharLen :: Char -> Int+utf8CharLen c+  | n < 0x80    = 1+  | n < 0x800   = 2+  | n < 0x10000 = 3+  | otherwise   = 4+  where+    !n = ord c++{-# INLINE utf16CharLen #-}+-- | Return UTF-16 code-unit length of a Unicode code point (1 for BMP, 2 for surrogate pair).+utf16CharLen :: Char -> Int+utf16CharLen c = if ord c >= 0x10000 then 2 else 1++{-# INLINE charDispWidth #-}+-- | Return terminal display cell width of a character (0 for control/formatting, 2 for wide/full-width/emoji, 1 for regular).+charDispWidth :: Char -> Int+charDispWidth c+  | n < 0x20 || n == 0x7F = 0+  | (n >= 0x1100 && n <= 0x115F)+    || (n >= 0x2E80 && n <= 0xA4CF)+    || (n >= 0xAC00 && n <= 0xD7A3)+    || (n >= 0xF900 && n <= 0xFAFF)+    || (n >= 0x1F300 && n <= 0x1FAFF) = 2+  | otherwise = 1+  where+    !n = ord c++-- | Computes the 5-coordinate 'TextMetrics' of a 'Text' chunk in one strict pass.+measureText :: Text -> TextMetrics+measureText = T.foldl' step mempty+  where+    step (TextMetrics b u l g w) c =+      let !b' = b + utf8CharLen c+          !u' = u + utf16CharLen c+          !l' = if c == '\n' then l + 1 else l+          !g' = g + 1+          !w' = w + charDispWidth c+      in TextMetrics b' u' l' g' w'++-- | Height-balanced persistent piece-rope with monoidal 'TextMetrics' summaries.+data PieceRope+  = RopeEmpty+  | RopeLeaf !TextMetrics !Text+  | RopeNode {-# UNPACK #-} !Int !TextMetrics !PieceRope !PieceRope+  deriving stock (Show)++instance Eq PieceRope where+  r1 == r2 = toText r1 == toText r2++-- | Empty 'PieceRope'.+emptyRope :: PieceRope+emptyRope = RopeEmpty++{-# INLINE ropeHeight #-}+-- | Height of the rope tree.+ropeHeight :: PieceRope -> Int+ropeHeight RopeEmpty          = 0+ropeHeight (RopeLeaf _ _)     = 1+ropeHeight (RopeNode h _ _ _) = h++-- | Returns the O(1) root 'TextMetrics' summary.+{-# INLINE ropeMetrics #-}+ropeMetrics :: PieceRope -> TextMetrics+ropeMetrics RopeEmpty          = mempty+ropeMetrics (RopeLeaf m _)     = m+ropeMetrics (RopeNode _ m _ _) = m++-- | Returns the O(1) UTF-8 byte length of the rope.+{-# INLINE ropeByteLength #-}+ropeByteLength :: PieceRope -> Int+ropeByteLength = tmUtf8Bytes . ropeMetrics++-- | Construct a leaf from non-empty text, or RopeEmpty if empty.+mkLeaf :: Text -> PieceRope+mkLeaf t+  | T.null t  = RopeEmpty+  | otherwise = RopeLeaf (measureText t) t++-- | Smart constructor for internal node maintaining height and metric summaries.+mkNode :: PieceRope -> PieceRope -> PieceRope+mkNode RopeEmpty r = r+mkNode l RopeEmpty = l+mkNode l r =+  let !h = 1 + max (ropeHeight l) (ropeHeight r)+      !m = ropeMetrics l <> ropeMetrics r+  in RopeNode h m l r++-- | AVL rebalancing operator keeping subtree height delta <= 1.+balance :: PieceRope -> PieceRope -> PieceRope+balance RopeEmpty r = r+balance l RopeEmpty = l+balance l r+  | hl > hr + 1 =+      case l of+        RopeNode _ _ ll lr+          | ropeHeight ll >= ropeHeight lr -> mkNode ll (balance lr r)+          | otherwise ->+              case lr of+                RopeNode _ _ lrl lrr -> mkNode (mkNode ll lrl) (mkNode lrr r)+                _                    -> mkNode l r+        _ -> mkNode l r+  | hr > hl + 1 =+      case r of+        RopeNode _ _ rl rr+          | ropeHeight rr >= ropeHeight rl -> mkNode (balance l rl) rr+          | otherwise ->+              case rl of+                RopeNode _ _ rll rlr -> mkNode (mkNode l rll) (mkNode rlr rr)+                _                    -> mkNode l r+        _ -> mkNode l r+  | otherwise = mkNode l r+  where+    !hl = ropeHeight l+    !hr = ropeHeight r++-- | Splits a 'Text' strictly at or just before @targetByte@ on a valid code-point boundary.+splitTextAtByte :: Int -> Text -> (Text, Text)+splitTextAtByte !targetByte txt+  | targetByte <= 0 = (T.empty, txt)+  | otherwise       = T.splitAt (findCharCount 0 0 txt) txt+  where+    findCharCount !bytes !chars remTxt =+      case T.uncons remTxt of+        Nothing -> chars+        Just (c, rest) ->+          let !b' = bytes + utf8CharLen c+          in if b' > targetByte+               then chars+               else findCharCount b' (chars + 1) rest++-- | Constructs a balanced 'PieceRope' chunked into Sub4KB leaves.+fromText :: Text -> PieceRope+fromText txt+  | T.null txt = RopeEmpty+  | otherwise  = buildChunks (chunkText txt)+  where+    chunkText t+      | T.null t  = []+      | otherwise =+          let (pfx, rest) = splitTextAtByte maxLeafBytes t+          in if T.null pfx+               then [mkLeaf t]+               else mkLeaf pfx : chunkText rest++    buildChunks []  = RopeEmpty+    buildChunks [x] = x+    buildChunks xs  =+      let (a, b) = splitAt (length xs `div` 2) xs+      in balance (buildChunks a) (buildChunks b)++-- | Materializes the entire 'PieceRope' as a contiguous 'Text'.+toText :: PieceRope -> Text+toText = T.concat . go []+  where+    go acc RopeEmpty          = acc+    go acc (RopeLeaf _ t)     = t : acc+    go acc (RopeNode _ _ l r) = go (go acc r) l++-- | Concatenates two ropes in O(log N) while coalescing tiny adjacent leaves.+appendRope :: PieceRope -> PieceRope -> PieceRope+appendRope RopeEmpty r = r+appendRope l RopeEmpty = l+appendRope (RopeLeaf ml tl) (RopeLeaf mr tr)+  | tmUtf8Bytes ml + tmUtf8Bytes mr <= maxLeafBytes =+      RopeLeaf (ml <> mr) (tl <> tr)+appendRope l r = balance l r++-- | Splits a rope at UTF-8 byte offset @off@ in O(log N).+splitAtByte :: Int -> PieceRope -> (PieceRope, PieceRope)+splitAtByte !_ RopeEmpty = (RopeEmpty, RopeEmpty)+splitAtByte !off rope+  | off <= 0                   = (RopeEmpty, rope)+  | off >= ropeByteLength rope = (rope, RopeEmpty)+splitAtByte !off (RopeLeaf _ t) =+  let (l, r) = splitTextAtByte off t+  in (mkLeaf l, mkLeaf r)+splitAtByte !off (RopeNode _ _ l r) =+  let !lb = ropeByteLength l+  in if off < lb+       then let (ll, lr) = splitAtByte off l+            in (ll, appendRope lr r)+       else if off > lb+         then let (rl, rr) = splitAtByte (off - lb) r+              in (appendRope l rl, rr)+         else (l, r)++-- | Extracts the UTF-8 byte range @[start, end)@ as a 'Text'.+sliceBytes :: Int -> Int -> PieceRope -> Text+sliceBytes !start !end rope+  | end <= start = T.empty+  | otherwise =+      let (_, rest) = splitAtByte start rope+          (mid, _)  = splitAtByte (end - start) rest+      in toText mid++-- | Inserts @txt@ at UTF-8 byte offset @off@ in O(log N).+insertAtByte :: Int -> Text -> PieceRope -> PieceRope+insertAtByte !off txt rope+  | T.null txt = rope+  | otherwise =+      let (l, r) = splitAtByte off rope+      in appendRope (appendRope l (fromText txt)) r++-- | Deletes the half-open UTF-8 byte range @[start, end)@ in O(log N).+deleteRangeByte :: Int -> Int -> PieceRope -> PieceRope+deleteRangeByte !start !end rope+  | end <= start = rope+  | otherwise =+      let (l, rest) = splitAtByte start rope+          (_, r)    = splitAtByte (end - start) rest+      in appendRope l r++-- | Converts a UTF-8 byte offset to zero-based @(line, byteColOnLine)@ in O(log N).+byteToLineCol :: PieceRope -> Int -> (Int, Int)+byteToLineCol rope !off =+  let (pfx, _) = splitAtByte off rope+      !lineNo  = tmLines (ropeMetrics pfx)+      !lineStart = lineColToByte rope (lineNo, 0)+  in (lineNo, max 0 (ropeByteLength pfx - lineStart))++-- | Converts zero-based @(line, byteColOnLine)@ to a UTF-8 byte offset in O(log N).+lineColToByte :: PieceRope -> (Int, Int) -> Int+lineColToByte rope (!targetLine, !targetCol)+  | targetLine <= 0 = clampOff targetCol+  | otherwise       = clampOff (goLine 0 targetLine rope + max 0 targetCol)+  where+    !total = ropeByteLength rope+    clampOff !x = max 0 (min total x)++    goLine !accBytes !_ RopeEmpty = accBytes+    goLine !accBytes !remLines (RopeLeaf _ t) =+      accBytes + scanNewlines 0 remLines t+    goLine !accBytes !remLines (RopeNode _ _ l r) =+      let !lm = ropeMetrics l+      in if remLines <= tmLines lm+           then goLine accBytes remLines l+           else goLine (accBytes + tmUtf8Bytes lm) (remLines - tmLines lm) r++    scanNewlines !b !remLinesRemaining t+      | remLinesRemaining <= 0 = b+      | otherwise =+          case T.uncons t of+            Nothing -> b+            Just (c, rest) ->+              let !b' = b + utf8CharLen c+                  !rem' = if c == '\n' then remLinesRemaining - 1 else remLinesRemaining+              in scanNewlines b' rem' rest++-- | Converts a UTF-8 byte offset to a UTF-16 code-unit offset (LSP) in O(log N).+byteToUtf16 :: PieceRope -> Int -> Int+byteToUtf16 rope !off =+  let (pfx, _) = splitAtByte off rope+  in tmUtf16Units (ropeMetrics pfx)++-- | Converts a UTF-16 code-unit offset (LSP) to a UTF-8 byte offset in O(log N).+utf16ToByte :: PieceRope -> Int -> Int+utf16ToByte rope !targetU16+  | targetU16 <= 0 = 0+  | otherwise      = go 0 targetU16 rope+  where+    go !accBytes !_ RopeEmpty = accBytes+    go !accBytes !remU (RopeLeaf _ t) =+      accBytes + scanU16 0 remU t+    go !accBytes !remU (RopeNode _ _ l r) =+      let !lm = ropeMetrics l+      in if remU <= tmUtf16Units lm+           then go accBytes remU l+           else go (accBytes + tmUtf8Bytes lm) (remU - tmUtf16Units lm) r++    scanU16 !b !remUnits t+      | remUnits <= 0 = b+      | otherwise =+          case T.uncons t of+            Nothing -> b+            Just (c, rest) ->+              let !u = utf16CharLen c+              in if u > remUnits+                   then b+                   else scanU16 (b + utf8CharLen c) (remUnits - u) rest
src/Pykinos/Tree/BPlus.hs view
@@ -1,4 +1,4 @@-{-# LANGUAGE BangPatterns, DeriveFunctor, DeriveFoldable, ScopedTypeVariables #-}+{-# LANGUAGE BangPatterns, DeriveTraversable, ScopedTypeVariables #-}  {- | Module      : Pykinos.Tree.BPlus@@ -77,7 +77,7 @@       , bpiChildren :: {-# UNPACK #-} !(SmallArray (BPlusNode k v))         -- ^ Child node pointers (size is @sizeofSmallArray bpiPivots + 1@).       }-  deriving (Eq, Show, Functor, Foldable)+  deriving (Eq, Show, Functor, Foldable, Traversable)  -- | Persistent B+ tree key-value map. data BPlusMap k v = BPlusMap@@ -85,7 +85,7 @@     -- ^ Total number of key-value associations stored in the map.   , bpmRoot :: !(BPlusNode k v)     -- ^ Root node of the B+ tree hierarchy.-  } deriving (Eq, Show, Functor, Foldable)+  } deriving (Eq, Show, Functor, Foldable, Traversable)  -- | Construct an empty 'BPlusMap'. --
test/Spec.hs view
@@ -8,8 +8,31 @@ import Pykinos.Schema.HiddenClass import qualified Data.Text as T import Control.Monad.ST (runST)+import Data.Char (ord)+import Pykinos.Text.PieceRope import Pykinos.Tree.BPlus import Pykinos.Tree.FAST+import Pykinos.Queue.BitTrie64+import Pykinos.Queue.WordRing+import Pykinos.Queue.WordWorklist+import Pykinos.Queue.RadixHeap+import Pykinos.Queue.TimingWheel+import Pykinos.Queue.WordHeap8+import qualified Data.IntSet as IntSet+import qualified Data.IntMap.Strict as IntMap+import Control.Monad (forM_)+import Data.Word (Word32, Word64)+import Pykinos.DSU.WordDSU+import Pykinos.Interval.IntervalMap+import Pykinos.Filter.BlockedBloom+import Pykinos.Filter.Ribbon+import Pykinos.Storage.WalSlab+import Pykinos.Graph.WorkDAG+import Pykinos.Rel.DynamicRel+import Pykinos.Net.SackWindow+import Pykinos.Net.MsgAssoc+import qualified Data.ByteString as BS+import qualified Data.ByteString.Char8 as BSC  assertBool :: String -> Bool -> IO () assertBool name cond =@@ -123,4 +146,388 @@   assertBool "beta fid is 1" (lookupFieldId lx (T.pack "beta") == Just (FieldId 1))   assertBool "gamma fid is 2" (lookupFieldId lx (T.pack "gamma") == Just (FieldId 2)) -  putStrLn "=== [pykinos-core-test] ALL 33 PROPERTIES AND UNIT CHECKS PASSED ==="+  -- 9. Pykinos.Text.PieceRope Tests+  -- 9.1 Empty rope properties+  let rEmpty = emptyRope+  assertBool "rEmpty has 0 bytes" (ropeByteLength rEmpty == 0)+  assertBool "rEmpty toText is empty" (toText rEmpty == T.empty)+  assertBool "rEmpty metrics are mempty" (ropeMetrics rEmpty == mempty)++  -- 9.2 Basic construction and metrics+  let sample1 = T.pack "Hello world!\n"+      r1 = fromText sample1+  assertBool "r1 toText matches" (toText r1 == sample1)+  assertBool "r1 byte length is 13" (ropeByteLength r1 == 13)+  let m1 = ropeMetrics r1+  assertBool "r1 lines is 1" (tmLines m1 == 1)+  assertBool "r1 utf8Bytes is 13" (tmUtf8Bytes m1 == 13)+  assertBool "r1 utf16Units is 13" (tmUtf16Units m1 == 13)++  -- 9.3 Multi-script metrics (Devanagari, CJK, Emoji)+  let multiScript = T.pack "A\nä\nनमस्ते\n日本語\n🚀🌟\n"+      rMulti = fromText multiScript+  assertBool "rMulti toText roundtrip" (toText rMulti == multiScript)+  assertBool "rMulti lines is 5" (tmLines (ropeMetrics rMulti) == 5)+  assertBool "rMulti UTF-16 surrogate count" (byteToUtf16 (fromText (T.pack "🚀")) 4 == 2)+  assertBool "rMulti UTF-16 to byte reverse" (utf16ToByte (fromText (T.pack "🚀")) 2 == 4)+  assertBool "rMulti UTF-16 middle surrogate snap" (utf16ToByte (fromText (T.pack "🚀")) 1 == 0)++  -- 9.4 Differential Edit Model against Data.Text+  let refSplit !b !t+        | b <= 0 = (T.empty, t)+        | otherwise = T.splitAt (goChar 0 0 t) t+        where+          goChar !bytes !chars remTxt =+            case T.uncons remTxt of+              Nothing -> chars+              Just (c, rest) ->+                let b' = bytes + if ord c < 0x80 then 1 else if ord c < 0x800 then 2 else if ord c < 0x10000 then 3 else 4+                in if b' > b then chars else goChar b' (chars + 1) rest++      refInsert !b !ins !t =+        let (l, r) = refSplit b t+        in l <> ins <> r++      refDelete !s !e !t+        | e <= s = t+        | otherwise =+            let (l, rest) = refSplit s t+                (_, r)    = refSplit (e - s) rest+            in l <> r++      refSlice !s !e !t+        | e <= s = T.empty+        | otherwise =+            let (_, rest) = refSplit s t+                (mid, _)  = refSplit (e - s) rest+            in mid++  let initialT = T.pack "Initial document content with multiple words and lines.\nLine 2.\nLine 3.\n"+      initialR = fromText initialT++      ops = [ (0, "START: ")+            , (15, " [MID1] ")+            , (30, " [MID2] ")+            , (50, " [MID3] ")+            , (10, " [MID4] ")+            ]+      (finalR, finalT) = foldl' (\(r, t) (off, ins) ->+          let insT = T.pack ins+              r' = insertAtByte off insT r+              t' = refInsert off insT t+          in (r', t')+        ) (initialR, initialT) ops++  assertBool "differential insert bit-for-bit parity" (toText finalR == finalT)++  -- Slicing checks+  let sliceR = sliceBytes 10 35 finalR+      sliceT = refSlice (10 :: Int) (35 :: Int) finalT+  assertBool "differential slice bit-for-bit parity" (sliceR == sliceT)++  -- Deletion checks+  let delR = deleteRangeByte 10 35 finalR+      delT = refDelete (10 :: Int) (35 :: Int) finalT+  assertBool "differential delete bit-for-bit parity" (toText delR == delT)++  -- 9.5 Coordinate Roundtrips on multiScript+  let offsets = [0, 2, 4, 14, 24, ropeByteLength rMulti]+      checkLineCol off =+        let lc = byteToLineCol rMulti off+            off' = lineColToByte rMulti lc+        in off' == off+  assertBool "byteToLineCol roundtrips on key offsets" (all checkLineCol offsets)++  -- 9.6 Large rebalancing (> 1000 bytes into small 512-byte leaves)+  let bigChunk = T.replicate 100 (T.pack "1234567890\n")+      rBig = fromText bigChunk+  assertBool "rBig byte length is 1100" (ropeByteLength rBig == 1100)+  assertBool "rBig height is balanced (<= 6)" (ropeHeight rBig <= 6)+  assertBool "rBig toText roundtrip" (toText rBig == bigChunk)++  -- 10. WordQueue Systems Primitives+  putStrLn "=== [pykinos-core-test] Testing WordQueues Systems Primitives ==="++  -- 10.1 WordRing FIFO & LIFO parity vs Data.Sequence+  let (ringFifoOut, ringLifoOut) = runST $ do+        ring <- newWordRing 16+        forM_ [1..1000 :: Word32] (pushBack ring)+        l <- ringLength ring+        let popAllFifo 0 acc = pure (reverse acc)+            popAllFifo n acc = do+              m <- popFront ring+              case m of+                Nothing -> pure (reverse acc)+                Just v  -> popAllFifo (n - 1) (v : acc)+        fifoRes <- popAllFifo l []+        -- Test LIFO popBack+        forM_ [1..500 :: Word32] (pushBack ring)+        let popAllLifo (0 :: Int) acc = pure (reverse acc)+            popAllLifo n acc = do+              m <- popBack ring+              case m of+                Nothing -> pure (reverse acc)+                Just v  -> popAllLifo (n - 1) (v : acc)+        lifoRes <- popAllLifo 500 []+        pure (fifoRes, lifoRes)++  assertBool "WordRing FIFO parity vs Data.Sequence" (ringFifoOut == [1..1000])+  assertBool "WordRing LIFO popBack is reverse" (ringLifoOut == [500, 499 .. 1])++  -- 10.2 WordWorklist O(1) deduplication vs Data.IntSet+  let (worklistItems, worklistFinalLen) = runST $ do+        wl <- newWordWorklist 10000+        -- Insert with duplicate elements+        forM_ ([1..1000] ++ [500..1500] ++ [1..200] :: [Word32]) (enqueueUnique wl)+        lenBefore <- worklistLength wl+        let drain acc = do+              m <- dequeueWork wl+              case m of+                Nothing -> pure (reverse acc)+                Just x  -> drain (x : acc)+        items <- drain []+        lenAfter <- worklistLength wl+        pure (items, (lenBefore, lenAfter))++  assertBool "WordWorklist deduplicated to exactly 1500 elements" (fst worklistFinalLen == 1500)+  assertBool "WordWorklist drained to 0" (snd worklistFinalLen == 0)+  assertBool "WordWorklist matches unique elements" (worklistItems == [1..1500])++  -- 10.3 BitTrie64 parity vs Data.IntSet+  let trieKeys = [42, 0, 1000, 262143, 63, 64, 4095, 4096, 777] :: [Int]+  let (trieMembers, trieMin, trieMax, trieSorted) = runST $ do+        bt <- newBitTrie64+        forM_ trieKeys (insertTrie bt)+        memChecks <- mapM (memberTrie bt) [0, 42, 999, 1000, 262143]+        mn <- findMinTrie bt+        mx <- findMaxTrie bt+        let popAll acc = do+              m <- popMinTrie bt+              case m of+                Nothing -> pure (reverse acc)+                Just k  -> popAll (k : acc)+        popped <- popAll []+        pure (memChecks, mn, mx, popped)++  let refSet = IntSet.fromList trieKeys+  assertBool "BitTrie64 member checks" (trieMembers == [True, True, False, True, True])+  assertBool "BitTrie64 findMin matches IntSet" (trieMin == Just (IntSet.findMin refSet))+  assertBool "BitTrie64 findMax matches IntSet" (trieMax == Just (IntSet.findMax refSet))+  assertBool "BitTrie64 popMin matches IntSet toAscList" (trieSorted == IntSet.toAscList refSet)++  -- 10.4 RadixHeap Monotone Extraction Order vs Data.IntMap+  let radixPairs = [(0, 10), (5, 20), (5, 21), (12, 30), (100, 40), (1000, 50), (1000, 51), (99999, 60)] :: [(Word64, Word32)]+  let radixPopped = runST $ do+        rh <- newRadixHeap+        forM_ radixPairs (\(k, v) -> insertRadix rh k v)+        let drain acc = do+              m <- popMinRadix rh+              case m of+                Nothing -> pure (reverse acc)+                Just kv -> drain (kv : acc)+        drain []+  assertBool "RadixHeap extracts in non-decreasing key order" (map fst radixPopped == map fst radixPairs)+  assertBool "RadixHeap extracted all 8 pairs" (length radixPopped == 8)++  -- 10.5 WordHeap8 8-ary Min-Heap Parity vs Data.IntMap+  let heapKeys = [500, 20, 10000, 3, 42, 99999, 1, 77, 888, 2, 0, 99, 15] :: [Word64]+  let heapPopped = runST $ do+        h <- newWordHeap8 16+        forM_ heapKeys (\k -> insertHeap8 h k (fromIntegral k))+        let drain acc = do+              m <- popMinHeap8 h+              case m of+                Nothing -> pure (reverse acc)+                Just (k, _) -> drain (k : acc)+        drain []+  let expectedSorted = IntMap.keys (IntMap.fromList [(fromIntegral k :: Int, ()) | k <- heapKeys])+  assertBool "WordHeap8 extracts in strictly sorted order" (map fromIntegral heapPopped == expectedSorted)++  -- 10.6 TimingWheel Tick Advancement & Cascading+  let firedHandles = runST $ do+        tw <- newTimingWheel+        armTimer tw 2 101+        armTimer tw 2 102+        armTimer tw 5 105+        armTimer tw 70 170  -- crosses level 1 boundary (> 64)+        h1 <- advanceTick tw -- tick 1+        h2 <- advanceTick tw -- tick 2+        _ <- advanceTick tw -- tick 3+        _ <- advanceTick tw -- tick 4+        h5 <- advanceTick tw -- tick 5+        -- Advance up to tick 70+        let advanceTo (70 :: Int) acc = do+              hs <- advanceTick tw+              pure (reverse (hs : acc))+            advanceTo t acc = do+              hs <- advanceTick tw+              advanceTo (t + 1) (hs : acc)+        rest <- advanceTo 6 []+        pure (h1, h2, h5, concat rest)++  let (f1, f2, f5, fRest) = firedHandles+  assertBool "TimingWheel tick 1 no fire" (null f1)+  assertBool "TimingWheel tick 2 fires 101 and 102" (101 `elem` f2 && 102 `elem` f2)+  assertBool "TimingWheel tick 5 fires 105" (105 `elem` f5)+  assertBool "TimingWheel tick 70 fires 170 from cascaded L1" (170 `elem` fRest)+++  -- ========================================================================+  -- 11. Companion Systems Primitives (TP-PYKINOS-COMPANIONS-001)+  -- ========================================================================++  -- 11.1 WordDSU Unboxed Disjoint-Set+  let dsuPassed = runST $ do+        dsu <- newWordDSU 100+        u1 <- unionNodes dsu 1 2+        u2 <- unionNodes dsu 2 3+        u3 <- unionNodes dsu 4 5+        uDup <- unionNodes dsu 1 3+        s13 <- sameSet dsu 1 3+        s14 <- sameSet dsu 1 4+        r1 <- findRoot dsu 1+        r3 <- findRoot dsu 3+        pure (u1, u2, u3, not uDup, s13, not s14, r1 == r3)+  let (du1, du2, du3, dnoDup, ds13, ds14, drEq) = dsuPassed+  assertBool "WordDSU unions return True for disjoint sets" (du1 && du2 && du3)+  assertBool "WordDSU returns False for duplicate union" dnoDup+  assertBool "WordDSU transitively unified 1 and 3" ds13+  assertBool "WordDSU distinct sets 1 and 4" ds14+  assertBool "WordDSU roots match for unified nodes" drEq++  -- 11.2 IntervalMap Non-Overlapping Extents & Coalescing+  let m0 = emptyIntervalMap+      Right m1 = insertExtent 10 20 ("chunkA" :: String) m0+      Right m2 = insertExtent 25 35 "chunkB" m1+      -- Coalesce immediately adjacent extent [20, 25) with chunkA+      Right m3 = insertExtent 20 25 "chunkA" m2+      -- Overlap rejection: [15, 22) overlaps with [10, 25)+      overlapRes = insertExtent 15 22 "chunkC" m3+  assertBool "IntervalMap coalesced [10,20) and [20,25) into single extent" (intervalMapSize m3 == 2)+  assertBool "IntervalMap rejects overlapping extent insertion" (case overlapRes of Left _ -> True; Right _ -> False)+  assertBool "IntervalMap lookupPoint stabbed 15" (lookupPoint 15 m3 == Just "chunkA")+  assertBool "IntervalMap lookupPoint stabbed 22" (lookupPoint 22 m3 == Just "chunkA")+  assertBool "IntervalMap lookupPoint stabbed 30" (lookupPoint 30 m3 == Just "chunkB")+  assertBool "IntervalMap lookupPoint misses gap at 8" (lookupPoint 8 m3 == Nothing)+  let overlaps = queryOverlap 15 28 m3+  assertBool "IntervalMap queryOverlap finds both extents" (length overlaps == 2)+  assertBool "IntervalMap findFreeGap before first extent" (findFreeGap 0 100 5 m3 == Just 0)+  assertBool "IntervalMap findFreeGap after all extents" (findFreeGap 26 100 5 m3 == Just 35)++  -- 11.3 BlockedBloom Filter (512-bit cache line block, 0% false negatives)+  let bloomKeys = [1000 .. 2000] :: [Word64]+      bloom = buildBlockedBloom bloomKeys+      bloomAllFound = all (\k -> memberBlockedBloom k bloom) bloomKeys+      bloomNegatives = [3000 .. 4000] :: [Word64]+      bloomFpCount = length (filter (\k -> memberBlockedBloom k bloom) bloomNegatives)+  assertBool "BlockedBloom 0% false negatives for 1000 enrolled keys" bloomAllFound+  assertBool "BlockedBloom false positive rate is low (< 10%)" (bloomFpCount < 100)++  -- 11.4 RibbonFilter Banded Linear System over GF(2) (0% false negatives)+  let ribbonKeys = [5000 .. 5300] :: [Word64]+      ribbon = buildRibbonFilter ribbonKeys+      ribbonAllFound = all (\k -> memberRibbonFilter k ribbon) ribbonKeys+      ribbonBpk = ribbonBitsPerKey ribbon+  assertBool "RibbonFilter 0% false negatives for enrolled keys" ribbonAllFound+  assertBool "RibbonFilter bits per key is compact (< 15.0 bpk)" (ribbonBpk < 15.0)++  -- 11.5 WalSlab Append, Checksum & Torn-Tail Detection+  wal <- newWalSlab+  appendWalRecord wal 1 (BSC.pack "payload-epoch-1")+  appendWalRecord wal 2 (BSC.pack "payload-epoch-2")+  appendWalRecord wal 3 (BSC.pack "payload-epoch-3")+  walBytes <- walSlabBytes wal+  let (recsClean, tornClean) = replayWalSlab walBytes+  assertBool "WalSlab clean replay has 0 torn tails" (not tornClean)+  assertBool "WalSlab recovered 3 records" (length recsClean == 3)+  assertBool "WalSlab verified epoch order" (map recEpoch recsClean == [1, 2, 3])++  -- Truncated tail (torn write simulation)+  let truncatedBytes = BS.take (BS.length walBytes - 5) walBytes+      (recsTrunc, tornTrunc) = replayWalSlab truncatedBytes+  assertBool "WalSlab detects torn tail on truncated bytes" tornTrunc+  assertBool "WalSlab recovers valid prefix preceding torn tail" (length recsTrunc == 2)++  -- Corrupted payload (CRC mismatch simulation)+  let corruptedBytes = BS.init walBytes <> BS.singleton 0xAA+      (recsCorrupt, tornCorrupt) = replayWalSlab corruptedBytes+  assertBool "WalSlab detects torn tail on CRC corruption" tornCorrupt+  assertBool "WalSlab recovers valid prefix preceding CRC corruption" (length recsCorrupt == 2)++  -- 12. Dynamic Structures: WorkDAG, DynamicRel, SackWindow, MsgAssoc+  -- 12.1 WorkDAG: Pearce-Kelly incremental dynamic topological sort+  let (dagRankOk, dagCycleOk, dagReadyNodes) = runST $ do+        dag <- newWorkDAG+        res1 <- addEdgePK dag 1 2+        res2 <- addEdgePK dag 2 3+        res3 <- addEdgePK dag 1 3+        r1 <- getNodeRank dag 1+        r2 <- getNodeRank dag 2+        r3 <- getNodeRank dag 3+        let ranksValid = res1 == Right () && res2 == Right () && res3 == Right () && r1 < r2 && r2 < r3+        -- Cycle insertion: 3 -> 1 should be detected+        resCycle <- addEdgePK dag 3 1+        let cycleDetected = case resCycle of+              Left _  -> True+              Right _ -> False+        -- Complete node 1: successors 2 and 3 should have inDegree updated+        ready1 <- completeNode dag 1+        pure (ranksValid, cycleDetected, ready1)++  assertBool "WorkDAG Pearce-Kelly fast-path maintained valid ranks ord[1] < ord[2] < ord[3]" dagRankOk+  assertBool "WorkDAG detected directed cycle on backward edge 3 -> 1" dagCycleOk+  assertBool "WorkDAG completeNode 1 returned newly ready nodes" (2 `elem` dagReadyNodes)++  -- 12.2 DynamicRel: 3-tier Semi-Naive & Leapfrog Triejoin WCOJ+  let rel0 = insertDelta 1 2 (insertDelta 2 3 (insertDelta 1 3 emptyDynamicRel))+      relStep1 = stepSemiNaive rel0+      triangles = triangleJoinWCOJ relStep1+      -- Equivalent naive nested loop join+      stableEdges = getStableEdges relStep1+      naiveTriangles =+        [ (x, y, z)+        | (x, y) <- stableEdges+        , (y', z) <- stableEdges+        , y == y'+        , (x', z') <- stableEdges+        , x == x' && z == z'+        ]+  assertBool "DynamicRel promoted delta edges to stable" (length stableEdges == 3)+  assertBool "DynamicRel Leapfrog WCOJ found triangle (1, 2, 3)" (triangles == [(1, 2, 3)])+  assertBool "DynamicRel Leapfrog WCOJ matches naive join equivalence" (triangles == naiveTriangles)++  -- 12.3 SackWindow: RFC 1982 wrap-around arithmetic and ctz SACK gap extraction+  let sw0 = initSackWindow 100+      (out1, sw1) = recordTsn 100 sw0+      (out3, sw3) = recordTsn 102 sw1+      (out4, sw4) = recordTsn 103 sw3+      (out6, sw6) = recordTsn 105 sw4+      gaps = extractSackGaps sw6+  assertBool "SackWindow accepted initial TSN 100" (out1 == TsnAcceptedNew && swCumTsn sw1 == 100)+  assertBool "SackWindow accepted out-of-order TSNs" (out3 == TsnAcceptedNew && out6 == TsnAcceptedNew)+  assertBool "SackWindow cumulative TSN remained at 100 pending gap fill" (swCumTsn sw6 == 100)+  assertBool "SackWindow extracted SACK gap-ack blocks" (not (null gaps))++  -- Fill gap at 101: cumulative TSN should advance across 102 and 103+  let (out2, swAdvance) = recordTsn 101 sw6+  assertBool "SackWindow cumulative TSN advanced to 103 on filling gap" (out2 == TsnAcceptedNew && swCumTsn swAdvance == 103)++  -- 12.4 MsgAssoc: Zero-HoL Blocking for Unordered Streams+  let ma0 = initMsgAssoc 1+      chunkOrd0 = MsgChunk 1 0 0 StreamOrdered (BSC.pack "ord-0")+      chunkOrd2 = MsgChunk 3 0 2 StreamOrdered (BSC.pack "ord-2")  -- Gap: SSN 1 missing!+      chunkUnord = MsgChunk 2 1 0 StreamUnordered (BSC.pack "unord-data")+      (_, ma1, d1) = receiveChunk chunkOrd0 ma0+      (_, ma2, d2) = receiveChunk chunkOrd2 ma1+      (_, ma3, d3) = receiveChunk chunkUnord ma2+  assertBool "MsgAssoc delivered in-order chunkOrd0 immediately" (d1 == [BSC.pack "ord-0"])+  assertBool "MsgAssoc buffered out-of-order chunkOrd2 without delivery" (null d2)+  assertBool "MsgAssoc delivered StreamUnordered chunk with zero HoL blocking" (d3 == [BSC.pack "unord-data"])++  -- Now deliver missing SSN 1: both SSN 1 and buffered SSN 2 must drain!+  let chunkOrd1 = MsgChunk 4 0 1 StreamOrdered (BSC.pack "ord-1")+      (_, _, d4) = receiveChunk chunkOrd1 ma3+  assertBool "MsgAssoc drained contiguous ordered chunks once gap was filled" (d4 == [BSC.pack "ord-1", BSC.pack "ord-2"])++  putStrLn "=== [pykinos-core-test] ALL 80 PROPERTIES AND UNIT CHECKS PASSED ==="+