service

package
v0.0.0-...-18e9b2d Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 22, 2026 License: GPL-2.0 Imports: 24 Imported by: 0

Documentation

Overview

Package service provides core business logic for graph-engine.

Package service provides core services for the graph-engine.

Package service provides core services for the graph-engine.

Package service provides core services for the graph-engine.

Package service provides core services for the graph-engine.

Index

Constants

View Source
const (
	// DefaultMaxCorridorEdges is the maximum number of edges allowed for mincut
	DefaultMaxCorridorEdges = 10000
	// DefaultMinCutTimeout is the default timeout for mincut computation
	DefaultMinCutTimeout = 30 * time.Second
)

MinCut configuration constants

Variables

This section is empty.

Functions

func ComputeSingleSourceDistances

func ComputeSingleSourceDistances(
	version *GraphVersion,
	view *View,
	sourceID uint64,
	weighted bool,
) (map[uint64]float64, error)

ComputeSingleSourceDistances computes distances from a single source to all reachable nodes.

func EstimateCorridorSize

func EstimateCorridorSize(
	version *GraphVersion,
	view *View,
	sourceID, targetID uint64,
	hops uint32,
	cfg *ShortestPathConfig,
) (uint64, error)

EstimateCorridorSize estimates the number of edges in a corridor without actually building it. Useful for size checks before running mincut.

func HashBFSParams

func HashBFSParams(src uint64, maxDepth uint32, mode string, viewHash string) string

HashBFSParams generates a hash for BFS cache key normalization.

func HashBetweennessParams

func HashBetweennessParams(sampleSize uint32, normalized bool, weightColumn string, viewHash string) string

HashBetweennessParams generates a hash for betweenness cache key normalization.

func HashClosenessParams

func HashClosenessParams(mode int32, normalized bool, weightColumn string, viewHash string) string

HashClosenessParams generates a hash for closeness cache key normalization.

func HashCommunitiesParams

func HashCommunitiesParams(algorithm string, resolution float64, viewHash string) string

HashCommunitiesParams generates a hash for communities cache key normalization.

func HashKCoreParams

func HashKCoreParams(k uint32, viewHash string) string

HashKCoreParams generates a hash for k-core cache key normalization.

func HashKSPParams

func HashKSPParams(src, dst uint64, k uint32, weightColumn string, viewHash string) string

HashKSPParams generates a hash for KSP cache key normalization.

func HashNeighborhoodParams

func HashNeighborhoodParams(seeds []uint64, hops uint32, mode string, viewHash string) string

HashNeighborhoodParams generates a hash for neighborhood cache key normalization.

func HashPageRankParams

func HashPageRankParams(damping float64, maxIterations uint32, epsilon float64, weightColumn string, viewHash string) string

HashPageRankParams generates a hash for PageRank cache key normalization.

func HashParams

func HashParams(params ...interface{}) string

HashParams creates a hash from algorithm parameters for cache key.

func HashViewSpec

func HashViewSpec(spec *gepb.ViewSpec) string

HashViewSpec creates a hash of a ViewSpec for caching.

func ValidateBFSRequest

func ValidateBFSRequest(maxDepth uint32, mode string) error

ValidateBFSRequest validates a BFS request.

func ValidateBetweennessRequest

func ValidateBetweennessRequest(sampleSize uint32) error

ValidateBetweennessRequest validates a betweenness request.

func ValidateClosenessRequest

func ValidateClosenessRequest(mode int32) error

ValidateClosenessRequest validates a closeness request.

func ValidateCommunitiesRequest

func ValidateCommunitiesRequest(algorithm string, resolution float64) error

ValidateCommunitiesRequest validates a communities request.

func ValidateCorridorSpec

func ValidateCorridorSpec(spec *gepb.CorridorSpec) error

ValidateCorridorSpec validates a CorridorSpec.

func ValidateKCoreRequest

func ValidateKCoreRequest(k uint32) error

ValidateKCoreRequest validates a k-core request.

func ValidateKSPRequest

func ValidateKSPRequest(k, maxCandidates uint32) error

ValidateKSPRequest validates a K-shortest paths request.

func ValidateMinCutRequest

func ValidateMinCutRequest(
	version *GraphVersion,
	view *View,
	sourceID, targetID uint64,
	maxEdges int,
) error

ValidateMinCutRequest validates parameters for a mincut request.

func ValidateNeighborhoodRequest

func ValidateNeighborhoodRequest(hops uint32, mode string) error

ValidateNeighborhoodRequest validates a neighborhood request.

func ValidatePageRankRequest

func ValidatePageRankRequest(damping float64) error

ValidatePageRankRequest validates a PageRank request.

Types

type AlgoKind

type AlgoKind string

AlgoKind represents the type of algorithm.

const (
	AlgoKindComponents   AlgoKind = "components"
	AlgoKindCommunities  AlgoKind = "communities"
	AlgoKindShortestPath AlgoKind = "shortest_path"
	AlgoKindKSP          AlgoKind = "k_shortest_paths"
	AlgoKindDistances    AlgoKind = "distances"
	AlgoKindBFS          AlgoKind = "bfs"
	AlgoKindNeighborhood AlgoKind = "neighborhood"
	AlgoKindSTMinCut     AlgoKind = "st_mincut"
	AlgoKindCorridor     AlgoKind = "corridor"
	AlgoKindKCore        AlgoKind = "kcore"
	AlgoKindBetweenness  AlgoKind = "betweenness"
	AlgoKindCloseness    AlgoKind = "closeness"
	AlgoKindPageRank     AlgoKind = "pagerank"
)

type AlgoResult

type AlgoResult struct {
	// Identity
	ID        string
	VersionID string
	AlgoKind  AlgoKind
	CreatedAt time.Time

	// Cache key components
	ParamsHash string

	// Result data (depending on algorithm)
	MembershipU32 []uint32  // For components/communities
	PathVertices  []uint64  // For shortest path
	PathEdges     []uint64  // For shortest path
	PathCost      float64   // For shortest path
	DistancesF64  []float64 // For distances
	VerticesU64   []uint64  // For BFS/Neighborhood result vertices
	CutValue      float64   // For st_mincut
	CutEdges      []uint64  // For st_mincut

	// K-shortest paths results
	KSPPaths []*KSPPath // For k_shortest_paths

	// K-Core results
	NodeIDsU64  []uint64 // External node IDs (parallel with CorenessU32)
	CorenessU32 []uint32 // Coreness value per vertex
	MaxCore     uint32   // Maximum k found

	// Betweenness centrality results
	BetweennessF64 []float64 // Betweenness score per vertex

	// Closeness centrality results
	ClosenessF64 []float64 // Closeness score per vertex

	// PageRank results
	PageRankF64        []float64 // PageRank score per vertex
	PageRankIterations uint32    // Number of iterations performed
	PageRankConverged  bool      // Whether the algorithm converged

	// Trace spans for observability
	Spans []*TraceSpan

	// Metadata
	Meta map[string]string
	// contains filtered or unexported fields
}

AlgoResult represents the result of an algorithm execution.

func ComputeComponents

func ComputeComponents(version *GraphVersion, weak bool, cfg *ComponentsConfig) (*AlgoResult, error)

ComputeComponents computes connected components using igraph. If weak is true, computes weakly connected components (ignoring edge direction). If weak is false, computes strongly connected components (respecting direction).

This function requires a configured ShimGraph. The igraph C shim is always used for optimal performance.

func NewAlgoResult

func NewAlgoResult(versionID string, algoKind AlgoKind, paramsHash string) *AlgoResult

NewAlgoResult creates a new AlgoResult.

func (*AlgoResult) AddSpan

func (r *AlgoResult) AddSpan(span *TraceSpan)

AddSpan adds a completed trace span to the result.

func (*AlgoResult) CacheKey

func (r *AlgoResult) CacheKey() string

CacheKey returns the cache key for this result.

func (*AlgoResult) EstimateMemory

func (r *AlgoResult) EstimateMemory() uint64

EstimateMemory calculates memory usage in bytes.

func (*AlgoResult) Pin

func (r *AlgoResult) Pin()

Pin increments the reference count.

func (*AlgoResult) RecordSpan

func (r *AlgoResult) RecordSpan(name string, duration time.Duration, tags map[string]string)

RecordSpan records a span with a given duration (for already-timed operations).

func (*AlgoResult) RefCount

func (r *AlgoResult) RefCount() int

RefCount returns the current reference count.

func (*AlgoResult) StartSpan

func (r *AlgoResult) StartSpan(name string) *TraceSpan

StartSpan creates and starts a new trace span, returning it for deferred End() call.

func (*AlgoResult) Unpin

func (r *AlgoResult) Unpin() bool

Unpin decrements the reference count.

type AlgoResultSnapshot

type AlgoResultSnapshot struct {
	ID         string            `json:"id"`
	VersionID  string            `json:"version_id"`
	AlgoKind   string            `json:"algo_kind"`
	ParamsHash string            `json:"params_hash"`
	CreatedAt  time.Time         `json:"created_at"`
	Meta       map[string]string `json:"meta"`

	// Result data
	MembershipU32 []uint32  `json:"membership_u32,omitempty"`
	PathVertices  []uint64  `json:"path_vertices,omitempty"`
	PathEdges     []uint64  `json:"path_edges,omitempty"`
	PathCost      float64   `json:"path_cost,omitempty"`
	DistancesF64  []float64 `json:"distances_f64,omitempty"`
	CutValue      float64   `json:"cut_value,omitempty"`
	CutEdges      []uint64  `json:"cut_edges,omitempty"`
	KSPPaths      []KSPPath `json:"ksp_paths,omitempty"`
}

AlgoResultSnapshot holds serializable algorithm result.

type BFSConfig

type BFSConfig struct {
	// MaxDepth limits the search depth (0 = unlimited).
	MaxDepth uint32

	// Mode specifies traversal direction.
	Mode BFSMode

	// ReturnExternalIDs indicates whether to populate VisitedExternal.
	ReturnExternalIDs bool
}

BFSConfig contains configuration for BFS.

func DefaultBFSConfig

func DefaultBFSConfig() *BFSConfig

