pidsmaker 4.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of pidsmaker might be problematic. Click here for more details.

Files changed (338) hide show
  1. pidsmaker/__init__.py +22 -0
  2. pidsmaker/cli.py +32 -0
  3. pidsmaker/config/__init__.py +2 -0
  4. pidsmaker/config/config.py +2100 -0
  5. pidsmaker/config/pipeline.py +1768 -0
  6. pidsmaker/config/schemas.py +1032 -0
  7. pidsmaker/datasets.py +222 -0
  8. pidsmaker/debug_tests.py +30 -0
  9. pidsmaker/decoders/__init__.py +5 -0
  10. pidsmaker/decoders/custom_edge_mlp_decoder.py +17 -0
  11. pidsmaker/decoders/custom_mlp_decoder.py +10 -0
  12. pidsmaker/decoders/edge_linear_decoder.py +16 -0
  13. pidsmaker/decoders/inner_product_decoder.py +18 -0
  14. pidsmaker/decoders/nodlink_decoder.py +56 -0
  15. pidsmaker/detection/__init__.py +0 -0
  16. pidsmaker/detection/evaluation_methods/__init__.py +9 -0
  17. pidsmaker/detection/evaluation_methods/edge_evaluation.py +259 -0
  18. pidsmaker/detection/evaluation_methods/evaluation_utils.py +1730 -0
  19. pidsmaker/detection/evaluation_methods/host_two_stage_evaluation.py +115 -0
  20. pidsmaker/detection/evaluation_methods/node_evaluation.py +463 -0
  21. pidsmaker/detection/evaluation_methods/node_tw_evaluation.py +196 -0
  22. pidsmaker/detection/evaluation_methods/plot.py +192 -0
  23. pidsmaker/detection/evaluation_methods/queue_evaluation.py +451 -0
  24. pidsmaker/detection/evaluation_methods/tw_evaluation.py +95 -0
  25. pidsmaker/detection/flash_detection.py +162 -0
  26. pidsmaker/detection/magic_knn.py +190 -0
  27. pidsmaker/detection/node_scoring.py +52 -0
  28. pidsmaker/detection/threatrace_detection.py +65 -0
  29. pidsmaker/detection/training_methods/__init__.py +1 -0
  30. pidsmaker/detection/training_methods/inference_loop.py +293 -0
  31. pidsmaker/detection/training_methods/ocrapt_early_stop.py +165 -0
  32. pidsmaker/detection/training_methods/threatrace_training.py +169 -0
  33. pidsmaker/detection/training_methods/training_loop.py +377 -0
  34. pidsmaker/encoders/__init__.py +22 -0
  35. pidsmaker/encoders/argus_encoder.py +69 -0
  36. pidsmaker/encoders/custom_mlp.py +75 -0
  37. pidsmaker/encoders/custom_mlp_encoder.py +10 -0
  38. pidsmaker/encoders/egraphsage_encoder.py +56 -0
  39. pidsmaker/encoders/gat.py +67 -0
  40. pidsmaker/encoders/gcn.py +27 -0
  41. pidsmaker/encoders/gin.py +48 -0
  42. pidsmaker/encoders/glstm.py +298 -0
  43. pidsmaker/encoders/graph_attention.py +63 -0
  44. pidsmaker/encoders/gru.py +29 -0
  45. pidsmaker/encoders/hetero/__init__.py +4 -0
  46. pidsmaker/encoders/hetero/ancestor_encoder.py +98 -0
  47. pidsmaker/encoders/hetero/entity_encoder.py +33 -0
  48. pidsmaker/encoders/hetero/event_encoder.py +81 -0
  49. pidsmaker/encoders/hetero/hetero_graph_transformer.py +40 -0
  50. pidsmaker/encoders/lares_encoder.py +68 -0
  51. pidsmaker/encoders/linear_encoder.py +16 -0
  52. pidsmaker/encoders/magic_encoder.py +161 -0
  53. pidsmaker/encoders/rcaid_encoder.py +81 -0
  54. pidsmaker/encoders/rgcn.py +75 -0
  55. pidsmaker/encoders/sage.py +51 -0
  56. pidsmaker/encoders/shadewatcher_encoder.py +149 -0
  57. pidsmaker/encoders/sum_aggregation.py +20 -0
  58. pidsmaker/encoders/temporal_wrappers.py +80 -0
  59. pidsmaker/encoders/textrcnn.py +82 -0
  60. pidsmaker/encoders/tgn_encoder.py +193 -0
  61. pidsmaker/experiments/tuning.py +102 -0
  62. pidsmaker/experiments/uncertainty.py +261 -0
  63. pidsmaker/factory.py +1456 -0
  64. pidsmaker/featurization/__init__.py +0 -0
  65. pidsmaker/featurization/feat_inference_methods/__init__.py +7 -0
  66. pidsmaker/featurization/feat_inference_methods/feat_inference_HFH.py +31 -0
  67. pidsmaker/featurization/feat_inference_methods/feat_inference_TRW.py +67 -0
  68. pidsmaker/featurization/feat_inference_methods/feat_inference_alacarte.py +16 -0
  69. pidsmaker/featurization/feat_inference_methods/feat_inference_doc2vec.py +54 -0
  70. pidsmaker/featurization/feat_inference_methods/feat_inference_fasttext.py +38 -0
  71. pidsmaker/featurization/feat_inference_methods/feat_inference_flash.py +70 -0
  72. pidsmaker/featurization/feat_inference_methods/feat_inference_graph2vec.py +85 -0
  73. pidsmaker/featurization/feat_inference_methods/feat_inference_ocrapt_features.py +95 -0
  74. pidsmaker/featurization/feat_inference_methods/feat_inference_pretrained.py +1729 -0
  75. pidsmaker/featurization/feat_inference_methods/feat_inference_word2vec.py +56 -0
  76. pidsmaker/featurization/featurization_methods/__init__.py +0 -0
  77. pidsmaker/featurization/featurization_methods/build_trw.py +67 -0
  78. pidsmaker/featurization/featurization_methods/featurization_alacarte.py +748 -0
  79. pidsmaker/featurization/featurization_methods/featurization_doc2vec.py +99 -0
  80. pidsmaker/featurization/featurization_methods/featurization_fasttext.py +75 -0
  81. pidsmaker/featurization/featurization_methods/featurization_flash.py +203 -0
  82. pidsmaker/featurization/featurization_methods/featurization_graph2vec.py +243 -0
  83. pidsmaker/featurization/featurization_methods/featurization_trw.py +115 -0
  84. pidsmaker/featurization/featurization_methods/featurization_word2vec.py +87 -0
  85. pidsmaker/featurization/featurization_utils.py +275 -0
  86. pidsmaker/featurization/utils/build_random_walks.py +68 -0
  87. pidsmaker/featurization/utils/trw.py +203 -0
  88. pidsmaker/hetero.py +81 -0
  89. pidsmaker/losses.py +170 -0
  90. pidsmaker/main.py +377 -0
  91. pidsmaker/mimicry.py +284 -0
  92. pidsmaker/model.py +382 -0
  93. pidsmaker/objectives/__init__.py +16 -0
  94. pidsmaker/objectives/autoencode_edge_emb.py +43 -0
  95. pidsmaker/objectives/deep_graph_infomax.py +94 -0
  96. pidsmaker/objectives/detect_few_shot.py +21 -0
  97. pidsmaker/objectives/one_class.py +75 -0
  98. pidsmaker/objectives/predict_edge_contrastive.py +165 -0
  99. pidsmaker/objectives/predict_edge_supervised.py +77 -0
  100. pidsmaker/objectives/predict_edge_type.py +28 -0
  101. pidsmaker/objectives/predict_masked_struct.py +49 -0
  102. pidsmaker/objectives/predict_node_type.py +36 -0
  103. pidsmaker/objectives/predict_process_tag.py +169 -0
  104. pidsmaker/objectives/predict_snapshot_embedding.py +97 -0
  105. pidsmaker/objectives/reconstruct_edge_emb.py +16 -0
  106. pidsmaker/objectives/reconstruct_masked_feat.py +51 -0
  107. pidsmaker/objectives/reconstruct_node_emb.py +13 -0
  108. pidsmaker/objectives/reconstruct_node_feat.py +13 -0
  109. pidsmaker/objectives/validation_wrapper.py +55 -0
  110. pidsmaker/preprocessing/__init__.py +0 -0
  111. pidsmaker/preprocessing/build_graph_methods/__init__.py +1 -0
  112. pidsmaker/preprocessing/build_graph_methods/build_default_graphs.py +830 -0
  113. pidsmaker/preprocessing/build_graph_methods/build_magic_graphs.py +220 -0
  114. pidsmaker/preprocessing/cleaning.py +258 -0
  115. pidsmaker/preprocessing/transformation_methods/__init__.py +2 -0
  116. pidsmaker/preprocessing/transformation_methods/attack_generation/synthetic_attack_naive.py +194 -0
  117. pidsmaker/preprocessing/transformation_methods/transformation_dag.py +28 -0
  118. pidsmaker/preprocessing/transformation_methods/transformation_merge_edges.py +136 -0
  119. pidsmaker/preprocessing/transformation_methods/transformation_rcaid_pseudo_graph.py +510 -0
  120. pidsmaker/preprocessing/transformation_methods/transformation_undirected.py +24 -0
  121. pidsmaker/preprocessing/transformation_methods/transformation_utils.py +36 -0
  122. pidsmaker/pretrained/__init__.py +5 -0
  123. pidsmaker/pretrained/data/__init__.py +4 -0
  124. pidsmaker/pretrained/data/behavior_signatures.py +548 -0
  125. pidsmaker/pretrained/data/canonical_tokens.py +1035 -0
  126. pidsmaker/pretrained/data/edge_filter.py +381 -0
  127. pidsmaker/pretrained/data/entity_classes.py +476 -0
  128. pidsmaker/pretrained/data/sampler.py +926 -0
  129. pidsmaker/pretrained/data/tokenizer_bpe.py +1659 -0
  130. pidsmaker/pretrained/detect.py +1432 -0
  131. pidsmaker/pretrained/embedding_generator.py +252 -0
  132. pidsmaker/pretrained/finetune.py +1437 -0
  133. pidsmaker/pretrained/models/__init__.py +20 -0
  134. pidsmaker/pretrained/models/behavior.py +348 -0
  135. pidsmaker/pretrained/models/bert.py +286 -0
  136. pidsmaker/pretrained/models/deepwalk.py +128 -0
  137. pidsmaker/pretrained/models/dgi.py +120 -0
  138. pidsmaker/pretrained/models/gae.py +114 -0
  139. pidsmaker/pretrained/models/gnn_distill.py +475 -0
  140. pidsmaker/pretrained/models/graphmae.py +373 -0
  141. pidsmaker/pretrained/models/hf_pretrained.py +213 -0
  142. pidsmaker/pretrained/models/llama.py +110 -0
  143. pidsmaker/pretrained/models/modernbert.py +567 -0
  144. pidsmaker/pretrained/models/roberta.py +147 -0
  145. pidsmaker/pretrained/models/rope_utils.py +99 -0
  146. pidsmaker/pretrained/models/ropebert.py +322 -0
  147. pidsmaker/pretrained/models/spider.py +204 -0
  148. pidsmaker/pretrained/models/tgn.py +770 -0
  149. pidsmaker/pretrained/pretrain/__init__.py +3 -0
  150. pidsmaker/pretrained/pretrain/pretrain_behavior_cluster.py +513 -0
  151. pidsmaker/pretrained/pretrain/pretrain_common.py +585 -0
  152. pidsmaker/pretrained/pretrain/pretrain_deepwalk.py +31 -0
  153. pidsmaker/pretrained/pretrain/pretrain_dgi.py +143 -0
  154. pidsmaker/pretrained/pretrain/pretrain_gae.py +143 -0
  155. pidsmaker/pretrained/pretrain/pretrain_gnn_distill.py +438 -0
  156. pidsmaker/pretrained/pretrain/pretrain_graphmae.py +151 -0
  157. pidsmaker/pretrained/pretrain/pretrain_hf.py +169 -0
  158. pidsmaker/pretrained/pretrain/pretrain_main.py +276 -0
  159. pidsmaker/pretrained/pretrain/pretrain_mlm.py +491 -0
  160. pidsmaker/pretrained/pretrain/pretrain_spider.py +502 -0
  161. pidsmaker/pretrained/training_utils.py +157 -0
  162. pidsmaker/process_reapr_gt.py +101 -0
  163. pidsmaker/resources/Ground_Truth/orthrus/E3-CADETS/node_Nginx_Backdoor_06.csv +8 -0
  164. pidsmaker/resources/Ground_Truth/orthrus/E3-CADETS/node_Nginx_Backdoor_11.csv +4 -0
  165. pidsmaker/resources/Ground_Truth/orthrus/E3-CADETS/node_Nginx_Backdoor_12.csv +43 -0
  166. pidsmaker/resources/Ground_Truth/orthrus/E3-CADETS/node_Nginx_Backdoor_13.csv +24 -0
  167. pidsmaker/resources/Ground_Truth/orthrus/E3-CLEARSCOPE/node_clearscope_e3_firefox_0411.csv +41 -0
  168. pidsmaker/resources/Ground_Truth/orthrus/E3-CLEARSCOPE/node_clearscope_e3_firefox_0412.csv +0 -0
  169. pidsmaker/resources/Ground_Truth/orthrus/E3-FIVEDIRECTIONS/node_fivedirections_e3_browser_0412.csv +1 -0
  170. pidsmaker/resources/Ground_Truth/orthrus/E3-FIVEDIRECTIONS/node_fivedirections_e3_excel_0409.csv +63 -0
  171. pidsmaker/resources/Ground_Truth/orthrus/E3-FIVEDIRECTIONS/node_fivedirections_e3_firefox_0411.csv +56 -0
  172. pidsmaker/resources/Ground_Truth/orthrus/E3-THEIA/node_Browser_Extension_Drakon_Dropper.csv +61 -0
  173. pidsmaker/resources/Ground_Truth/orthrus/E3-THEIA/node_Firefox_Backdoor_Drakon_In_Memory.csv +58 -0
  174. pidsmaker/resources/Ground_Truth/orthrus/E3-TRACE/node_trace_e3_firefox_0410.csv +11 -0
  175. pidsmaker/resources/Ground_Truth/orthrus/E3-TRACE/node_trace_e3_phishing_executable_0413.csv +11 -0
  176. pidsmaker/resources/Ground_Truth/orthrus/E3-TRACE/node_trace_e3_pine_0413.csv +14 -0
  177. pidsmaker/resources/Ground_Truth/orthrus/E5-CADETS/node_Nginx_Drakon_APT.csv +19 -0
  178. pidsmaker/resources/Ground_Truth/orthrus/E5-CADETS/node_Nginx_Drakon_APT_17.csv +107 -0
  179. pidsmaker/resources/Ground_Truth/orthrus/E5-CLEARSCOPE/node_clearscope_e5_appstarter_0515.csv +26 -0
  180. pidsmaker/resources/Ground_Truth/orthrus/E5-CLEARSCOPE/node_clearscope_e5_firefox_0517.csv +1 -0
  181. pidsmaker/resources/Ground_Truth/orthrus/E5-CLEARSCOPE/node_clearscope_e5_lockwatch_0517.csv +17 -0
  182. pidsmaker/resources/Ground_Truth/orthrus/E5-CLEARSCOPE/node_clearscope_e5_tester_0517.csv +8 -0
  183. pidsmaker/resources/Ground_Truth/orthrus/E5-FIVEDIRECTIONS/node_fivedirections_e5_bits_0515.csv +54 -0
  184. pidsmaker/resources/Ground_Truth/orthrus/E5-FIVEDIRECTIONS/node_fivedirections_e5_copykatz_0509.csv +87 -0
  185. pidsmaker/resources/Ground_Truth/orthrus/E5-FIVEDIRECTIONS/node_fivedirections_e5_dns_0517.csv +11 -0
  186. pidsmaker/resources/Ground_Truth/orthrus/E5-FIVEDIRECTIONS/node_fivedirections_e5_drakon_0517.csv +6 -0
  187. pidsmaker/resources/Ground_Truth/orthrus/E5-THEIA/node_THEIA_1_Firefox_Drakon_APT_BinFmt_Elevate_Inject.csv +70 -0
  188. pidsmaker/resources/Ground_Truth/orthrus/E5-TRACE/node_Trace_Firefox_Drakon.csv +71 -0
  189. pidsmaker/resources/Ground_Truth/orthrus/atlasv2_edr/atlasv2_edr_m1.csv +1 -0
  190. pidsmaker/resources/Ground_Truth/orthrus/atlasv2_edr/atlasv2_edr_m2.csv +1 -0
  191. pidsmaker/resources/Ground_Truth/orthrus/atlasv2_edr/atlasv2_edr_m3.csv +1 -0
  192. pidsmaker/resources/Ground_Truth/orthrus/atlasv2_edr/atlasv2_edr_m4.csv +5 -0
  193. pidsmaker/resources/Ground_Truth/orthrus/atlasv2_edr/atlasv2_edr_m5.csv +23 -0
  194. pidsmaker/resources/Ground_Truth/orthrus/atlasv2_edr/atlasv2_edr_m6.csv +18 -0
  195. pidsmaker/resources/Ground_Truth/orthrus/atlasv2_edr/atlasv2_edr_s1.csv +1 -0
  196. pidsmaker/resources/Ground_Truth/orthrus/atlasv2_edr/atlasv2_edr_s2.csv +1 -0
  197. pidsmaker/resources/Ground_Truth/orthrus/atlasv2_edr/atlasv2_edr_s3.csv +16 -0
  198. pidsmaker/resources/Ground_Truth/orthrus/atlasv2_edr/atlasv2_edr_s4.csv +22 -0
  199. pidsmaker/resources/Ground_Truth/orthrus/atlasv2_h1/node_h1_m1.csv +126 -0
  200. pidsmaker/resources/Ground_Truth/orthrus/atlasv2_h1/node_h1_m2.csv +105 -0
  201. pidsmaker/resources/Ground_Truth/orthrus/atlasv2_h1/node_h1_m3.csv +94 -0
  202. pidsmaker/resources/Ground_Truth/orthrus/atlasv2_h1/node_h1_m4.csv +139 -0
  203. pidsmaker/resources/Ground_Truth/orthrus/atlasv2_h1/node_h1_m5.csv +228 -0
  204. pidsmaker/resources/Ground_Truth/orthrus/atlasv2_h1/node_h1_m6.csv +131 -0
  205. pidsmaker/resources/Ground_Truth/orthrus/atlasv2_h1/node_h1_s1.csv +118 -0
  206. pidsmaker/resources/Ground_Truth/orthrus/atlasv2_h1/node_h1_s2.csv +89 -0
  207. pidsmaker/resources/Ground_Truth/orthrus/atlasv2_h1/node_h1_s3.csv +133 -0
  208. pidsmaker/resources/Ground_Truth/orthrus/atlasv2_h1/node_h1_s4.csv +135 -0
  209. pidsmaker/resources/Ground_Truth/orthrus/carbanakv2_edr/carbanakv2_edr.csv +2453 -0
  210. pidsmaker/resources/Ground_Truth/orthrus/h051/node_h051_0925.csv +114 -0
  211. pidsmaker/resources/Ground_Truth/orthrus/h201/node_h201_0923.csv +2905 -0
  212. pidsmaker/resources/Ground_Truth/orthrus/h501/node_h501_0924.csv +749 -0
  213. pidsmaker/resources/Ground_Truth/orthrus/readme.md +98 -0
  214. pidsmaker/resources/Ground_Truth/reapr/E3-CADETS/node_Nginx_Backdoor_06.csv +3 -0
  215. pidsmaker/resources/Ground_Truth/reapr/E3-CADETS/node_Nginx_Backdoor_12.csv +655 -0
  216. pidsmaker/resources/Ground_Truth/reapr/E3-CADETS/node_Nginx_Backdoor_13.csv +770 -0
  217. pidsmaker/resources/Ground_Truth/reapr/E3-FIVEDIRECTIONS/node_fivedirections_e3_excel_0409.csv +0 -0
  218. pidsmaker/resources/Ground_Truth/reapr/E3-FIVEDIRECTIONS/node_fivedirections_e3_firefox_0411.csv +18 -0
  219. pidsmaker/resources/Ground_Truth/reapr/E3-THEIA/node_Browser_Extension_Drakon_Dropper.csv +42 -0
  220. pidsmaker/resources/Ground_Truth/reapr/E3-THEIA/node_Firefox_Backdoor_Drakon_In_Memory.csv +81 -0
  221. pidsmaker/resources/Ground_Truth/reapr/E3-TRACE/node_trace_e3_firefox_0410.csv +37 -0
  222. pidsmaker/resources/Ground_Truth/reapr/E3-TRACE/node_trace_e3_phishing_executable_0413.csv +9 -0
  223. pidsmaker/resources/Ground_Truth/reapr/E3-TRACE/node_trace_e3_pine_0413.csv +40 -0
  224. pidsmaker/resources/Ground_Truth/threatrace/E3-CADETS/ground_truth.txt +12858 -0
  225. pidsmaker/resources/Ground_Truth/threatrace/E3-FIVEDIRECTIONS/ground_truth.txt +18420 -0
  226. pidsmaker/resources/Ground_Truth/threatrace/E3-THEIA/ground_truth.txt +25363 -0
  227. pidsmaker/resources/Ground_Truth/threatrace/E3-TRACE/ground_truth.txt +68265 -0
  228. pidsmaker/resources/Ground_Truth/threatrace/README.md +123 -0
  229. pidsmaker/resources/config/anomal_e.yml +25 -0
  230. pidsmaker/resources/config/argus.yml +56 -0
  231. pidsmaker/resources/config/attack_edges/cadets_e3.yml +435 -0
  232. pidsmaker/resources/config/attack_edges/cadets_e5.yml +407 -0
  233. pidsmaker/resources/config/attack_edges/theia_e3.yml +382 -0
  234. pidsmaker/resources/config/attack_edges/theia_e5.yml +387 -0
  235. pidsmaker/resources/config/attack_edges/trace_e3.yml +415 -0
  236. pidsmaker/resources/config/attack_edges/trace_e5.yml +417 -0
  237. pidsmaker/resources/config/default.yml +315 -0
  238. pidsmaker/resources/config/egraphsage.yml +95 -0
  239. pidsmaker/resources/config/euler.yml +104 -0
  240. pidsmaker/resources/config/eval/eval_set_clustering.json +3170 -0
  241. pidsmaker/resources/config/experiments/tuning/components/tuning_featurization_methods.yml +29 -0
  242. pidsmaker/resources/config/experiments/tuning/systems/clearscope_e5/tuning_orthrus.yml +14 -0
  243. pidsmaker/resources/config/experiments/tuning/systems/default/tuning_default_baselines.yml +13 -0
  244. pidsmaker/resources/config/experiments/tuning/systems/default/tuning_orthrus_fixed.yml +16 -0
  245. pidsmaker/resources/config/experiments/uncertainty/none.yml +5 -0
  246. pidsmaker/resources/config/experiments/uncertainty/run_n_times.yml +12 -0
  247. pidsmaker/resources/config/experiments/uncertainty/run_n_times_hyperparameters.yml +12 -0
  248. pidsmaker/resources/config/experiments/uncertainty/uncertainty.yml +22 -0
  249. pidsmaker/resources/config/flash.yml +79 -0
  250. pidsmaker/resources/config/jbeil.yml +65 -0
  251. pidsmaker/resources/config/kairos.yml +121 -0
  252. pidsmaker/resources/config/lares.yml +115 -0
  253. pidsmaker/resources/config/magic.yml +86 -0
  254. pidsmaker/resources/config/nodlink.yml +79 -0
  255. pidsmaker/resources/config/ocrapt.yml +91 -0
  256. pidsmaker/resources/config/orthrus.yml +120 -0
  257. pidsmaker/resources/config/orthrus_fixed.yml +17 -0
  258. pidsmaker/resources/config/orthrus_non_snooped.yml +17 -0
  259. pidsmaker/resources/config/pretrained/README.md +101 -0
  260. pidsmaker/resources/config/pretrained/cybergfm/cybergfm.yml +49 -0
  261. pidsmaker/resources/config/pretrained/pretrained.yml +190 -0
  262. pidsmaker/resources/config/pretrained/pretrained_flash.yml +9 -0
  263. pidsmaker/resources/config/pretrained/pretrained_kairos.yml +12 -0
  264. pidsmaker/resources/config/pretrained/pretrained_magic.yml +1 -0
  265. pidsmaker/resources/config/pretrained/pretrained_nodlink.yml +1 -0
  266. pidsmaker/resources/config/pretrained/pretrained_orthrus.yml +1 -0
  267. pidsmaker/resources/config/pretrained/pretrained_supervised.yml +13 -0
  268. pidsmaker/resources/config/pretrained/pretrained_threatrace.yml +8 -0
  269. pidsmaker/resources/config/pretrained/pretrained_velox.yml +14 -0
  270. pidsmaker/resources/config/prographer.yml +136 -0
  271. pidsmaker/resources/config/rcaid.yml +88 -0
  272. pidsmaker/resources/config/shadewatcher.yml +146 -0
  273. pidsmaker/resources/config/tests.yml +10 -0
  274. pidsmaker/resources/config/threatrace.yml +73 -0
  275. pidsmaker/resources/config/tuned_baselines/optc_net/tuned_argus.yml +4 -0
  276. pidsmaker/resources/config/tuned_baselines/optc_net/tuned_lares.yml +13 -0
  277. pidsmaker/resources/config/velox.yml +10 -0
  278. pidsmaker/resources/config/viz_config.yml +10 -0
  279. pidsmaker/tasks/__init__.py +10 -0
  280. pidsmaker/tasks/batching.py +49 -0
  281. pidsmaker/tasks/construction.py +31 -0
  282. pidsmaker/tasks/evaluation.py +232 -0
  283. pidsmaker/tasks/feat_inference.py +413 -0
  284. pidsmaker/tasks/featurization.py +43 -0
  285. pidsmaker/tasks/training.py +19 -0
  286. pidsmaker/tasks/transformation.py +308 -0
  287. pidsmaker/tasks/triage.py +143 -0
  288. pidsmaker/tgn.py +635 -0
  289. pidsmaker/tokenization/__init__.py +112 -0
  290. pidsmaker/tokenization/base.py +58 -0
  291. pidsmaker/tokenization/bpe_tokenizer.py +83 -0
  292. pidsmaker/tokenization/hf_tokenizer.py +61 -0
  293. pidsmaker/tokenization/hierarchical_tokenizer.py +44 -0
  294. pidsmaker/tokenization/label_tokenizer.py +24 -0
  295. pidsmaker/tokenization/nltk_tokenizer.py +84 -0
  296. pidsmaker/tokenization/substitution.py +295 -0
  297. pidsmaker/triage/__init__.py +0 -0
  298. pidsmaker/triage/tracing_methods/__init__.py +1 -0
  299. pidsmaker/triage/tracing_methods/depimpact.py +213 -0
  300. pidsmaker/triage/tracing_methods/depimpact_utils.py +537 -0
  301. pidsmaker/triage/tracing_methods/ocrapt_subgraph.py +267 -0
  302. pidsmaker/utils/__init__.py +0 -0
  303. pidsmaker/utils/cache_utils.py +256 -0
  304. pidsmaker/utils/data_utils.py +1742 -0
  305. pidsmaker/utils/database.py +204 -0
  306. pidsmaker/utils/dataset_utils.py +413 -0
  307. pidsmaker/utils/dataset_writer.py +1057 -0
  308. pidsmaker/utils/graph_store.py +634 -0
  309. pidsmaker/utils/labelling.py +447 -0
  310. pidsmaker/utils/loss_files.py +193 -0
  311. pidsmaker/utils/process_tags.py +44 -0
  312. pidsmaker/utils/utils.py +730 -0
  313. pidsmaker/vizgen/__init__.py +1 -0
  314. pidsmaker/vizgen/dimensionality_reduction.py +249 -0
  315. pidsmaker/vizgen/embed_exporter.py +467 -0
  316. pidsmaker/vizgen/exporter.py +493 -0
  317. pidsmaker/vizgen/html_builder.py +936 -0
  318. pidsmaker/vizgen/web/__init__.py +1 -0
  319. pidsmaker/vizgen/web/export.py +62 -0
  320. pidsmaker/vizgen/web/static/css/app.css +250 -0
  321. pidsmaker/vizgen/web/static/index.html +182 -0
  322. pidsmaker/vizgen/web/static/js/app.js +627 -0
  323. pidsmaker/vizgen/web/static/js/campaign.js +123 -0
  324. pidsmaker/vizgen/web/static/js/data.js +119 -0
  325. pidsmaker/vizgen/web/static/js/dialogs.js +240 -0
  326. pidsmaker/vizgen/web/static/js/jobs.js +75 -0
  327. pidsmaker/vizgen/web/static/js/scene.js +651 -0
  328. pidsmaker/vizgen/web/static/js/ui.js +370 -0
  329. pidsmaker/vizgen/web/static/vendor/OrbitControls.js +1045 -0
  330. pidsmaker/vizgen/web/static/vendor/d3.v4.min.js +2 -0
  331. pidsmaker/vizgen/web/static/vendor/three.min.js +6 -0
  332. pidsmaker/vizgen/web/viz_server.py +2176 -0
  333. pidsmaker-4.0.0.dist-info/METADATA +596 -0
  334. pidsmaker-4.0.0.dist-info/RECORD +338 -0
  335. pidsmaker-4.0.0.dist-info/WHEEL +5 -0
  336. pidsmaker-4.0.0.dist-info/entry_points.txt +2 -0
  337. pidsmaker-4.0.0.dist-info/licenses/LICENSE +201 -0
  338. pidsmaker-4.0.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,1057 @@
