packages feed

pykinos-penelope 0.1.0.2 → 0.1.1.0

raw patch · 6 files changed

+578/−61 lines, 6 filesdep ~pykinos-penelopePVP ok

version bump matches the API change (PVP)

Dependency ranges changed: pykinos-penelope

API changes (from Hackage documentation)

+ Pykinos.Penelope.ConditionalTrail: Checkpoint :: Epoch -> Int -> Checkpoint
+ Pykinos.Penelope.ConditionalTrail: Epoch :: Int -> Epoch
+ Pykinos.Penelope.ConditionalTrail: TrailEntry :: Int -> Maybe (SlotState v) -> TrailEntry v
+ Pykinos.Penelope.ConditionalTrail: [cpEpoch] :: Checkpoint -> Epoch
+ Pykinos.Penelope.ConditionalTrail: [cpTrailMark] :: Checkpoint -> Int
+ Pykinos.Penelope.ConditionalTrail: [teKey] :: TrailEntry v -> Int
+ Pykinos.Penelope.ConditionalTrail: [tePrevVal] :: TrailEntry v -> Maybe (SlotState v)
+ Pykinos.Penelope.ConditionalTrail: [unEpoch] :: Epoch -> Int
+ Pykinos.Penelope.ConditionalTrail: checkpointTrail :: ConditionalTrail s v -> ST s Checkpoint
+ Pykinos.Penelope.ConditionalTrail: data Checkpoint
+ Pykinos.Penelope.ConditionalTrail: data ConditionalTrail s v
+ Pykinos.Penelope.ConditionalTrail: data TrailEntry v
+ Pykinos.Penelope.ConditionalTrail: instance GHC.Internal.Classes.Eq Pykinos.Penelope.ConditionalTrail.Checkpoint
+ Pykinos.Penelope.ConditionalTrail: instance GHC.Internal.Classes.Eq Pykinos.Penelope.ConditionalTrail.Epoch
+ Pykinos.Penelope.ConditionalTrail: instance GHC.Internal.Classes.Eq v => GHC.Internal.Classes.Eq (Pykinos.Penelope.ConditionalTrail.SlotState v)
+ Pykinos.Penelope.ConditionalTrail: instance GHC.Internal.Classes.Eq v => GHC.Internal.Classes.Eq (Pykinos.Penelope.ConditionalTrail.TrailEntry v)
+ Pykinos.Penelope.ConditionalTrail: instance GHC.Internal.Classes.Ord Pykinos.Penelope.ConditionalTrail.Checkpoint
+ Pykinos.Penelope.ConditionalTrail: instance GHC.Internal.Classes.Ord Pykinos.Penelope.ConditionalTrail.Epoch
+ Pykinos.Penelope.ConditionalTrail: instance GHC.Internal.Show.Show Pykinos.Penelope.ConditionalTrail.Checkpoint
+ Pykinos.Penelope.ConditionalTrail: instance GHC.Internal.Show.Show Pykinos.Penelope.ConditionalTrail.Epoch
+ Pykinos.Penelope.ConditionalTrail: instance GHC.Internal.Show.Show v => GHC.Internal.Show.Show (Pykinos.Penelope.ConditionalTrail.SlotState v)
+ Pykinos.Penelope.ConditionalTrail: instance GHC.Internal.Show.Show v => GHC.Internal.Show.Show (Pykinos.Penelope.ConditionalTrail.TrailEntry v)
+ Pykinos.Penelope.ConditionalTrail: newConditionalTrail :: ST s (ConditionalTrail s v)
+ Pykinos.Penelope.ConditionalTrail: newtype Epoch
+ Pykinos.Penelope.ConditionalTrail: readSlot :: ConditionalTrail s v -> Int -> ST s (Maybe v)
+ Pykinos.Penelope.ConditionalTrail: rollbackTrail :: ConditionalTrail s v -> Checkpoint -> ST s ()
+ Pykinos.Penelope.ConditionalTrail: trailLogLength :: ConditionalTrail s v -> ST s Int
+ Pykinos.Penelope.ConditionalTrail: writeSlot :: ConditionalTrail s v -> Int -> v -> ST s ()
+ Pykinos.Penelope.EffectProfile: StaticEffectProfile :: Bool -> Bool -> Bool -> Bool -> Bool -> StaticEffectProfile
+ Pykinos.Penelope.EffectProfile: StrategyFrozenFast :: ReaderStrategy
+ Pykinos.Penelope.EffectProfile: StrategyPersistentART :: ReaderStrategy
+ Pykinos.Penelope.EffectProfile: StrategyShallowUndoTrail :: ReaderStrategy
+ Pykinos.Penelope.EffectProfile: [sepUsesCatchRollback] :: StaticEffectProfile -> Bool
+ Pykinos.Penelope.EffectProfile: [sepUsesListenCensor] :: StaticEffectProfile -> Bool
+ Pykinos.Penelope.EffectProfile: [sepUsesLocal] :: StaticEffectProfile -> Bool
+ Pykinos.Penelope.EffectProfile: [sepUsesMultiShot] :: StaticEffectProfile -> Bool
+ Pykinos.Penelope.EffectProfile: [sepUsesParallelRace] :: StaticEffectProfile -> Bool
+ Pykinos.Penelope.EffectProfile: data ReaderStrategy
+ Pykinos.Penelope.EffectProfile: data StaticEffectProfile
+ Pykinos.Penelope.EffectProfile: defaultProfile :: StaticEffectProfile
+ Pykinos.Penelope.EffectProfile: instance GHC.Internal.Classes.Eq Pykinos.Penelope.EffectProfile.ReaderStrategy
+ Pykinos.Penelope.EffectProfile: instance GHC.Internal.Classes.Eq Pykinos.Penelope.EffectProfile.StaticEffectProfile
+ Pykinos.Penelope.EffectProfile: instance GHC.Internal.Classes.Ord Pykinos.Penelope.EffectProfile.ReaderStrategy
+ Pykinos.Penelope.EffectProfile: instance GHC.Internal.Enum.Bounded Pykinos.Penelope.EffectProfile.ReaderStrategy
+ Pykinos.Penelope.EffectProfile: instance GHC.Internal.Enum.Enum Pykinos.Penelope.EffectProfile.ReaderStrategy
+ Pykinos.Penelope.EffectProfile: instance GHC.Internal.Show.Show Pykinos.Penelope.EffectProfile.ReaderStrategy
+ Pykinos.Penelope.EffectProfile: instance GHC.Internal.Show.Show Pykinos.Penelope.EffectProfile.StaticEffectProfile
+ Pykinos.Penelope.EffectProfile: selectReaderStrategy :: StaticEffectProfile -> ReaderStrategy
+ Pykinos.Penelope.ReaderTrail: data PersistentReaderEnv v
+ Pykinos.Penelope.ReaderTrail: data ReaderTrail s v
+ Pykinos.Penelope.ReaderTrail: emptyPersistentEnv :: PersistentReaderEnv v
+ Pykinos.Penelope.ReaderTrail: insertTrail :: ReaderTrail s v -> Int -> v -> ST s ()
+ Pykinos.Penelope.ReaderTrail: instance GHC.Internal.Classes.Eq v => GHC.Internal.Classes.Eq (Pykinos.Penelope.ReaderTrail.PersistentReaderEnv v)
+ Pykinos.Penelope.ReaderTrail: instance GHC.Internal.Show.Show v => GHC.Internal.Show.Show (Pykinos.Penelope.ReaderTrail.PersistentReaderEnv v)
+ Pykinos.Penelope.ReaderTrail: lookupPersistent :: PersistentReaderEnv v -> Int -> Maybe v
+ Pykinos.Penelope.ReaderTrail: lookupTrail :: ReaderTrail s v -> Int -> ST s (Maybe v)
+ Pykinos.Penelope.ReaderTrail: newReaderTrail :: ST s (ReaderTrail s v)
+ Pykinos.Penelope.ReaderTrail: withLocalBindings :: ReaderTrail s v -> [(Int, v)] -> ST s a -> ST s a
+ Pykinos.Penelope.ReaderTrail: withPersistentBindings :: [(Int, v)] -> PersistentReaderEnv v -> PersistentReaderEnv v
+ Pykinos.Penelope.WriterSlab: SlabMark :: Int -> SlabMark
+ Pykinos.Penelope.WriterSlab: [unSlabMark] :: SlabMark -> Int
+ Pykinos.Penelope.WriterSlab: censorSlice :: WriterSlab s a -> SlabMark -> (a -> a) -> ST s ()
+ Pykinos.Penelope.WriterSlab: data WriterSlab s a
+ Pykinos.Penelope.WriterSlab: freezeSlab :: WriterSlab s a -> ST s [a]
+ Pykinos.Penelope.WriterSlab: instance GHC.Internal.Classes.Eq Pykinos.Penelope.WriterSlab.SlabMark
+ Pykinos.Penelope.WriterSlab: instance GHC.Internal.Classes.Ord Pykinos.Penelope.WriterSlab.SlabMark
+ Pykinos.Penelope.WriterSlab: instance GHC.Internal.Show.Show Pykinos.Penelope.WriterSlab.SlabMark
+ Pykinos.Penelope.WriterSlab: listenSlice :: WriterSlab s a -> SlabMark -> ST s [a]
+ Pykinos.Penelope.WriterSlab: markSlab :: WriterSlab s a -> ST s SlabMark
+ Pykinos.Penelope.WriterSlab: newWriterSlab :: ST s (WriterSlab s a)
+ Pykinos.Penelope.WriterSlab: newtype SlabMark
+ Pykinos.Penelope.WriterSlab: slabChunkSize :: Int
+ Pykinos.Penelope.WriterSlab: tellManySlab :: Foldable t => WriterSlab s a -> t a -> ST s ()
+ Pykinos.Penelope.WriterSlab: tellSlab :: WriterSlab s a -> a -> ST s ()