DefaultBFSConfig returns a BFSConfig with sensible defaults.

type BFSMode

type BFSMode int

BFSMode specifies the traversal direction for BFS.

const (
	// BFSModeAll traverses both directions (undirected).
	BFSModeAll BFSMode = iota
	// BFSModeOut traverses outgoing edges only.
	BFSModeOut
	// BFSModeIn traverses incoming edges only.
	BFSModeIn
)

func ParseBFSMode

func ParseBFSMode(s string) (BFSMode, error)

ParseBFSMode parses a string to BFSMode.

func (BFSMode) String

func (m BFSMode) String() string

type BFSResult

type BFSResult struct {
	// Visited contains vertices in BFS traversal order.
	Visited []uint32

	// VisitedExternal contains external node IDs in BFS traversal order.
	VisitedExternal []uint64

	// Depths maps each visited vertex to its distance from source.
	Depths []uint32

	// Parents maps each visited vertex to its parent (-1 or MaxUint32 for source).
	Parents []uint32

	// DepthMap provides O(1) lookup of depth by vertex index.
	DepthMap map[uint32]uint32

	// NumVisited is the number of vertices visited.
	NumVisited uint32

	// MaxDepthReached is the maximum depth reached during traversal.
	MaxDepthReached uint32

	// Meta contains algorithm metadata.
	Meta map[string]string
}

BFSResult contains the result of a breadth-first search.

func ComputeBFS

func ComputeBFS(
	ctx context.Context,
	version *GraphVersion,
	view *View,
	sourceID uint64,
	config *BFSConfig,
	shimCfg *BFSShimConfig,
) (*BFSResult, error)

ComputeBFS performs a breadth-first search from a source vertex using igraph.

This function requires a configured ShimGraph. The igraph C shim is always used for optimal performance.

func (*BFSResult) GetDepth

func (r *BFSResult) GetDepth(vertexIdx uint32) (uint32, bool)

GetDepth returns the depth of a vertex from the source. Returns (depth, true) if found, (0, false) if vertex was not visited.

func (*BFSResult) GetPath

func (r *BFSResult) GetPath(targetIdx uint32) []uint32

GetPath reconstructs the path from source to a target vertex. Returns nil if the target was not visited.

func (*BFSResult) GetVerticesAtDepth

func (r *BFSResult) GetVerticesAtDepth(depth uint32) []uint32

GetVerticesAtDepth returns all vertices at a specific depth.

func (*BFSResult) GetVerticesAtDepthExternal

func (r *BFSResult) GetVerticesAtDepthExternal(depth uint32, version *GraphVersion) []uint64

GetVerticesAtDepthExternal returns external IDs of all vertices at a specific depth.

func (*BFSResult) WasVisited

func (r *BFSResult) WasVisited(vertexIdx uint32) bool

WasVisited checks if a vertex was visited during BFS.

type BFSShimConfig

type BFSShimConfig struct {
	// ShimGraph is the shim graph to use (required).
	ShimGraph *shim.Graph

	// ShimView is the shim view to use for view-based queries (optional).
	ShimView *shim.View
}

BFSShimConfig holds shim configuration for BFS computation.

type BetweennessConfig

type BetweennessConfig struct {
	// SampleSize specifies the number of source vertices to sample (0 = all vertices).
	// Sampling significantly speeds up computation for large graphs while
	// providing approximate results.
	SampleSize uint32

	// Normalized indicates whether to normalize scores.
	// If true, scores are normalized by 2/((n-1)(n-2)) for undirected graphs
	// or 1/((n-1)(n-2)) for directed graphs.
	Normalized bool

	// WeightColumn specifies the edge weight column to use (empty = unweighted).
	WeightColumn string
}

BetweennessConfig contains configuration for betweenness centrality computation.

func DefaultBetweennessConfig

func DefaultBetweennessConfig() *BetweennessConfig

DefaultBetweennessConfig returns a BetweennessConfig with sensible defaults.

type BetweennessResult

type BetweennessResult struct {
	// Scores contains the betweenness centrality score for each vertex.
	// Higher scores indicate vertices that lie on more shortest paths.
	Scores []float64

	// MaxScore is the maximum betweenness score found.
	MaxScore float64

	// MinScore is the minimum betweenness score found (usually 0).
	MinScore float64

	// Meta contains algorithm metadata.
	Meta map[string]string
}

BetweennessResult contains the result of betweenness centrality computation.

func ComputeBetweenness

func ComputeBetweenness(
	ctx context.Context,
	version *GraphVersion,
	view *View,
	config *BetweennessConfig,
	shimCfg *BetweennessShimConfig,
) (*BetweennessResult, error)

ComputeBetweenness computes the betweenness centrality of all vertices.

Betweenness centrality measures the extent to which a vertex lies on paths between other vertices. Vertices with high betweenness may have considerable influence within a network by virtue of their control over information passing between others.

Betweenness computation requires the igraph shim.

func (*BetweennessResult) GetTopKVertices

func (r *BetweennessResult) GetTopKVertices(k int) []struct {
	VertexIdx uint32
	Score     float64
}

GetTopKVertices returns the top K vertices by betweenness score.

func (*BetweennessResult) GetTopKVerticesExternal

func (r *BetweennessResult) GetTopKVerticesExternal(k int, version *GraphVersion) []struct {
	NodeID uint64
	Score  float64
}

GetTopKVerticesExternal returns the top K vertices by betweenness with external IDs.

func (*BetweennessResult) GetVertexBetweenness

func (r *BetweennessResult) GetVertexBetweenness(vertexIdx uint32) (float64, bool)

GetVertexBetweenness returns the betweenness score for a specific vertex.

func (*BetweennessResult) GetVertexBetweennessByExternalID

func (r *BetweennessResult) GetVertexBetweennessByExternalID(nodeID uint64, version *GraphVersion) (float64, bool)

GetVertexBetweennessByExternalID returns the betweenness for a vertex given its external ID.

func (*BetweennessResult) GetVerticesAboveThreshold

func (r *BetweennessResult) GetVerticesAboveThreshold(threshold float64) []uint32

GetVerticesAboveThreshold returns all vertices with betweenness score above a threshold.

type BetweennessShimConfig

type BetweennessShimConfig struct {
	// ShimGraph is the shim graph to use (required).
	ShimGraph *shim.Graph

	// ShimView is the shim view to use for view-based queries (optional).
	ShimView *shim.View
}

BetweennessShimConfig holds shim configuration for betweenness computation.

type Build

type Build struct {
	ID        string
	GraphName string
	Directed  bool
	CreatedAt time.Time

	// Vertex data
	VerticesU64 []uint64
	VerticesStr []string

	// Edge data
	EdgesSrcU64 []uint64
	EdgesDstU64 []uint64
	EdgesSrcStr []string
	EdgesDstStr []string
	EdgesKind   []uint32
	EdgesWeight []float32

	// Column data
	VertexColumns map[string]*ColumnData
	EdgeColumns   map[string]*ColumnData

	// Metadata
	Labels map[string]string
	// contains filtered or unexported fields
}

Build represents an in-progress graph build.

func (*Build) EdgeCount

func (b *Build) EdgeCount() uint64

EdgeCount returns the number of edges in the build.

func (*Build) Validate

func (b *Build) Validate(limits ValidationLimits) *ValidationResult

Validate checks the build for errors.

func (*Build) VertexCount

func (b *Build) VertexCount() uint64

VertexCount returns the number of vertices in the build.

type BuildStore

type BuildStore struct {
	// contains filtered or unexported fields
}

BuildStore provides thread-safe storage for in-progress builds.

func NewBuildStore

func NewBuildStore(maxBuilds int) *BuildStore

NewBuildStore creates a new BuildStore with the specified limits.

func (*BuildStore) AddEdgeColumn

func (s *BuildStore) AddEdgeColumn(buildID, name string, data *ColumnData) error

AddEdgeColumn adds an edge column to a build. Column values must align with edge order (length should match edge count).

func (*BuildStore) AddEdgesStr

func (s *BuildStore) AddEdgesStr(buildID string, src, dst []string, kind []uint32, weight []float32) error

AddEdgesStr adds edges with string node IDs to a build.

func (*BuildStore) AddEdgesU64

func (s *BuildStore) AddEdgesU64(buildID string, src, dst []uint64, kind []uint32, weight []float32) error

AddEdgesU64 adds edges with uint64 node IDs to a build.

func (*BuildStore) AddVertexColumn

func (s *BuildStore) AddVertexColumn(buildID, name string, data *ColumnData) error

AddVertexColumn adds a vertex column to a build. Column values must align with vertex order (length should match vertex count).

func (*BuildStore) AddVerticesStr

func (s *BuildStore) AddVerticesStr(buildID string, vertices []string) error

AddVerticesStr adds string vertex IDs to a build.

func (*BuildStore) AddVerticesU64

func (s *BuildStore) AddVerticesU64(buildID string, vertices []uint64) error

AddVerticesU64 adds uint64 vertex IDs to a build.

func (*BuildStore) Count

func (s *BuildStore) Count() int

Count returns the number of builds in the store.

func (*BuildStore) CreateBuild

func (s *BuildStore) CreateBuild(graphName string, directed bool, labels map[string]string) (string, error)

CreateBuild creates a new build and returns its ID.

func (*BuildStore) DeleteBuild

func (s *BuildStore) DeleteBuild(buildID string) bool

DeleteBuild removes a build from the store.

func (*BuildStore) GetBuild

func (s *BuildStore) GetBuild(buildID string) *Build

GetBuild returns a build by ID, or nil if not found.

func (*BuildStore) ListBuilds

func (s *BuildStore) ListBuilds() []string

ListBuilds returns all build IDs in the store.

type ClosenessConfig

type ClosenessConfig struct {
	// Mode specifies the direction mode for directed graphs.
	// 0 = ALL (default, for undirected), 1 = OUT, 2 = IN
	Mode int32

	// Normalized indicates whether to normalize scores.
	// If true, scores are normalized to the 0-1 range.
	Normalized bool

	// WeightColumn specifies the edge weight column to use (empty = unweighted).
	WeightColumn string
}

ClosenessConfig contains configuration for closeness centrality computation.

