-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathzgraph-project_dump.txt
More file actions
3586 lines (2809 loc) · 119 KB
/
zgraph-project_dump.txt
File metadata and controls
3586 lines (2809 loc) · 119 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
📦 Dumping from: C:\Workspaces\Zigadel\code\ZLibs\ZGraph
📤 Output: C:\Workspaces\Zigadel\code\ZLibs\ZGraph\project_dump.txt
📁 Max file size: 104857600 bytes
🚫 Ignore rules (in order):
.git
.github
.zig-cache
C:/Workspaces/Zigadel/code/ZLibs/ZGraph/project_dump.txt
🧱 Filtered Tree:
- .dpignore
- .gitignore
- build.zig
- build.zig.zon
- docs
- docs/algorithms
- docs/conversion_strategies.md
- docs/file_specs
- docs/file_specs/zgraph-spec.md
- docs/file_specs/zgraphb-spec.md
- docs/perf_tuning.md
- docs/roadmap.md
- docs/safety_and_threading.md
- docs/storage_design.md
- docs/zson_config.md
- LICENSE
- project_dump.txt
- README.md
- src
- src/lib
- src/lib/algorithms
- src/lib/algorithms/flow
- src/lib/algorithms/flow/edmonds_karp.zig
- src/lib/algorithms/flow/flow.zig
- src/lib/algorithms/flow/ford_fulkerson.zig
- src/lib/algorithms/mst
- src/lib/algorithms/mst/kruskal.zig
- src/lib/algorithms/mst/mst.zig
- src/lib/algorithms/mst/prim.zig
- src/lib/algorithms/shortest_path
- src/lib/algorithms/shortest_path/bellman_ford.zig
- src/lib/algorithms/shortest_path/djikstra.zig
- src/lib/algorithms/shortest_path/floyd_warshall.zig
- src/lib/algorithms/shortest_path/shortest_path.zig
- src/lib/algorithms/spectral
- src/lib/algorithms/spectral/cheeger_inequality.zig
- src/lib/algorithms/spectral/eigenvalues.zig
- src/lib/algorithms/spectral/eigenvectors.zig
- src/lib/algorithms/spectral/graph_fourier_transform.zig
- src/lib/algorithms/spectral/laplacian_matrix.zig
- src/lib/algorithms/spectral/pagerank_spectral.zig
- src/lib/algorithms/spectral/spectral_clustering.zig
- src/lib/algorithms/spectral/spectral.zig
- src/lib/algorithms/traversal
- src/lib/algorithms/traversal/bfs.zig
- src/lib/algorithms/traversal/bidirectional_bfs.zig
- src/lib/algorithms/traversal/connected_components.zig
- src/lib/algorithms/traversal/dfs.zig
- src/lib/algorithms/traversal/traversal.zig
- src/lib/core
- src/lib/core/edge.zig
- src/lib/core/graph_storage.zig
- src/lib/core/graph.zig
- src/lib/core/node.zig
- src/lib/data_structures
- src/lib/data_structures/adjacency_list.zig
- src/lib/data_structures/adjacency_matrix.zig
- src/lib/data_structures/gpu
- src/lib/data_structures/gpu/adjacency_matrix_vram.zig
- src/lib/data_structures/gpu/compressed_sparse_column.zig
- src/lib/data_structures/gpu/compressed_sparse_row.zig
- src/lib/data_structures/gpu/gpu_graph.zig
- src/lib/data_structures/incidence_matrix.zig
- src/main.zig
- src/root.zig
- ZGraph.MasterPlan.md
- ZGraph.Spec.md
📄 File Contents:
`.dpignore`: >>>
.git
.github
.zig-cache
<<<
`.gitignore`: >>>
.zig-cache/
zig-out/
.DS_Store
.env
<<<
`build.zig`: >>>
const std = @import("std");
pub fn build(b: *std.Build) void {
const target = b.standardTargetOptions(.{});
const optimize = b.standardOptimizeOption(.{});
// ---- Core module (reused everywhere) ------------------------------------
const zgraph_root = b.createModule(.{
.root_source_file = b.path("src/root.zig"),
.target = target,
.optimize = optimize,
});
// ---- Static library (installable) ---------------------------------------
const lib = b.addLibrary(.{
.name = "zgraph",
.linkage = .static, // replacement for addStaticLibrary on 0.16
.root_module = zgraph_root,
});
b.installArtifact(lib);
// ---- CLI executable (installable + runnable) ----------------------------
const exe = b.addExecutable(.{
.name = "zgraph-cli",
.root_module = b.createModule(.{
.root_source_file = b.path("src/main.zig"),
.target = target,
.optimize = optimize,
}),
// NOTE: no .target / .optimize here; they belong on the module
});
// Allow @import("zgraph_root") in src/main.zig
exe.root_module.addImport("zgraph_root", zgraph_root);
b.installArtifact(exe);
// `zig build run`
const run_step = b.step("run", "Run zgraph CLI");
const run_cmd = b.addRunArtifact(exe);
run_step.dependOn(&run_cmd.step);
// ---- Unit tests (module tests) ------------------------------------------
const unit_tests = b.addTest(.{
.root_module = zgraph_root,
// NOTE: no .target / .optimize here either
});
const run_unit = b.addRunArtifact(unit_tests);
const test_step = b.step("test", "Run unit tests");
test_step.dependOn(&run_unit.step);
// ---- Integration tests (optional; skip if file missing) -----------------
const integration_step = b.step("integration-test", "Run integration tests");
const integration_path = "src/tests/integration/integration_tests.zig";
const have_integration = blk: {
_ = std.fs.cwd().statFile(integration_path) catch break :blk false;
break :blk true;
};
if (have_integration) {
const integration_tests = b.addTest(.{
.root_module = b.createModule(.{
.root_source_file = b.path(integration_path),
.target = target,
.optimize = optimize,
}),
});
integration_tests.root_module.addImport("zgraph_root", zgraph_root);
const run_integration = b.addRunArtifact(integration_tests);
integration_step.dependOn(&run_integration.step);
} else {
// Replaced b.print(...) with std.log.info(...)
std.log.info("note: integration tests not found at '{s}', skipping.", .{integration_path});
}
// ---- Aggregate: `zig build test-all` ------------------------------------
const all_tests = b.step("test-all", "Run unit + integration tests");
all_tests.dependOn(&run_unit.step);
all_tests.dependOn(integration_step);
}
<<<
`build.zig.zon`: >>>
.{
// This is the default name used by packages depending on this one. For
// example, when a user runs `zig fetch --save <url>`, this field is used
// as the key in the `dependencies` table. Although the user can choose a
// different name, most users will stick with this provided value.
//
// It is redundant to include "zig" in this name because it is already
// within the Zig package namespace.
.name = .zgraph,
.fingerprint = 0xd41c7dc566f3ae8e,
// This is a [Semantic Version](https://semver.org/).
// In a future version of Zig it will be used for package deduplication.
.version = "0.0.0",
// This field is optional.
// This is currently advisory only; Zig does not yet do anything
// with this value.
//.minimum_zig_version = "0.11.0",
// This field is optional.
// Each dependency must either provide a `url` and `hash`, or a `path`.
// `zig build --fetch` can be used to fetch all dependencies of a package, recursively.
// Once all dependencies are fetched, `zig build` no longer requires
// internet connectivity.
.dependencies = .{
// See `zig fetch --save <url>` for a command-line interface for adding dependencies.
//.example = .{
// // When updating this field to a new URL, be sure to delete the corresponding
// // `hash`, otherwise you are communicating that you expect to find the old hash at
// // the new URL. If the contents of a URL change this will result in a hash mismatch
// // which will prevent zig from using it.
// .url = "https://example.com/foo.tar.gz",
//
// // This is computed from the file contents of the directory of files that is
// // obtained after fetching `url` and applying the inclusion rules given by
// // `paths`.
// //
// // This field is the source of truth; packages do not come from a `url`; they
// // come from a `hash`. `url` is just one of many possible mirrors for how to
// // obtain a package matching this `hash`.
// //
// // Uses the [multihash](https://multiformats.io/multihash/) format.
// .hash = "...",
//
// // When this is provided, the package is found in a directory relative to the
// // build root. In this case the package's hash is irrelevant and therefore not
// // computed. This field and `url` are mutually exclusive.
// .path = "foo",
//
// // When this is set to `true`, a package is declared to be lazily
// // fetched. This makes the dependency only get fetched if it is
// // actually used.
// .lazy = false,
//},
},
// Specifies the set of files and directories that are included in this package.
// Only files and directories listed here are included in the `hash` that
// is computed for this package. Only files listed here will remain on disk
// when using the zig package manager. As a rule of thumb, one should list
// files required for compilation plus any license(s).
// Paths are relative to the build root. Use the empty string (`""`) to refer to
// the build root itself.
// A directory listed here means that all files within, recursively, are included.
.paths = .{
"build.zig",
"build.zig.zon",
"src",
// For example...
//"LICENSE",
//"README.md",
},
}
<<<
`LICENSE`: >>>
<<<
`README.md`: >>>
# ZGraph
ZGraph is a high-performance, in-memory graph library with:
- **Pluggable storages**: adjacency list, adjacency matrix, incidence matrix.
- **Compile-time graph semantics**: `directed` / `undirected`, `weighted` / `unweighted`.
- **Unified algorithms** that operate across storages via a common trait surface.
- **Portable formats**:
- `.zgraph` – human-readable, human-writable
- `.zgraphb` – compressed, chunked binary for fast I/O / mmap
- **Robust conversion strategies** (duplicate, streamed, chunked, copy-on-write) to switch layouts under tight memory budgets.
ZGraphDB (paged container) builds on the same chunks and APIs; algorithms continue to live in ZGraph.
## Status
- ✅ Core storages compile and pass tests on Zig 0.16.
- ✅ `AdjacencyList`, `AdjacencyMatrix`, `IncidenceMatrix` with CRUD + neighbor ops.
- ✅ `.zgraph` / `.zgraphb` specifications documented; parsers/writers in progress.
- 🚧 Conversion strategies module & CLI utilities.
See **[ZGraph.Spec.md](./ZGraph.Spec.md)** for the canonical checklist and roadmap.
## Install
```bash
zig build test
zig build run
```
Zig: 0.16.x
## Quick start
```c++
const GS = @import("src/lib/core/graph_storage.zig").GraphStorage;
const Storage = GS(.AdjacencyList, true, true); // directed, weighted
var g = Storage.init(std.heap.page_allocator);
defer g.deinit();
try g.addEdge(0, 1, 3.5);
try g.addEdge(1, 1, 7.5);
if (g.getNeighbors(0)) |edges| {
// ...
}
```
### Convert storage (e.g., list → matrix) with a memory budget
```zig
const conv = @import("src/lib/conversion/strategies.zig");
var dst = try conv.convertStorage(
std.heap.page_allocator,
Storage, // source type
.AdjacencyMatrix, true, true, // dest type + semantics
&g,
.Streamed, // strategy
.{ .max_bytes_in_flight = 4 * 1024 * 1024 * 1024 }, // 4 GiB
);
defer dst.deinit();
```
### Import / Export
```bash
# text -> binary
zig build run -- convert --in graph.zgraph --out graph.zgraphb
# validate and print stats
zig build run -- stats --in graph.zgraphb
```
## Design pillars
- **Predictable performance**: zero-copy views, cache-friendly CSR, zstd block compression.
- **Compatibility**: readers ignore unknown chunks; text & binary round-trip.
- **Safety**: memory ownership is explicit; threads guarded by mutexes where needed.
- **Tested**: unit, property, and fuzz tests; algorithm parity across storages.
## Repo layout (idealized)
```
ZGraph/
├─ README.md
├─ ZGraph.Spec.md # Source of truth (feature checklist)
├─ LICENSE
├─ build.zig
├─ zig.mod
├─ docs/
│ ├─ formats/
│ │ ├─ zgraph-text-spec.md
│ │ └─ zgraphb-binary-spec.md
│ ├─ algorithms/
│ │ ├─ traversal.md
│ │ ├─ shortest_paths.md
│ │ ├─ connectivity.md
│ │ ├─ flow_cut.md
│ │ ├─ centrality.md
│ │ └─ spectral.md
│ ├─ storage_design.md
│ ├─ conversion_strategies.md
│ ├─ perf_tuning.md
│ ├─ safety_and_threading.md
│ └─ roadmap.md
├─ examples/
│ ├─ tiny/
│ │ ├─ triangle.zgraph
│ │ ├─ weighted_digraph.zgraph
│ │ └─ attributes.zgraph
│ ├─ conversions/
│ │ ├─ list_to_matrix.zig
│ │ └─ streamed_live_convert.zig
│ └─ cli/
│ ├─ import_export.zig
│ └─ metrics.zig
├─ src/
│ ├─ root.zig
│ ├─ lib/
│ │ ├─ core/
│ │ │ ├─ node.zig
│ │ │ ├─ edge.zig
│ │ │ ├─ graph_storage.zig
│ │ │ ├─ iterators.zig
│ │ │ └─ attributes.zig
│ │ ├─ data_structures/
│ │ │ ├─ adjacency_list.zig
│ │ │ ├─ adjacency_matrix.zig
│ │ │ └─ incidence_matrix.zig
│ │ ├─ formats/
│ │ │ ├─ zgraph_text.zig
│ │ │ ├─ zgraphb.zig
│ │ │ └─ chunk_provider.zig
│ │ ├─ conversion/
│ │ │ ├─ strategies.zig
│ │ │ ├─ duplicate_convert.zig
│ │ │ ├─ streamed_convert.zig
│ │ │ ├─ chunked_convert.zig
│ │ │ └─ cow_convert.zig
│ │ ├─ indices/
│ │ │ ├─ csr.zig
│ │ │ └─ degree_table.zig
│ │ ├─ algorithms/
│ │ │ ├─ traversal/
│ │ │ │ ├─ bfs.zig
│ │ │ │ └─ dfs.zig
│ │ │ ├─ shortest_paths/
│ │ │ │ ├─ dijkstra.zig
│ │ │ │ ├─ bellman_ford.zig
│ │ │ │ └─ floyd_warshall.zig
│ │ │ ├─ connectivity/
│ │ │ │ ├─ union_find.zig
│ │ │ │ └─ strongly_connected.zig
│ │ │ ├─ flow_cut/
│ │ │ │ ├─ edmonds_karp.zig
│ │ │ │ └─ dinic.zig
│ │ │ ├─ centrality/
│ │ │ │ ├─ pagerank.zig
│ │ │ │ └─ betweenness.zig
│ │ │ └─ spectral/
│ │ │ ├─ laplacian.zig
│ │ │ └─ power_iteration.zig
│ │ ├─ io/
│ │ │ ├─ file.zig
│ │ │ ├─ csv.zig
│ │ │ └─ zstd.zig
│ │ ├─ mem/
│ │ │ ├─ alloc.zig
│ │ │ └─ pool.zig
│ │ └─ util/
│ │ ├─ bitset.zig
│ │ ├─ hash.zig
│ │ └─ time.zig
│ └─ cli/
│ ├─ zgraph.zig
│ └─ subcommands/
│ ├─ convert.zig
│ ├─ validate.zig
│ ├─ build_index.zig
│ └─ stats.zig
├─ tests/
│ ├─ unit/
│ │ ├─ adjacency_list_test.zig
│ │ ├─ adjacency_matrix_test.zig
│ │ ├─ incidence_matrix_test.zig
│ │ ├─ formats_text_test.zig
│ │ ├─ formats_binary_test.zig
│ │ ├─ conversion_strategies_test.zig
│ │ └─ algorithms_smoke_test.zig
│ ├─ property/
│ │ ├─ graph_idempotence_test.zig
│ │ └─ random_graph_agreement_test.zig
│ ├─ fuzz/
│ │ └─ fuzzer.zig
│ └─ data/
│ ├─ tiny_graphs/*.zgraph
│ └─ medium_graphs/*.zgraph
├─ tools/
│ ├─ scripts/
│ │ ├─ gen_random_graph.zig
│ │ └─ bench_matrix_vs_list.zig
│ └─ perf/
│ └─ flamegraph_instructions.md
└─ benches/
├─ micro/
│ ├─ csr_iter_bench.zig
│ └─ parse_zgraph_bench.zig
└─ macro/
├─ bfs_vs_dijkstra_bench.zig
└─ convert_streamed_vs_duplicate.zig
```
## License
MIT
<<<
`ZGraph.MasterPlan.md`: >>>
# ZGraph — Unified Master Plan (Reconciled)
This document merges the current repository state with the idealized goals and becomes the **single source of truth**. Items are marked as:
- ✅ Done
- 🚧 Partial / scaffolding present
- ⭕ Not started
---
## A. Semantics & Types
- ✅ A1. Compile-time graph semantics (`directed`, `weighted`) across storages
- ✅ A2. Self-loops & multi-edges covered by tests
- ⭕ A3. Attributes (node/edge KV with typed values)
- ✅ A4. Numeric node IDs (u64/usize) in use
- ⭕ A5. Storage-agnostic iterators (common trait iterators)
## B. Storage Backends (in-memory)
- ✅ B1. AdjacencyList: CRUD + neighbor ops + tests
- ✅ B2. AdjacencyMatrix: CRUD + present bitset + tests
- ✅ B3. IncidenceMatrix: rows, sign/weight semantics, edge_set, parallel builder, tests
- ⭕ B4. CSR / ReverseCSR indices (standalone, optional overlays)
- ⭕ B5. Attribute storage (typed, columnar, interning)
## C. Common Trait Surface
- ✅ C1. `GraphStorage(type, directed, weighted)` factory
- ✅ C2. Core ops: init/deinit/add/remove/has/getNeighbors
- ⭕ C3. Attribute API (node/edge getters/setters)
- ⭕ C4. Iteration policy & attribute filters
## D. Conversion Strategies
- ⭕ D1–D7. Strategies + API + tests (`Duplicate`, `Streamed`, `Chunked`, `CopyOnWrite`)
## E. File Formats
- 🚧 E1. `.zgraph` text spec documented; runtime reader/writer pending
- 🚧 E2. `.zgraphb` binary spec documented; runtime reader/writer pending
## F. Algorithms
- 🚧 F1. Traversal (BFS/DFS/CC) — source files exist; unify over trait; add tests
- 🚧 F2. Shortest paths (Dijkstra/Bellman-Ford/Floyd-Warshall) — wire and test
- 🚧 F3. Connectivity (SCC) — add Tarjan/Kosaraju; tests
- 🚧 F4. Flow (Edmonds-Karp present; add Dinic); tests
- 🚧 F5. Centrality (PageRank present; add Betweenness); tests
- 🚧 F6. Spectral (Laplacian, eigen routines present); tests & trait integration
## G. Indices & Acceleration
- ⭕ G1. CSR build/use
- ⭕ G2. Reverse CSR (directed)
- ⭕ G3. Degree table
- ⭕ G4. Index persistence in `.zgraphb` optional blocks
- ⭕ G5. Rebuild-on-demand hooks
## H. Attributes
- ⭕ H1. Node & Edge KV (`int|float|bool|string`)
- ⭕ H2. Storage-agnostic attribute map with typed accessors
- ⭕ H3. Text↔Binary column mapping (string table)
- ⭕ H4. Attribute filters in iterators
- ⭕ H5. Tests for mixed types, missing values, interning
## I. I/O & CLI
- ⭕ I1. CLI subcommands: `convert`, `validate`, `build-index`, `stats`
- ⭕ I2. Streaming I/O (chunked) for both formats
- ⭕ I3. zstd dictionaries & auto-tuning
## J. Concurrency & Memory
- ✅ J0. IncidenceMatrix parallel builder + mutex guarding
- ⭕ J1. Threading doc & invariants
- ⭕ J2. Parallel builders for CSR & conversions where safe
- ⭕ J3. Allocator strategy knobs (GPA/Arena/Page) + docs
- ⭕ J4. Zero-copy `.zgraphb` readers (mmap)
- ⭕ J5. Stress tests (OOM behavior)
## K. Testing & Quality
- ✅ K1. Unit tests for storages
- ⭕ K2. Property tests (round-trips, cross-storage equivalence)
- ⭕ K3. Fuzzers for text/binary parsers
- ⭕ K4. Benchmarks (micro/macro) and tracked results
- ⭕ K5. CI (Win/macOS/Linux; Zig 0.16.x)
- ⭕ K6. `zig fmt` + static checks gates
## L. Documentation
- ✅ L1. README
- 🚧 L2. Detailed specs for `.zgraph`/`.zgraphb` (needs sync with runtime)
- ⭕ L3. Algorithm docs and complexity notes
- ⭕ L4. Conversion strategy doc (memory math & decision table)
- ⭕ L5. Perf tuning guide (allocators, cache, zstd params)
- ⭕ L6. Roadmap milestones mapping to this checklist
---
# Execution Order (Do This Next, Exactly)
## Phase 1 — Lock the Core Interfaces
1. **Define common trait surface (`GraphLike`)** with adapters over existing storages:
- `neighbors(u)`, `hasEdge(u,v)`, `weight(u,v)?`, `nodeCount()`, `edgeCount()`
2. **Iterator policy**: stable order + attribute filter hooks; basic `NodeIter`, `EdgeFromIter`
## Phase 2 — Attributes (foundation for formats)
3. **Typed attribute store** (node & edge): `int|float|bool|string` + string interning
4. **Attribute API** on the trait surface + tests
5. **Iterator filters** using attributes
## Phase 3 — File Formats (runtime)
6. **`.zgraph` reader/writer** (streaming CSV-ish with schemas; tolerant of unknown sections); round-trip tests
7. **`.zgraphb` reader/writer** (chunked blocks + zstd + mmap-friendly); round-trip & parity tests
8. **Text↔Binary parity**: load(text)->save(binary)->load(binary) == load(text)
## Phase 4 — Conversion Strategies (memory-bounded)
9. `convertStorage` API + **Duplicate** strategy
10. **Streamed** strategy (destroy-as-you-go option; memory ceiling tests)
11. **Chunked** strategy (node sharding; parallel)
12. **Copy-On-Write** adapter (lazy migration) + background compaction
13. **Invariants & ceilings** property tests
## Phase 5 — Indices & Acceleration
14. **CSR/ReverseCSR** build & use as optional overlays for any storage
15. **Degree table** and **index persistence** blocks in `.zgraphb`
16. **Rebuild-on-demand** hooks
## Phase 6 — Algorithms (unify + verify)
17. Traversal (BFS/DFS/CC) over trait + CSR; tests across storages
18. Shortest paths (Dijkstra/BF/FW) with layout decision table; tests
19. Connectivity/SCC (Tarjan/Kosaraju); tests
20. Flow (finish Dinic); tests
21. Centrality (PageRank + Betweenness); tests
22. Spectral (laplacian, eigen); tests & perf
## Phase 7 — CLI, Streaming I/O, Docs, Quality Gates
23. CLI subcommands: `convert`, `validate`, `build-index`, `stats`
24. Streaming I/O for both formats + zstd dictionaries
25. Documentation: conversion strategies, perf tuning, thread model; keep specs synced
26. Property tests, fuzzers, benches; CI on all platforms; formatting/static checks gates
---
## Acceptance Criteria (per phase, condensed)
- **Formats:** Round-trips preserve counts, attributes, weights; unknown sections/blocks ignored.
- **Conversion:** Peak memory measured below ceiling; equivalence of neighbor sets/weights post-convert.
- **Indices:** CSR neighbors == storage neighbors; persisted indices reload correctly.
- **Algorithms:** Identical results across storages (given same semantics); perf within expected bounds.
- **CLI:** Non-zero exit on invalid files; stats match library queries; build-index regenerates CSR.
- **Docs:** Examples compile; decision tables match implemented behavior.
<<<
`ZGraph.Spec.md`: >>>
# ZGraph.Spec — Canonical Specification (Full & Final)
**Status:** Authoritative source of truth
**Versioning:** Spec v1.0 (maps to ZGraph 1.x)
**Scope:** ZGraph library (in-memory storages, algorithms, formats, conversion, CLI). ZGraphDB is a separate paged container that **reuses** these formats and **calls into** ZGraph algorithms.
> In Zig, **unit tests live with their source**. Integration/e2e and other suites live under `tests/*` and are wired via `build.zig`.
---
## 0. Design Goals (Non‑negotiables)
- **One trait surface**: All algorithms operate across any storage (list/matrix/incidence/CSR).
- **Compile-time semantics**: `directed`, `weighted` as comptime flags, no runtime branches in hot loops.
- **Attributes first‑class**: Node/edge KV attributes (`int|float|bool|string`), columnar under the hood.
- **Zero-copy where possible**: mmap `.zgraphb`, zstd-chunked blocks, CSR overlays.
- **Memory-bounded conversions**: multiple strategies with verifiable ceilings.
- **Forward-compatible formats**: readers ignore unknown sections/blocks. Round-trip `.zgraph` ⇄ `.zgraphb`.
- **Determinism**: canonical iteration order and serialized output for reproducible builds.
- **Safety**: explicit allocators, clear ownership; synchronization in parallel builders only.
---
## 1. Module Topology (Final Layout)
```
ZGraph/
├─ README.md # quickstart
├─ ZGraph.Spec.md # THIS file (canonical spec & checklist)
├─ LICENSE
├─ build.zig
├─ zig.mod
├─ docs/
│ ├─ formats/
│ │ ├─ zgraph-text-spec.md # extracted from §6.1
│ │ └─ zgraphb-binary-spec.md # extracted from §6.2
│ ├─ algorithms/*.md # explainer docs per family
│ ├─ conversion_strategies.md
│ ├─ perf_tuning.md
│ └─ safety_and_threading.md
├─ src/
│ ├─ root.zig
│ ├─ lib/
│ │ ├─ core/
│ │ │ ├─ types.zig # common types & Error sets
│ │ │ ├─ graph_like.zig # trait surface + adapters
│ │ │ ├─ attributes.zig # schema + column store + API
│ │ │ ├─ graph_storage.zig # GraphStorage(Enum..) factory
│ │ │ └─ iterators.zig # NodeIter, EdgeFromIter, AllEdgeIter
│ │ ├─ data_structures/
│ │ │ ├─ adjacency_list.zig
│ │ │ ├─ adjacency_matrix.zig
│ │ │ └─ incidence_matrix.zig
│ │ ├─ indices/
│ │ │ ├─ csr.zig # forward CSR
│ │ │ └─ csr_reverse.zig # reverse CSR
│ │ ├─ formats/
│ │ │ ├─ zgraph_text.zig # streaming reader/writer
│ │ │ └─ zgraphb.zig # chunked binary reader/writer + mmap
│ │ ├─ conversion/
│ │ │ ├─ strategies.zig # public API (ConvertStrategy, convertStorage)
│ │ │ ├─ duplicate_convert.zig
│ │ │ ├─ streamed_convert.zig
│ │ │ ├─ chunked_convert.zig
│ │ │ └─ cow_convert.zig
│ │ ├─ algorithms/
│ │ │ ├─ traversal/
│ │ │ │ ├─ bfs.zig
│ │ │ │ └─ dfs.zig
│ │ │ ├─ connectivity/
│ │ │ │ ├─ components.zig # UF + CC
│ │ │ │ └─ scc.zig # Tarjan / Kosaraju
│ │ │ ├─ shortest_paths/
│ │ │ │ ├─ dijkstra.zig
│ │ │ │ ├─ bellman_ford.zig
│ │ │ │ └─ floyd_warshall.zig
│ │ │ ├─ flow/
│ │ │ │ ├─ edmonds_karp.zig
│ │ │ │ └─ dinic.zig
│ │ │ ├─ centrality/
│ │ │ │ ├─ pagerank.zig
│ │ │ │ └─ betweenness.zig
│ │ │ └─ spectral/
│ │ │ ├─ laplacian.zig
│ │ │ └─ power_iteration.zig
│ │ ├─ io/
│ │ │ ├─ file.zig # path/FS utils
│ │ │ └─ zstd.zig # compression shim
│ │ ├─ mem/
│ │ │ ├─ alloc.zig # GPA/Arena convenience
│ │ │ └─ pool.zig # edge/node pools (optional)
│ │ └─ util/
│ │ ├─ bitset.zig
│ │ ├─ hash.zig
│ │ └─ time.zig
│ └─ cli/
│ ├─ zgraph.zig # CLI entry
│ └─ subcommands/
│ ├─ convert.zig
│ ├─ validate.zig
│ ├─ build_index.zig
│ └─ stats.zig
├─ tests/
│ ├─ integration/
│ │ ├─ convert_roundtrip_test.zig
│ │ ├─ conversion_memory_ceiling_test.zig
│ │ └─ algorithms_cross_storage_test.zig
│ ├─ e2e/
│ │ ├─ cli_convert_and_stats_test.zig
│ │ └─ cli_build_index_test.zig
│ ├─ property/
│ │ ├─ random_graph_equivalence_test.zig
│ │ └─ formats_fuzz_text_binary.zig
│ └─ data/
│ ├─ tiny/*.zgraph
│ └─ medium/*.zgraph
└─ benches/
├─ micro/*.zig
└─ macro/*.zig
```
---
## 2. Common Types & Error Sets (`core/types.zig`)
```zig
pub const NodeId = u64;
pub const Weight = f64; // Present only when weighted=true
pub const Semantic = struct {
directed: bool,
weighted: bool,
};
pub const GraphError = error{
OutOfMemory,
InvalidNode,
InvalidEdge,
EdgeNotFound,
EdgeAlreadyExists,
GraphNotWeighted,
ParseError,
UnsupportedVersion,
IoError,
SchemaMismatch,
Overflow,
};
```
---
## 3. Trait Surface (`core/graph_like.zig`)
### 3.1. Interface (generic over storages)
```zig
pub fn GraphLike(comptime directed: bool, comptime weighted: bool) type {
return struct {
// Required
pub fn nodeCount(self: *const @This()) usize;
pub fn edgeCount(self: *const @This()) usize;
pub fn hasNode(self: *const @This(), u: NodeId) bool;
pub fn hasEdge(self: *const @This(), u: NodeId, v: NodeId) bool;
pub fn addNode(self: *@This(), u: NodeId) !void;
pub fn removeNode(self: *@This(), u: NodeId) !void;
pub fn addEdge(self: *@This(), u: NodeId, v: NodeId, weight: if (weighted) Weight else void) !void;
pub fn removeEdge(self: *@This(), u: NodeId, v: NodeId) !void;
// Iteration (stable order)
pub fn nodeIter(self: *const @This()) NodeIter;
pub fn edgeFromIter(self: *const @This(), u: NodeId) EdgeFromIter;
// Optional weight accessor
pub fn getWeight(self: *const @This(), u: NodeId, v: NodeId) if (weighted) ?Weight else void;
// Attributes are attached via Attributes API (§5) and accessed by id
};
}
```
### 3.2. Iterators (`core/iterators.zig`)
```zig
pub const NodeIter = struct {
// next() -> ?NodeId
};
pub const EdgeFromIter = struct {
// next() -> ?struct{ dst: NodeId, weight: if (weighted) ?Weight else void }
};
pub const AllEdgeIter = struct {
// next() -> ?struct{ src: NodeId, dst: NodeId, weight: if (weighted) ?Weight else void }
};
```
---
## 4. Graph Storage Factory (`core/graph_storage.zig`)
```zig
pub const GraphStorageType = enum { AdjacencyList, AdjacencyMatrix, IncidenceMatrix };
pub fn GraphStorage(comptime st: GraphStorageType, comptime directed: bool, comptime weighted: bool) type;
```
Each storage implements the GraphLike interface via thin adapters (or directly match the surface).
---
## 5. Attributes (Schema + Column Store) (`core/attributes.zig`)
### 5.1. Types
```zig
pub const ValueType = enum { Int, Float, Bool, String };
pub const Value = union(ValueType) {
Int: i64,
Float: f64,
Bool: bool,
String: u32, // interned string id (0xFFFFFFFF == null)
};
pub const ColumnDesc = struct { name: []const u8, ty: ValueType };
pub const Schema = struct {
node: []const ColumnDesc,
edge: []const ColumnDesc,
};
```
### 5.2. Column Storage
- Node columns: arrays keyed by node index (sparse map for arbitrary NodeId → dense index mapping).
- Edge columns: arrays keyed by **edge ordinal** (storage-provided stable edge id) or `(src,dst)` mapping.
- Strings: UTF‑8 table with dedup; id `0xFFFFFFFF` = null.
### 5.3. API
```zig
pub const Attributes = struct {
pub fn init(alloc: std.mem.Allocator, schema: Schema) !Attributes;
pub fn deinit(self: *Attributes) void;
// Node attributes
pub fn setNode(self: *Attributes, node: NodeId, key: []const u8, val: Value) !void;
pub fn getNode(self: *const Attributes, node: NodeId, key: []const u8) ?Value;
// Edge attributes (by endpoints; storage adapter resolves edge id)
pub fn setEdge(self: *Attributes, src: NodeId, dst: NodeId, key: []const u8, val: Value) !void;
pub fn getEdge(self: *const Attributes, src: NodeId, dst: NodeId, key: []const u8) ?Value;
// String table
pub fn intern(self: *Attributes, s: []const u8) !u32;
pub fn lookup(self: *const Attributes, id: u32) ?[]const u8;
};
```
### 5.4. Filters (for iterators)
```zig
pub const AttrFilter = struct {
// Example: key="active", op="==", val=true
key: []const u8,
op: enum { Eq, Ne, Lt, Le, Gt, Ge, Exists },
val: ?Value = null,
};
// Applied via iterator adaptors:
pub fn filteredNodeIter(g: anytype, attrs: *const Attributes, filter: AttrFilter) NodeIter;
```
---
## 6. File Formats (Runtime + On-disk) (`formats/*`)
### 6.1. `.zgraph` — Text (Human)
**Header** (required):
```
#!zgraph 1
graph = directed|undirected
weights = weighted|unweighted
schema.node = name:string,group:int,active:bool
schema.edge = label:string,capacity:float
```
**Sections** (order-free, repeatable, append behavior):
- `[NODES]` rows: `id, <node-props-by-schema>`
- `[EDGES]`
- if weighted: `src, dst, weight, <edge-props>`
- else: `src, dst, <edge-props>`
- `[META]` free-form `key=value` lines (ignored by reader unless known)
- `[INDEX]` hints (optional), ignored by reader
- `[TAGS]` free-form labels
**CSV rules**: RFC4180-ish; quoted fields with `""`; empty -> unset.
**Reader/Writer API** (`formats/zgraph_text.zig`):
```zig
pub const TextOptions = struct { canonical: bool = true };
pub fn read(alloc: Allocator, rdr: anytype) !struct{
semantic: Semantic,
schema: Schema,
nodes: []NodeId,
edges: []struct{ src: NodeId, dst: NodeId, weight: ?Weight },
attrs: Attributes,
};
pub fn write(alloc: Allocator, w: anytype, g: anytype, attrs: *const Attributes, opts: TextOptions) !void;
```
### 6.2. `.zgraphb` — Binary (Chunked, Compressed)
**Header**:
- Magic: `ZGB1`
- Version: u16
- Flags: bitfield (directed, weighted, varint_ids, has_indices, compression)
- Offsets to blocks; global CRC32
**Blocks** (individually zstd-compressed if enabled):
- **StringTable**: contiguous UTF‑8, u32 ids
- **SchemaBlock**: column descriptors (node/edge)
- **NodeTable**: COUNT, varint NodeId list (or fixed u64), optional NodeId→dense map
- **EdgeTable**: COUNT, varint src, varint dst, `[f64 weight]` if weighted
- **NodeColumns** / **EdgeColumns**: per-column typed vectors
- **Indices** (optional): CSR, ReverseCSR, DegreeTable
- **Meta**: key/value table
**Reader/Writer API** (`formats/zgraphb.zig`):
```zig
pub const BinaryOptions = struct {
compression: enum { none, zstd } = .zstd,
block_size: usize = 1 << 20, // 1 MiB
mmap: bool = true,
};
pub fn read(alloc: Allocator, rdr_or_path: anytype) !struct{
semantic: Semantic,
schema: Schema,
provider: ChunkProvider, // zero-copy block access if mmap
attrs: AttributesView, // read-only view
edge_index: ?CSRView,
};
pub fn write(alloc: Allocator, w_or_path: anytype, g: anytype, attrs: *const Attributes, opts: BinaryOptions) !void;
```
**Forward compatibility**: unknown blocks skipped; offsets allow appending blocks; version gates behavior.
---
## 7. Conversion Strategies (`conversion/*`)
### 7.1. API
```zig
pub const ConvertStrategy = enum { Duplicate, Streamed, Chunked, CopyOnWrite };
pub const ConvertOpts = struct {
max_bytes_in_flight: usize = 0, // 0 = auto
chunk_nodes: usize = 0, // only for Chunked
destroy_source: bool = false, // allowed for Streamed
};
pub fn convertStorage(
alloc: Allocator,
comptime Src: type,
comptime dst_type: GraphStorageType,
comptime directed: bool,
comptime weighted: bool,
src: *Src,
strategy: ConvertStrategy,
opts: ConvertOpts,
) !anytype; // returns destination storage
```
### 7.2. Behavior Guarantees