packages feed

canontra-0.4.0.0: src/Canontra/Repository/Parallel.hs

{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE StrictData #-}

{- |
Module      : Canontra.Repository.Parallel
Description : Mutable ring-buffer Chase-Lev work-stealing parallel repository processor.

Implements a capability-aware work-stealing scheduler using mutable power-of-2
ring-buffer deques ('MV.IOVector') and a zero-contention pre-allocated result vector:
- O(1) pushBottom / popBottom / stealTop / stealBatchTop with zero whole-vector copies.
- O(1) worker deque lookup via boxed 'V.Vector'.
- Zero-contention parallel writes directly into disjoint slots of 'MV.IOVector b',
  preserving exact input stream order with zero final sort overhead.
-}
module Canontra.Repository.Parallel
  ( -- * Chase-Lev Deque & Work-Stealing Engine
    ChaseLevDeque (..)
  , DequeState (..)
  , newChaseLevDeque
  , pushBottom
  , popBottom
  , stealTop
  , stealBatchTop
  , dequeSize
  , isDequeEmpty

    -- * Work-Stealing Parallel Processing
  , parProcessWorkStealing
  , parWorkStealing
  , parMapChunks
  , parFingerprintFiles
  , parFingerprintWorkStealing
  , parFingerprintWithPrograms
  ) where

import Control.Concurrent (yield)
import Control.Concurrent.Async (forConcurrently)
import Control.Concurrent.MVar (MVar, modifyMVar, modifyMVar_, newMVar, readMVar)
import Control.Monad (forM_)
import Data.Bits ((.&.))
import qualified Data.ByteString as BS
import qualified Data.Text.Encoding as TE
import qualified Data.Vector as V
import qualified Data.Vector.Mutable as MV
import GHC.Conc (getNumCapabilities)
import System.FilePath ((</>))

import Canontra.Fingerprint.Bundle (computeBundle, computeBundleAndProgram)
import Canontra.IR.Program (Program)
import Canontra.Types (FileEntry (..), ParseError)

-- ============================================================================
-- Chase-Lev Ring-Buffer Work-Stealing Deque
-- ============================================================================

-- | Internal state of a mutable power-of-2 ring-buffer Chase-Lev deque.
data DequeState a = DequeState
  { dsTop    :: !Int
  , dsBottom :: !Int
  , dsBuffer :: !(MV.IOVector (Maybe a))
  }

instance Show (DequeState a) where
  show (DequeState t b buf) =
    "DequeState {dsTop = " ++ show t ++ ", dsBottom = " ++ show b ++ ", dsCapacity = " ++ show (MV.length buf) ++ "}"

-- | A Chase-Lev work-stealing deque bound to a worker capability.
data ChaseLevDeque a = ChaseLevDeque
  { cldId    :: !Int
  , cldState :: !(MVar (DequeState a))
  }

-- | Allocate a new Chase-Lev deque with default initial circular buffer capacity (256 slots).
newChaseLevDeque :: Int -> IO (ChaseLevDeque a)
newChaseLevDeque workerId = do
  buf <- MV.replicate 256 Nothing
  ref <- newMVar (DequeState 0 0 buf)
  pure $ ChaseLevDeque workerId ref

-- | Push a task to the bottom of the deque in amortized O(1) time (owner thread).
pushBottom :: ChaseLevDeque a -> a -> IO ()
pushBottom (ChaseLevDeque _ mvar) item =
  modifyMVar_ mvar $ \s@DequeState{..} -> do
    let !cap = MV.length dsBuffer
        !size = dsBottom - dsTop
        !mask = cap - 1
    if size >= cap
      then do
        let !newCap = cap * 2
        newBuf <- MV.replicate newCap Nothing
        forM_ [0 .. size - 1] $ \k -> do
          val <- MV.unsafeRead dsBuffer ((dsTop + k) .&. mask)
          MV.unsafeWrite newBuf k val
        MV.unsafeWrite newBuf size (Just item)
        pure (DequeState 0 (size + 1) newBuf)
      else do
        MV.unsafeWrite dsBuffer (dsBottom .&. mask) (Just item)
        pure s { dsBottom = dsBottom + 1 }

-- | Pop a task from the bottom of the deque in LIFO O(1) time (owner thread).
popBottom :: ChaseLevDeque a -> IO (Maybe a)
popBottom (ChaseLevDeque _ mvar) =
  modifyMVar mvar $ \s@DequeState{..} ->
    if dsBottom <= dsTop
      then pure (s { dsBottom = dsTop }, Nothing)
      else do
        let !b = dsBottom - 1
            !slot = b .&. (MV.length dsBuffer - 1)
        mItem <- MV.unsafeRead dsBuffer slot
        MV.unsafeWrite dsBuffer slot Nothing
        pure (s { dsBottom = b }, mItem)

-- | Steal a single task from the top of the deque in FIFO O(1) time (thieves).
stealTop :: ChaseLevDeque a -> IO (Maybe a)
stealTop (ChaseLevDeque _ mvar) =
  modifyMVar mvar $ \s@DequeState{..} ->
    if dsTop >= dsBottom
      then pure (s, Nothing)
      else do
        let !slot = dsTop .&. (MV.length dsBuffer - 1)
        mItem <- MV.unsafeRead dsBuffer slot
        MV.unsafeWrite dsBuffer slot Nothing
        pure (s { dsTop = dsTop + 1 }, mItem)

-- | Steal a batch of up to @maxBatch@ tasks from the top of the deque in a single atomic step.
stealBatchTop :: ChaseLevDeque a -> Int -> IO [a]
stealBatchTop (ChaseLevDeque _ mvar) maxBatch =
  modifyMVar mvar $ \s@DequeState{..} -> do
    let !available = dsBottom - dsTop
    if available <= 0 || maxBatch <= 0
      then pure (s, [])
      else do
        let !batchSize = min maxBatch (max 1 (available `quot` 2))
            !mask = MV.length dsBuffer - 1
        stolen <- collectSlice dsBuffer mask dsTop batchSize
        pure (s { dsTop = dsTop + batchSize }, stolen)
  where
    collectSlice !buf !mask !start !cnt = go 0 []
      where
        go !k acc
          | k >= cnt = pure (reverse acc)
          | otherwise = do
              let !slot = (start + k) .&. mask
              mVal <- MV.unsafeRead buf slot
              MV.unsafeWrite buf slot Nothing
              case mVal of
                Just v  -> go (k + 1) (v : acc)
                Nothing -> go (k + 1) acc

-- | Current number of active tasks in the deque.
dequeSize :: ChaseLevDeque a -> IO Int
dequeSize (ChaseLevDeque _ mvar) = do
  s <- readMVar mvar
  pure $ max 0 (dsBottom s - dsTop s)

-- | Returns 'True' if the deque currently contains zero tasks.
isDequeEmpty :: ChaseLevDeque a -> IO Bool
isDequeEmpty (ChaseLevDeque _ mvar) = do
  s <- readMVar mvar
  pure (dsBottom s <= dsTop s)

-- ============================================================================
-- Work-Stealing Parallel Execution Engine
-- ============================================================================

-- | High-throughput capability-aware work-stealing parallel processor.
-- Partitions work across private worker deques, dynamically balances execution via
-- batch work-stealing, and writes results directly into disjoint slots of a pre-allocated
-- mutable vector for zero-contention deterministic output ordering.
parProcessWorkStealing :: (a -> IO b) -> [a] -> IO [b]
parProcessWorkStealing _ [] = pure []
parProcessWorkStealing f items = do
  numCaps <- getNumCapabilities
  let !numWorkers = max 1 numCaps
      !totalItems = length items
  deques <- V.generateM numWorkers newChaseLevDeque
  resultsVec <- MV.new totalItems

  -- Distribute initial work across capability deques in O(N)
  forM_ (zip ([0..] :: [Int]) items) $ \(idx, item) -> do
    let !target = idx `rem` numWorkers
    pushBottom (deques V.! target) (idx, item)

  let workerLoop !wId = do
        let !localDeque = deques V.! wId
            !otherDeques = [deques V.! j | j <- [0 .. numWorkers - 1], j /= wId]
        step localDeque otherDeques

      step !localDeque otherDeques = do
        mTask <- popBottom localDeque
        case mTask of
          Just (idx, item) -> do
            !res <- f item
            MV.unsafeWrite resultsVec idx res
            step localDeque otherDeques
          Nothing -> do
            stolen <- trySteal otherDeques
            case stolen of
              (firstTask : restTasks) -> do
                forM_ restTasks (pushBottom localDeque)
                let (idx, item) = firstTask
                !res <- f item
                MV.unsafeWrite resultsVec idx res
                step localDeque otherDeques
              [] -> do
                allEmpty <- allDequesEmpty 0
                if allEmpty
                  then pure ()
                  else do
                    yield
                    step localDeque otherDeques

      trySteal [] = pure []
      trySteal (d:ds) = do
        batch <- stealBatchTop d 16
        if null batch
          then trySteal ds
          else pure batch

      allDequesEmpty !i
        | i >= numWorkers = pure True
        | otherwise = do
            empty <- isDequeEmpty (deques V.! i)
            if not empty then pure False else allDequesEmpty (i + 1)

  _ <- forConcurrently [0 .. numWorkers - 1] workerLoop
  frozen <- V.unsafeFreeze resultsVec
  pure (V.toList frozen)

-- | Alias for 'parProcessWorkStealing'.
parWorkStealing :: (a -> IO b) -> [a] -> IO [b]
parWorkStealing = parProcessWorkStealing

-- | Distribute items across lightweight threads using dynamic Chase-Lev work-stealing.
parMapChunks :: (a -> IO b) -> [a] -> IO [b]
parMapChunks = parProcessWorkStealing

-- | Dynamic work-stealing file fingerprinting across all CPU capabilities.
parFingerprintWorkStealing :: FilePath -> [FilePath] -> IO [Either ParseError FileEntry]
parFingerprintWorkStealing rootDir relPaths =
  parProcessWorkStealing processFile relPaths
  where
    processFile relPath = do
      let fullPath = rootDir </> relPath
      rawBytes <- BS.readFile fullPath
      let textContent = TE.decodeUtf8Lenient rawBytes
      case computeBundle relPath rawBytes textContent of
        Left err     -> pure (Left err)
        Right bundle -> pure (Right (FileEntry relPath bundle))

-- | Compute fingerprints for multiple files in parallel using dynamic work-stealing.
parFingerprintFiles :: FilePath -> [FilePath] -> IO [Either ParseError FileEntry]
parFingerprintFiles = parFingerprintWorkStealing

-- | Dynamic work-stealing file fingerprinting returning both FileEntry and parsed Program.
parFingerprintWithPrograms :: FilePath -> [FilePath] -> IO [Either ParseError (FileEntry, Program)]
parFingerprintWithPrograms rootDir relPaths =
  parProcessWorkStealing processFile relPaths
  where
    processFile relPath = do
      let fullPath = rootDir </> relPath
      rawBytes <- BS.readFile fullPath
      let textContent = TE.decodeUtf8Lenient rawBytes
      case computeBundleAndProgram relPath rawBytes textContent of
        Left err          -> pure (Left err)
        Right (bundle, p) -> pure (Right (FileEntry relPath bundle, p))