func DefaultClosenessConfig

func DefaultClosenessConfig() *ClosenessConfig

DefaultClosenessConfig returns a ClosenessConfig with sensible defaults.

type ClosenessResult

type ClosenessResult struct {
	// Scores contains the closeness centrality score for each vertex.
	// Higher scores indicate vertices that can reach others more quickly.
	Scores []float64

	// MaxScore is the maximum closeness score found.
	MaxScore float64

	// MinScore is the minimum closeness score found.
	MinScore float64

	// Meta contains algorithm metadata.
	Meta map[string]string
}

ClosenessResult contains the result of closeness centrality computation.

func ComputeCloseness

func ComputeCloseness(
	ctx context.Context,
	version *GraphVersion,
	view *View,
	config *ClosenessConfig,
	shimCfg *ClosenessShimConfig,
) (*ClosenessResult, error)

ComputeCloseness computes the closeness centrality of all vertices.

Closeness centrality measures how close a vertex is to all other vertices. It is defined as the reciprocal of the sum of shortest path distances from a vertex to all other vertices. Vertices with high closeness can reach other vertices more quickly.

For disconnected graphs, closeness is only computed for reachable vertices.

Closeness computation requires the igraph shim.

func (*ClosenessResult) GetTopKVertices

func (r *ClosenessResult) GetTopKVertices(k int) []struct {
	VertexIdx uint32
	Score     float64
}

GetTopKVertices returns the top K vertices by closeness score.

func (*ClosenessResult) GetVertexCloseness

func (r *ClosenessResult) GetVertexCloseness(vertexIdx uint32) (float64, bool)

GetVertexCloseness returns the closeness score for a specific vertex.

func (*ClosenessResult) GetVertexClosenessByExternalID

func (r *ClosenessResult) GetVertexClosenessByExternalID(nodeID uint64, version *GraphVersion) (float64, bool)

GetVertexClosenessByExternalID returns the closeness for a vertex given its external ID.

type ClosenessShimConfig

type ClosenessShimConfig struct {
	// ShimGraph is the shim graph to use (required).
	ShimGraph *shim.Graph

	// ShimView is the shim view to use for view-based queries (optional).
	ShimView *shim.View
}

ClosenessShimConfig holds shim configuration for closeness computation.

type ColumnData

type ColumnData struct {
	Name    string
	Type    ColumnType
	BoolVal []bool
	U32Val  []uint32
	U64Val  []uint64
	F32Val  []float32
	F64Val  []float64
	StrVal  []string
}

ColumnData holds typed column data for vertices or edges.

func (*ColumnData) Length

func (c *ColumnData) Length() int

Length returns the number of values in the column.

type ColumnType

type ColumnType int32

ColumnType represents the data type of a column.

const (
	ColumnTypeBool   ColumnType = 0
	ColumnTypeU32    ColumnType = 1
	ColumnTypeU64    ColumnType = 2
	ColumnTypeF32    ColumnType = 3
	ColumnTypeF64    ColumnType = 4
	ColumnTypeString ColumnType = 5
)

type CommunitiesConfig

type CommunitiesConfig struct {
	// Algorithm specifies which algorithm to use.
	Algorithm CommunityAlgorithm

	// Resolution controls community granularity (for Leiden/Louvain).
	// Higher values produce more, smaller communities.
	// Default: 1.0
	Resolution float64

	// Steps is the number of random walk steps for Walktrap.
	// Default: 4
	Steps uint32

	// Spins is the number of spins for Spinglass.
	// Default: 25
	Spins uint32

	// Gamma is the resolution parameter for Spinglass.
	// Default: 1.0
	Gamma float64

	// Trials is the number of optimization trials for Infomap.
	// Default: 10
	Trials uint32
}

CommunitiesConfig contains configuration for community detection.

func DefaultCommunitiesConfig

func DefaultCommunitiesConfig() *CommunitiesConfig

DefaultCommunitiesConfig returns a CommunitiesConfig with sensible defaults.

type CommunitiesResult

type CommunitiesResult struct {
	// Membership maps vertex index to community ID.
	Membership []uint32

	// Modularity is the modularity score of the partition.
	// Higher values indicate better community structure.
	Modularity float64

	// NumCommunities is the number of communities found.
	NumCommunities uint32

	// CommunitySize maps community ID to number of members.
	CommunitySize map[uint32]uint32

	// Meta contains algorithm metadata.
	Meta map[string]string
}

CommunitiesResult contains the result of community detection.

func ComputeCommunities

func ComputeCommunities(
	ctx context.Context,
	version *GraphVersion,
	view *View,
	config *CommunitiesConfig,
	shimCfg *CommunitiesShimConfig,
) (*CommunitiesResult, error)

ComputeCommunities detects communities in the graph using the specified algorithm.

Community detection is only available via the igraph shim - there is no pure Go fallback. When shimCfg.UseShim is false or shimCfg.ShimGraph is nil, returns an error.

func (*CommunitiesResult) AreInSameCommunity

func (r *CommunitiesResult) AreInSameCommunity(vertexIdx1, vertexIdx2 uint32) bool

AreInSameCommunity checks if two vertices are in the same community.

func (*CommunitiesResult) GetCommunityMembers

func (r *CommunitiesResult) GetCommunityMembers(communityID uint32) []uint32

GetCommunityMembers returns the vertex indices belonging to a specific community.

func (*CommunitiesResult) GetCommunityMembersExternal

func (r *CommunitiesResult) GetCommunityMembersExternal(communityID uint32, version *GraphVersion) []uint64

GetCommunityMembersExternal returns the external vertex IDs belonging to a specific community.

func (*CommunitiesResult) GetLargestCommunities

func (r *CommunitiesResult) GetLargestCommunities(n int) []struct {
	CommunityID uint32
	Size        uint32
}

GetLargestCommunities returns the top N communities by size.

func (*CommunitiesResult) GetVertexCommunity

func (r *CommunitiesResult) GetVertexCommunity(vertexIdx uint32) (uint32, bool)

GetVertexCommunity returns the community ID for a specific vertex.

func (*CommunitiesResult) GetVertexCommunityByExternalID

func (r *CommunitiesResult) GetVertexCommunityByExternalID(nodeID uint64, version *GraphVersion) (uint32, bool)

GetVertexCommunityByExternalID returns the community ID for a vertex given its external ID.

type CommunitiesShimConfig

type CommunitiesShimConfig struct {
	// UseShim enables the igraph shim for community detection.
	UseShim bool

	// FallbackOnError falls back to pure Go if the shim encounters an error.
	// Note: There is no pure Go fallback for community detection,
	// so this will return an error if the shim fails.
	FallbackOnError bool

	// ShimGraph is the shim graph to use (if UseShim is true).
	ShimGraph *shim.Graph

	// ShimView is the shim view to use for view-based queries (optional).
	ShimView *shim.View
}

CommunitiesShimConfig holds shim configuration for community detection.

type CommunityAlgorithm

type CommunityAlgorithm int

CommunityAlgorithm specifies which community detection algorithm to use.

const (
	// CommunityAlgorithmLeiden uses the Leiden algorithm (recommended).
	// Generally produces better quality communities than Louvain.
	CommunityAlgorithmLeiden CommunityAlgorithm = iota

	// CommunityAlgorithmLouvain uses the Louvain algorithm.
	// Faster than Leiden but may produce lower quality communities.
	CommunityAlgorithmLouvain

	// CommunityAlgorithmLabelPropagation uses the Label Propagation algorithm.
	// Very fast O(m), but non-deterministic.
	CommunityAlgorithmLabelPropagation

	// CommunityAlgorithmInfomap uses the Infomap algorithm.
	// Information-theoretic method, good for finding flow-based communities.
	CommunityAlgorithmInfomap

	// CommunityAlgorithmWalktrap uses the Walktrap algorithm.
	// Random walk based, O(mn) complexity.
	CommunityAlgorithmWalktrap

	// CommunityAlgorithmFastGreedy uses the Fast Greedy algorithm.
	// Greedy modularity optimization, O(n·log²n) complexity.
	CommunityAlgorithmFastGreedy

	// CommunityAlgorithmEdgeBetweenness uses the Edge Betweenness algorithm.
	// Accurate but slow O(n³), not recommended for large graphs.
	CommunityAlgorithmEdgeBetweenness

	// CommunityAlgorithmLeadingEigenvector uses the Leading Eigenvector algorithm.
	// Newman's spectral method, O(n²+m) complexity.
	CommunityAlgorithmLeadingEigenvector

	// CommunityAlgorithmSpinglass uses the Spinglass algorithm.
	// Statistical physics approach. Only works on connected graphs.
	CommunityAlgorithmSpinglass
)

func ParseCommunityAlgorithm

func ParseCommunityAlgorithm(s string) (CommunityAlgorithm, error)

ParseCommunityAlgorithm parses a string to CommunityAlgorithm.

func (CommunityAlgorithm) String

func (a CommunityAlgorithm) String() string

type ComponentStats

type ComponentStats struct {
	NumComponents    int
	LargestSize      int
	SmallestSize     int
	AverageSize      float64
	IsolatedVertices int
}

ComponentStats returns statistics about connected components.

func GetComponentStats

func GetComponentStats(membership []uint32) ComponentStats

GetComponentStats computes statistics from a membership array.

type ComponentsConfig

type ComponentsConfig struct {
	// ShimGraph is the shim graph to use (required).
	ShimGraph *shim.Graph
}

ComponentsConfig holds configuration for components computation.

type CorridorConfig

type CorridorConfig struct {
	// ShimGraph is the shim graph to use (required for SP and KSP computations).
	ShimGraph *shim.Graph
}

CorridorConfig holds configuration for corridor computation.

type CorridorMethod

type CorridorMethod string

CorridorMethod represents the method used to construct a corridor.

const (
	CorridorMethodShortestPathHull CorridorMethod = "SHORTEST_PATH_HULL"
	CorridorMethodKSPHull          CorridorMethod = "KSP_HULL"
	CorridorMethodCommunityAware   CorridorMethod = "COMMUNITY_AWARE"
)

type CorridorResult

