graph

package
v0.25.1 Latest Latest
Warning

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

Go to latest
Published: Sep 24, 2026 License: MIT Imports: 9 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package graph owns every interaction with the Neo4j derived projection.

PostgreSQL is the source of truth; Neo4j is a projection that can be thrown away and rebuilt at any time (see the Part B plan, "Global Constraints"). Two invariants shape this package:

  1. The projection worker is the ONLY writer. Read paths go through Client.Read, which opens a read-mode session — a Cypher write clause reaching a read session is rejected by the server, so "the read API cannot mutate the graph" is enforced by the transport, not by review.
  2. Relationship types and node labels cannot be parameterised in Cypher. Every literal that ends up concatenated into a query string comes from a code-level whitelist (reltypes.go), never from a database value.

Index

Constants

View Source
const MentionedInRelType = "MENTIONED_IN"

MentionedInRelType is the projection of document_entities. It is not part of the 8-item closed vocabulary (which describes entity-to-entity relations), so it lives as its own constant rather than inside the map.

Variables

This section is empty.

Functions

func AllCypherRelTypes

func AllCypherRelTypes() []string

AllCypherRelTypes returns the 8 entity-to-entity literals, sorted, for use as the allow-set when validating caller-supplied filters.

func ClampEntryLimit

func ClampEntryLimit(n int) int

The four Clamp* wrappers exist so the HTTP layer clamps against exactly the same numbers this package enforces, instead of keeping a second copy of the constants that can drift. The Reader clamps again on its own input — the limit is enforced at the boundary that owns the query, not only at the edge.

func ClampEvidenceLimit

func ClampEvidenceLimit(n int) int

func ClampExpandLimit

func ClampExpandLimit(n int) int

func ClampSearchLimit

func ClampSearchLimit(n int) int

func CypherEntityLabel

func CypherEntityLabel(entityType string) (string, bool)

CypherEntityLabel returns the secondary node label for an entities.type value, and false for anything outside the 4 known types.

func CypherRelType

func CypherRelType(t model.RelationType) (string, bool)

CypherRelType returns the Cypher literal for t, and false when t is not one of the 8 closed-vocabulary values. A false return means "do not project this row" — never "fall back to something".

func EntityTypeValues

func EntityTypeValues() []string

EntityTypeValues returns the 4 entity type values, used by callers that need to validate a filter before building an EntryFilter.

Types

type Client

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

Client owns one driver for the whole process. Sessions are short-lived and never shared between goroutines (a neo4j session is not safe for concurrent use); the driver itself is.

func New

func New(ctx context.Context, cfg Config) (*Client, error)

New validates cfg, constructs the driver and verifies connectivity once. Verification happens here on purpose: callers (collector worker, server wiring) treat a failure as "graph disabled for this process" and must learn about it at startup rather than on the first tick.

func (*Client) Close

func (c *Client) Close(ctx context.Context) error

Close releases the driver's connection pool.

func (*Client) EnsureSchema

func (c *Client) EnsureSchema(ctx context.Context) error

EnsureSchema applies the DDL above. Every statement is IF NOT EXISTS, so repeated calls are safe — the worker calls it once per process on its first successful tick.

One transaction per statement is required, not stylistic: Neo4j refuses to mix schema and data operations inside a single transaction, and batching several schema commands together is also rejected on some versions.

func (*Client) Read

func (c *Client) Read(ctx context.Context, work func(tx neo4j.ManagedTransaction) (any, error)) (any, error)

Read runs work inside a managed READ transaction. Read never opens a write-mode session: that is one of the defence lines behind "the read API cannot change the graph".

func (*Client) Write

func (c *Client) Write(ctx context.Context, work func(tx neo4j.ManagedTransaction) (any, error)) (any, error)

Write runs work inside a managed WRITE transaction. Only the projection worker (and schema bootstrap) may call this.

type Config

type Config struct {
	URI         string
	Username    string
	Password    string
	MaxPoolSize int
	Timeout     time.Duration
}

Config holds the connection settings for the Neo4j projection store.

type EntityHit

type EntityHit struct {
	PgID int64  `json:"entity_id"`
	Name string `json:"name"`
	Type string `json:"type"`
}

EntityHit is one entity matched by prefix search.

type EntryFilter

type EntryFilter struct {
	Since         time.Time
	MinConfidence float64
	EntityTypes   []string
	Limit         int
}

EntryFilter selects the starting nodes of an exploration.

type EntryNode

type EntryNode struct {
	PgID   int64  `json:"entity_id"`
	Name   string `json:"name"`
	Type   string `json:"type"`
	Degree int64  `json:"degree"`
}