Files

pykinos-penelope.cabal view
@@ -1,11 +1,12 @@ cabal-version: 3.0 name: pykinos-penelope-version: 0.1.0.2+version: 0.1.1.0 synopsis: Transient Epoch mutation and lockless MVCC handles for Pykinos description:   Penelope effect system integration with Pykinos unboxed data structures,-  providing transient epoch isolation (withTransientEpoch) and lockless-  categorical pushout merges (pushoutMergeMVCC) over divergent transaction branches.+  providing transient epoch isolation (withTransientEpoch), lockless+  categorical pushout merges (pushoutMergeMVCC), chunked WriterSlab,+  ReaderTrail, and WAM ConditionalTrail. license: EUPL-1.2 OR Apache-2.0 license-file: LICENSE author: Nadia Yvette Chambers@@ -17,7 +18,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@@ -28,18 +29,22 @@   exposed-modules:     Pykinos.Effect.Penelope     Pukinos.Effect.Penelope+    Pykinos.Penelope.ConditionalTrail+    Pykinos.Penelope.EffectProfile+    Pykinos.Penelope.ReaderTrail+    Pykinos.Penelope.WriterSlab   hs-source-dirs: src   default-language: GHC2024   ghc-options:     -Wall     -Wcompat     -Widentities-    -Wno-unused-imports+    -Wredundant-constraints   build-depends:     base >= 4.19 && < 5,-    pykinos-core >= 0.1.0.0 && < 0.2,+    containers >= 0.6 && < 0.9,     primitive >= 0.9 && < 0.10,-    containers >= 0.6 && < 0.9+    pykinos-core >= 0.1.0.0 && < 0.2  test-suite pykinos-penelope-test   type: exitcode-stdio-1.0@@ -49,6 +54,7 @@   ghc-options: -threaded -rtsopts -with-rtsopts=-N   build-depends:     base >= 4.19 && < 5,+    containers >= 0.6 && < 0.9,+    primitive >= 0.9 && < 0.10,     pykinos-core >= 0.1.0.0 && < 0.2,-    pykinos-penelope >= 0.1.0.0 && < 0.2,-    primitive >= 0.9 && < 0.10+    pykinos-penelope
+ src/Pykinos/Penelope/ConditionalTrail.hs view
@@ -0,0 +1,136 @@+{-# LANGUAGE BangPatterns #-}+{-# LANGUAGE DerivingStrategies #-}++-- | Module: Pykinos.Penelope.ConditionalTrail+-- Description: WAM-style epoch-guarded conditional undo trail+--+-- Implements Warren Abstract Machine (WAM) conditional trailing: modifications+-- are only recorded in the undo log when a slot was created or last modified in+-- an earlier epoch (@slotEpoch < currentChoiceEpoch@). Repeated mutations in the+-- same epoch require zero trailing overhead and roll back in O(mutations).+module Pykinos.Penelope.ConditionalTrail+  ( Epoch(..)+  , Checkpoint(..)+  , TrailEntry(..)+  , ConditionalTrail+  , newConditionalTrail+  , readSlot+  , writeSlot+  , checkpointTrail+  , rollbackTrail+  , trailLogLength+  ) where++import Control.Monad (forM_)+import Control.Monad.ST (ST)+import Data.IntMap.Strict (IntMap)+import qualified Data.IntMap.Strict as IntMap+import Data.STRef (STRef, newSTRef, readSTRef, writeSTRef)++-- | Monotonically increasing choice point epoch identifier.+newtype Epoch = Epoch { unEpoch :: Int }+  deriving stock (Eq, Ord, Show)++-- | O(1) restoration marker capturing epoch and undo-log watermark.+data Checkpoint = Checkpoint+  { cpEpoch     :: !Epoch+  , cpTrailMark :: !Int+  } deriving stock (Eq, Ord, Show)++-- | Value paired with its last-modified epoch.+data SlotState v = SlotState+  { slotVal   :: !v+  , slotEpoch :: !Epoch+  } deriving stock (Eq, Show)++-- | Undo log entry recording prior slot state for restoration.+data TrailEntry v = TrailEntry+  { teKey     :: !Int+  , tePrevVal :: !(Maybe (SlotState v))+  } deriving stock (Eq, Show)++data TrailState v = TrailState+  { tsSlots  :: !(IntMap (SlotState v))+  , tsEpoch  :: !Epoch+  , tsLogRev :: ![TrailEntry v]+  , tsLogLen :: !Int+  }++-- | Mutable conditional trail in @ST s@.+newtype ConditionalTrail s v = ConditionalTrail (STRef s (TrailState v))++-- | Allocates a fresh empty 'ConditionalTrail' at epoch 0.+newConditionalTrail :: ST s (ConditionalTrail s v)+newConditionalTrail = do+  ref <- newSTRef (TrailState IntMap.empty (Epoch 0) [] 0)+  pure (ConditionalTrail ref)++-- | Reads the current value of slot @k@.+readSlot :: ConditionalTrail s v -> Int -> ST s (Maybe v)+readSlot (ConditionalTrail ref) !k = do+  st <- readSTRef ref+  pure (slotVal <$> IntMap.lookup k (tsSlots st))++-- | Writes a value into slot @k@, applying WAM conditional trailing rules.+writeSlot :: ConditionalTrail s v -> Int -> v -> ST s ()+writeSlot (ConditionalTrail ref) !k !val = do+  st <- readSTRef ref+  let curEpoch = tsEpoch st+      existing = IntMap.lookup k (tsSlots st)+  case existing of+    Nothing -> do+      -- Fresh slot: record that it previously did not exist+      let entry = TrailEntry k Nothing+      writeSTRef ref st+        { tsSlots  = IntMap.insert k (SlotState val curEpoch) (tsSlots st)+        , tsLogRev = entry : tsLogRev st+        , tsLogLen = tsLogLen st + 1+        }+    Just oldSlot+      | slotEpoch oldSlot < curEpoch -> do+          -- Modified across epoch boundary: trail prior state+          let entry = TrailEntry k (Just oldSlot)+          writeSTRef ref st+            { tsSlots  = IntMap.insert k (SlotState val curEpoch) (tsSlots st)+            , tsLogRev = entry : tsLogRev st+            , tsLogLen = tsLogLen st + 1+            }+      | otherwise -> do+          -- Modified within the same epoch: NO trailing needed!+          writeSTRef ref st+            { tsSlots = IntMap.insert k (SlotState val curEpoch) (tsSlots st)+            }++-- | Creates a new choice point checkpoint, advancing the active epoch.+checkpointTrail :: ConditionalTrail s v -> ST s Checkpoint+checkpointTrail (ConditionalTrail ref) = do+  st <- readSTRef ref+  let curCp = Checkpoint (tsEpoch st) (tsLogLen st)+      nextEpoch = Epoch (unEpoch (tsEpoch st) + 1)+  writeSTRef ref st { tsEpoch = nextEpoch }+  pure curCp++-- | Rolls back the trail state to the specified checkpoint.+rollbackTrail :: ConditionalTrail s v -> Checkpoint -> ST s ()+rollbackTrail (ConditionalTrail ref) cp = do+  st <- readSTRef ref+  let targetLen = cpTrailMark cp+      toUndoCount = tsLogLen st - targetLen+  if toUndoCount <= 0+    then writeSTRef ref st { tsEpoch = cpEpoch cp }+    else do+      let (toRevert, remainingLog) = splitAt toUndoCount (tsLogRev st)+          restoredSlots = foldl revertSlot (tsSlots st) toRevert+      writeSTRef ref st+        { tsSlots  = restoredSlots+        , tsEpoch  = cpEpoch cp+        , tsLogRev = remainingLog+        , tsLogLen = targetLen+        }+  where+    revertSlot slots (TrailEntry k Nothing)            = IntMap.delete k slots+    revertSlot slots (TrailEntry k (Just prevSlot))     = IntMap.insert k prevSlot slots++-- | Returns the total number of entries currently in the undo log.+trailLogLength :: ConditionalTrail s v -> ST s Int+trailLogLength (ConditionalTrail ref) = tsLogLen <$> readSTRef ref
+ src/Pykinos/Penelope/EffectProfile.hs view
@@ -0,0 +1,56 @@+{-# LANGUAGE DerivingStrategies #-}++-- | Module: Pykinos.Penelope.EffectProfile+-- Description: Static effect usage profiles and dynamic reader carrier selection+--+-- Analyzes compile-time or pipeline-level effect requirements to choose the+-- optimal physical carrier strategy for reader/environment effects.+module Pykinos.Penelope.EffectProfile+  ( -- * Static Effect Profile+    StaticEffectProfile(..)+  , defaultProfile+    -- * Reader Strategy+  , ReaderStrategy(..)+  , selectReaderStrategy+  ) where++-- | Static summary of effect usage characteristics within an execution pipeline.+data StaticEffectProfile = StaticEffectProfile+  { sepUsesLocal         :: !Bool+    -- ^ Whether reader environment modification ('local') is invoked.+  , sepUsesMultiShot     :: !Bool+    -- ^ Whether continuations may be invoked multiple times (e.g. non-determinism).+  , sepUsesCatchRollback :: !Bool+    -- ^ Whether transactional rollback or exception recovery is needed.+  , sepUsesParallelRace  :: !Bool+    -- ^ Whether concurrent branches race over the environment.+  , sepUsesListenCensor  :: !Bool+    -- ^ Whether writer introspection ('listen' / 'censor') is active.+  } deriving stock (Eq, Show)++-- | Conservative default effect profile assuming only single-shot linear execution.+defaultProfile :: StaticEffectProfile+defaultProfile = StaticEffectProfile+  { sepUsesLocal         = False+  , sepUsesMultiShot     = False+  , sepUsesCatchRollback = False+  , sepUsesParallelRace  = False+  , sepUsesListenCensor  = False+  }++-- | Physical representation strategy for reader environment state.+data ReaderStrategy+  = StrategyFrozenFast+    -- ^ Pure immutable single-reference pointer (fastest when no 'local' is used).+  | StrategyShallowUndoTrail+    -- ^ In-place mutable environment with an undo log for scoped lexical restoration.+  | StrategyPersistentART+    -- ^ Persistent radix-tree environment supporting branching, backtracking, and races.+  deriving stock (Eq, Ord, Show, Enum, Bounded)++-- | Selects the optimal reader strategy based on the static effect profile.+selectReaderStrategy :: StaticEffectProfile -> ReaderStrategy+selectReaderStrategy prof+  | not (sepUsesLocal prof) = StrategyFrozenFast+  | sepUsesMultiShot prof || sepUsesParallelRace prof = StrategyPersistentART+  | otherwise = StrategyShallowUndoTrail
+ src/Pykinos/Penelope/ReaderTrail.hs view
@@ -0,0 +1,90 @@+{-# LANGUAGE BangPatterns #-}+{-# LANGUAGE DerivingStrategies #-}++-- | Module: Pykinos.Penelope.ReaderTrail+-- Description: Shallow-binding undo-trailed environment and persistent ART fallback+--+-- Implements high-performance scoped lexical environment modifications for+-- @Reader@ effects. Under 'StrategyShallowUndoTrail', modifications mutate an+-- in-place environment while pushing previous bindings onto a restoration trail.+-- Under 'StrategyPersistentART', a purely functional radix map is maintained.+module Pykinos.Penelope.ReaderTrail+  ( -- * Shallow Undo Trail+    ReaderTrail+  , newReaderTrail+  , lookupTrail+  , insertTrail+  , withLocalBindings+    -- * Persistent Radix Fallback+  , PersistentReaderEnv+  , emptyPersistentEnv+  , lookupPersistent+  , withPersistentBindings+  ) where++import Control.Monad.ST (ST)+import Data.IntMap.Strict (IntMap)+import qualified Data.IntMap.Strict as IntMap+import Data.STRef (STRef, newSTRef, readSTRef, writeSTRef)++-- | In-place mutable environment with an undo trail stack in @ST s@.+newtype ReaderTrail s v = ReaderTrail (STRef s (IntMap v))++-- | Allocates a fresh empty 'ReaderTrail'.+newReaderTrail :: ST s (ReaderTrail s v)+newReaderTrail = ReaderTrail <$> newSTRef IntMap.empty++-- | Looks up a key in the active shallow-binding environment.+lookupTrail :: ReaderTrail s v -> Int -> ST s (Maybe v)+lookupTrail (ReaderTrail ref) !k = IntMap.lookup k <$> readSTRef ref++-- | Inserts a binding directly without trailing (outer initialization).+insertTrail :: ReaderTrail s v -> Int -> v -> ST s ()+insertTrail (ReaderTrail ref) !k !v = do+  env <- readSTRef ref+  writeSTRef ref (IntMap.insert k v env)++-- | Executes an action within a lexically scoped local overlay.+--+-- Saves shadowed bindings before running @action@ and unconditionally restores+-- them on exit.+withLocalBindings :: ReaderTrail s v -> [(Int, v)] -> ST s a -> ST s a+withLocalBindings (ReaderTrail ref) bindings action = do+  env0 <- readSTRef ref+  -- Record previous values for all modified keys+  let undoList = [(k, IntMap.lookup k env0) | (k, _) <- bindings]+  -- Apply new bindings+  let env1 = foldl (\acc (k, v) -> IntMap.insert k v acc) env0 bindings+  writeSTRef ref env1++  -- Execute action+  res <- action++  -- Restore previous state unconditionally+  let restore acc (k, Just oldV) = IntMap.insert k oldV acc+      restore acc (k, Nothing)   = IntMap.delete k acc+      envRestored = foldl restore env1 undoList+  writeSTRef ref envRestored++  pure res++-- ----------------------------------------------------------------------------+-- Persistent Radix Fallback (StrategyPersistentART)+-- ----------------------------------------------------------------------------++-- | Persistent environment wrapper for multi-shot and concurrent reader pipelines.+newtype PersistentReaderEnv v = PersistentReaderEnv (IntMap v)+  deriving stock (Eq, Show)++-- | Empty persistent reader environment.+emptyPersistentEnv :: PersistentReaderEnv v+emptyPersistentEnv = PersistentReaderEnv IntMap.empty++-- | Looks up a key in a persistent reader environment.+lookupPersistent :: PersistentReaderEnv v -> Int -> Maybe v+lookupPersistent (PersistentReaderEnv m) !k = IntMap.lookup k m++-- | Purely functional scoped local binding overlay.+withPersistentBindings :: [(Int, v)] -> PersistentReaderEnv v -> PersistentReaderEnv v+withPersistentBindings bindings (PersistentReaderEnv m) =+  PersistentReaderEnv (foldl (\acc (k, v) -> IntMap.insert k v acc) m bindings)
+ src/Pykinos/Penelope/WriterSlab.hs view
@@ -0,0 +1,146 @@+{-# LANGUAGE BangPatterns #-}+{-# LANGUAGE DerivingStrategies #-}+{-# LANGUAGE TupleSections #-}++-- | Module: Pykinos.Penelope.WriterSlab+-- Description: Sub-4KB chunked append slab with O(1) watermark Listen and in-place Censor+--+-- Replaces pointer-chasing @[a]@ / @DList@ Writer accumulators with contiguous+-- 64-slot 'SmallMutableArray' chunks (512 bytes per chunk, strictly nursery-safe+-- under GHC's 3277-byte @BF_LARGE@ threshold).+module Pykinos.Penelope.WriterSlab+  ( slabChunkSize+  , SlabMark(..)+  , WriterSlab+  , newWriterSlab+  , tellSlab+  , tellManySlab+  , markSlab+  , listenSlice+  , censorSlice+  , freezeSlab+  ) where++import Control.Monad (forM_)+import Control.Monad.ST (ST)+import Data.Primitive.SmallArray+  ( SmallMutableArray+  , newSmallArray+  , readSmallArray+  , writeSmallArray+  )+import Data.STRef (STRef, newSTRef, readSTRef, writeSTRef)++-- | Fixed chunk capacity (64 words = 512 bytes; strictly Sub4KB nursery-safe).+slabChunkSize :: Int+slabChunkSize = 64++-- | O(1) cursor watermark into a 'WriterSlab'.+newtype SlabMark = SlabMark { unSlabMark :: Int }+  deriving stock (Eq, Ord, Show)++-- | Internal linked list of fixed-capacity chunks (stored newest-first for O(1) append).+data SlabState s a = SlabState+  { ssTotal     :: !Int+  , ssChunkUsed :: !Int+  , ssCurrent   :: !(SmallMutableArray s a)+  , ssFullRev   :: ![SmallMutableArray s a]+  }++-- | Transient chunked append slab for high-throughput @Writer@ effects in @ST s@.+newtype WriterSlab s a = WriterSlab (STRef s (SlabState s a))++-- | Allocates a fresh empty 'WriterSlab'.+newWriterSlab :: ST s (WriterSlab s a)+newWriterSlab = do+  arr <- newSmallArray slabChunkSize (error "WriterSlab: uninitialized slot")+  ref <- newSTRef (SlabState 0 0 arr [])+  pure (WriterSlab ref)++-- | Appends a single element in amortized O(1) time.+tellSlab :: WriterSlab s a -> a -> ST s ()+tellSlab (WriterSlab ref) !x = do+  st <- readSTRef ref+  if ssChunkUsed st < slabChunkSize+    then do+      writeSmallArray (ssCurrent st) (ssChunkUsed st) x+      writeSTRef ref st+        { ssTotal     = ssTotal st + 1+        , ssChunkUsed = ssChunkUsed st + 1+        }+    else do+      fresh <- newSmallArray slabChunkSize (error "WriterSlab: uninitialized slot")+      writeSmallArray fresh 0 x+      writeSTRef ref SlabState+        { ssTotal     = ssTotal st + 1+        , ssChunkUsed = 1+        , ssCurrent   = fresh+        , ssFullRev   = ssCurrent st : ssFullRev st+        }++-- | Appends a foldable sequence of elements.+tellManySlab :: Foldable t => WriterSlab s a -> t a -> ST s ()+tellManySlab slab = mapM_ (tellSlab slab)++-- | Captures the current append position in O(1) for 'listenSlice' or 'censorSlice'.+markSlab :: WriterSlab s a -> ST s SlabMark+markSlab (WriterSlab ref) = SlabMark . ssTotal <$> readSTRef ref++-- | Materializes all chunks in chronological order with their active lengths.+orderedChunks :: SlabState s a -> [(SmallMutableArray s a, Int)]+orderedChunks st =+  map (, slabChunkSize) (reverse (ssFullRev st))+    ++ [(ssCurrent st, ssChunkUsed st)]++-- | Extracts all elements appended since watermark @startMark@ without allocating+-- a separate nested Writer buffer.+listenSlice :: WriterSlab s a -> SlabMark -> ST s [a]+listenSlice (WriterSlab ref) (SlabMark startIdx) = do+  st <- readSTRef ref+  let total = ssTotal st+      clampedStart = max 0 (min startIdx total)+  readRange (orderedChunks st) 0 clampedStart total++readRange :: [(SmallMutableArray s a, Int)] -> Int -> Int -> Int -> ST s [a]+readRange [] _ _ _ = pure []+readRange ((arr, len) : rest) !base !lo !hi+  | base >= hi = pure []+  | base + len <= lo = readRange rest (base + len) lo hi+  | otherwise = do+      let localLo = max 0 (lo - base)+          localHi = min len (hi - base)+      xs <- go localLo localHi+      ys <- readRange rest (base + len) lo hi+      pure (xs ++ ys)+  where+    go !i !end+      | i >= end = pure []+      | otherwise = do+          v <- readSmallArray arr i+          vs <- go (i + 1) end+          pure (v : vs)++-- | Transforms elements appended since watermark @startMark@ in place (O(slice length)).+censorSlice :: WriterSlab s a -> SlabMark -> (a -> a) -> ST s ()+censorSlice (WriterSlab ref) (SlabMark startIdx) f = do+  st <- readSTRef ref+  let total = ssTotal st+      clampedStart = max 0 (min startIdx total)+  goChunks (orderedChunks st) 0 clampedStart total+  where+    goChunks [] _ _ _ = pure ()+    goChunks ((arr, len) : rest) !base !lo !hi+      | base >= hi = pure ()+      | base + len <= lo = goChunks rest (base + len) lo hi+      | otherwise = do+          let localLo = max 0 (lo - base)+              localHi = min len (hi - base)+          forM_ [localLo .. localHi - 1] $ \i -> do+            v <- readSmallArray arr i+            let !v' = f v+            writeSmallArray arr i v'+          goChunks rest (base + len) lo hi++-- | Freezes the full accumulated slab contents in chronological order.+freezeSlab :: WriterSlab s a -> ST s [a]+freezeSlab slab = listenSlice slab (SlabMark 0)
test/Spec.hs view
@@ -1,68 +1,151 @@-{-# LANGUAGE BangPatterns #-} module Main (main) where +import Control.Monad.ST (runST) import System.Exit (exitFailure)-import Pykinos.Tree.BPlus-import Pykinos.Tree.FAST-import Pykinos.Effect.Penelope+import Pykinos.Penelope.ConditionalTrail+  ( checkpointTrail+  , newConditionalTrail+  , readSlot+  , rollbackTrail+  , trailLogLength+  , writeSlot+  )+import Pykinos.Penelope.EffectProfile+  ( ReaderStrategy (..)+  , StaticEffectProfile (..)+  , defaultProfile+  , selectReaderStrategy+  )+import Pykinos.Penelope.ReaderTrail+  ( emptyPersistentEnv+  , insertTrail+  , lookupPersistent+  , lookupTrail+  , newReaderTrail+  , withLocalBindings+  , withPersistentBindings+  )+import Pykinos.Penelope.WriterSlab+  ( censorSlice+  , freezeSlab+  , listenSlice+  , markSlab+  , newWriterSlab+  , tellManySlab+  , tellSlab+  ) -assertBool :: String -> Bool -> IO ()-assertBool name cond =-  if cond-    then putStrLn $ "  [PASS] " ++ name-    else do-      putStrLn $ "  [FAIL] " ++ name-      exitFailure+assert :: String -> Bool -> IO ()+assert desc True  = putStrLn ("  [PASS] " ++ desc)+assert desc False = do+  putStrLn ("  [FAIL] " ++ desc)+  exitFailure  main :: IO () main = do-  putStrLn "=== [pykinos-penelope-test] Running Transient Epoch & MVCC Pushout Suite ==="+  putStrLn "=== pykinos-penelope Test Suite ===" -  -- 1. Transient Epoch batch mutation-  let baseTree = insertBPlus (1 :: Int) ("init1" :: String) emptyBPlus-      (ep1, tree1) = withTransientEpoch 0 baseTree $ \ep ins acc ->-        ins 2 "val2" (ins 3 "val3" acc)+  putStrLn "--- Section 1: WriterSlab Chunk Boundaries & Listen/Censor ---"+  testWriterSlab -  assertBool "epoch advanced to 1" (ep1 == 1)-  assertBool "tree1 contains 1" (lookupBPlus 1 tree1 == Just "init1")-  assertBool "tree1 contains 2" (lookupBPlus 2 tree1 == Just "val2")-  assertBool "tree1 contains 3" (lookupBPlus 3 tree1 == Just "val3")+  putStrLn "--- Section 2: EffectProfile Strategy Selection ---"+  testEffectProfile -  -- 2. Lockless MVCC Snapshot with FAST accelerator-  let snap1 = mvccSnapshot ep1 True tree1-  assertBool "snap1 epoch is 1" (msEpoch snap1 == 1)-  assertBool "snap1 has FAST accelerator" (case msFastAcc snap1 of Just _ -> True; Nothing -> False)-  let Just fAcc = msFastAcc snap1-  assertBool "FAST accelerator lookup 2" (lookupFAST 2 fAcc == Just "val2")+  putStrLn "--- Section 3: ReaderTrail Scoped Lexical Shadowing ---"+  testReaderTrail -  -- 3. Commutative Disjoint Pushout Merge-  -- Worker A inserts (4, "val4"), Worker B inserts (5, "val5")-  let treeA = insertBPlus 4 "val4" tree1-      treeB = insertBPlus 5 "val5" tree1-      resMerge = commitEpochPushout snap1 treeA treeB+  putStrLn "--- Section 4: ConditionalTrail WAM Epoch Guarding ---"+  testConditionalTrail -  assertBool "disjoint merge succeeds" (case resMerge of Right _ -> True; Left _ -> False)-  let Right mergedSnap = resMerge-  assertBool "mergedSnap epoch is 2" (msEpoch mergedSnap == 2)-  assertBool "merged contains 1" (lookupBPlus 1 (msTree mergedSnap) == Just "init1")-  assertBool "merged contains 4" (lookupBPlus 4 (msTree mergedSnap) == Just "val4")-  assertBool "merged contains 5" (lookupBPlus 5 (msTree mergedSnap) == Just "val5")+  putStrLn "=== All pykinos-penelope tests passed! ===" -  -- 4. Overlapping Equal Value Pushout Merge-  let treeA2 = insertBPlus 10 "same" tree1-      treeB2 = insertBPlus 10 "same" tree1-      resMerge2 = commitEpochPushout snap1 treeA2 treeB2-  assertBool "equal overlap merge succeeds" (case resMerge2 of Right _ -> True; Left _ -> False)+testWriterSlab :: IO ()+testWriterSlab = do+  -- Test 1: Tell > 200 items across 64-slot chunks+  let (fullList, sliceList, censoredFull) = runST $ do+        slab <- newWriterSlab+        tellManySlab slab [1 .. 50 :: Int]+        m1 <- markSlab slab+        tellManySlab slab [51 .. 180 :: Int]+        s1 <- listenSlice slab m1+        censorSlice slab m1 (* 2)+        tellManySlab slab [181 .. 250 :: Int]+        f1 <- freezeSlab slab+        pure ([1 .. 250 :: Int], s1, f1) -  -- 5. Conflicting Divergent Pushout Merge (H^1 Obstruction)-  let treeConfA = insertBPlus 10 "branchA" tree1-      treeConfB = insertBPlus 10 "branchB" tree1-      resConf = commitEpochPushout snap1 treeConfA treeConfB+  assert "listenSlice extracts exact middle slice [51..180]" $+    sliceList == [51 .. 180] -  assertBool "conflicting pushout returns Left" (case resConf of Left _ -> True; Right _ -> False)-  let Left [conflict] = resConf-  assertBool "conflict key is 10" (pcKey conflict == 10)-  assertBool "conflict left is branchA" (pcLeftVal conflict == "branchA")-  assertBool "conflict right is branchB" (pcRightVal conflict == "branchB")+  let expectedCensored = [1 .. 50] ++ map (* 2) [51 .. 180] ++ [181 .. 250]+  assert "censorSlice mutates only marked slice in-place across chunk boundaries" $+    censoredFull == expectedCensored -  putStrLn "=== [pykinos-penelope-test] ALL 14 PROPERTIES AND UNIT CHECKS PASSED ==="+testEffectProfile :: IO ()+testEffectProfile = do+  assert "defaultProfile selects StrategyFrozenFast" $+    selectReaderStrategy defaultProfile == StrategyFrozenFast++  let localProf = defaultProfile { sepUsesLocal = True }+  assert "Local-only profile selects StrategyShallowUndoTrail" $+    selectReaderStrategy localProf == StrategyShallowUndoTrail++  let multiShotProf = defaultProfile { sepUsesLocal = True, sepUsesMultiShot = True }+  assert "MultiShot profile selects StrategyPersistentART" $+    selectReaderStrategy multiShotProf == StrategyPersistentART++testReaderTrail :: IO ()+testReaderTrail = do+  let (outerVal, innerVal, restoredVal) = runST $ do+        trail <- newReaderTrail+        insertTrail trail 1 ("global" :: String)+        out0 <- lookupTrail trail 1+        (inn0, rest0) <- withLocalBindings trail [(1, "local"), (2, "temp")] $ do+          i <- lookupTrail trail 1+          pure (i, ())+        r <- lookupTrail trail 1+        t <- lookupTrail trail 2+        pure (out0, inn0, (r, t))++  assert "Initial lookup finds global value" $+    outerVal == Just "global"+  assert "withLocalBindings shadows key with local value" $+    innerVal == Just "local"+  assert "Scope exit restores outer binding and removes ephemeral key" $+    restoredVal == (Just "global", Nothing)++  -- Persistent env test+  let env0 = emptyPersistentEnv+      env1 = withPersistentBindings [(1, "val1" :: String)] env0+      env2 = withPersistentBindings [(1, "val2"), (2, "val3")] env1+  assert "Persistent env lookup reflects latest bindings" $+    lookupPersistent env2 1 == Just "val2"+      && lookupPersistent env1 1 == Just "val1"+      && lookupPersistent env2 2 == Just "val3"++testConditionalTrail :: IO ()+testConditionalTrail = do+  let (logLen1, logLen2, valAtCp, valAfterRollback) = runST $ do+        trail <- newConditionalTrail+        writeSlot trail 10 (100 :: Int)+        cp1 <- checkpointTrail trail+        -- Write slot 10 once in epoch 1 -> logs 1 entry+        writeSlot trail 10 200+        l1 <- trailLogLength trail+        -- Repeated write slot 10 in same epoch 1 -> NO additional log entry!+        writeSlot trail 10 300+        writeSlot trail 10 400+        l2 <- trailLogLength trail+        vBefore <- readSlot trail 10+        -- Rollback to cp1+        rollbackTrail trail cp1+        vAfter <- readSlot trail 10+        pure (l1, l2, vBefore, vAfter)++  assert "Initial mutation in epoch 1 trails prior state (len 2)" $+    logLen1 == 2 -- 1 for initial slot 10, 1 for epoch 1 mutation+  assert "Repeated mutations within epoch 1 do NOT add to trail log" $+    logLen2 == logLen1+  assert "Value before rollback is 400" $+    valAtCp == Just 400+  assert "Rollback restores slot 10 back to 100" $+    valAfterRollback == Just 100