type CorridorResult struct {
	// View is the corridor view (filtered subgraph)
	View *View
	// Method is the method used to construct the corridor
	Method CorridorMethod
	// PathSummary contains the underlying shortest path (for SHORTEST_PATH_HULL)
	PathSummary *ShortestPathResult
	// Meta contains explainability metadata
	Meta map[string]string
}

CorridorResult contains the result of a corridor computation.

func ComputeCorridor

func ComputeCorridor(
	version *GraphVersion,
	view *View,
	sourceID, targetID uint64,
	method gepb.CorridorSpec_Method,
	hops uint32,
	k uint32,
	cfg *ShortestPathConfig,
) (*CorridorResult, error)

ComputeCorridor computes a corridor (focused subgraph) between two nodes. The corridor includes nodes and edges around the path between source and target.

type DistancesResult

type DistancesResult struct {
	// Distances is a flattened matrix of distances (row-major order)
	// Index = sourceIndex * len(targets) + targetIndex
	Distances []float64
	// Sources are the source node IDs (external)
	Sources []uint64
	// Targets are the target node IDs (external)
	Targets []uint64
	// NumSources is the number of source nodes
	NumSources int
	// NumTargets is the number of target nodes
	NumTargets int
}

DistancesResult contains the result of a distances computation.

func ComputeAllPairsDistances

func ComputeAllPairsDistances(
	version *GraphVersion,
	view *View,
	weighted bool,
) (*DistancesResult, error)

ComputeAllPairsDistances computes distances between all pairs of vertices. Warning: This can be expensive for large graphs - O(V * (V + E) log V) for weighted.

func ComputeDistances

func ComputeDistances(
	version *GraphVersion,
	view *View,
	sourceIDs, targetIDs []uint64,
	weighted bool,
) (*DistancesResult, error)

ComputeDistances computes distances from multiple sources to multiple targets. If view is nil, uses the full graph. If weighted is false, uses hop count.

func (*DistancesResult) GetDistance

func (r *DistancesResult) GetDistance(sourceIdx, targetIdx int) float64

GetDistance returns the distance from source index to target index.

type EdgeMask

type EdgeMask struct {
	// contains filtered or unexported fields
}

EdgeMask provides backward-compatible access to edge inclusion status. Returns a wrapper that implements index-based access. DEPRECATED: Use EdgeMaskBitmap() for direct bitmap access in new code.

type ExportConfig

type ExportConfig struct {
	// Format is the output format
	Format ExportFormat

	// MaxEdges is the maximum number of edges to export (0 = use default)
	MaxEdges uint64

	// IncludeWeights includes edge weights in output
	IncludeWeights bool

	// IncludeKind includes edge kind/type in output
	IncludeKind bool

	// ChunkSize is the number of edges per chunk (for streaming)
	ChunkSize int
}

ExportConfig holds configuration for graph export.

func DefaultExportConfig

func DefaultExportConfig() ExportConfig

DefaultExportConfig returns default export configuration.

type ExportFormat

type ExportFormat int

ExportFormat represents the output format for graph export.

const (
	// ExportFormatEdgeList exports as "src_id dst_id [weight]" per line
	ExportFormatEdgeList ExportFormat = iota
	// ExportFormatCSV exports as CSV with headers
	ExportFormatCSV
)

type ExportResult

type ExportResult struct {
	// TotalEdges is the number of edges exported
	TotalEdges uint64

	// TotalBytes is the total size of exported data
	TotalBytes uint64

	// Truncated is true if export was limited by MaxEdges
	Truncated bool
}

ExportResult holds export operation results.

type GraphEntry

type GraphEntry struct {
	GraphName        string
	CurrentVersionID string
	PublishedAt      time.Time
}

GraphEntry represents a registered graph with its current version.

type GraphExporter

type GraphExporter struct {
	// contains filtered or unexported fields
}

GraphExporter exports graph data in various formats.

func NewGraphExporter

func NewGraphExporter(config ExportConfig) *GraphExporter

NewGraphExporter creates a new graph exporter.

func (*GraphExporter) CanExport

func (e *GraphExporter) CanExport(ecount uint64) (bool, uint64, string)

CanExport checks if the graph/view can be exported within size limits. Returns (canExport, edgeCount, error message).

func (*GraphExporter) ExportGraph

func (e *GraphExporter) ExportGraph(gv *GraphVersion) (<-chan []byte, *ExportResult, error)

ExportGraph exports a graph version to the specified format. Returns chunks of data for streaming.

func (*GraphExporter) ExportToWriter

func (e *GraphExporter) ExportToWriter(gv *GraphVersion, w io.Writer) (*ExportResult, error)

ExportToWriter exports graph data to an io.Writer (for non-streaming use).

func (*GraphExporter) ExportView

func (e *GraphExporter) ExportView(view *View) (<-chan []byte, *ExportResult, error)

ExportView exports a view to the specified format.

func (*GraphExporter) ExportViewToWriter

func (e *GraphExporter) ExportViewToWriter(view *View, w io.Writer) (*ExportResult, error)

ExportViewToWriter exports view data to an io.Writer.

type GraphRegistry

type GraphRegistry struct {
	// contains filtered or unexported fields
}

GraphRegistry tracks published graphs and their current versions. It provides atomic version swapping for the "one writer, many readers" pattern.

func NewGraphRegistry

func NewGraphRegistry(versionStore *VersionStore, maxGraphs int) *GraphRegistry

NewGraphRegistry creates a new GraphRegistry.

func (*GraphRegistry) Count

func (r *GraphRegistry) Count() int

Count returns the number of registered graphs.

func (*GraphRegistry) DeleteGraph

func (r *GraphRegistry) DeleteGraph(graphName string) bool

DeleteGraph removes a graph from the registry. All versions are marked for cleanup.

func (*GraphRegistry) GetCurrentVersion

func (r *GraphRegistry) GetCurrentVersion(graphName string) (*GraphVersion, error)

GetCurrentVersion returns the current version for a graph. The returned version is pinned and must be unpinned after use.

func (*GraphRegistry) GetGraphEntry

func (r *GraphRegistry) GetGraphEntry(graphName string) (*GraphEntry, bool)

GetGraphEntry returns the registry entry for a graph.

func (*GraphRegistry) GetVersion

func (r *GraphRegistry) GetVersion(graphName, versionID string) (*GraphVersion, error)

GetVersion returns a specific version by ID. The returned version is pinned and must be unpinned after use.

func (*GraphRegistry) GraphExists

func (r *GraphRegistry) GraphExists(graphName string) bool

GraphExists checks if a graph is registered.

func (*GraphRegistry) ListGraphs

func (r *GraphRegistry) ListGraphs() []*gepb.GraphSummary

ListGraphs returns summaries of all published graphs.

func (*GraphRegistry) Publish

func (r *GraphRegistry) Publish(graphName string, version *GraphVersion) error

Publish registers a new version as the current version for a graph. This operation is atomic - readers will see either the old or new version, never a partial state.

type GraphValidationResult

type GraphValidationResult struct {
	// Valid is true if no errors were found
	Valid bool

	// Errors are fatal issues that indicate data corruption
	Errors []*ValidationError

	// Warnings are non-fatal issues that might indicate problems
	Warnings []string

	// Metrics contains validation statistics
	Metrics map[string]string
}

GraphValidationResult holds the results of graph validation with metrics.

func NewGraphValidationResult

func NewGraphValidationResult() *GraphValidationResult

NewGraphValidationResult creates a new empty validation result.

func ValidateGraph

func ValidateGraph(gv *GraphVersion, deep bool) *GraphValidationResult

ValidateGraph performs validation on a GraphVersion. If deep is true, performs comprehensive validation. If deep is false, performs only shallow (fast) validation.

func ValidateViewGraph

func ValidateViewGraph(view *View, deep bool) *GraphValidationResult

ValidateViewGraph performs validation on a View.

func (*GraphValidationResult) AddError

func (r *GraphValidationResult) AddError(code, message string, details map[string]interface{})

AddError adds an error to the result and marks it as invalid.

func (*GraphValidationResult) AddWarning

func (r *GraphValidationResult) AddWarning(message string)

AddWarning adds a warning to the result.

func (*GraphValidationResult) SetMetric

func (r *GraphValidationResult) SetMetric(key, value string)

SetMetric sets a validation metric.

type GraphVersion

type GraphVersion struct {
	// Identity
	ID          string
	GraphName   string
	Directed    bool
	PublishedAt time.Time

	// Edge data using compact node indices
	// All arrays have the same length (number of edges)
	EdgeSrc    []uint32  // Source node indices
	EdgeDst    []uint32  // Destination node indices
	EdgeKind   []uint32  // Edge type/kind (optional)
	EdgeWeight []float32 // Edge weights (optional)

	// Column data (indexed by column name)
	VertexColumns map[string]*ColumnData
	EdgeColumns   map[string]*ColumnData

	// Schema definition
	Schema *gepb.Schema
	Labels map[string]string

	// Statistics
	VCount uint64 // Number of vertices
	ECount uint64 // Number of edges

	// Precomputed artifacts (optional, set during PublishBuild with BatchArtifacts)
	// Community membership (vertex index -> community ID)
	CommunityMembership []uint32
	NumCommunities      uint32

	// K-Core decomposition (vertex index -> coreness value)
	KCoreness []uint32
	MaxCore   uint32

	// Betweenness centrality scores (vertex index -> score)
	BetweennessScores []float64
	// contains filtered or unexported fields
}

GraphVersion represents a published, immutable graph version. Once published, a GraphVersion is read-only and can be accessed concurrently by multiple readers.

func NewGraphVersion

func NewGraphVersion(id, graphName string, directed bool, build *Build) (*GraphVersion, error)

NewGraphVersion creates a new GraphVersion from a Build.

func (*GraphVersion) EstimateMemory

func (gv *GraphVersion) EstimateMemory() uint64

EstimateMemory returns the estimated memory usage in bytes.

func (*GraphVersion) GetAllNodeIDs

func (gv *GraphVersion) GetAllNodeIDs() []uint64

GetAllNodeIDs returns a copy of all external node IDs.

func (*GraphVersion) GetCommunityMembers

