packages feed

pykinos-core-0.1.1.0: src/Pykinos/Graph/WorkDAG.hs

{-# 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)