examples/

directory
v0.10.0 Latest Latest
Warning

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

Go to latest
Published: Jul 24, 2026 License: MIT

README

GoGraph examples

This directory contains 34 runnable, self-documenting examples of GoGraph — from a shortest-path query to a persistent, kill -9-safe REST service. Each example serves the two objectives the project sets for examples: it demonstrates a capability in a realistic end-to-end application, and it exercises the module through a realistic, seeded, scale-parametrised scenario while collecting evidence — timing and throughput, memory and allocation, contention, and correctness. Each is a standalone package main with its own README.md, and each pins its deterministic facts with a regression test so the results below are guaranteed by CI, not just illustrative.

Run any example at its small deterministic default, or scale it up:

go run ./examples/<NN_name>                 # small deterministic default
go run ./examples/<NN_name> -h              # the scale/shape flags it accepts

Output is split into deterministic facts (bare lines, pinned by the test) and volatile telemetry (lines prefixed with # — durations, throughput, heap — which vary per run and per machine).

For the full contract every example follows — the realistic seeded generator, scale knobs, the evidence taxonomy, the # telemetry convention, testable extraction, and the per-example README.md template — see ../docs/examples-standard.md. examples/26_social_scale_bench is the reference end state.

Basics

Example What it demonstrates Evidence reported
01_basic Build a seeded weighted directed road network, freeze it into an immutable CSR snapshot, and run single-source search.Dijkstra, reading back distances and reconstructed routes. Build throughput, Dijkstra query latency, reachable-node count, live heap.
02_property_graph Build a seeded labelled property graph with an optional schema validator, run label- and property-indexed MATCH-style queries, and read typed properties back out. Build throughput, indexed-query latency, live heap and bytes per node.
03_advanced_algorithms Run four algorithms over one CSR snapshot of a seeded scale-free graph — BFS, Dijkstra, exact Brandes betweenness centrality, and PageRank. Per-algorithm timing, PageRank iterations, transient allocations, live heap.

Persistence and out-of-core

Example What it demonstrates Evidence reported
04_persistence The full durability path over a seeded graph: WAL-committed transactions, a v2 snapshot (CSR + labels + properties), then rebuild from disk with recovery.Open. Commit throughput, WAL/snapshot bytes on disk, recovery time, heap before/after.
05_out_of_core Tier 2 external memory: persist a seeded CSR snapshot as a csrfile, re-open it by mmap, and run semi-external PageRank over the mapped adjacency. On-disk size vs resident heap (the out-of-core advantage), mmap and query time.
17_transactional_log WAL-backed store over a seeded financial ledger with a background checkpointer that folds the log into a self-sufficient snapshot, plus recovery after a simulated crash. Write throughput, WAL bytes folded, snapshot bytes, checkpoint count, recovery time.
18_oocore_pipeline The full out-of-core pipeline over a seeded graph: CSV → CSR → csrfilemmap, then semi-external BFS and PageRank over the mapped region. Per-stage timing (parse/build/write/mmap/BFS/PageRank), on-disk size vs heap.
21_typed_recovery Generic recovery.Open[N, W] over a seeded (int64, float64) graph: round-trip edges (bit-exact float weights), labels, and typed properties through a v2 snapshot. Snapshot bytes, recovery time, heap, and a bit-exact float64 round-trip verification.

Cypher and Bolt

Example What it demonstrates Evidence reported
22_cypher The Cypher engine over a seeded social graph: a label scan with projection and ORDER BY, a WHERE filter, a relationship pattern, and a CREATE in a write transaction. Per-query latency, live heap.
23_bolt_server Bolt v5 end to end over a seeded graph: start the embedded server, connect the official neo4j-go-driver/v5, run many queries across concurrent sessions, and shut down cleanly with no goroutine leak. Query throughput, p50/p95/p99 latency distribution, live heap.
24_social_network_cli A one-shot CLI over a persistent LPG social network with an opt-in seeded scale mode, walking every layer: LPG, WAL + recovery, manual checkpoints, and Cypher reads streamed as JSON Lines. Seed throughput, live heap, per-query latency (via the -evidence flag).
25_software_house_api A persistent, kill -9-safe REST API (stdlib only) over a multi-layer LPG spanning Code/Work/People with an opt-in seeded scale mode, answering change-impact, ownership, and bus-factor questions in Cypher — plus CREATE INDEX/CREATE CONSTRAINT DDL, a CALL db.* schema endpoint, and EXPLAIN proving an index seek, all durable across restart. Graph size, live heap, bytes per element, per-query/seed latency (via /stats).
34_bolt_transactions The Bolt v5 write/transaction surface via the official neo4j-go-driver: BasicAuth (accept/reject), a committed ExecuteWrite, a rolled-back explicit transaction, a FAILURE + RESET recovery, and one read over an encrypted bolt+ssc (TLS) connection. Six wire-level guarantees pinned as facts; scenario wall-clock.

Interchange

Example What it demonstrates Evidence reported
06_csv_import The serialisation round-trip over a seeded edge list: read it with csv.ReadInto, then write the graph back out as CSV and as newline-delimited JSON (JSON Lines). Parse and serialise throughput (rows/s, MiB/s), bytes in/out, live heap.
07_graphml_roundtrip Graph interchange I/O over a seeded graph: parse a GraphML document with graphml.ReadInto, then serialise it back out to GraphML and Graphviz DOT, edges and weights intact. Parse and serialise throughput, bytes in/out per format, live heap.

Algorithms

Example What it demonstrates Evidence reported
08_pagerank PageRank over a seeded directed scale-free web (heavy-tailed in-degree), reading back the per-node rank vector ordered most- to least-important. Convergence iterations, timing, transient allocations, live heap.
09_leiden Modularity-optimising community detection with community.Leiden over a seeded stochastic-block-model graph of planted communities. Detection timing, achieved modularity, communities found.
10_dimacs9_routing Build a synthetic DIMACS 9 road network at scale, run a concrete search.Dijkstra route, and drive a seeded random source-target probe workload. Query throughput, p50/p95/p99 latency distribution, live heap.
14_routing_alternatives Three shortest-path flavours over one seeded k-NN spatial graph: Dijkstra, Yen's k-shortest paths, and search.AStar with an admissible Euclidean heuristic. Per-algorithm timing, nodes expanded (the A* vs Dijkstra advantage), live heap.
15_task_assignment Two bipartite assignment algorithms over a seeded instance: search.Hungarian (cheapest one-to-one assignment) and search.HopcroftKarp (largest matching). Per-algorithm timing, live heap.
16_centrality_analytics A centrality suite over one CSR snapshot of a seeded chain-of-clusters graph: Brandes betweenness plus closeness, harmonic, eigenvector and Katz, label-propagation community detection, and a disconnected-graph pass showing the distance-based measures stay finite. Per-analysis timing, convergence iterations, transient allocations, live heap.
28_negative_weights Negative-weight routing over a seeded layered DAG with rebate edges: search.BellmanFord (a negative-cost-optimal route Dijkstra refuses), ErrNegativeCycle detection under -arbitrage, cross-checked against a Johnson APSP oracle. Relaxation passes, timing, three-way distance agreement.
29_all_pairs All-pairs shortest paths three ways — DijkstraAPSP, FloydWarshall, JohnsonAPSP — asserted identical, then radius/diameter/eccentricity derived from the result. Per-algorithm timing, the O(V²) matrix footprint, three-way agreement.
30_min_spanning_tree Minimum spanning tree over a seeded geographic backbone: PrimMST and KruskalMST cross-checked for equal total weight and edge multiset, with the spanning-forest shape verified via WCC. Per-algorithm timing, total weight, savings vs all links.
32_euler Eulerian route inspection over a network built from edge-disjoint loops: Hierholzer (directed) and HierholzerUndirected find a circuit using every street once; -broken forces ErrNoEulerian. Per-tour timing; each-edge-once and circuit-closure verified as facts.

Real-world recipes

Example What it demonstrates Evidence reported
11_social_network An end-to-end social-network workload over a seeded LPG: PageRank influence ranking, Leiden community detection, and a manual friend-of-friend recommendation walk. Per-stage timing (PageRank/Leiden/FoF), live heap.
12_build_dependency Model a seeded build-dependency DAG, derive a valid build order with search.TopologicalSort (Kahn), and detect a circular dependency with search.TarjanSCC. Per-algorithm timing, DAG statistics, live heap.
13_network_reliability Two resilience analyses over one seeded transit-stub network: single points of failure (articulation points and bridges) and max throughput plus its limiting min-cut bottleneck. Per-analysis timing, max-flow value, min-cut size, live heap.
19_pattern_query The fluent graph/query API over a seeded dependency LPG: MATCH-style pattern queries combining label and property predicates with a one-hop expansion, reading matched properties back out. Per-query latency, matched-row counts, live heap.
20_concurrent_reads The lock-free read contract of a frozen CSR: Dijkstra, BFS, and PageRank run concurrently over one shared immutable seeded snapshot; plus intra-query parallel variants (WCCParallel, CountTrianglesParallel, BetweennessParallel) cross-checked against serial, and a -cap-to-cpus=false sweep to 64/256/1024 readers. Aggregate throughput, scaling across worker counts, serial-vs-parallel speedup, live heap.

Concurrency, transactions and observability

Example What it demonstrates Evidence reported
27_concurrent_txn Transactional isolation under concurrency: N writer goroutines run multi-statement BeginTx transfers and single-statement RunInTx writes while M readers read the total via BeginReadTx, over a WAL-backed engine under -race. Total-balance invariant holds on every read, zero lost updates, writer/reader throughput, contention.
31_metrics_observability The observability facade: install a Prometheus registry via metrics.SetBackend, run a mixed workload (Cypher, search, io/csv, Bolt pool), scrape /metrics, and assert the documented metric names are present. Presence of 12 documented metrics (facts); observed latencies and counts (telemetry).
33_generation_swap The read-mostly MVCC snapshot-swap of graph/generation: readers Acquire/Release while a publisher swaps in successively larger CSR snapshots — no torn reads, correct refcount accounting, under -race. Every read consistent, refcount accounted, read throughput, distinct generations observed.

Benchmarks

Example What it demonstrates Evidence reported
26_social_scale_bench A large-scale social network (up to 1M users, 30k articles, FRIEND and LIKE edges) built in memory and queried with Cypher — the reference end state for this standard, scale-parametrised via flags. Build throughput, Go heap footprint, bytes per edge, per-query latency.

Directories

Path Synopsis
Example 01_basic — build a weighted directed transport network, freeze it to an immutable CSR snapshot, and run a single-source Dijkstra shortest-paths query with route reconstruction.
Example 01_basic — build a weighted directed transport network, freeze it to an immutable CSR snapshot, and run a single-source Dijkstra shortest-paths query with route reconstruction.
Example 02_property_graph — build a labelled property graph (LPG) with an optional type schema, then run label- and property-indexed MATCH-style queries and read the typed properties back out.
Example 02_property_graph — build a labelled property graph (LPG) with an optional type schema, then run label- and property-indexed MATCH-style queries and read the typed properties back out.
Example 03_advanced_algorithms — runs four algorithms over one shared, immutable CSR snapshot: BFS, Dijkstra, exact Brandes betweenness centrality, and PageRank — and reports per-algorithm evidence.
Example 03_advanced_algorithms — runs four algorithms over one shared, immutable CSR snapshot: BFS, Dijkstra, exact Brandes betweenness centrality, and PageRank — and reports per-algorithm evidence.
Example 04_persistence — the full GoGraph durability path on a real directory, driven at a configurable, reproducible scale.
Example 04_persistence — the full GoGraph durability path on a real directory, driven at a configurable, reproducible scale.
Example 05_out_of_core — Tier 2 external memory: build a scale-free web graph, persist its CSR adjacency as an on-disk csrfile, re-open it by mmap, and run semi-external PageRank directly over the mapped region.
Example 05_out_of_core — Tier 2 external memory: build a scale-free web graph, persist its CSR adjacency as an on-disk csrfile, re-open it by mmap, and run semi-external PageRank directly over the mapped region.
Example 06_csv_import — an interchange round-trip benchmark for the edge-list serialisers: generate a seeded follower graph as CSV in memory, parse it back with csv.ReadIntoCtx, then re-serialise the resulting graph as CSV with csv.WriteCtx and as newline-delimited JSON (JSON Lines) with jsonl.WriteCtx, measuring each leg.
Example 06_csv_import — an interchange round-trip benchmark for the edge-list serialisers: generate a seeded follower graph as CSV in memory, parse it back with csv.ReadIntoCtx, then re-serialise the resulting graph as CSV with csv.WriteCtx and as newline-delimited JSON (JSON Lines) with jsonl.WriteCtx, measuring each leg.
Example 07_graphml_roundtrip — a GraphML interchange round-trip over a realistic, seeded link graph.
Example 07_graphml_roundtrip — a GraphML interchange round-trip over a realistic, seeded link graph.
Example 08_pagerank — runs PageRank over a seeded, scale-free directed web and reports the most authoritative pages, most to least important.
Example 08_pagerank — runs PageRank over a seeded, scale-free directed web and reports the most authoritative pages, most to least important.
Example 09_leiden — modularity-optimising community detection with community.Leiden over a realistic, seeded planted-partition graph.
Example 09_leiden — modularity-optimising community detection with community.Leiden over a realistic, seeded planted-partition graph.
Example 10_dimacs9_routing — build a deterministic synthetic road network with the DIMACS 9 harness, freeze it into an immutable CSR snapshot, run a concrete single-source shortest-paths query (search.Dijkstra) that reconstructs a route, and measure search performance with a distribution of random probe queries.
Example 10_dimacs9_routing — build a deterministic synthetic road network with the DIMACS 9 harness, freeze it into an immutable CSR snapshot, run a concrete single-source shortest-paths query (search.Dijkstra) that reconstructs a route, and measure search performance with a distribution of random probe queries.
Example 11_social_network — an end-to-end social-network workload over a labelled property graph (LPG): PageRank influence ranking, Leiden community detection, a manual friend-of-friend recommendation walk, and a structural-analytics pass (k-core, triangles, diameter, reachability), all over ONE seeded, scale-parametrised social graph.
Example 11_social_network — an end-to-end social-network workload over a labelled property graph (LPG): PageRank influence ranking, Leiden community detection, a manual friend-of-friend recommendation walk, and a structural-analytics pass (k-core, triangles, diameter, reachability), all over ONE seeded, scale-parametrised social graph.
Example 12_build_dependency — model a software build-dependency graph, derive a valid build order with search.TopologicalSort (Kahn's algorithm), and detect a circular dependency with search.TarjanSCC.
Example 12_build_dependency — model a software build-dependency graph, derive a valid build order with search.TopologicalSort (Kahn's algorithm), and detect a circular dependency with search.TarjanSCC.
Example 13_network_reliability — a suite of resilience analyses over ONE synthetic communication backbone, derived from a single capacitated edge list:
Example 13_network_reliability — a suite of resilience analyses over ONE synthetic communication backbone, derived from a single capacitated edge list:
Example 14_routing_alternatives — compare three flavours of shortest-path computation on ONE seeded coordinate routing graph: classical single-source Dijkstra, Yen's k-shortest loopless paths for ranked alternatives, and A* driven by a coordinate-based Euclidean heuristic that expands fewer nodes than Dijkstra for the same optimal cost.
Example 14_routing_alternatives — compare three flavours of shortest-path computation on ONE seeded coordinate routing graph: classical single-source Dijkstra, Yen's k-shortest loopless paths for ranked alternatives, and A* driven by a coordinate-based Euclidean heuristic that expands fewer nodes than Dijkstra for the same optimal cost.
Example 15_task_assignment — two bipartite assignment algorithms side by side over one seeded, scale-parametrised worker/task instance: search.Hungarian computes the globally cheapest one-to-one assignment over the full cost matrix, and search.HopcroftKarp computes the largest matching once a feasibility rule prunes the edges.
Example 15_task_assignment — two bipartite assignment algorithms side by side over one seeded, scale-parametrised worker/task instance: search.Hungarian computes the globally cheapest one-to-one assignment over the full cost matrix, and search.HopcroftKarp computes the largest matching once a feasibility rule prunes the edges.
Example 16_centrality_analytics — runs a suite of analytics over one shared, immutable CSR snapshot: exact Brandes betweenness centrality, four complementary whole-graph centralities (closeness and harmonic, distance-based; eigenvector and Katz, spectral/walk-based), and label-propagation community detection — with deterministic tie-breaking, and reports per-analysis evidence.
Example 16_centrality_analytics — runs a suite of analytics over one shared, immutable CSR snapshot: exact Brandes betweenness centrality, four complementary whole-graph centralities (closeness and harmonic, distance-based; eigenvector and Katz, spectral/walk-based), and label-propagation community detection — with deterministic tie-breaking, and reports per-analysis evidence.
Example 17_transactional_log — a durable financial ledger: a WAL-backed store with a background checkpointer that folds the log into a self-sufficient on-disk snapshot, plus recovery after a simulated crash.
Example 17_transactional_log — a durable financial ledger: a WAL-backed store with a background checkpointer that folds the log into a self-sufficient on-disk snapshot, plus recovery after a simulated crash.
Example 18_oocore_pipeline — the full out-of-core (Tier 2) pipeline: generate a directed web-link graph as a CSV edge list, ingest it through the CSV reader, freeze it into a CSR snapshot, persist that snapshot as an on-disk csrfile, re-open the file by mmap, and run semi-external BFS plus PageRank directly over the mapped region.
Example 18_oocore_pipeline — the full out-of-core (Tier 2) pipeline: generate a directed web-link graph as a CSV edge list, ingest it through the CSV reader, freeze it into a CSR snapshot, persist that snapshot as an on-disk csrfile, re-open the file by mmap, and run semi-external BFS plus PageRank directly over the mapped region.
Example 19_pattern_query — the fluent graph/query pattern API at scale.
Example 19_pattern_query — the fluent graph/query pattern API at scale.
Example 20_concurrent_reads — the lock-free read contract of a frozen CSR snapshot, exercised by many concurrent readers.
Example 20_concurrent_reads — the lock-free read contract of a frozen CSR snapshot, exercised by many concurrent readers.
Example 21_typed_recovery — durable recovery of a typed (int64, float64) graph through the canonical recovery.Open[N, W] path.
Example 21_typed_recovery — durable recovery of a typed (int64, float64) graph through the canonical recovery.Open[N, W] path.
Example 22_cypher — the GoGraph Cypher engine, the module's flagship (100% openCypher TCK compliant at the execution level), driven over a realistic, seeded social graph.
Example 22_cypher — the GoGraph Cypher engine, the module's flagship (100% openCypher TCK compliant at the execution level), driven over a realistic, seeded social graph.
Example 23_bolt_server drives the GoGraph Bolt v5 server end to end: it starts the embedded bolt/server over an in-memory labelled property graph, connects the official neo4j-go-driver/v5 as a real client, runs a battery of Cypher queries over driver sessions, and shuts everything down cleanly with no goroutine left behind.
Example 23_bolt_server drives the GoGraph Bolt v5 server end to end: it starts the embedded bolt/server over an in-memory labelled property graph, connects the official neo4j-go-driver/v5 as a real client, runs a battery of Cypher queries over driver sessions, and shuts everything down cleanly with no goroutine left behind.
Package main implements `24_social_network_cli`, an example one-shot CLI that demonstrates how to build, persist and query a labelled property graph for a social-network domain using GoGraph.
Package main implements `24_social_network_cli`, an example one-shot CLI that demonstrates how to build, persist and query a labelled property graph for a social-network domain using GoGraph.
Command 25_software_house_api is a persistent REST WebAPI that demonstrates how to build, query and mutate a multi-layer Labeled Property Graph (LPG) with GoGraph in a production-shaped service.
Command 25_software_house_api is a persistent REST WebAPI that demonstrates how to build, query and mutate a multi-layer Labeled Property Graph (LPG) with GoGraph in a production-shaped service.
Example 26_social_scale_bench — a large-scale social-network benchmark for query performance and resource consumption.
Example 26_social_scale_bench — a large-scale social-network benchmark for query performance and resource consumption.
Example 27_concurrent_txn — transactional ISOLATION and ATOMICITY of the WAL-backed Cypher engine, certified under concurrency and the race detector.
Example 27_concurrent_txn — transactional ISOLATION and ATOMICITY of the WAL-backed Cypher engine, certified under concurrency and the race detector.
Example 28_negative_weights — single-source shortest paths over a graph with NEGATIVE edge weights, using Bellman-Ford where Dijkstra cannot, and cross-checking the result against Johnson's all-pairs reweighting.
Example 28_negative_weights — single-source shortest paths over a graph with NEGATIVE edge weights, using Bellman-Ford where Dijkstra cannot, and cross-checking the result against Johnson's all-pairs reweighting.
Example 29_all_pairs — compute all-pairs shortest paths (APSP) over one shared, immutable CSR snapshot with all three APSP algorithms the module ships — search.DijkstraAPSP, search.FloydWarshall, and search.JohnsonAPSP — cross-check that the three distance matrices are bit-identical, and derive the classical graph metrics (radius, diameter, per-node eccentricity) from the result.
Example 29_all_pairs — compute all-pairs shortest paths (APSP) over one shared, immutable CSR snapshot with all three APSP algorithms the module ships — search.DijkstraAPSP, search.FloydWarshall, and search.JohnsonAPSP — cross-check that the three distance matrices are bit-identical, and derive the classical graph metrics (radius, diameter, per-node eccentricity) from the result.
Example 30_min_spanning_tree — minimum-cost backbone design over one shared, immutable CSR snapshot: it builds a seeded, scale-parametrised geographic site network, then computes its minimum spanning tree with BOTH of GoGraph's MST algorithms — Prim (search.PrimMST) and Kruskal (search.KruskalMST) — and cross-checks them against each other as a correctness oracle.
Example 30_min_spanning_tree — minimum-cost backbone design over one shared, immutable CSR snapshot: it builds a seeded, scale-parametrised geographic site network, then computes its minimum spanning tree with BOTH of GoGraph's MST algorithms — Prim (search.PrimMST) and Kruskal (search.KruskalMST) — and cross-checks them against each other as a correctness oracle.
Example 31_metrics_observability — GoGraph's observability surface, driven end-to-end over a realistic, seeded service-mesh call graph.
Example 31_metrics_observability — GoGraph's observability surface, driven end-to-end over a realistic, seeded service-mesh call graph.
Example 32_euler — Eulerian circuits over a route-inspection network, using Hierholzer's algorithm on both an undirected and a directed graph.
Example 32_euler — Eulerian circuits over a route-inspection network, using Hierholzer's algorithm on both an undirected and a directed graph.
Example 33_generation_swap — the read-mostly MVCC snapshot-swap pattern of graph/generation, under concurrent readers.
Example 33_generation_swap — the read-mostly MVCC snapshot-swap pattern of graph/generation, under concurrent readers.
Example 34_bolt_transactions — the Bolt v5 write and transaction surface, driven end to end with the official neo4j-go-driver against GoGraph's embedded Bolt server.
Example 34_bolt_transactions — the Bolt v5 write and transaction surface, driven end to end with the official neo4j-go-driver against GoGraph's embedded Bolt server.

Jump to

Keyboard shortcuts

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