func (gv *GraphVersion) GetCommunityMembers(communityID uint32) []uint32

GetCommunityMembers returns all vertex indices belonging to a specific community.

func (*GraphVersion) GetKCoreMembers

func (gv *GraphVersion) GetKCoreMembers(k uint32) []uint32

GetKCoreMembers returns all vertex indices with coreness >= k.

func (*GraphVersion) GetNodeID

func (gv *GraphVersion) GetNodeID(index uint32) (uint64, bool)

GetNodeID returns the external node ID for a compact index. Returns (nodeID, true) if valid, (0, false) if index out of range.

func (*GraphVersion) GetNodeIndex

func (gv *GraphVersion) GetNodeIndex(nodeID uint64) (uint32, bool)

GetNodeIndex returns the compact index for an external node ID. Returns (index, true) if found, (0, false) if not found.

func (*GraphVersion) GetVertexBetweenness

func (gv *GraphVersion) GetVertexBetweenness(vertexIdx uint32) (float64, bool)

GetVertexBetweenness returns the betweenness centrality score for a vertex. Returns (score, true) if found, (0.0, false) if not available.

func (*GraphVersion) GetVertexCommunity

func (gv *GraphVersion) GetVertexCommunity(vertexIdx uint32) (uint32, bool)

GetVertexCommunity returns the community ID for a vertex by its index. Returns (communityID, true) if found, (0, false) if not available.

func (*GraphVersion) GetVertexCoreness

func (gv *GraphVersion) GetVertexCoreness(vertexIdx uint32) (uint32, bool)

GetVertexCoreness returns the coreness value for a vertex by its index. Returns (coreness, true) if found, (0, false) if not available.

func (*GraphVersion) HasBetweenness

func (gv *GraphVersion) HasBetweenness() bool

HasBetweenness returns true if betweenness data is available.

func (*GraphVersion) HasCommunities

func (gv *GraphVersion) HasCommunities() bool

HasCommunities returns true if community data is available.

func (*GraphVersion) HasKCore

func (gv *GraphVersion) HasKCore() bool

HasKCore returns true if k-core data is available.

func (*GraphVersion) Pin

func (gv *GraphVersion) Pin()

Pin increments the reference count, preventing cleanup. Must be paired with Unpin.

func (*GraphVersion) RefCount

func (gv *GraphVersion) RefCount() int

RefCount returns the current reference count.

func (*GraphVersion) SetBetweenness

func (gv *GraphVersion) SetBetweenness(scores []float64)

SetBetweenness stores precomputed betweenness centrality scores.

func (*GraphVersion) SetCommunities

func (gv *GraphVersion) SetCommunities(membership []uint32, numCommunities uint32)

SetCommunities stores precomputed community membership data.

func (*GraphVersion) SetKCore

func (gv *GraphVersion) SetKCore(coreness []uint32, maxCore uint32)

SetKCore stores precomputed k-core decomposition data.

func (*GraphVersion) ToSummary

func (gv *GraphVersion) ToSummary() *gepb.GraphSummary

ToSummary returns a GraphSummary proto for this version.

func (*GraphVersion) Unpin

func (gv *GraphVersion) Unpin() bool

Unpin decrements the reference count. Returns true if the version can be cleaned up (refCount == 0).

type GraphVersionSnapshot

type GraphVersionSnapshot struct {
	ID        string            `json:"id"`
	GraphName string            `json:"graph_name"`
	Directed  bool              `json:"directed"`
	VCount    uint64            `json:"vcount"`
	ECount    uint64            `json:"ecount"`
	Labels    map[string]string `json:"labels"`
	CreatedAt time.Time         `json:"created_at"`

	// Topology data for restoration
	NodeIDs     []uint64  `json:"node_ids"`
	EdgesSrcU64 []uint64  `json:"edges_src_u64"`
	EdgesDstU64 []uint64  `json:"edges_dst_u64"`
	EdgesWeight []float32 `json:"edges_weight,omitempty"`
}

GraphVersionSnapshot holds serializable graph version metadata.

type Job

type Job struct {
	ID        string
	TenantID  string
	AlgoKind  AlgoKind
	Priority  int32
	State     JobState
	CreatedAt time.Time
	StartedAt time.Time
	EndedAt   time.Time
	ResultID  string
	Error     error
	// contains filtered or unexported fields
}

Job represents a scheduled algorithm job.

func NewJob

func NewJob(tenantID string, algoKind AlgoKind, priority int32, execFn func(ctx context.Context) (*AlgoResult, error)) *Job

NewJob creates a new job.

func (*Job) Cancel

func (j *Job) Cancel()

Cancel cancels the job.

func (*Job) Wait

func (j *Job) Wait(ctx context.Context) error

Wait blocks until the job completes.

type JobState

type JobState int

JobState represents the state of a job.

const (
	JobStatePending JobState = iota
	JobStateRunning
	JobStateSucceeded
	JobStateFailed
	JobStateCanceled
)

func (JobState) String

func (s JobState) String() string

String returns the string representation of JobState.

type KCoreConfig

type KCoreConfig struct {
	// K specifies a specific k value to extract (0 = compute full decomposition).
	// If K > 0, only vertices with coreness >= K will have their coreness computed.
	K uint32
}

KCoreConfig contains configuration for k-core computation.

func DefaultKCoreConfig

func DefaultKCoreConfig() *KCoreConfig

DefaultKCoreConfig returns a KCoreConfig with sensible defaults.

type KCoreResult

type KCoreResult struct {
	// Coreness maps vertex index to its coreness value.
	// The coreness of a vertex is the largest k such that the vertex
	// belongs to a k-core.
	Coreness []uint32

	// MaxCore is the maximum coreness value found in the graph.
	MaxCore uint32

	// CoreSize maps k value to the number of vertices with coreness >= k.
	CoreSize map[uint32]uint32

	// Meta contains algorithm metadata.
	Meta map[string]string
}

KCoreResult contains the result of k-core decomposition.

func ComputeKCore

func ComputeKCore(
	ctx context.Context,
	version *GraphVersion,
	view *View,
	config *KCoreConfig,
	shimCfg *KCoreShimConfig,
) (*KCoreResult, error)

ComputeKCore computes the k-core decomposition of the graph.

The k-core of a graph is the maximal subgraph in which every vertex has degree at least k. The coreness of a vertex is the largest k for which it belongs to a k-core.

K-core decomposition requires the igraph shim.

func (*KCoreResult) GetCoreShells

func (r *KCoreResult) GetCoreShells() map[uint32][]uint32

GetCoreShells returns vertices grouped by their coreness value. Each shell contains vertices with exactly that coreness value.

func (*KCoreResult) GetKCoreMembers

func (r *KCoreResult) GetKCoreMembers(k uint32) []uint32

GetKCoreMembers returns all vertex indices belonging to the k-core. A vertex belongs to the k-core if its coreness is >= k.

func (*KCoreResult) GetKCoreMembersExternal

func (r *KCoreResult) GetKCoreMembersExternal(k uint32, version *GraphVersion) []uint64

GetKCoreMembersExternal returns the external vertex IDs belonging to the k-core.

func (*KCoreResult) GetVertexCoreness

func (r *KCoreResult) GetVertexCoreness(vertexIdx uint32) (uint32, bool)

GetVertexCoreness returns the coreness value for a specific vertex.

func (*KCoreResult) GetVertexCorenessByExternalID

func (r *KCoreResult) GetVertexCorenessByExternalID(nodeID uint64, version *GraphVersion) (uint32, bool)

GetVertexCorenessByExternalID returns the coreness for a vertex given its external ID.

type KCoreShimConfig

type KCoreShimConfig struct {
	// ShimGraph is the shim graph to use (required).
	ShimGraph *shim.Graph

	// ShimView is the shim view to use for view-based queries (optional).
	ShimView *shim.View
}

KCoreShimConfig holds shim configuration for k-core computation.

type KSPConfig

type KSPConfig struct {
	// K is the number of shortest paths to find
	K int
	// MaxCandidates limits the candidate heap size (0 = default: 10*K)
	MaxCandidates int
	// PerPathTimeout is the timeout for finding each individual path
	PerPathTimeout time.Duration
	// DiversityPenalty is a multiplier applied to edges already used in found paths (1.0 = no penalty)
	DiversityPenalty float64
	// Weighted indicates whether to use edge weights
	Weighted bool
	// ReturnVertices indicates whether to return path vertices
	ReturnVertices bool
	// ReturnEdges indicates whether to return path edges
	ReturnEdges bool
}

KSPConfig contains configuration for the KSP algorithm.

func DefaultKSPConfig

func DefaultKSPConfig(k int) *KSPConfig

DefaultKSPConfig returns a KSPConfig with sensible defaults.

type KSPPath

type KSPPath struct {
	Vertices []uint64
	Edges    []uint64
	Cost     float64
}

KSPPath represents a single path in K-shortest paths result.

type KSPResult

type KSPResult struct {
	// Paths contains the K shortest paths found
	Paths []*ShortestPathResult
	// PathsFound is the number of paths actually found (may be < K if not enough paths exist)
	PathsFound int
	// Meta contains algorithm metadata
	Meta map[string]string
	// CandidatesExplored is the number of candidate paths explored
	CandidatesExplored int
}

KSPResult contains the result of a K-shortest paths computation.

func ComputeKShortestPaths

func ComputeKShortestPaths(
	ctx context.Context,
	version *GraphVersion,
	view *View,
	sourceID, targetID uint64,
	config *KSPConfig,
	shimCfg *KSPShimConfig,
) (*KSPResult, error)

ComputeKShortestPaths computes K shortest paths using Yen's algorithm via igraph.

This function requires a configured ShimGraph. The igraph C shim is always used for optimal performance.

type KSPShimConfig

type KSPShimConfig struct {
	// ShimGraph is the shim graph to use (required).
	ShimGraph *shim.Graph
	// ShimView is the shim view to use for view-based queries (optional).
	// If not provided but a service View is passed, one will be created automatically.
	ShimView *shim.View
}

KSPShimConfig holds shim configuration for KSP computation.

type MinCutConfig

