pykinos-core-0.1.1.0: src/Pykinos/Rel/DynamicRel.hs
{-# 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