EntryNode is one candidate entry point, ranked by degree within the filter.

type EvidenceRef

type EvidenceRef struct {
	DocumentID string     `json:"document_id"`
	SourceType string     `json:"source_type"`
	OccurredAt *time.Time `json:"occurred_at"`
	Confidence float64    `json:"confidence"`
	ObservedAt time.Time  `json:"observed_at"`
}

EvidenceRef points at the document that justified one observation. It carries no document text — the UI links to the existing document API, which is behind the same auth.

type ExpandFilter

type ExpandFilter struct {
	EntityPgID    int64
	Since         time.Time
	MinConfidence float64
	RelTypes      []string
	Limit         int
}

ExpandFilter selects one node's neighbours (always exactly one hop).

type Neighbor

type Neighbor struct {
	PgID      int64     `json:"entity_id"`
	Name      string    `json:"name"`
	Type      string    `json:"type"`
	RelType   string    `json:"rel_type"`
	Direction string    `json:"direction"` // "out" | "in"
	Weight    int64     `json:"weight"`
	LastSeen  time.Time `json:"last_seen"`
}

Neighbor is one entity adjacent to the expanded node. Weight is the number of parallel edges of that type (one edge per Postgres row), i.e. how many times the relation was observed.

type Projector

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

Projector performs the PostgreSQL → Neo4j projection. It is the ONLY writer to the graph; that fact is what replaces the relationship uniqueness constraint Neo4j Community does not offer.

func NewProjector

func NewProjector(c *Client) *Projector

NewProjector returns a Projector writing through c.

func (*Projector) EnsureSchema

func (p *Projector) EnsureSchema(ctx context.Context) error

EnsureSchema forwards to the client so callers only depend on the projector.

func (*Projector) SetLastRelationID

func (p *Projector) SetLastRelationID(ctx context.Context, id int64) error

SetLastRelationID advances the watermark. Callers must only call this after the corresponding batch has been written successfully.

func (*Projector) SetResetToken

func (p *Projector) SetResetToken(ctx context.Context, token string) error

SetResetToken records the rebuild token that produced the current graph.

func (*Projector) State

State reads (creating on first call) the projection bookkeeping node.

func (*Projector) UpsertMentions

func (p *Projector) UpsertMentions(ctx context.Context, rows []model.ProjectionMention) error

UpsertMentions projects document_entities rows as (:Entity)-[:MENTIONED_IN]->(:Document).

:Document carries pgId, sourceType and occurredAt only. Title and content are deliberately absent: a leaked graph volume must expose structure, not conversation text (privacy policy §1).

func (*Projector) UpsertRelations

func (p *Projector) UpsertRelations(ctx context.Context, rows []model.ProjectionRelation) error

UpsertRelations projects a batch of relations. Rows are grouped by relationship type because the type is a Cypher literal that cannot be parameterised; the literal always comes from CypherRelType, never from the row. Rows whose type is outside the whitelist are dropped (counted, not named — privacy policy §4).

The whole batch is one transaction: either the batch lands or the watermark does not move.

func (*Projector) Wipe

func (p *Projector) Wipe(ctx context.Context) error

Wipe deletes the entire graph, including the ProjectionState node — a rebuild has to restart from watermark 0, and leaving the watermark behind would make the rebuilt graph permanently missing everything below it.

Deletion is chunked because a single DETACH DELETE of the whole graph would build one enormous transaction.

type Reader

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

Reader executes the fixed query catalogue. Every method goes through Client.Read (read-mode session, 5s transaction timeout).

func NewReader

func NewReader(c *Client) *Reader

NewReader returns a Reader backed by c.

func (*Reader) EntryPoints

func (r *Reader) EntryPoints(ctx context.Context, f EntryFilter) ([]EntryNode, error)

EntryPoints returns the highest-degree entities matching the filter.

func (*Reader) Evidence

func (r *Reader) Evidence(ctx context.Context, fromPgID, toPgID int64, relType string, limit int) ([]EvidenceRef, error)

Evidence returns the documents backing one (from, to, relType) pair. relType must be one of the whitelisted literals; anything else is refused before a query is issued.

func (*Reader) Expand

func (r *Reader) Expand(ctx context.Context, f ExpandFilter) ([]Neighbor, error)

Expand returns one hop of neighbours around f.EntityPgID.

func (*Reader) SearchEntities

func (r *Reader) SearchEntities(ctx context.Context, prefix string, limit int) ([]EntityHit, error)

SearchEntities does a prefix lookup over normalizedName. The prefix is normalised the same way the projection normalises names, so callers can pass what the user typed.

Jump to

Keyboard shortcuts

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