type MinCutConfig struct {
	// ShimGraph is the shim graph to use (required).
	ShimGraph *shim.Graph
	// ShimView is the shim view to use for view-based queries (optional).
	// If not provided but a service View is passed, one will be created automatically.
	ShimView *shim.View
}

MinCutConfig holds configuration for mincut computation.

type MinCutResult

type MinCutResult struct {
	// CutValue is the total capacity of edges in the minimum cut
	CutValue float64
	// SourceSideVertices contains the external node IDs on the source side of the cut
	SourceSideVertices []uint64
	// CutEdges contains the edge indices that form the cut
	CutEdges []uint64
	// Meta contains additional information about the computation
	Meta map[string]string
}

MinCutResult contains the result of an s-t minimum cut computation.

func ComputeSTMinCut

func ComputeSTMinCut(
	ctx context.Context,
	version *GraphVersion,
	view *View,
	sourceID, targetID uint64,
	useWeights bool,
	maxEdges int,
	cfg *MinCutConfig,
) (*MinCutResult, error)

ComputeSTMinCut computes the minimum s-t cut using igraph. The cut separates source from target with minimum total edge capacity. If useWeights is false, all edges have capacity 1.

This function requires a configured ShimGraph. The igraph C shim is always used for optimal performance.

func ComputeSTMinCutWithTimeout

func ComputeSTMinCutWithTimeout(
	version *GraphVersion,
	view *View,
	sourceID, targetID uint64,
	useWeights bool,
	maxEdges int,
	timeout time.Duration,
	cfg *MinCutConfig,
) (*MinCutResult, error)

ComputeSTMinCutWithTimeout wraps ComputeSTMinCut with a timeout.

type NeighborhoodConfig

type NeighborhoodConfig struct {
	// Hops is the maximum number of hops from seeds (1 = immediate neighbors).
	Hops uint32

	// Mode specifies traversal direction.
	Mode NeighborhoodMode

	// ReturnExternalIDs indicates whether to populate VerticesExternal.
	ReturnExternalIDs bool

	// GroupByDistance indicates whether to populate VerticesByDistance.
	GroupByDistance bool
}

NeighborhoodConfig contains configuration for neighborhood queries.

func DefaultNeighborhoodConfig

func DefaultNeighborhoodConfig(hops uint32) *NeighborhoodConfig

DefaultNeighborhoodConfig returns a NeighborhoodConfig with sensible defaults.

type NeighborhoodMode

type NeighborhoodMode int

NeighborhoodMode specifies the traversal direction for neighborhood queries.

const (
	// NeighborhoodModeAll traverses both directions (undirected).
	NeighborhoodModeAll NeighborhoodMode = iota
	// NeighborhoodModeOut traverses outgoing edges only.
	NeighborhoodModeOut
	// NeighborhoodModeIn traverses incoming edges only.
	NeighborhoodModeIn
)

func ParseNeighborhoodMode

func ParseNeighborhoodMode(s string) (NeighborhoodMode, error)

ParseNeighborhoodMode parses a string to NeighborhoodMode.

func (NeighborhoodMode) String

func (m NeighborhoodMode) String() string

type NeighborhoodResult

type NeighborhoodResult struct {
	// Vertices contains all vertices in the neighborhood (including seeds).
	Vertices []uint32

	// VerticesExternal contains external node IDs of vertices in the neighborhood.
	VerticesExternal []uint64

	// Distances maps each vertex to its distance from the nearest seed.
	Distances []uint32

	// DistanceMap provides O(1) lookup of distance by vertex index.
	DistanceMap map[uint32]uint32

	// NumVertices is the total number of vertices in the neighborhood.
	NumVertices uint32

	// VerticesByDistance groups vertices by their distance from seeds.
	VerticesByDistance map[uint32][]uint32

	// Meta contains algorithm metadata.
	Meta map[string]string
}

NeighborhoodResult contains the result of a neighborhood query.

func ComputeNeighborhood

func ComputeNeighborhood(
	ctx context.Context,
	version *GraphVersion,
	view *View,
	seedIDs []uint64,
	config *NeighborhoodConfig,
	shimCfg *NeighborhoodShimConfig,
) (*NeighborhoodResult, error)

ComputeNeighborhood finds all vertices within a specified number of hops from seed vertices using igraph.

This function requires a configured ShimGraph. The igraph C shim is always used for optimal performance.

func (*NeighborhoodResult) Contains

func (r *NeighborhoodResult) Contains(vertexIdx uint32) bool

Contains checks if a vertex is in the neighborhood.

func (*NeighborhoodResult) GetDistance

func (r *NeighborhoodResult) GetDistance(vertexIdx uint32) (uint32, bool)

GetDistance returns the distance of a vertex from the nearest seed. Returns (distance, true) if found, (0, false) if vertex not in neighborhood.

func (*NeighborhoodResult) GetImmediateNeighbors

func (r *NeighborhoodResult) GetImmediateNeighbors() []uint32

GetImmediateNeighbors returns vertices at distance 1 (immediate neighbors of seeds).

func (*NeighborhoodResult) GetSeeds

func (r *NeighborhoodResult) GetSeeds() []uint32

GetSeeds returns the seed vertices (at distance 0).

func (*NeighborhoodResult) GetVerticesAtDistance

func (r *NeighborhoodResult) GetVerticesAtDistance(distance uint32) []uint32

GetVerticesAtDistance returns all vertices at a specific distance from seeds.

func (*NeighborhoodResult) GetVerticesAtDistanceExternal

func (r *NeighborhoodResult) GetVerticesAtDistanceExternal(distance uint32, version *GraphVersion) []uint64

GetVerticesAtDistanceExternal returns external IDs of vertices at a specific distance.

type NeighborhoodShimConfig

type NeighborhoodShimConfig struct {
	// ShimGraph is the shim graph to use (required).
	ShimGraph *shim.Graph

	// ShimView is the shim view to use for view-based queries (optional).
	ShimView *shim.View
}

NeighborhoodShimConfig holds shim configuration for neighborhood computation.

type PageRankConfig

type PageRankConfig struct {
	// Damping is the damping factor (probability of following a link vs random jump).
	// Typical value: 0.85. Default: 0.85.
	Damping float64

	// MaxIterations is the maximum number of iterations.
	// Default: 100.
	MaxIterations uint32

	// Epsilon is the convergence tolerance (stop when change < epsilon).
	// Default: 1e-6.
	Epsilon float64

	// WeightColumn specifies the edge weight column to use (empty = unweighted).
	WeightColumn string
}

PageRankConfig contains configuration for PageRank computation.

func DefaultPageRankConfig

func DefaultPageRankConfig() *PageRankConfig

DefaultPageRankConfig returns a PageRankConfig with sensible defaults.

type PageRankResult

type PageRankResult struct {
	// Scores contains the PageRank score for each vertex.
	// Higher scores indicate more "important" nodes in the link structure.
	Scores []float64

	// MaxScore is the maximum PageRank score found.
	MaxScore float64

	// MinScore is the minimum PageRank score found.
	MinScore float64

	// Iterations is the number of iterations performed.
	Iterations uint32

	// Converged indicates whether the algorithm converged.
	Converged bool

	// Meta contains algorithm metadata.
	Meta map[string]string
}

PageRankResult contains the result of PageRank computation.

func ComputePageRank

func ComputePageRank(
	ctx context.Context,
	version *GraphVersion,
	view *View,
	config *PageRankConfig,
	shimCfg *PageRankShimConfig,
) (*PageRankResult, error)

ComputePageRank computes the PageRank of all vertices.

PageRank is an algorithm used to rank web pages based on their link structure. In a network context, it measures the "importance" of nodes based on the structure of incoming links. Nodes with high PageRank receive many links from other high-PageRank nodes.

PageRank computation requires the igraph shim.

func (*PageRankResult) GetTopKVertices

func (r *PageRankResult) GetTopKVertices(k int) []struct {
	VertexIdx uint32
	Score     float64
}

GetTopKVertices returns the top K vertices by PageRank score.

func (*PageRankResult) GetVertexPageRank

func (r *PageRankResult) GetVertexPageRank(vertexIdx uint32) (float64, bool)

GetVertexPageRank returns the PageRank score for a specific vertex.

func (*PageRankResult) GetVertexPageRankByExternalID

func (r *PageRankResult) GetVertexPageRankByExternalID(nodeID uint64, version *GraphVersion) (float64, bool)

GetVertexPageRankByExternalID returns the PageRank for a vertex given its external ID.

type PageRankShimConfig

type PageRankShimConfig struct {
	// ShimGraph is the shim graph to use (required).
	ShimGraph *shim.Graph

	// ShimView is the shim view to use for view-based queries (optional).
	ShimView *shim.View
}

PageRankShimConfig holds shim configuration for PageRank computation.

type PersistenceConfig

type PersistenceConfig struct {
	// Enabled indicates whether persistence is enabled.
	Enabled bool

	// DataDir is the directory for snapshot files.
	DataDir string

	// SnapshotInterval is how often to auto-save snapshots.
	// 0 means no auto-save.
	SnapshotInterval time.Duration

	// MaxSnapshots is the maximum number of snapshots to retain.
	MaxSnapshots int

	// CompressSnapshots enables gzip compression for snapshots.
	CompressSnapshots bool
}

PersistenceConfig holds configuration for the persistence layer.

func DefaultPersistenceConfig

func DefaultPersistenceConfig() PersistenceConfig

DefaultPersistenceConfig returns default persistence configuration.

type PersistenceManager

type PersistenceManager struct {
	// contains filtered or unexported fields
}

PersistenceManager handles snapshot export and import.

func NewPersistenceManager

func NewPersistenceManager(
	config PersistenceConfig,
	logger *slog.Logger,
	versionStore *VersionStore,
	resultStore *ResultStore,
	viewStore *ViewStore,
) *PersistenceManager

NewPersistenceManager creates a new persistence manager.

func (*PersistenceManager) LoadSnapshot

func (pm *PersistenceManager) LoadSnapshot() error

LoadSnapshot loads the most recent snapshot.

func (*PersistenceManager) SaveSnapshot

func (pm *PersistenceManager) SaveSnapshot() error

SaveSnapshot creates a snapshot of current state.