1
+ """Writing of Parquet datasets (format and order of rows: see `pidsmaker/utils/database.py`).
2
+
3
+ Shared by the scripts that build datasets from their raw files (`dataset_preprocessing/`), which
4
+ give rows from Python (`DatasetBuilder`), and by the export of Postgres databases
5
+ (`dataset_preprocessing/export_parquet.py`), so that both write the same files:
6
+
7
+ - a node table is a single file, whose rows are in the physical order of the Postgres table
8
+ (the order of `SELECT * FROM table`). It is not exactly the order in which the rows were
9
+ inserted, as Postgres fills the free space of earlier pages with short rows: the builder
10
+ finds the position of each row as Postgres does (see `HeapLayout`);
11
+ - the event table is sorted by `timestamp_rec, event_uuid`, one file per day (UTC). DuckDB
12
+ compares strings byte by byte, Postgres with the collation of the database (en_US.utf8, which
13
+ ignores dashes and case at first). Both orders are the same when the event UUIDs pass
14
+ `check_tie_order`, whose result is recorded in the manifest (`tie_order`). Events of a same
15
+ timestamp and UUID (duplicate records), whose order Postgres does not define, are in the order
16
+ of their `_id` in the datasets of the builder.
17
+
18
+ Values are those that Postgres stored with the scripts that loaded the datasets into Postgres
19
+ (before Parquet): the columns of a table keep the names, order and types of the Postgres table
20
+ (see `TableSpec`), and the serial column `_id` of event tables numbers the events from 1 in the
21
+ order in which they are given.
22
+ """
23
+
24
+ import datetime
25
+ import json
26
+ import os
27
+ import shutil
28
+ import time
29
+ from dataclasses import dataclass
30
+
31
+ EVENT_ORDER = "timestamp_rec, event_uuid"
32
+ DAY_NS = 86_400 * 10**9
33
+ # Event UUIDs whose byte order is the order of the collation of Postgres (see `check_tie_order`)
34
+ UUID_PATTERNS = {
35
+ "uuid_upper": "[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}",
36
+ "uuid_lower": "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",
37
+ "alnum_upper": "[0-9A-Z]*",
38
+ "alnum_lower": "[0-9a-z]*",
39
+ }
40
+ # Collation of the Postgres databases of the datasets, whose order the event files follow
41
+ COLLATION = "en_US.utf8"
42
+ ROW_GROUP_SIZE = 1_000_000
43
+
44
+ # Postgres types of the columns of the datasets (as named by information_schema), and their
45
+ # DuckDB types
46
+ VARCHAR, BIGINT, INTEGER, SMALLINT, DOUBLE = (
47
+ "character varying",
48
+ "bigint",
49
+ "integer",
50
+ "smallint",
51
+ "double precision",
52
+ )
53
+ DUCKDB_TYPES = {
54
+ VARCHAR: "VARCHAR",
55
+ BIGINT: "BIGINT",
56
+ INTEGER: "INTEGER",
57
+ SMALLINT: "SMALLINT",
58
+ DOUBLE: "DOUBLE",
59
+ }
60
+ # Largest value of a serial column (SERIAL, BIGSERIAL), whose sequence fails beyond
61
+ SERIAL_MAX = {INTEGER: 2**31 - 1, BIGINT: 2**63 - 1}
62
+
63
+
64
+ def sql_str(s):
65
+ return "'" + s.replace("'", "''") + "'"
66
+
67
+
68
+ def sql_list(paths):
69
+ return "[" + ", ".join(sql_str(p) for p in paths) + "]"
70
+
71
+
72
+ def free_gb(path):
73
+ return shutil.disk_usage(path).free / 1e9
74
+
75
+
76
+ def utc_now():
77
+ return datetime.datetime.now(datetime.timezone.utc).isoformat(timespec="seconds")
78
+
79
+
80
+ def connect_duckdb(temp_dir, threads=None, memory_gb=None):
81
+ """DuckDB connection that writes Parquet files: rows of queries without ORDER BY are kept in
82
+ the order of their source, and large sorts spill to `temp_dir`."""
83
+ import duckdb
84
+
85
+ config = {"temp_directory": temp_dir, "preserve_insertion_order": True}
86
+ if threads:
87
+ config["threads"] = threads
88
+ if memory_gb:
89
+ config["memory_limit"] = f"{memory_gb}GB"
90
+ return duckdb.connect(config=config)
91
+
92
+
93
+ def copy_to_parquet(db, query, path, row_group_size=ROW_GROUP_SIZE):
94
+ """Writes the rows of `query` to the Parquet file `path`, in the order of the query."""
95
+ db.execute(
96
+ f"COPY ({query}) TO {sql_str(path)} "
97
+ f"(FORMAT parquet, COMPRESSION zstd, ROW_GROUP_SIZE {row_group_size});"
98
+ )
99
+
100
+
101
+ def count_rows(db, paths):
102
+ return db.execute(f"SELECT count(*) FROM read_parquet({sql_list(paths)});").fetchone()[0]
103
+
104
+
105
+ def check_tie_order(db, events, log=print):
106
+ """Whether the byte order of the event UUIDs of `events` (a DuckDB relation) is the order
107
+ of the collation of Postgres, for the events of a same timestamp.
108
+
109
+ Both orders are the same when all the event UUIDs are canonical UUIDs of a single case, or
110
+ alphanumeric strings of a single case, or more generally when no letter has both cases and
111
+ the events of each timestamp have IDs of the same shape (same length and separators at the
112
+ same places, e.g. `agraph_12_0000001` in LANL). Returns the name of the check that passed,
113
+ or `unverified`."""
114
+ checks = ", ".join(
115
+ f"count(*) FILTER (WHERE NOT regexp_full_match(event_uuid, '{p}'))"
116
+ for p in UUID_PATTERNS.values()
117
+ )
118
+ mismatches = db.execute(f"SELECT {checks} FROM {events};").fetchone()
119
+ patterns = [name for name, n in zip(UUID_PATTERNS, mismatches) if n == 0]
120
+ if patterns:
121
+ return patterns[0]
122
+ mixed_case = db.execute(
123
+ f"SELECT bool_or(regexp_matches(event_uuid, '[a-z]')) "
124
+ f"AND bool_or(regexp_matches(event_uuid, '[A-Z]')) FROM {events};"
125
+ ).fetchone()[0]
126
+ mixed_shapes = db.execute(
127
+ f"SELECT count(*) FROM (SELECT timestamp_rec FROM {events} GROUP BY timestamp_rec "
128
+ "HAVING count(DISTINCT regexp_replace(event_uuid, '[0-9A-Za-z]', 'x', 'g')) > 1);"
129
+ ).fetchone()[0]
130
+ if not mixed_case and mixed_shapes == 0:
131
+ return "same_shape_in_ties"
132
+ log(
133
+ f"WARNING: event UUIDs match none of {list(UUID_PATTERNS)}, letters of both cases: "
134
+ f"{bool(mixed_case)}, timestamps with UUIDs of several shapes: {mixed_shapes}. The order "
135
+ "of the events of a same timestamp may differ from Postgres"
136
+ )
137
+ return "unverified"
138
+
139
+
140
+ def write_events_by_day(
141
+ db, source, columns, staging, table_dir, row_group_size=ROW_GROUP_SIZE, log=print, order=None
142
+ ):
143
+ """Writes the events of `source` (a DuckDB relation with the `columns` of the event table)
144
+ sorted by `order` (default: `EVENT_ORDER`), one file per day (UTC) in `table_dir`.
145
+
146
+ Events are copied unsorted, partitioned by day, in `staging` (removed at the end), then
147
+ each day is sorted. Returns the description of the table in the manifest."""
148
+ db.execute(
149
+ f"COPY (SELECT *, timestamp_rec // {DAY_NS} AS _day FROM {source}) "
150
+ f"TO {sql_str(staging)} (FORMAT parquet, COMPRESSION zstd, PARTITION_BY (_day));"
151
+ )
152
+ log("copied, sorting each day")
153
+ stage = f"read_parquet({sql_str(staging + '/*/*.parquet')}, hive_partitioning = true)"
154
+
155
+ tie_order = check_tie_order(db, stage, log)
156
+
157
+ # Partition folders are `_day=<day>`, NULL timestamps (if any) in a non-numeric one, sorted
158
+ # last as by ORDER BY in Postgres
159
+ def day_key(folder):
160
+ value = folder.split("=", 1)[1]
161
+ return (0, int(value)) if value.lstrip("-").isdigit() else (1, 0)
162
+
163
+ names = ", ".join(f'"{n}"' for n in columns)
164
+ files = []
165
+ for folder in sorted(os.listdir(staging), key=day_key):
166
+ is_day, day = day_key(folder)
167
+ name = (
168
+ f"part-{datetime.datetime.utcfromtimestamp(day * 86400):%Y-%m-%d}.parquet"
169
+ if is_day == 0
170
+ else "part-null.parquet"
171
+ )
172
+ day_dir = os.path.join(staging, folder)
173
+ copy_to_parquet(
174
+ db,
175
+ f"SELECT {names} FROM read_parquet({sql_str(day_dir + '/*.parquet')}) "
176
+ f"ORDER BY {order or EVENT_ORDER}",
177
+ os.path.join(table_dir, name),
178
+ row_group_size,
179
+ )
180
+ files.append(name)
181
+ shutil.rmtree(day_dir)
182
+ shutil.rmtree(staging)
183
+ return {"files": files, "order": f"ORDER BY {EVENT_ORDER}", "tie_order": tie_order}
184
+
185
+
186
+ def write_manifest(dataset_dir, database, source, tables, collation=COLLATION, exported_at=None):
187
+ """Writes the manifest of a dataset. `tables` is {table: description} (files, order, number
188
+ of rows and columns of each table)."""
189
+ manifest = {
190
+ "format_version": 1,
191
+ "database": database,
192
+ "source": source,
193
+ "collation": collation,
194
+ "exported_at": exported_at or utc_now(),
195
+ "tables": tables,
196
+ }
197
+ with open(os.path.join(dataset_dir, "manifest.json"), "w") as f:
198
+ json.dump(manifest, f, indent=2)
199
+
200
+
201
+ # --------------------------------------------------------------------------------------
202
+ # Datasets built from Python
203
+ # --------------------------------------------------------------------------------------
204
+
205
+
206
+ @dataclass
207
+ class TableSpec:
208
+ """A table of a dataset.
209
+
210
+ Attributes:
211
+ name: name of the table.
212
+ columns: [(column, Postgres type)] in the order of the table.
213
+ not_null: columns that cannot be null (NOT NULL or primary key in Postgres).
214
+ serial: column numbering the rows from 1 in the order in which they are given, as a
215
+ SERIAL column of Postgres (filled by the writer, not given in rows), or None.
216
+ """
217
+
218
+ name: str
219
+ columns: list
220
+ not_null: tuple = ()
221
+ serial: str = None
222
+
223
+ @property
224
+ def names(self):
225
+ return [name for name, _ in self.columns]
226
+
227
+ @property
228
+ def row_columns(self):
229
+ """[(column, type)] of the values of the rows given to the writer (all but `serial`)."""
230
+ return [(name, kind) for name, kind in self.columns if name != self.serial]
231
+
232
+ @property
233
+ def is_event_table(self):
234
+ return "timestamp_rec" in self.names and "event_uuid" in self.names
235
+
236
+
237
+ def node_table_spec(table, attribute_columns):
238
+ """Node table: `node_uuid`, `hash_id`, the attribute columns (strings) and `index_id`."""
239
+ columns = [("node_uuid", VARCHAR), ("hash_id", VARCHAR)]
240
+ columns += [(column, VARCHAR) for column in attribute_columns] + [("index_id", BIGINT)]
241
+ return TableSpec(table, columns, not_null=("node_uuid", "hash_id"))
242
+
243
+
244
+ def event_table_spec(table, extra_columns=(), serial_type=BIGINT):
245
+ """Event table: the standard event columns, then `extra_columns` [(column, type)]."""
246
+ columns = [
247
+ ("src_node", VARCHAR),
248
+ ("src_index_id", VARCHAR),
249
+ ("operation", VARCHAR),
250
+ ("dst_node", VARCHAR),
251
+ ("dst_index_id", VARCHAR),
252
+ ("event_uuid", VARCHAR),
253
+ ("timestamp_rec", BIGINT),
254
+ ("_id", serial_type),
255
+ ] + list(extra_columns)
256
+ return TableSpec(table, columns, not_null=("event_uuid",), serial="_id")
257
+
258
+
259
+ def schema_tables(schema, serial_type=BIGINT):
260
+ """[TableSpec] of the tables of a dataset schema (see `pidsmaker/config/schemas.py`): a node
261
+ table per node type, with the columns of its attributes, and the event table, with the
262
+ columns of the edge attributes (strings for categorical ones, floats for numeric ones) and
263
+ the label column. The `_id` of events is an `integer` (SERIAL) in the databases of the
264
+ provenance datasets, a `bigint` (BIGSERIAL) in those of the network datasets."""
265
+ tables = [node_table_spec(nt.table, [col for _, col in nt.columns]) for nt in schema.node_types]
266
+ extra = [
267
+ (a.column, VARCHAR if a.kind == "categorical" else DOUBLE) for a in schema.edge_attributes
268
+ ]
269
+ if schema.label_column:
270
+ extra.append((schema.label_column, SMALLINT))
271
+ tables.append(event_table_spec(schema.event_table, extra, serial_type))
272
+ return tables
273
+
274
+
275
+ # --------------------------------------------------------------------------------------
276
+ # Physical order of the node tables
277
+ # --------------------------------------------------------------------------------------
278
+
279
+ # Constants of Postgres (8 kB pages, 8-byte MAXALIGN), see src/include/storage/bufpage.h,
280
+ # access/htup_details.h, storage/fsm_internals.h and access/heaptoast.h
281
+ BLCKSZ = 8192
282
+ PAGE_HEADER = 24
283
+ ITEM_ID = 4
284
+ TUPLE_HEADER = 23 # offsetof(HeapTupleHeaderData, t_bits)
285
+ MAX_HEAP_TUPLES_PER_PAGE = 291
286
+ TOAST_TUPLE_THRESHOLD = 2032
287
+ FSM_CAT_STEP = BLCKSZ // 256
288
+ MAX_FSM_REQUEST_SIZE = BLCKSZ - 32 # MaxHeapTupleSize
289
+ FSM_NODES = BLCKSZ - PAGE_HEADER - 4 # NodesPerPage
290
+ FSM_NON_LEAF_NODES = BLCKSZ // 2 - 1 # NonLeafNodesPerPage
291
+ FSM_SLOTS = FSM_NODES - FSM_NON_LEAF_NODES # SlotsPerFSMPage: heap pages per FSM leaf page
292
+
293
+
294
+ def _maxalign(n):
295
+ return (n + 7) & ~7
296
+
297
+
298
+ def heap_tuple_sizes(arrays, kinds):
299
+ """Length (t_len) of the heap tuples of the rows of a Postgres table, from the Arrow
300
+ arrays of its columns (`heap_form_tuple`): a header with the null bitmap, then the
301
+ values, aligned by type. Strings of at most 126 bytes have a 1-byte header and no
302
+ alignment, longer ones a 4-byte header and an alignment of 4 bytes. Values are not
303
+ compressed (tuples longer than TOAST_TUPLE_THRESHOLD are compressed by Postgres)."""
304
+ import numpy as np
305
+ import pyarrow.compute as pc
306
+
307
+ n = len(arrays[0])
308
+ offset = np.zeros(n, dtype=np.int64)
309
+ has_null = np.zeros(n, dtype=bool)
310
+ for array, kind in zip(arrays, kinds):
311
+ null = array.is_null().to_numpy(zero_copy_only=False)
312
+ has_null |= null
313
+ if kind == VARCHAR:
314
+ length = pc.fill_null(pc.binary_length(array), 0).to_numpy().astype(np.int64)
315
+ short = length <= 126
316
+ value = np.where(short, offset + length + 1, ((offset + 3) & ~3) + length + 4)
317
+ else:
318
+ size = {BIGINT: 8, DOUBLE: 8, INTEGER: 4, SMALLINT: 2}[kind]
319
+ value = ((offset + size - 1) & ~(size - 1)) + size
320
+ offset = np.where(null, offset, value)
321
+ bitmap = (len(kinds) + 7) // 8
322
+ header = np.where(has_null, _maxalign(TUPLE_HEADER + bitmap), _maxalign(TUPLE_HEADER))
323
+ return header + offset
324
+
325
+
326
+ class _FSMPage:
327
+ """A page of the free space map (FSM): a binary tree whose leaves are the free space
328
+ categories of the pages below it (heap pages, or FSM pages of the level below), and whose
329
+ nodes are the maximum of their children (storage/freespace/fsmpage.c)."""
330
+
331
+ def __init__(self):
332
+ self.nodes = bytearray(FSM_NODES)
333
+ self.next_slot = 0
334
+
335
+ def set_avail(self, slot, value):
336
+ nodes = self.nodes
337
+ node = FSM_NON_LEAF_NODES + slot
338
+ if nodes[node] == value and value <= nodes[0]:
339
+ return
340
+ nodes[node] = value
341
+ while node > 0:
342
+ node = (node - 1) // 2
343
+ left = 2 * node + 1
344
+ new = nodes[left]
345
+ if left + 1 < FSM_NODES:
346
+ new = max(new, nodes[left + 1])
347
+ if nodes[node] == new:
348
+ break
349
+ nodes[node] = new
350
+
351
+ def search_avail(self, min_value, advance_next):
352
+ """Slot with at least `min_value`, the first one to the right of `next_slot` (wrapping
353
+ around), or -1."""
354
+ nodes = self.nodes
355
+ if nodes[0] < min_value:
356
+ return -1
357
+ target = self.next_slot
358
+ if target < 0 or target >= FSM_SLOTS:
359
+ target = 0
360
+ node = target + FSM_NON_LEAF_NODES
361
+ while node > 0:
362
+ if nodes[node] >= min_value:
363
+ break
364
+ # Move right, wrapping around to the leftmost node of the next level, and climb up
365
+ node += 1
366
+ if ((node + 1) & node) == 0:
367
+ node = (node - 1) // 2
368
+ node = (node - 1) // 2
369
+ while node < FSM_NON_LEAF_NODES:
370
+ child = 2 * node + 1
371
+ if child < FSM_NODES and nodes[child] >= min_value:
372
+ node = child
373
+ elif child + 1 < FSM_NODES and nodes[child + 1] >= min_value:
374
+ node = child + 1
375
+ else:
376
+ raise RuntimeError("Inconsistent free space map")
377
+ slot = node - FSM_NON_LEAF_NODES
378
+ self.next_slot = slot + (1 if advance_next else 0)
379
+ return slot
380
+
381
+
382
+ def _avail_to_cat(avail):
383
+ return 255 if avail >= MAX_FSM_REQUEST_SIZE else min(avail // FSM_CAT_STEP, 254)
384
+
385
+
386
+ def _needed_to_cat(needed):
387
+ return 1 if needed == 0 else min((needed + FSM_CAT_STEP - 1) // FSM_CAT_STEP, 255)
388
+
389
+
390
+ class HeapLayout:
391
+ """Positions (page, line) of the rows inserted into a new Postgres table, in a single
392
+ session, which give its physical order: the order of `SELECT * FROM table`.
393
+
394
+ Rows are not stored in the order of their insertion. When a row does not fit in the
395
+ current page, Postgres records the free space of the page in the free space map (FSM),
396
+ and looks in the FSM for a page with enough space before adding pages to the table
397
+ (`RelationGetBufferForTuple` of access/heap/hio.c): a short row inserted after long ones
398
+ can thus fill the end of an earlier page. This emulates Postgres 17 on 8 kB pages, for
399
+ rows inserted by INSERT (`insert`, one row at a time), or by COPY (`multi_insert` of each
400
+ batch of rows, written to pages added several at a time, see `CopyLayout`,
401
+ `heap_multi_insert` of access/heap/heapam.c and `CopyFrom` of commands/copyfrom.c). The
402
+ positions are those of Postgres for tables of hundreds of thousands of rows loaded both
403
+ ways, and the physical order of the node tables of the DARPA TC and OpTC databases
404
+ (restored from dumps by COPY) is the order given by both emulations in a row. Rows longer
405
+ than TOAST_TUPLE_THRESHOLD, which Postgres compresses, are not supported."""
406
+
407
+ def __init__(self, bulk=False):
408
+ self.bulk = bulk # COPY, with a BulkInsertState
409
+ self.upper = [] # pd_upper of each page
410
+ self.lines = [] # number of line pointers of each page
411
+ self.fsm = {} # FSM pages, by (level, logical page number)
412
+ self.fsm_size = 0 # number of pages of the FSM
413
+ self.target = None # page of the last insertion
414
+ self.next_free = None # pages added in advance by COPY: next_free..last_free
415
+ self.last_free = None
416
+ self.extended_by = 0
417
+
418
+ # Free space map (storage/freespace/freespace.c), whose tree has 3 levels of FSM pages
419
+
420
+ @staticmethod
421
+ def _fsm_block(level, page):
422
+ """Block of an FSM page in the FSM (fsm_logical_to_physical)."""
423
+ leaf = page * FSM_SLOTS**level
424
+ pages = 0
425
+ for _ in range(3):
426
+ pages += leaf + 1
427
+ leaf //= FSM_SLOTS
428
+ return pages - level - 1
429
+
430
+ def _fsm_page(self, level, page, extend):
431
+ if self._fsm_block(level, page) >= self.fsm_size:
432
+ if not extend:
433
+ return None
434
+ self.fsm_size = self._fsm_block(level, page) + 1
435
+ fsm = self.fsm.get((level, page))
436
+ if fsm is None:
437
+ fsm = self.fsm[(level, page)] = _FSMPage()
438
+ return fsm
439
+
440
+ def _set_and_search(self, level, page, slot, value, min_value):
441
+ fsm = self._fsm_page(level, page, extend=True)
442
+ fsm.set_avail(slot, value)
443
+ return fsm.search_avail(min_value, level == 0) if min_value else -1
444
+
445
+ def _search(self, min_cat):
446
+ """fsm_search: a heap page with a category of at least `min_cat`, or None."""
447
+ level, page, restarts = 2, 0, 0
448
+ while True:
449
+ fsm = self._fsm_page(level, page, extend=False)
450
+ slot = -1 if fsm is None else fsm.search_avail(min_cat, level == 0)
451
+ if slot != -1:
452
+ if level == 0:
453
+ return page * FSM_SLOTS + slot
454
+ level, page = level - 1, page * FSM_SLOTS + slot
455
+ elif level == 2:
456
+ return None
457
+ else:
458
+ # The upper level was out of date: fix it and restart from the root
459
+ max_avail = 0 if fsm is None else fsm.nodes[0]
460
+ self._set_and_search(level + 1, page // FSM_SLOTS, page % FSM_SLOTS, max_avail, 0)
461
+ restarts += 1
462
+ if restarts > 10000:
463
+ return None
464
+ level, page = 2, 0
465
+
466
+ def _vacuum(self, level, page, start, end):
467
+ """fsm_vacuum_page: updates the upper levels from the leaves for heap pages
468
+ start..end-1. Returns (maximum category of the page, end of the FSM reached)."""
469
+ fsm = self._fsm_page(level, page, extend=False)
470
+ if fsm is None:
471
+ return 0, True
472
+ if level > 0:
473
+ start_page, start_slot = divmod(start, FSM_SLOTS)
474
+ end_page, end_slot = divmod(end - 1, FSM_SLOTS)
475
+ for _ in range(level):
476
+ start_page, start_slot = divmod(start_page, FSM_SLOTS)
477
+ end_page, end_slot = divmod(end_page, FSM_SLOTS)
478
+ if start_page != page:
479
+ start_slot = FSM_SLOTS if start_page > page else 0
480
+ if end_page != page:
481
+ end_slot = FSM_SLOTS - 1 if end_page > page else -1
482
+ eof = False
483
+ for slot in range(start_slot, end_slot + 1):
484
+ child = 0
485
+ if not eof:
486
+ child, eof = self._vacuum(level - 1, page * FSM_SLOTS + slot, start, end)
487
+ if fsm.nodes[FSM_NON_LEAF_NODES + slot] != child:
488
+ fsm.set_avail(slot, child)
489
+ fsm.next_slot = 0
490
+ return fsm.nodes[0], False
491
+
492
+ def _record(self, heap_page, avail):
493
+ """RecordPageWithFreeSpace."""
494
+ page, slot = divmod(heap_page, FSM_SLOTS)
495
+ self._set_and_search(0, page, slot, _avail_to_cat(avail), 0)
496
+
497
+ def _record_and_search(self, heap_page, avail, needed):
498
+ """RecordAndGetPageWithFreeSpace."""
499
+ page, slot = divmod(heap_page, FSM_SLOTS)
500
+ found = self._set_and_search(0, page, slot, _avail_to_cat(avail), _needed_to_cat(needed))
501
+ if found != -1 and page * FSM_SLOTS + found < len(self.upper):
502
+ return page * FSM_SLOTS + found
503
+ return self._search(_needed_to_cat(needed))
504
+
505
+ # Heap pages (access/heap/hio.c)
506
+
507
+ def _free_space(self, page):
508
+ """PageGetHeapFreeSpace."""
509
+ if self.lines[page] >= MAX_HEAP_TUPLES_PER_PAGE:
510
+ return 0
511
+ return max(self.upper[page] - (PAGE_HEADER + ITEM_ID * self.lines[page]) - ITEM_ID, 0)
512
+
513
+ def _add_pages(self, num_pages):
514
+ """RelationAddBlocks: adds pages to the table, and returns the first one."""
515
+ extend_by = num_pages
516
+ if self.bulk:
517
+ extend_by = max(extend_by, self.extended_by)
518
+ extend_by = min(extend_by, 64)
519
+ # Pages added for the rows to insert are not in the FSM
520
+ not_in_fsm = 1 if num_pages > 1 and not self.bulk else num_pages
521
+ first = len(self.upper)
522
+ self.upper += [BLCKSZ] * extend_by
523
+ self.lines += [0] * extend_by
524
+ for i in range(max(not_in_fsm, 1), extend_by):
525
+ self._record(first + i, BLCKSZ - PAGE_HEADER)
526
+ if not_in_fsm < extend_by:
527
+ self._vacuum(2, 0, first + not_in_fsm, first + extend_by)
528
+ if self.bulk:
529
+ if extend_by > 1:
530
+ self.next_free, self.last_free = first + 1, first + extend_by - 1
531
+ else:
532
+ self.next_free = self.last_free = None
533
+ self.extended_by += extend_by
534
+ return first
535
+
536
+ def _page_for(self, length, num_pages=1):
537
+ """RelationGetBufferForTuple: page of a row whose heap tuple has `length` bytes."""
538
+ needed = _maxalign(length)
539
+ page = self.target
540
+ if page is None:
541
+ page = self._search(_needed_to_cat(needed))
542
+ if page is None and self.upper:
543
+ page = len(self.upper) - 1
544
+ while page is not None:
545
+ avail = self._free_space(page)
546
+ if needed <= avail:
547
+ self.target = page
548
+ return page
549
+ if self.bulk and self.next_free is not None:
550
+ # Pages added in advance are used in order
551
+ self._record(page, avail)
552
+ page = self.next_free
553
+ if self.next_free >= self.last_free:
554
+ self.next_free = self.last_free = None
555
+ else:
556
+ self.next_free += 1
557
+ else:
558
+ page = self._record_and_search(page, avail, needed)
559
+ self.target = self._add_pages(max(num_pages, 1))
560
+ return self.target
561
+
562
+ def _put(self, page, length):
563
+ self.upper[page] -= _maxalign(length)
564
+ self.lines[page] += 1
565
+ return page, self.lines[page]
566
+
567
+ def insert(self, length):
568
+ """Position (page, line) of a row inserted by INSERT (heap_insert)."""
569
+ return self._put(self._page_for(length), length)
570
+
571
+ def multi_insert(self, lengths):
572
+ """Positions of a batch of rows inserted by COPY (heap_multi_insert)."""
573
+ positions, done, n = [], 0, len(lengths)
574
+ starting_with_empty_page, num_pages, used = False, 0, 0
575
+ while done < n:
576
+ if done == 0 or not starting_with_empty_page:
577
+ # Pages needed for the remaining rows (heap_multi_insert_pages)
578
+ num_pages, avail = 1, BLCKSZ - PAGE_HEADER
579
+ for length in lengths[done:]:
580
+ size = ITEM_ID + _maxalign(length)
581
+ if avail < size:
582
+ num_pages += 1
583
+ avail = BLCKSZ - PAGE_HEADER
584
+ avail -= size
585
+ used = 0
586
+ else:
587
+ used += 1
588
+ page = self._page_for(lengths[done], num_pages - used)
589
+ starting_with_empty_page = self.lines[page] == 0
590
+ positions.append(self._put(page, lengths[done]))
591
+ done += 1
592
+ while done < n and self._free_space(page) >= _maxalign(lengths[done]):
593
+ positions.append(self._put(page, lengths[done]))
594
+ done += 1
595
+ return positions
596
+
597
+
598
+ # Rows of a batch of COPY (MAX_BUFFERED_TUPLES and MAX_BUFFERED_BYTES of commands/copyfrom.c)
599
+ COPY_BATCH_ROWS = 1000
600
+ COPY_BATCH_BYTES = 65535
601
+
602
+
603
+ class CopyLayout:
604
+ """Positions of the rows loaded by a COPY, given the length of their tuples and of their
605
+ line in the input (without its end of line): rows are inserted by batches of
606
+ COPY_BATCH_ROWS rows, or less when their lines reach COPY_BATCH_BYTES bytes."""
607
+
608
+ def __init__(self):
609
+ self.heap = HeapLayout(bulk=True)
610
+ self.lengths = []
611
+ self.batch_bytes = 0
612
+
613
+ def add(self, length, line_length):
614
+ """Adds a row, and returns the positions of the rows of the batch it completes."""
615
+ self.lengths.append(length)
616
+ self.batch_bytes += line_length
617
+ if len(self.lengths) >= COPY_BATCH_ROWS or self.batch_bytes >= COPY_BATCH_BYTES:
618
+ return self.flush()
619
+ return []
620
+
621
+ def flush(self):
622
+ positions = self.heap.multi_insert(self.lengths) if self.lengths else []
623
+ self.lengths, self.batch_bytes = [], 0
624
+ return positions
625
+
626
+
627
+ def _text(value, column):
628
+ """Value of a text column, as stored by Postgres from a Python value."""
629
+ if value is None or isinstance(value, str):
630
+ return value
631
+ if isinstance(value, int) and not isinstance(value, bool):
632
+ return str(value)
633
+ raise TypeError(f"Invalid value {value!r} ({type(value).__name__}) of text column {column}")
634
+
635
+
636
+ def to_arrow(values, column, kind, not_null=False, empty_as_null=False):
637
+ """Arrow array of the Python values of a column of Postgres type `kind`.
638
+
639
+ Values are checked as Postgres checks them: integers must fit the type, strings cannot
640
+ contain NUL characters, and `not_null` columns cannot be null. Integers given to text
641
+ columns are stored as strings. With `empty_as_null`, empty strings are null, as with the
642
+ COPY (FORMAT csv) of Postgres."""
643
+ import pyarrow as pa
644
+ import pyarrow.compute as pc
645
+
646
+ if kind == VARCHAR:
647
+ try:
648
+ array = pa.array(values, pa.string())
649
+ except (pa.ArrowTypeError, pa.ArrowInvalid):
650
+ array = pa.array([_text(v, column) for v in values], pa.string())
651
+ if pc.any(pc.match_substring(array, "\x00")).as_py():
652
+ raise ValueError(f"Column {column}: strings cannot contain NUL (0x00) characters")
653
+ if empty_as_null:
654
+ array = pc.if_else(pc.equal(array, ""), pa.scalar(None, pa.string()), array)
655
+ elif kind == DOUBLE:
656
+ array = pa.array(values, pa.float64())
657
+ else:
658
+ # Integers are converted after inference, so that floats are refused (instead of
659
+ # being truncated), and values out of the range of the type raise an error
660
+ array = pa.array(values)
661
+ if not (pa.types.is_integer(array.type) or pa.types.is_null(array.type)):
662
+ raise TypeError(f"Column {column} ({kind}) expects integers, got {array.type}")
663
+ target = {BIGINT: pa.int64(), INTEGER: pa.int32(), SMALLINT: pa.int16()}[kind]
664
+ array = array.cast(target)
665
+ if not_null and array.null_count:
666
+ raise ValueError(f"Null value in column {column}, which cannot be null")
667
+ return array
668
+
669
+
670
+ INSERT, COPY = "insert", "copy"
671
+
672
+
673
+ class TableWriter:
674
+ """Appends rows to a staging Parquet file of a table, in order.
675
+
676
+ Rows are tuples of the values of `spec.row_columns`, which are converted as Postgres stores
677
+ them when they are loaded by `load`: INSERT (with psycopg2), or COPY (FORMAT csv) of the
678
+ rows written by `csv.writer` (empty strings are null). They are buffered and written by
679
+ batches of `buffer_rows`.
680
+
681
+ A writer of the event table can be used in another process than the builder (e.g. to load
682
+ files in parallel): its file is then given to `DatasetBuilder.add_staging_file`. The rows of
683
+ the other tables are written with the length of their heap tuple and of their line in the
684
+ COPY input, from which `DatasetBuilder` finds their position in the Postgres table (see
685
+ `HeapLayout`)."""
686
+
687
+ def __init__(self, spec, path, load=INSERT, buffer_rows=1_000_000):
688
+ import pyarrow as pa
689
+
690
+ if load not in (INSERT, COPY):
691
+ raise ValueError(f"Unknown load {load}")
692
+ self.spec = spec
693
+ self.path = path
694
+ self.load = load
695
+ self.buffer_rows = buffer_rows
696
+ self.columns = spec.row_columns
697
+ type_of = {VARCHAR: pa.string(), BIGINT: pa.int64(), INTEGER: pa.int32()}
698
+ type_of.update({SMALLINT: pa.int16(), DOUBLE: pa.float64()})
699
+ fields = [(name, type_of[kind]) for name, kind in self.columns]
700
+ self.physical = not spec.is_event_table
701
+ if self.physical:
702
+ fields += [("_tuple_length", pa.int32()), ("_line_length", pa.int32())]
703
+ self.schema = pa.schema(fields)
704
+ self.rows = []
705
+ self.num_rows = 0
706
+ self._writer = None
707
+
708
+ def add(self, row):
709
+ self.rows.append(row)
710
+ if len(self.rows) >= self.buffer_rows:
711
+ self.flush()
712
+
713
+ def add_rows(self, rows):
714
+ for row in rows:
715
+ self.add(row)
716
+
717
+ def _line_lengths(self):
718
+ """Lengths in bytes of the lines of COPY (FORMAT csv) of the rows, without end of line."""
719
+ import csv
720
+ import io
721
+
722
+ buffer = io.StringIO()
723
+ writer = csv.writer(buffer)
724
+ lengths = []
725
+ for row in self.rows:
726
+ buffer.seek(0)
727
+ buffer.truncate()
728
+ writer.writerow(row)
729
+ lengths.append(len(buffer.getvalue().encode()) - len(writer.dialect.lineterminator))
730
+ return lengths
731
+
732
+ def flush(self):
733
+ if not self.rows:
734
+ return
735
+ import pyarrow as pa
736
+ import pyarrow.parquet as pq
737
+
738
+ width = len(self.columns)
739
+ for row in self.rows:
740
+ if len(row) != width:
741
+ raise ValueError(
742
+ f"{self.spec.name}: row of {len(row)} values instead of {width}: {row!r}"
743
+ )
744
+ arrays = [
745
+ to_arrow(values, name, kind, name in self.spec.not_null, self.load == COPY)
746
+ for values, (name, kind) in zip(zip(*self.rows), self.columns)
747
+ ]
748
+ if self.physical:
749
+ sizes = heap_tuple_sizes(arrays, [kind for _, kind in self.columns])
750
+ lines = self._line_lengths() if self.load == COPY else [0] * len(self.rows)
751
+ arrays += [pa.array(sizes, pa.int32()), pa.array(lines, pa.int32())]
752
+ if self._writer is None:
753
+ os.makedirs(os.path.dirname(self.path), exist_ok=True)
754
+ self._writer = pq.ParquetWriter(
755
+ self.path, self.schema, compression="zstd", compression_level=1
756
+ )
757
+ self._writer.write_batch(pa.RecordBatch.from_arrays(arrays, schema=self.schema))
758
+ self.num_rows += len(self.rows)
759
+ self.rows = []
760
+ if self.spec.serial:
761
+ check_serial(self.spec, self.num_rows)
762
+
763
+ def close(self):
764
+ """Writes the remaining rows. Returns the number of rows of the file (no file is written
765
+ without rows)."""
766
+ self.flush()
767
+ if self._writer is not None:
768
+ self._writer.close()
769
+ self._writer = None
770
+ return self.num_rows
771
+
772
+
773
+ def physical_positions(path, load, log=print):
774
+ """Positions (pages, lines) in the Postgres table of the rows of a staging file of a node
775
+ table, in the order of the file (see `HeapLayout`)."""
776
+ import pyarrow.parquet as pq
777
+
778
+ table = pq.read_table(path, columns=["_tuple_length", "_line_length"])
779
+ lengths = table.column("_tuple_length").to_pylist()
780
+ toasted = sum(1 for length in lengths if length > TOAST_TUPLE_THRESHOLD)
781
+ if toasted:
782
+ log(
783
+ f"WARNING: {toasted} rows of {path} are longer than the TOAST threshold of Postgres "
784
+ f"({TOAST_TUPLE_THRESHOLD} bytes), which compresses them: the order of the rows may "
785
+ "differ from the order of the Postgres table"
786
+ )
787
+ if load == INSERT:
788
+ heap = HeapLayout()
789
+ positions = [heap.insert(length) for length in lengths]
790
+ else:
791
+ layout = CopyLayout()
792
+ positions = []
793
+ for length, line in zip(lengths, table.column("_line_length").to_pylist()):
794
+ positions += layout.add(length, line)
795
+ positions += layout.flush()
796
+ pages, lines = zip(*positions)
797
+ return pages, lines
798
+
799
+
800
+ def check_serial(spec, num_rows):
801
+ kind = dict(spec.columns)[spec.serial]
802
+ if num_rows > SERIAL_MAX[kind]:
803
+ raise OverflowError(
804
+ f"{spec.name}: {num_rows} rows, more than the maximum value of its serial column "
805
+ f"{spec.serial} ({kind}, {SERIAL_MAX[kind]})"
806
+ )
807
+
808
+
809
+ class DatasetBuilder:
810
+ """Builds a Parquet dataset from rows given by Python code.
811
+
812
+ with DatasetBuilder(dataset_dir, tables, source="...") as builder:
813
+ builder.table("file_node_table").add(row)
814
+ ...
815
+
816
+ Rows of each table are written to staging Parquet files as they come (see `TableWriter`),
817
+ so that memory does not depend on the size of the dataset. At the end of the `with` block
818
+ (or with `finish`), node tables are copied in the order of their rows, events are sorted
819
+ (see `write_events_by_day`), and the manifest is written. The dataset is written to
820
+ `<dataset_dir>.tmp`, renamed to `dataset_dir` when complete, and removed on errors.
821
+
822
+ Args:
823
+ dataset_dir: folder of the dataset (`<datasets_dir>/<database>`).
824
+ tables: [TableSpec] of the tables of the dataset.
825
+ source: how the dataset was built, recorded in the manifest.
826
+ overwrite: replaces an existing dataset (otherwise, raises FileExistsError).
827
+ load: how the scripts that built the dataset in Postgres loaded it (see `TableWriter`):
828
+ `insert` or `copy`. It determines the null values and the physical order of the node
829
+ tables.
830
+ threads, memory_gb: DuckDB threads and memory limit (default: DuckDB's defaults).
831
+ log: function printing progress messages.
832
+ """
833
+
834
+ def __init__(
835
+ self,
836
+ dataset_dir,
837
+ tables,
838
+ source,
839
+ overwrite=False,
840
+ load=INSERT,
841
+ threads=None,
842
+ memory_gb=None,
843
+ row_group_size=ROW_GROUP_SIZE,
844
+ log=print,
845
+ ):
846
+ self.dataset_dir = os.path.abspath(dataset_dir)
847
+ if os.path.exists(self.dataset_dir) and not overwrite:
848
+ raise FileExistsError(
849
+ f"The dataset {self.dataset_dir} already exists. Use --overwrite to replace it."
850
+ )
851
+ self.specs = {spec.name: spec for spec in tables}
852
+ self.source = source
853
+ self.load = load
854
+ self.threads = threads or min(16, os.cpu_count() or 1)
855
+ self.memory_gb = memory_gb
856
+ self.row_group_size = row_group_size
857
+ self.log = log
858
+ self.tmp_dir = self.dataset_dir + ".tmp"
859
+ if os.path.exists(self.tmp_dir):
860
+ shutil.rmtree(self.tmp_dir)
861
+ os.makedirs(self.tmp_dir)
862
+ self.staging_dir = os.path.join(self.tmp_dir, "_staging")
863
+ self._writers = {}
864
+ self._staging = {name: [] for name in self.specs} # [(path, number of rows)]
865
+ self._done = False
866
+
867
+ def table(self, name):
868
+ """TableWriter of a table, whose rows come after those of the files already added."""
869
+ if name not in self._writers:
870
+ self._writers[name] = TableWriter(
871
+ self.specs[name], self.staging_path(name, "main"), self.load
872
+ )
873
+ return self._writers[name]
874
+
875
+ def staging_path(self, table, key):
876
+ """Path of a staging file of a table, for a TableWriter of another process."""
877
+ return os.path.join(self.staging_dir, table, f"{key}.parquet")
878
+
879
+ def add_staging_file(self, table, path, num_rows):
880
+ """Adds the rows of a staging file of the event table (written by a TableWriter of
881
+ `spec(table)`) after the rows already added to the table."""
882
+ if not self.specs[table].is_event_table:
883
+ raise ValueError(f"{table}: the rows of node tables must be given by `table()`")
884
+ if num_rows:
885
+ self._staging[table].append((path, num_rows))
886
+
887
+ def spec(self, table):
888
+ return self.specs[table]
889
+
890
+ def __enter__(self):
891
+ return self
892
+
893
+ def __exit__(self, exc_type, exc, tb):
894
+ if exc_type is not None:
895
+ self.abort()
896
+ elif not self._done:
897
+ try:
898
+ self.finish()
899
+ except BaseException:
900
+ self.abort()
901
+ raise
902
+ return False
903
+
904
+ def abort(self):
905
+ for writer in self._writers.values():
906
+ try:
907
+ writer.close()
908
+ except Exception:
909
+ pass
910
+ shutil.rmtree(self.tmp_dir, ignore_errors=True)
911
+
912
+ def _query(self, db, spec, files):
913
+ """Query of the rows of a table (with the columns of the table): the rows of node tables
914
+ in the physical order of their Postgres table, events with their serial column."""
915
+ if not files:
916
+ cols = ", ".join(f'CAST(NULL AS {DUCKDB_TYPES[k]}) AS "{n}"' for n, k in spec.columns)
917
+ return f"SELECT {cols} LIMIT 0"
918
+ paths = sql_list([path for path, _ in files])
919
+ import pyarrow as pa
920
+
921
+ if not spec.serial:
922
+ # Rows in the physical order of the Postgres table (see `HeapLayout`)
923
+ ((path, num_rows),) = files
924
+ pages, lines = physical_positions(path, self.load, self.log)
925
+ view = f"_positions_{spec.name}"
926
+ positions = {"_row": range(num_rows), "_page": pages, "_line": lines}
927
+ db.register(view, pa.table(positions))
928
+ cols = ", ".join(f's."{n}"' for n in spec.names)
929
+ return (
930
+ f"SELECT {cols} FROM read_parquet({paths}, hive_partitioning = false, "
931
+ f"file_row_number = true) s JOIN {view} p ON s.file_row_number = p._row "
932
+ "ORDER BY p._page, p._line"
933
+ )
934
+ # The serial column numbers the rows in the order of the files and of their rows
935
+
936
+ offsets, total = [], 0
937
+ for _, num_rows in files:
938
+ offsets.append(total)
939
+ total += num_rows
940
+ check_serial(spec, total)
941
+ view = f"_offsets_{spec.name}"
942
+ db.register(view, pa.table({"_file": [p for p, _ in files], "_offset": offsets}))
943
+ kind = DUCKDB_TYPES[dict(spec.columns)[spec.serial]]
944
+ cols = ", ".join(
945
+ f'CAST(o._offset + s.file_row_number + 1 AS {kind}) AS "{n}"'
946
+ if n == spec.serial
947
+ else f's."{n}"'
948
+ for n in spec.names
949
+ )
950
+ return (
951
+ f"SELECT {cols} FROM read_parquet({paths}, hive_partitioning = false, "
952
+ f"filename = true, file_row_number = true) s JOIN {view} o ON s.filename = o._file"
953
+ )
954
+
955
+ def finish(self):
956
+ """Writes the tables and the manifest, and renames the dataset to its final folder."""
957
+ t0 = time.time()
958
+ for name, writer in self._writers.items():
959
+ # The rows of `table()` come after the files of other processes
960
+ if writer.close():
961
+ self._staging[name].append((writer.path, writer.num_rows))
962
+ duck_tmp = os.path.join(self.tmp_dir, "_duckdb_tmp")
963
+ db = connect_duckdb(duck_tmp, self.threads, self.memory_gb)
964
+ tables = {}
965
+ for name in sorted(self.specs):
966
+ spec, files = self.specs[name], self._staging[name]
967
+ expected = sum(n for _, n in files)
968
+ table_dir = os.path.join(self.tmp_dir, name)
969
+ os.makedirs(table_dir)
970
+ t = time.time()
971
+ query = self._query(db, spec, files)
972
+ if spec.is_event_table:
973
+ if not files:
974
+ raise ValueError(f"No events in {name}")
975
+ order = EVENT_ORDER + (f', "{spec.serial}"' if spec.serial else "")
976
+ info = write_events_by_day(
977
+ db,
978
+ f"({query})",
979
+ spec.names,
980
+ os.path.join(self.tmp_dir, f"_staging_{name}"),
981
+ table_dir,
982
+ self.row_group_size,
983
+ lambda msg: self.log(f"{name}: {msg}"),
984
+ order,
985
+ )
986
+ else:
987
+ path = os.path.join(table_dir, "part-00000.parquet")
988
+ copy_to_parquet(db, query, path, self.row_group_size)
989
+ info = {"files": ["part-00000.parquet"], "order": "physical"}
990
+ num_rows = count_rows(db, [os.path.join(table_dir, f) for f in info["files"]])
991
+ if num_rows != expected:
992
+ raise RuntimeError(f"{name}: {num_rows} rows written, {expected} given")
993
+ info.update(num_rows=num_rows, columns=[list(c) for c in spec.columns])
994
+ tables[name] = info
995
+ for path, _ in files:
996
+ os.remove(path)
997
+ self.log(
998
+ f"{name}: {num_rows:,} rows, {len(info['files'])} files ({time.time() - t:.0f}s)"
999
+ )
1000
+ db.close()
1001
+ shutil.rmtree(duck_tmp, ignore_errors=True)
1002
+ shutil.rmtree(self.staging_dir, ignore_errors=True)
1003
+ write_manifest(self.tmp_dir, os.path.basename(self.dataset_dir), self.source, tables)
1004
+ if os.path.exists(self.dataset_dir):
1005
+ shutil.rmtree(self.dataset_dir)
1006
+ os.rename(self.tmp_dir, self.dataset_dir)
1007
+ self._done = True
1008
+ size = sum(
1009
+ os.path.getsize(os.path.join(root, f))
1010
+ for root, _, names in os.walk(self.dataset_dir)
1011
+ for f in names
1012
+ )
1013
+ self.log(
1014
+ f"Dataset written to {self.dataset_dir}: {size / 1e9:.2f} GB "
1015
+ f"({(time.time() - t0) / 60:.1f} min to sort and write the tables)"
1016
+ )
1017
+
1018
+
1019
+ def update_table(dataset_dir, table, column, value, where, relations=None, note=None, log=print):
1020
+ """`UPDATE table SET column = value WHERE where` on a Parquet dataset: rewrites the files of
1021
+ the table in place (rows keep their order). `relations` ({name: Arrow table}) are tables
1022
+ that `where` may query. `note` is added to the source of the dataset in its manifest.
1023
+ Returns the number of rows matched by `where`."""
1024
+ with open(os.path.join(dataset_dir, "manifest.json")) as f:
1025
+ manifest = json.load(f)
1026
+ info = manifest["tables"][table]
1027
+ db = connect_duckdb(os.path.join(dataset_dir, "_duckdb_tmp"))
1028
+ for name, relation in (relations or {}).items():
1029
+ db.register(name, relation)
1030
+ cols = ", ".join(
1031
+ f'CAST(CASE WHEN {where} THEN {value} ELSE "{name}" END AS {DUCKDB_TYPES[kind]}) '
1032
+ f'AS "{name}"'
1033
+ if name == column
1034
+ else f'"{name}"'
1035
+ for name, kind in info["columns"]
1036
+ )
1037
+ updated = 0
1038
+ for name in info["files"]:
1039
+ path = os.path.join(dataset_dir, table, name)
1040
+ rows = f"read_parquet({sql_str(path)}, file_row_number = true)"
1041
+ n = db.execute(f"SELECT count(*) FROM {rows} WHERE {where};").fetchone()[0]
1042
+ if n:
1043
+ tmp = path + ".tmp"
1044
+ # `where` may be a join, which does not keep the order of the rows
1045
+ copy_to_parquet(db, f"SELECT {cols} FROM {rows} ORDER BY file_row_number", tmp)
1046
+ if count_rows(db, [tmp]) != count_rows(db, [path]):
1047
+ raise RuntimeError(f"{tmp}: wrong number of rows")
1048
+ os.replace(tmp, path)
1049
+ log(f"{table}/{name}: {n} rows updated")
1050
+ updated += n
1051
+ db.close()
1052
+ shutil.rmtree(os.path.join(dataset_dir, "_duckdb_tmp"), ignore_errors=True)
1053
+ if note and note not in manifest["source"]:
1054
+ manifest["source"] += f", {note}"
1055
+ with open(os.path.join(dataset_dir, "manifest.json"), "w") as f:
1056
+ json.dump(manifest, f, indent=2)
1057
+ return updated