func (*PersistenceManager) Stats

Stats returns persistence statistics.

func (*PersistenceManager) Stop

func (pm *PersistenceManager) Stop()

Stop stops the persistence manager.

type PersistenceStats

type PersistenceStats struct {
	Enabled            bool
	SnapshotCount      int
	TotalSizeBytes     int64
	LatestSnapshotTime time.Time
	DataDir            string
}

PersistenceStats holds persistence statistics.

type ResultStore

type ResultStore struct {
	// contains filtered or unexported fields
}

ResultStore stores algorithm results with caching and LRU eviction.

func NewResultStore

func NewResultStore(maxItems int, maxMemory uint64, ttl time.Duration) *ResultStore

NewResultStore creates a new ResultStore.

func (*ResultStore) Close

func (rs *ResultStore) Close()

Close stops the background cleanup goroutine.

func (*ResultStore) Count

func (rs *ResultStore) Count() int

Count returns the number of results in the store.

func (*ResultStore) Delete

func (rs *ResultStore) Delete(resultID string) error

Delete removes a result by ID.

func (*ResultStore) Get

func (rs *ResultStore) Get(resultID string) (*AlgoResult, error)

Get retrieves and pins a result by ID.

func (*ResultStore) GetByKey

func (rs *ResultStore) GetByKey(versionID string, algoKind AlgoKind, paramsHash string) (*AlgoResult, bool)

GetByKey retrieves a cached result by cache key.

func (*ResultStore) Stats

func (rs *ResultStore) Stats() ResultStoreStats

Stats returns store statistics.

func (*ResultStore) Store

func (rs *ResultStore) Store(result *AlgoResult) error

Store adds a result to the store.

func (*ResultStore) TotalMemory

func (rs *ResultStore) TotalMemory() uint64

TotalMemory returns total memory usage.

type ResultStoreStats

type ResultStoreStats struct {
	TotalItems  int
	TotalMemory uint64
	MaxItems    int
	MaxMemory   uint64
}

ResultStoreStats contains statistics about the result store.

type Scheduler

type Scheduler struct {
	// contains filtered or unexported fields
}

Scheduler manages job execution with concurrency limits.

func NewScheduler

func NewScheduler(config SchedulerConfig, logger *slog.Logger) *Scheduler

NewScheduler creates a new job scheduler.

func (*Scheduler) Acquire

func (s *Scheduler) Acquire(ctx context.Context) (func(), error)

Acquire acquires a slot, blocking until available or context canceled. Returns a release function if successful.

func (*Scheduler) CancelJob

func (s *Scheduler) CancelJob(jobID string) bool

CancelJob cancels a job by ID.

func (*Scheduler) GetJob

func (s *Scheduler) GetJob(jobID string) (*Job, bool)

GetJob returns a job by ID.

func (*Scheduler) RunSync

func (s *Scheduler) RunSync(ctx context.Context, execFn func(ctx context.Context) (*AlgoResult, error)) (*AlgoResult, error)

RunSync executes a job synchronously (bypasses queue). Useful for high-priority or cache-hit scenarios.

func (*Scheduler) Shutdown

func (s *Scheduler) Shutdown(ctx context.Context) error

Shutdown gracefully shuts down the scheduler.

func (*Scheduler) Stats

func (s *Scheduler) Stats() SchedulerStats

Stats returns scheduler statistics.

func (*Scheduler) Submit

func (s *Scheduler) Submit(job *Job) error

Submit submits a job for execution. Returns error if queue is full.

func (*Scheduler) TenantJobCount

func (s *Scheduler) TenantJobCount(tenantID string) int32

TenantJobCount returns the number of active jobs for a tenant.

func (*Scheduler) TryAcquire

func (s *Scheduler) TryAcquire() func()

TryAcquire attempts to acquire a slot without blocking. Returns a release function if successful, nil otherwise.

type SchedulerConfig

type SchedulerConfig struct {
	MaxParallelJobs int
	MaxQueueSize    int
	JobTimeout      time.Duration
}

SchedulerConfig holds configuration for the scheduler.

func DefaultSchedulerConfig

func DefaultSchedulerConfig() SchedulerConfig

DefaultSchedulerConfig returns default scheduler configuration.

type SchedulerStats

type SchedulerStats struct {
	ActiveJobs      int64
	QueuedJobs      int64
	TotalJobs       int64
	CompletedOK     int64
	CompletedErr    int64
	MaxParallelJobs int
	MaxQueueSize    int
}

SchedulerStats holds scheduler statistics.

type ShortestPathConfig

type ShortestPathConfig struct {
	// ShimGraph is the shim graph to use (required).
	ShimGraph *shim.Graph
}

ShortestPathConfig holds configuration for shortest path computation.

type ShortestPathResult

type ShortestPathResult struct {
	// PathVertices contains the external node IDs in the path (source to target)
	PathVertices []uint64
	// PathEdges contains the edge indices in the path
	PathEdges []int
	// TotalCost is the total path cost (hop count for unweighted, sum of weights for weighted)
	TotalCost float64
	// Found indicates whether a path was found
	Found bool
	// Source indicates the algorithm source ("igraph")
	Source string
}

ShortestPathResult contains the result of a shortest path computation.

func ComputeShortestPath

func ComputeShortestPath(
	version *GraphVersion,
	view *View,
	sourceID, targetID uint64,
	weighted bool,
	returnEdges, returnVertices bool,
	cfg *ShortestPathConfig,
) (*ShortestPathResult, error)

ComputeShortestPath computes the shortest path between two nodes using igraph. If view is nil, uses the full graph. If weighted is true, uses edge weights. Otherwise uses hop count.

This function requires a configured ShimGraph. The igraph C shim is always used for optimal performance.

func ComputeShortestPathBatch

func ComputeShortestPathBatch(
	version *GraphVersion,
	view *View,
	sources, targets []uint64,
	weighted bool,
	cfg *ShortestPathConfig,
) ([]*ShortestPathResult, error)

ComputeShortestPathBatch computes shortest paths for multiple source-target pairs.

type SnapshotData

type SnapshotData struct {
	Version   string    `json:"version"`
	Timestamp time.Time `json:"timestamp"`

	// Graph versions (metadata only, not full graph data)
	GraphVersions []GraphVersionSnapshot `json:"graph_versions"`

	// Algorithm results
	AlgoResults []AlgoResultSnapshot `json:"algo_results"`

	// Views
	Views []ViewSnapshot `json:"views"`
}

SnapshotData holds the complete snapshot of service state.

type TraceSpan

type TraceSpan struct {
	Name      string
	StartTime time.Time
	Duration  time.Duration
	Tags      map[string]string
}

TraceSpan represents a timing span during algorithm execution.

func NewTraceSpan

func NewTraceSpan(name string) *TraceSpan

NewTraceSpan creates a new trace span starting now.

func (*TraceSpan) AddTag

func (s *TraceSpan) AddTag(key, value string) *TraceSpan

AddTag adds a tag to the span.

func (*TraceSpan) End

func (s *TraceSpan) End()

End marks the span as complete.

type ValidationError

type ValidationError struct {
	Code    string
	Message string
	Details map[string]interface{}
}

ValidationError contains details about a validation failure.

func (*ValidationError) Error

func (e *ValidationError) Error() string

type ValidationLimits

type ValidationLimits struct {
	MaxVertices uint64
	MaxEdges    uint64
}

ValidationLimits defines size limits for validation.

func DefaultValidationLimits

func DefaultValidationLimits() ValidationLimits

DefaultValidationLimits returns default validation limits.

type ValidationResult

type ValidationResult struct {
	Valid    bool
	Errors   []*ValidationError
	Warnings []string
}

ValidationResult contains the result of build validation.

func (*ValidationResult) AddError

func (r *ValidationResult) AddError(code, message string, details map[string]interface{})

AddError adds an error to the validation result.

func (*ValidationResult) AddWarning

func (r *ValidationResult) AddWarning(message string)

AddWarning adds a warning to the validation result.

type VersionStore

type VersionStore struct {
	// contains filtered or unexported fields
}

VersionStore stores GraphVersion objects and manages their lifecycle. It implements RCU-style pin/unpin for safe concurrent access.

func NewVersionStore

func NewVersionStore(cleanupTTL time.Duration, memoryLimit uint64) *VersionStore

NewVersionStore creates a new VersionStore.

func (*VersionStore) Cleanup

func (vs *VersionStore) Cleanup() int

Cleanup removes versions that are marked for cleanup, past TTL, and have no refs.

func (*VersionStore) Count

func (vs *VersionStore) Count() int

Count returns the number of versions in the store.

func (*VersionStore) Delete

func (vs *VersionStore) Delete(versionID string) error

Delete immediately removes a version (use with caution). Returns error if version is still referenced.

func (*VersionStore) Get

func (vs *VersionStore) Get(versionID string) (*GraphVersion, error)

Get retrieves and pins a GraphVersion by ID. The caller must call Unpin on the version when done.

func (*VersionStore) GetWithoutPin

func (vs *VersionStore) GetWithoutPin(versionID string) (*GraphVersion, error)

GetWithoutPin retrieves a GraphVersion without pinning. Use only for read-only operations that don't escape the call.

func (*VersionStore) ListVersionIDs

func (vs *VersionStore) ListVersionIDs() []string

ListVersionIDs returns all version IDs in the store.

func (*VersionStore) MarkForCleanup

func (vs *VersionStore) MarkForCleanup(versionID string)

MarkForCleanup marks a version for eventual cleanup. The version won't be removed until TTL expires and refcount is zero.

func (*VersionStore) MemoryLimit

func (vs *VersionStore) MemoryLimit() uint64

MemoryLimit returns the configured memory limit.

func (*VersionStore) Stats

func (vs *VersionStore) Stats() VersionStoreStats

Stats returns store statistics.

func (*VersionStore) Store

func (vs *VersionStore) Store(version *GraphVersion) error

Store adds a GraphVersion to the store.

func (*VersionStore) TotalMemory

func (vs *VersionStore) TotalMemory() uint64

TotalMemory returns the total estimated memory usage.

type VersionStoreStats

type VersionStoreStats struct {
	TotalVersions    int
	TotalMemory      uint64
	MemoryLimit      uint64
	MarkedForCleanup int
}

VersionStoreStats contains statistics about the version store.

type VertexMask

type VertexMask struct {
	// contains filtered or unexported fields
}

VertexMask provides backward-compatible access to vertex inclusion status. Returns a wrapper that implements index-based access. DEPRECATED: Use VertexMaskBitmap() for direct bitmap access in new code.

type View

type View struct {
	// Identity
	ID        string
	VersionID string
	GraphName string
	CreatedAt time.Time

	// SpecHash for caching - hash of the ViewSpec used to create this view
	SpecHash string

	// Cached counts of included elements
	VCount uint64
	ECount uint64
	// contains filtered or unexported fields
}

View represents a filtered subgraph of a GraphVersion. Views use roaring bitmaps for edge/vertex masks for memory-efficient storage.

func NewView

func NewView(version *GraphVersion) *View

NewView creates a new empty View from a GraphVersion. All edges and vertices are initially included.

func NewViewFromSpec

func NewViewFromSpec(version *GraphVersion, spec *gepb.ViewSpec) (*View, error)

NewViewFromSpec creates a View by applying a ViewSpec to a GraphVersion.

func (*View) ApplyEdgeFilter

func (v *View) ApplyEdgeFilter(filter *gepb.EdgeFilter) error

ApplyEdgeFilter applies edge predicates to filter the view.

func (*View) ApplyExclusions

func (v *View) ApplyExclusions(excludeVertices, excludeEdges []uint64)

ApplyExclusions removes specific vertices and edges from the view.

func (*View) ApplyInducedVertices

func (v *View) ApplyInducedVertices(vertices []uint64) error

ApplyInducedVertices restricts the view to only the specified vertices and edges between them.

func (*View) ApplyNeighborhood

func (v *View) ApplyNeighborhood(spec *gepb.NeighborhoodSpec) error

ApplyNeighborhood expands the view to include the neighborhood around seed vertices.

func (*View) ApplyVertexFilter

func (v *View) ApplyVertexFilter(filter *gepb.VertexFilter) error

ApplyVertexFilter applies vertex predicates to filter the view.

func (*View) Clone

func (v *View) Clone() *View

Clone creates a deep copy of the view.

func (*View) ContainsEdge

func (v *View) ContainsEdge(edgeIdx int) bool

ContainsEdge checks if an edge (by index) is in the view.

func (*View) ContainsVertex

func (v *View) ContainsVertex(nodeID uint64) bool

ContainsVertex checks if a vertex (by external ID) is in the view.

func (*View) ContainsVertexByIndex

func (v *View) ContainsVertexByIndex(idx uint32) bool

ContainsVertexByIndex checks if a vertex (by internal index) is in the view.

func (*View) Difference

func (v *View) Difference(other *View) (*View, error)

Difference creates a new view with elements from this view that are not in other. Both views must be based on the same GraphVersion.

func (*View) EdgeMaskBitmap

func (v *View) EdgeMaskBitmap() *roaring.Bitmap

EdgeMaskBitmap returns the underlying roaring bitmap for edge mask. This is the preferred way to access edge mask in new code.

func (*View) EdgeMaskContains

func (v *View) EdgeMaskContains(idx uint32) bool

EdgeMaskContains checks if an edge index is included in the view.

func (*View) EstimateMemory

func (v *View) EstimateMemory() uint64

EstimateMemory returns the estimated memory usage in bytes.

func (*View) GetEdgeIndices

func (v *View) GetEdgeIndices() []uint32

GetEdgeIndices returns the indices of included edges.

func (*View) GetEdgeMaskBytes

func (v *View) GetEdgeMaskBytes() []byte

GetEdgeMaskBytes returns the edge mask as a packed byte array for shim compatibility. Each bit represents one edge (bit 0 of byte 0 = edge 0, etc.).

func (*View) GetEdges

func (v *View) GetEdges() (src, dst []uint32)

GetEdges returns the filtered edge arrays (using compact indices).

func (*View) GetEdgesWithWeights

func (v *View) GetEdgesWithWeights() (src, dst []uint32, weights []float32)

GetEdgesWithWeights returns filtered edges with their weights.

func (*View) GetVersion

func (v *View) GetVersion() *GraphVersion

GetVersion returns the underlying GraphVersion.

func (*View) GetVertexIndices

func (v *View) GetVertexIndices() []uint32

GetVertexIndices returns the indices of included vertices.

func (*View) GetVertexMaskBytes

func (v *View) GetVertexMaskBytes() []byte

GetVertexMaskBytes returns the vertex mask as a packed byte array for shim compatibility.

func (*View) GetVertices

func (v *View) GetVertices() []uint64

GetVertices returns the external node IDs of included vertices.

func (*View) Intersect

func (v *View) Intersect(other *View) (*View, error)

Intersect creates a new view that is the intersection of this view and another. Both views must be based on the same GraphVersion.

func (*View) Pin

func (v *View) Pin()

Pin increments the reference count.

func (*View) RefCount

func (v *View) RefCount() int

RefCount returns the current reference count.

func (*View) Stats

func (v *View) Stats() ViewStats

Stats returns statistics about the view.

func (*View) Union

func (v *View) Union(other *View) (*View, error)

Union creates a new view that is the union of this view and another. Both views must be based on the same GraphVersion.

func (*View) Unpin

func (v *View) Unpin() bool

Unpin decrements the reference count. Returns true if the view can be cleaned up.

func (*View) VertexMaskBitmap

func (v *View) VertexMaskBitmap() *roaring.Bitmap

VertexMaskBitmap returns the underlying roaring bitmap for vertex mask. This is the preferred way to access vertex mask in new code.

func (*View) VertexMaskContains

func (v *View) VertexMaskContains(idx uint32) bool

VertexMaskContains checks if a vertex index is included in the view.

type ViewManager

type ViewManager struct {
	// contains filtered or unexported fields
}

ViewManager orchestrates view creation and caching.

func NewViewManager

func NewViewManager(viewStore *ViewStore, versionStore *VersionStore, logger *slog.Logger) *ViewManager

NewViewManager creates a new ViewManager.

func (*ViewManager) CreateView

func (vm *ViewManager) CreateView(version *GraphVersion, spec *gepb.ViewSpec) (*View, error)

CreateView creates a new view from a GraphVersion and ViewSpec. It checks the cache first and returns a cached view if available.

func (*ViewManager) DeleteView

func (vm *ViewManager) DeleteView(viewID string) error

DeleteView removes a view from the store.

func (*ViewManager) GetView

func (vm *ViewManager) GetView(viewID string) (*View, error)

GetView retrieves a view by ID.

func (*ViewManager) GetViewForVersion

func (vm *ViewManager) GetViewForVersion(versionID string, spec *gepb.ViewSpec) (*View, error)

GetViewForVersion retrieves or creates a view for a version with the given spec. If spec is nil, returns a full-graph view.

func (*ViewManager) ReleaseView

func (vm *ViewManager) ReleaseView(viewID string) error

ReleaseView releases a view, decrementing its reference count.

func (*ViewManager) Stats

func (vm *ViewManager) Stats() ViewManagerStats

Stats returns statistics about the view manager.

func (*ViewManager) StoreView

func (vm *ViewManager) StoreView(view *View) error

StoreView stores a view in the cache. Use this for views created externally (e.g., corridor views).

func (*ViewManager) ValidateViewSpec

func (vm *ViewManager) ValidateViewSpec(spec *gepb.ViewSpec) error

ValidateViewSpec validates a ViewSpec without creating a view.

type ViewManagerStats

type ViewManagerStats struct {
	CachedViews int
	TotalMemory uint64
	MaxViews    int
	MaxMemory   uint64
}

ViewManagerStats contains statistics about the view manager.

type ViewSnapshot

type ViewSnapshot struct {
	ID        string    `json:"id"`
	VersionID string    `json:"version_id"`
	SpecHash  string    `json:"spec_hash"`
	VCount    uint64    `json:"vcount"`
	ECount    uint64    `json:"ecount"`
	CreatedAt time.Time `json:"created_at"`

	// Vertex and edge sets for restoration
	VertexSet []uint64 `json:"vertex_set"`
}

ViewSnapshot holds serializable view data.

type ViewStats

type ViewStats struct {
	VertexCount      uint64
	EdgeCount        uint64
	VertexMaskBytes  uint64
	EdgeMaskBytes    uint64
	TotalMemoryBytes uint64
	Density          float64 // ECount / (VCount * (VCount - 1)) for directed
}

ViewStats returns statistics about the view.

type ViewStore

type ViewStore struct {
	// contains filtered or unexported fields
}

ViewStore stores View objects with caching and LRU eviction.

func NewViewStore

func NewViewStore(maxItems int, maxMemory uint64, ttl time.Duration) *ViewStore

NewViewStore creates a new ViewStore.

func (*ViewStore) Count

func (vs *ViewStore) Count() int

Count returns the number of views in the store.

func (*ViewStore) Delete

func (vs *ViewStore) Delete(viewID string) error

Delete removes a view by ID.

func (*ViewStore) Get

func (vs *ViewStore) Get(viewID string) (*View, error)

Get retrieves and pins a view by ID.

func (*ViewStore) GetByKey

func (vs *ViewStore) GetByKey(versionID, specHash string) (*View, bool)

GetByKey retrieves a cached view by version ID and spec hash.

func (*ViewStore) ListViewIDs

func (vs *ViewStore) ListViewIDs() []string

ListViewIDs returns all view IDs in the store.

func (*ViewStore) Stats

func (vs *ViewStore) Stats() ViewStoreStats

Stats returns store statistics.

func (*ViewStore) Store

func (vs *ViewStore) Store(view *View) error

Store adds a view to the store.

func (*ViewStore) TotalMemory

func (vs *ViewStore) TotalMemory() uint64

TotalMemory returns total memory usage.

type ViewStoreStats

type ViewStoreStats struct {
	TotalItems  int
	TotalMemory uint64
	MaxItems    int
	MaxMemory   uint64
}

ViewStoreStats contains statistics about the view store.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址