Repository navigation
Expand file tree
/
Copy pathpost-ingest.py
More file actions
executable file
·1009 lines (885 loc) · 39.4 KB
/
Copy pathpost-ingest.py
File metadata and controls
executable file
·1009 lines (885 loc) · 39.4 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
#!/usr/bin/env python3
# /// script
# requires-python = ">=3.11"
# dependencies = []
# ///
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright the Vortex contributors
"""Ingest benchmark JSONL records into the v4 Postgres store.
`vortex-bench --ingest-jsonl` writes the current versioned JSONL record shape. This script
fills commit metadata from `git show`, computes the internal `measurement_id`,
then atomically upserts the whole file into the RDS fact tables.
The wire contract is shared with the benchmarks-website repository:
- `vortex-bench/src/v3.rs` owns the producer record shape.
- `benchmarks-website/CONTRACT.md` documents the transport and schema contract.
- `benchmarks-website/web/lib/schema-version.ts` is the `SCHEMA_VERSION` source
of truth that the constant below must match.
"""
from __future__ import annotations
import argparse
import json
import math
import os
import subprocess
import sys
import urllib.request
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
from types import ModuleType
# MUST equal `benchmarks-website/web/lib/schema-version.ts::SCHEMA_VERSION`.
# Bumping this is a coordinated change across the website contract, v3.rs, and
# this script.
SCHEMA_VERSION = 3
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description="Ingest benchmark JSONL records into RDS Postgres.")
parser.add_argument(
"jsonl_path",
type=Path,
help="Path to the JSONL file written by vortex-bench --ingest-jsonl.",
)
parser.add_argument(
"--postgres",
metavar="DSN",
required=True,
help=(
"Libpq DSN for the RDS Postgres ingest target, e.g. "
"'postgresql://bench_ingest@host:5432/benchmarks?sslmode=verify-full"
"&sslrootcert=/path/rds-ca.pem'. Computes measurement_id locally and "
"upserts via INSERT ... ON CONFLICT DO UPDATE. If the DSN carries no "
"password, an RDS IAM auth token is minted for the DSN's user."
),
)
parser.add_argument(
"--region",
default=None,
help=(
"AWS region for RDS IAM token minting. Precedence: "
"this explicit --region, then the boto3 session region, then the region "
"parsed from the RDS hostname."
),
)
parser.add_argument(
"--commit-sha",
required=True,
help="40-hex commit SHA. Usually ${{ github.sha }} in CI.",
)
parser.add_argument(
"--repo-url",
default="https://github.com/vortex-data/vortex",
help="Base repo URL used to build the commits.url field.",
)
parser.add_argument(
"--git-dir",
type=Path,
default=None,
help="Run `git show` in this directory (default: current directory).",
)
parser.add_argument(
"--timeout",
type=float,
default=30.0,
help="Site cache refresh timeout in seconds (default: 30).",
)
return parser.parse_args()
def read_records(path: Path) -> list[dict]:
# The JSONL comes from the project's own `vortex-bench` CI on the same run (trusted UTF-8
# input); a malformed line still fails loud with `path:line` context for debuggability.
records: list[dict] = []
with path.open(encoding="utf-8") as f:
for line_no, line in enumerate(f, start=1):
line = line.strip()
if not line:
continue
try:
records.append(json.loads(line))
except json.JSONDecodeError as exc:
raise SystemExit(f"{path}:{line_no}: invalid JSON: {exc}") from exc
return records
def git_show_field(sha: str, fmt: str, cwd: Path | None) -> str:
"""Run `git show -s --format=<fmt> <sha>` and return its stdout (stripped).
The metadata comes from the project's own (UTF-8) git history.
"""
result = subprocess.run(
["git", "show", "-s", f"--format={fmt}", sha],
cwd=cwd,
check=True,
capture_output=True,
text=True,
)
return result.stdout.strip()
def build_commit(sha: str, repo_url: str, git_dir: Path | None) -> dict:
sha = sha.strip().lower()
if len(sha) != 40 or any(c not in "0123456789abcdef" for c in sha):
raise SystemExit(f"commit SHA must be 40-hex lowercase, got: {sha!r}")
timestamp = git_show_field(sha, "%cI", git_dir)
message = git_show_field(sha, "%s", git_dir)
author_name = git_show_field(sha, "%an", git_dir)
author_email = git_show_field(sha, "%ae", git_dir)
committer_name = git_show_field(sha, "%cn", git_dir)
committer_email = git_show_field(sha, "%ce", git_dir)
tree_sha = git_show_field(sha, "%T", git_dir)
return {
"sha": sha,
"timestamp": timestamp,
"message": message,
"author_name": author_name,
"author_email": author_email,
"committer_name": committer_name,
"committer_email": committer_email,
"tree_sha": tree_sha,
"url": f"{repo_url.rstrip('/')}/commit/{sha}",
}
# `psycopg`, `boto3`, and `_measurement_id` (which pulls in `xxhash`) are
# imported lazily below so `--help` and syntax checks need no optional packages.
# Per-`kind` record field sets. `required` plus `optional` is the exact set of
# fields a record of that `kind` may carry (besides `kind` itself); unknown
# fields fail loudly so producer/schema drift cannot silently drop data.
# `optional` fields default to NULL.
_RECORD_FIELDS: dict[str, tuple[frozenset[str], frozenset[str]]] = {
"query_measurement": (
frozenset(
{
"commit_sha",
"dataset",
"query_idx",
"storage",
"engine",
"format",
"value_ns",
"all_runtimes_ns",
}
),
frozenset(
{
"dataset_variant",
"scale_factor",
"peak_physical",
"peak_virtual",
"physical_delta",
"virtual_delta",
"env_triple",
}
),
),
"compression_time": (
frozenset({"commit_sha", "dataset", "format", "op", "value_ns", "all_runtimes_ns"}),
frozenset({"dataset_variant", "env_triple"}),
),
"compression_size": (
frozenset({"commit_sha", "dataset", "format", "value_bytes", "uncompressed_bytes"}),
frozenset({"dataset_variant"}),
),
"random_access_time": (
frozenset({"commit_sha", "dataset", "format", "open_mode", "value_ns", "all_runtimes_ns"}),
frozenset({"env_triple"}),
),
"vector_search_run": (
frozenset(
{
"commit_sha",
"dataset",
"layout",
"flavor",
"threshold",
"value_ns",
"all_runtimes_ns",
"matches",
"rows_scanned",
"bytes_scanned",
"iterations",
}
),
frozenset({"env_triple"}),
),
}
_MEASUREMENT_ID_MODULE: ModuleType | None = None
def _measurement_id_module() -> ModuleType:
"""Lazily load `scripts/_measurement_id.py` by path (cached).
Loaded by file path rather than `import _measurement_id` so it resolves
regardless of cwd / `sys.path` (the test harness loads sibling scripts the
same way). Importing it pulls in `xxhash`, so it only happens here on the
`--postgres` path.
"""
global _MEASUREMENT_ID_MODULE
if _MEASUREMENT_ID_MODULE is None:
import importlib.util
path = Path(__file__).resolve().parent / "_measurement_id.py"
spec = importlib.util.spec_from_file_location("_measurement_id", path)
assert spec is not None and spec.loader is not None
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
_MEASUREMENT_ID_MODULE = module
return _MEASUREMENT_ID_MODULE
def _validate_record_fields(record: object, index: int) -> str:
"""Validate a record's `kind` and field set; return the `kind`.
A non-object record, an unknown `kind`, an unknown field, or a missing
required field is a loud error keyed by the record's index.
"""
if not isinstance(record, dict):
raise SystemExit(f"record {index}: expected a JSON object, got {type(record).__name__}")
kind = record.get("kind")
# `isinstance(kind, str)` first: a non-scalar kind (e.g. a list) is unhashable
# and would raise TypeError at the `in` membership check rather than this
# controlled record-indexed error.
if not isinstance(kind, str) or kind not in _RECORD_FIELDS:
raise SystemExit(f"record {index}: unknown kind {kind!r}; expected one of {sorted(_RECORD_FIELDS)}")
required, optional = _RECORD_FIELDS[kind]
present = set(record) - {"kind"}
unknown = present - required - optional
if unknown:
raise SystemExit(f"record {index} ({kind}): unknown field(s) {sorted(unknown)}")
missing = required - present
if missing:
raise SystemExit(f"record {index} ({kind}): missing required field(s) {sorted(missing)}")
return kind
def _require_finite(value: object, field: str, kind: str, index: int) -> None:
"""Raise loudly unless `value` is a finite number.
Guards every f64 dim that feeds a `measurement_id` hash (currently only
`vector_search_run.threshold`). A NaN/Inf would hash differently across the
Rust `to_bits()` and Python `struct.pack('<d', ...)` encodings, silently
producing a duplicate row instead of an upsert; fail loud instead.
"""
is_finite_number = isinstance(value, (int, float)) and not isinstance(value, bool)
if is_finite_number:
is_finite_number = math.isfinite(value)
if not is_finite_number:
raise SystemExit(
f"record {index} ({kind}): {field}={value!r} is not a finite number; refusing to "
"write a row whose measurement_id would diverge between the Rust and Python hashers "
"(NaN/Inf bit patterns differ across struct.pack and to_bits)."
)
# i32/i64 bounds enforced by the Postgres INTEGER/BIGINT columns.
_INT32_MIN, _INT32_MAX = -(2**31), 2**31 - 1
_INT64_MIN, _INT64_MAX = -(2**63), 2**63 - 1
def _require_int(value: object, field: str, kind: str, index: int, *, bits: int) -> None:
"""Raise loudly unless `value` is a plain (non-bool) integer within i32/i64 range.
The integer columns bind straight to INTEGER/BIGINT; psycopg adapts a Python
float to float8 and Postgres assignment-casts (rounds) it, so a JSON float
would silently persist a rounded value. An out-of-range integer would otherwise fail late as an uncaught
`struct.error` (i32 hash dims via `_write_i32`) or a raw Postgres 22003
overflow; validate the type AND width here so a malformed scalar fails loud
with its record index.
"""
lo, hi = (_INT32_MIN, _INT32_MAX) if bits == 32 else (_INT64_MIN, _INT64_MAX)
if isinstance(value, bool) or not isinstance(value, int):
raise SystemExit(f"record {index} ({kind}): {field} must be an integer, got {value!r}")
if not (lo <= value <= hi):
raise SystemExit(f"record {index} ({kind}): {field}={value!r} is out of int{bits} range")
def _require_int_list(value: object, field: str, kind: str, index: int) -> None:
"""Raise loudly unless `value` is a JSON array of plain (non-bool) i64 integers.
Guards the `all_runtimes_ns` -> `bigint[]` bind: the explicit `::bigint[]`
cast accepts values that are not valid JSON integer arrays. psycopg
sends the string `"{}"` as text and the cast parses it into an empty array, a
`[1, null]` list adapts to `{1,NULL}`, and an out-of-i64 element hits a raw
Postgres 22003. Validate the element type AND i64 range so a malformed value
fails loud.
"""
if not isinstance(value, list) or any(isinstance(x, bool) or not isinstance(x, int) for x in value):
raise SystemExit(f"record {index} ({kind}): {field} must be a JSON array of integers, got {value!r}")
if any(not (_INT64_MIN <= x <= _INT64_MAX) for x in value):
raise SystemExit(f"record {index} ({kind}): {field} has an element out of int64 range")
def _require_str(value: object, field: str, kind: str, index: int) -> None:
"""Raise loudly unless `value` is a string."""
if not isinstance(value, str):
raise SystemExit(f"record {index} ({kind}): {field} must be a string, got {value!r}")
def _require_opt_str(value: object, field: str, kind: str, index: int) -> None:
"""Raise loudly unless `value` is a string or null. Mirrors `Option<String>`."""
if value is not None and not isinstance(value, str):
raise SystemExit(f"record {index} ({kind}): {field} must be a string or null, got {value!r}")
def _memory_quartet_consistent(r: dict) -> bool:
"""The four `query_measurements` memory columns are all set or all absent.
A partial quartet is a validation error, not a half-populated row.
"""
present = [
r.get("peak_physical") is not None,
r.get("peak_virtual") is not None,
r.get("physical_delta") is not None,
r.get("virtual_delta") is not None,
]
return not any(present) or all(present)
# Per-kind field -> type token. Every field is type/range-validated before the
# direct Postgres write. Tokens:
# "str" required String "opt_str" Option<String>
# "i32" required i32 "i64" required i64
# "opt_i64" Option<i64> "i64_list" Vec<i64> (all_runtimes_ns)
# "f64" finite f64 (threshold).
# Required tokens (every non-opt_*) line up with `_RECORD_FIELDS` required sets, so
# `record[field]` is always present by the time `_validate_record_values` runs.
_FIELD_TYPES: dict[str, tuple[tuple[str, str], ...]] = {
"query_measurement": (
("commit_sha", "str"),
("dataset", "str"),
("dataset_variant", "opt_str"),
("scale_factor", "opt_str"),
("query_idx", "i32"),
("storage", "str"),
("engine", "str"),
("format", "str"),
("value_ns", "i64"),
("all_runtimes_ns", "i64_list"),
("peak_physical", "opt_i64"),
("peak_virtual", "opt_i64"),
("physical_delta", "opt_i64"),
("virtual_delta", "opt_i64"),
("env_triple", "opt_str"),
),
"compression_time": (
("commit_sha", "str"),
("dataset", "str"),
("dataset_variant", "opt_str"),
("format", "str"),
("op", "str"),
("value_ns", "i64"),
("all_runtimes_ns", "i64_list"),
("env_triple", "opt_str"),
),
"compression_size": (
("commit_sha", "str"),
("dataset", "str"),
("dataset_variant", "opt_str"),
("format", "str"),
("value_bytes", "i64"),
("uncompressed_bytes", "i64"),
),
"random_access_time": (
("commit_sha", "str"),
("dataset", "str"),
("format", "str"),
("open_mode", "str"),
("value_ns", "i64"),
("all_runtimes_ns", "i64_list"),
("env_triple", "opt_str"),
),
"vector_search_run": (
("commit_sha", "str"),
("dataset", "str"),
("layout", "str"),
("flavor", "str"),
("threshold", "f64"),
("value_ns", "i64"),
("all_runtimes_ns", "i64_list"),
("matches", "i64"),
("rows_scanned", "i64"),
("bytes_scanned", "i64"),
("iterations", "i32"),
("env_triple", "opt_str"),
),
}
def _validate_record_values(record: dict, kind: str, index: int) -> None:
"""Validate every field's type/range before the Postgres write.
Runs before any transaction, where the record index is known. It drives
type/range checks from `_FIELD_TYPES`, then applies semantic checks the type
alone does not cover (the storage enum + memory quartet for query_measurements).
"""
for field, typ in _FIELD_TYPES[kind]:
if typ == "str":
_require_str(record[field], field, kind, index)
elif typ == "opt_str":
_require_opt_str(record.get(field), field, kind, index)
elif typ == "i32":
_require_int(record[field], field, kind, index, bits=32)
elif typ == "i64":
_require_int(record[field], field, kind, index, bits=64)
elif typ == "opt_i64":
if record.get(field) is not None:
_require_int(record[field], field, kind, index, bits=64)
elif typ == "i64_list":
_require_int_list(record[field], field, kind, index)
elif typ == "f64":
_require_finite(record[field], field, kind, index)
if kind == "query_measurement":
if record["storage"] not in ("nvme", "s3"):
raise SystemExit(
f"record {index} (query_measurement): storage must be 'nvme' or 's3', got {record['storage']!r}"
)
if not _memory_quartet_consistent(record):
raise SystemExit(
f"record {index} (query_measurement): memory fields must be populated together (all four or none)"
)
elif kind == "random_access_time" and record["open_mode"] not in ("cached", "reopen"):
raise SystemExit(
f"record {index} (random_access_time): open_mode must be 'cached' or 'reopen', got {record['open_mode']!r}"
)
def _upsert_returning_was_update(conn, sql: str, params: tuple) -> bool:
"""Run an `INSERT ... ON CONFLICT DO UPDATE ... RETURNING (xmax = 0)` upsert
and return whether the row was an update (vs a fresh insert).
Classifies inserted-vs-updated atomically from the upsert itself: a fresh
INSERT leaves the new tuple's system column `xmax = 0`, while `ON CONFLICT
DO UPDATE` stamps `xmax` with the current transaction id. A preflight SELECT
(the prior approach) would race the upsert under concurrent re-ingest of the
same `measurement_id`, miscounting a concurrent loser as inserted; deriving
the flag from the single atomic statement removes that window. A duplicate
`measurement_id` within ONE transaction is also handled correctly: the second
upsert locks the tuple the first created (stamping its xmax), so it is
classified as an update. `sql` must end with
`RETURNING (xmax = 0) AS inserted`.
"""
row = conn.execute(sql, params).fetchone()
return not row[0]
def _query_measurement_id(mid_mod, r: dict) -> int:
"""Compute the `query_measurements` primary key."""
return mid_mod.measurement_id_query(
commit_sha=r["commit_sha"],
dataset=r["dataset"],
dataset_variant=r.get("dataset_variant"),
scale_factor=r.get("scale_factor"),
query_idx=r["query_idx"],
storage=r["storage"],
engine=r["engine"],
format=r["format"],
)
def _insert_query_measurement(conn, mid: int, r: dict) -> bool:
"""Upsert a `query_measurements` row.
Record values are validated by `_validate_record_values` before dispatch.
"""
return _upsert_returning_was_update(
conn,
"""
INSERT INTO query_measurements (
measurement_id, commit_sha, dataset, dataset_variant, scale_factor,
query_idx, storage, engine, format,
value_ns, all_runtimes_ns,
peak_physical, peak_virtual, physical_delta, virtual_delta,
env_triple, commit_timestamp
) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s::bigint[], %s, %s, %s, %s, %s,
(SELECT timestamp FROM commits WHERE commit_sha = %s))
ON CONFLICT (measurement_id) DO UPDATE SET
commit_sha = excluded.commit_sha,
value_ns = excluded.value_ns,
all_runtimes_ns = excluded.all_runtimes_ns,
peak_physical = excluded.peak_physical,
peak_virtual = excluded.peak_virtual,
physical_delta = excluded.physical_delta,
virtual_delta = excluded.virtual_delta,
env_triple = excluded.env_triple,
commit_timestamp = excluded.commit_timestamp
RETURNING (xmax = 0) AS inserted
""",
(
mid,
r["commit_sha"],
r["dataset"],
r.get("dataset_variant"),
r.get("scale_factor"),
r["query_idx"],
r["storage"],
r["engine"],
r["format"],
r["value_ns"],
r["all_runtimes_ns"],
r.get("peak_physical"),
r.get("peak_virtual"),
r.get("physical_delta"),
r.get("virtual_delta"),
r.get("env_triple"),
# The denormalized `commit_timestamp` (migration 006) is resolved from the
# `commits` row that `ingest_postgres` commits before the fact transaction, so the
# read path's latest-per-series summary never sees a NULL from this writer.
r["commit_sha"],
),
)
def _compression_time_id(mid_mod, r: dict) -> int:
"""Compute the `compression_times` primary key."""
return mid_mod.measurement_id_compression_time(
commit_sha=r["commit_sha"],
dataset=r["dataset"],
dataset_variant=r.get("dataset_variant"),
format=r["format"],
op=r["op"],
)
def _insert_compression_time(conn, mid: int, r: dict) -> bool:
"""Upsert a `compression_times` row."""
return _upsert_returning_was_update(
conn,
"""
INSERT INTO compression_times (
measurement_id, commit_sha, dataset, dataset_variant,
format, op, value_ns, all_runtimes_ns, env_triple
) VALUES (%s, %s, %s, %s, %s, %s, %s, %s::bigint[], %s)
ON CONFLICT (measurement_id) DO UPDATE SET
commit_sha = excluded.commit_sha,
value_ns = excluded.value_ns,
all_runtimes_ns = excluded.all_runtimes_ns,
env_triple = excluded.env_triple
RETURNING (xmax = 0) AS inserted
""",
(
mid,
r["commit_sha"],
r["dataset"],
r.get("dataset_variant"),
r["format"],
r["op"],
r["value_ns"],
r["all_runtimes_ns"],
r.get("env_triple"),
),
)
def _compression_size_id(mid_mod, r: dict) -> int:
"""Compute the `compression_sizes` primary key."""
return mid_mod.measurement_id_compression_size(
commit_sha=r["commit_sha"],
dataset=r["dataset"],
dataset_variant=r.get("dataset_variant"),
format=r["format"],
)
def _insert_compression_size(conn, mid: int, r: dict) -> bool:
"""Upsert a `compression_sizes` row."""
return _upsert_returning_was_update(
conn,
"""
INSERT INTO compression_sizes (
measurement_id, commit_sha, dataset, dataset_variant,
format, value_bytes, uncompressed_bytes
) VALUES (%s, %s, %s, %s, %s, %s, %s)
ON CONFLICT (measurement_id) DO UPDATE SET
commit_sha = excluded.commit_sha,
value_bytes = excluded.value_bytes,
uncompressed_bytes = excluded.uncompressed_bytes
RETURNING (xmax = 0) AS inserted
""",
(
mid,
r["commit_sha"],
r["dataset"],
r.get("dataset_variant"),
r["format"],
r["value_bytes"],
r["uncompressed_bytes"],
),
)
def _random_access_time_id(mid_mod, r: dict) -> int:
"""Compute the `random_access_times` primary key."""
return mid_mod.measurement_id_random_access(
commit_sha=r["commit_sha"],
dataset=r["dataset"],
format=r["format"],
open_mode=r["open_mode"],
)
def _insert_random_access(conn, mid: int, r: dict) -> bool:
"""Upsert a `random_access_times` row."""
return _upsert_returning_was_update(
conn,
"""
INSERT INTO random_access_times (
measurement_id, commit_sha, dataset, format, open_mode,
value_ns, all_runtimes_ns, env_triple
) VALUES (%s, %s, %s, %s, %s, %s, %s::bigint[], %s)
ON CONFLICT (measurement_id) DO UPDATE SET
commit_sha = excluded.commit_sha,
open_mode = excluded.open_mode,
value_ns = excluded.value_ns,
all_runtimes_ns = excluded.all_runtimes_ns,
env_triple = excluded.env_triple
RETURNING (xmax = 0) AS inserted
""",
(
mid,
r["commit_sha"],
r["dataset"],
r["format"],
r["open_mode"],
r["value_ns"],
r["all_runtimes_ns"],
r.get("env_triple"),
),
)
def _vector_search_run_id(mid_mod, r: dict) -> int:
"""Compute the `vector_search_runs` primary key."""
return mid_mod.measurement_id_vector_search(
commit_sha=r["commit_sha"],
dataset=r["dataset"],
layout=r["layout"],
flavor=r["flavor"],
threshold=float(r["threshold"]),
)
def _insert_vector_search(conn, mid: int, r: dict) -> bool:
"""Upsert a `vector_search_runs` row.
`threshold` is validated finite by `_validate_record_values` before dispatch.
"""
threshold = float(r["threshold"])
return _upsert_returning_was_update(
conn,
"""
INSERT INTO vector_search_runs (
measurement_id, commit_sha, dataset, layout, flavor, threshold,
value_ns, all_runtimes_ns, matches, rows_scanned, bytes_scanned,
iterations, env_triple
) VALUES (%s, %s, %s, %s, %s, %s, %s, %s::bigint[], %s, %s, %s, %s, %s)
ON CONFLICT (measurement_id) DO UPDATE SET
commit_sha = excluded.commit_sha,
value_ns = excluded.value_ns,
all_runtimes_ns = excluded.all_runtimes_ns,
matches = excluded.matches,
rows_scanned = excluded.rows_scanned,
bytes_scanned = excluded.bytes_scanned,
iterations = excluded.iterations,
env_triple = excluded.env_triple
RETURNING (xmax = 0) AS inserted
""",
(
mid,
r["commit_sha"],
r["dataset"],
r["layout"],
r["flavor"],
threshold,
r["value_ns"],
r["all_runtimes_ns"],
r["matches"],
r["rows_scanned"],
r["bytes_scanned"],
r["iterations"],
r.get("env_triple"),
),
)
# Dispatch from a record's `kind` to its per-table primary key and upsert. Keyed identically to
# `_RECORD_FIELDS`; the three maps are wired together when adding a fact table.
_MEASUREMENT_ID = {
"query_measurement": _query_measurement_id,
"compression_time": _compression_time_id,
"compression_size": _compression_size_id,
"random_access_time": _random_access_time_id,
"vector_search_run": _vector_search_run_id,
}
_APPLY_RECORD = {
"query_measurement": _insert_query_measurement,
"compression_time": _insert_compression_time,
"compression_size": _insert_compression_size,
"random_access_time": _insert_random_access,
"vector_search_run": _insert_vector_search,
}
def _upsert_commit(conn, commit: dict) -> None:
"""Upsert the `commits` dimension row."""
conn.execute(
"""
INSERT INTO commits (
commit_sha, timestamp, message, author_name, author_email,
committer_name, committer_email, tree_sha, url
) VALUES (%s, %s::timestamptz, %s, %s, %s, %s, %s, %s, %s)
ON CONFLICT (commit_sha) DO UPDATE SET
timestamp = excluded.timestamp,
message = excluded.message,
author_name = excluded.author_name,
author_email = excluded.author_email,
committer_name = excluded.committer_name,
committer_email = excluded.committer_email,
tree_sha = excluded.tree_sha,
url = excluded.url
""",
(
commit["sha"],
commit["timestamp"],
commit["message"],
commit["author_name"],
commit["author_email"],
commit["committer_name"],
commit["committer_email"],
commit["tree_sha"],
commit["url"],
),
)
def ingest_postgres(conn, commit: dict, records: list[dict]) -> tuple[int, int]:
"""Validate every record, then upsert the commit row and the file's fact rows.
Concurrent CI writers wait on each other only when their fact rows overlap, and never deadlock:
- The `commits` upsert commits in its own short transaction. Holding its row lock for the
whole file would make every writer for the same commit queue behind the others. Commit
metadata is a pure function of the SHA, and `commit-metadata.yml` already writes commit
rows without fact rows, so this row may land even when the fact transaction fails.
- The fact rows are upserted in one transaction, so a file lands all or nothing. They are
applied in (table, `measurement_id`) order, so two writers whose rows overlap take their
row locks in the same order and cannot deadlock.
Returns the number of fact rows inserted and updated.
"""
for idx, record in enumerate(records):
kind = _validate_record_fields(record, idx)
_validate_record_values(record, kind, idx)
if record["commit_sha"] != commit["sha"]:
raise SystemExit(
f"record {idx} ({kind}): commit_sha {record['commit_sha']!r} does not "
f"match the requested commit SHA {commit['sha']!r}"
)
mid_mod = _measurement_id_module()
rows = [(record["kind"], _MEASUREMENT_ID[record["kind"]](mid_mod, record), record) for record in records]
rows.sort(key=lambda row: row[:2])
with conn.transaction():
_upsert_commit(conn, commit)
inserted = 0
updated = 0
with conn.transaction():
for kind, mid, record in rows:
if _APPLY_RECORD[kind](conn, mid, record):
updated += 1
else:
inserted += 1
return inserted, updated
def _region_from_host(host: str) -> str | None:
"""Parse the AWS region out of an RDS endpoint hostname.
RDS endpoints look like `<name>.<id>.<region>.rds.amazonaws.com` (instance)
or `<name>.proxy-<id>.<region>.rds.amazonaws.com` (proxy); the region is the
label immediately before `rds.amazonaws.com`. Returns None for any other
shape.
"""
parts = host.split(".")
if len(parts) >= 4 and parts[-3:] == ["rds", "amazonaws", "com"]:
return parts[-4]
return None
def _rds_iam_token(*, host: str, port: int, user: str, region: str | None) -> str:
"""Mint a short-lived RDS IAM auth token to use as the connection password."""
import boto3
session = boto3.session.Session()
resolved = region or session.region_name or _region_from_host(host)
if not resolved:
raise SystemExit(
"could not determine the AWS region for the RDS IAM token; pass --region or set AWS_DEFAULT_REGION."
)
client = session.client("rds", region_name=resolved)
return client.generate_db_auth_token(DBHostname=host, Port=port, DBUsername=user, Region=resolved)
# The least-privilege login role the v4 CI ingest path must authenticate as
# (created by `migrations/004_ingest_role.sql`; SELECT,INSERT,UPDATE only).
# Phase-2 BAN: do not authenticate the ingest write path as `migrator` /
# `GitHubBenchmarkSchemaRole`.
_INGEST_ROLE = "bench_ingest"
def connect_postgres(dsn: str, region: str | None) -> object:
"""Open a psycopg connection to the RDS Postgres ingest target.
Enforces the ingest contract: verify-full TLS, and authentication only as the
least-privilege `bench_ingest` role -- always, regardless of auth method (IAM
token or password) or host. This is the production RDS ingest connector; the
test suite exercises ingest via `ingest_postgres` directly, so there is no
local-affordance exception to carve out. A host-based "is this local?"
heuristic would be unreliable anyway because libpq can resolve the host from a
DSN `hostaddr=` or the `$PGHOST` environment variable, either of which could
bypass a DSN-host check. Parses `dsn`; if it carries no password, mints an RDS
IAM auth token for the DSN's user and host (the DSN is expected to also supply
`sslrootcert` for verify-full to validate against).
"""
import psycopg
from psycopg import conninfo
params = conninfo.conninfo_to_dict(dsn)
# verify-full is the ingest TLS contract. Default an absent value, but
# refuse a DSN that explicitly downgrades it rather than silently weakening
# the internet-reachable ingest connection.
sslmode = params.get("sslmode")
if sslmode is None:
params["sslmode"] = "verify-full"
elif sslmode != "verify-full":
raise SystemExit(
f"--postgres requires sslmode=verify-full for the RDS ingest path; DSN "
f"specified sslmode={sslmode!r}. Omit it (defaults to verify-full) or set "
f"it to verify-full."
)
user = params.get("user")
# Least-privilege: always the bench_ingest role. No host heuristic (see the
# docstring): a misconfigured DSN -- by host=, hostaddr=, or $PGHOST -- must
# never ingest as migrator/postgres.
if user != _INGEST_ROLE:
raise SystemExit(f"--postgres must connect as the least-privilege {_INGEST_ROLE!r} role; DSN user is {user!r}.")
if not params.get("password"):
# IAM-token path (production CI ingest): mint a token for the DSN's user.
host = params.get("host")
if not host:
raise SystemExit("--postgres DSN must specify host for IAM token minting")
try:
port = int(params.get("port", 5432))
except (TypeError, ValueError) as exc:
raise SystemExit(f"--postgres DSN has a non-numeric port: {params.get('port')!r}") from exc
params["password"] = _rds_iam_token(host=host, port=port, user=user, region=region)
# Force `search_path=public` so the writer's unqualified table names always resolve to the
# migration-owned `public.*` tables, regardless of any `search_path` baked into the DSN's
# `options=-c search_path=...` or the role's default. libpq applies repeated `-c` settings
# left-to-right (last wins), so appending ours last makes it authoritative even if the DSN
# already set one. The connect and statement timeouts stop a network or server hang from
# holding the job until its own timeout. `statement_timeout` also covers time spent waiting
# for locks, so no separate `lock_timeout` is needed.
existing_options = params.get("options") or ""
params["options"] = f"{existing_options} -c search_path=public -c statement_timeout=30000".strip()
params["connect_timeout"] = 10
conn = psycopg.connect(**params)
# Verify the RESOLVED transport actually used TLS, not merely that the DSN requested
# verify-full. The `sslmode` check above rejects an explicit downgrade, but it cannot stop a
# hostless / Unix-socket DSN (host omitted, `host=/...`, or libpq resolving via `$PGHOST`)
# from connecting over a local socket, where libpq silently ignores `sslmode`. Checking
# `ssl_in_use` post-connect validates the connection that actually happened rather than
# trusting the DSN string -- the same "verify the resolved state" reasoning the docstring
# uses to reject a DSN-host heuristic -- and so also closes the `$PGHOST` / `hostaddr` bypass.
# NOTE: `ssl_in_use` lives on the low-level libpq wrapper `conn.pgconn` (a `pq.PGconn`); it is
# NOT on the high-level `conn.info` (`ConnectionInfo`), which exposes only host/dbname/user/etc.
if not conn.pgconn.ssl_in_use:
conn.close()
raise SystemExit(
"--postgres requires a verify-full TLS connection, but the established connection is "
"not using TLS (a hostless or Unix-socket DSN bypasses sslmode); connect to the RDS "
"instance over TCP with sslmode=verify-full."
)
return conn
def _http(method: str, url: str, token: str | None, timeout: float) -> bytes:
"""Issue one HTTP request and return the body. Raises on any non-2xx or
transport error; callers in `refresh_site_cache` swallow those."""
headers = {"accept": "application/json"}
if token is not None:
headers["authorization"] = f"Bearer {token}"
req = urllib.request.Request(url, method=method, headers=headers)
with urllib.request.urlopen(req, timeout=timeout) as resp:
return resp.read()
def _warm_default_windows(base: str, timeout: float) -> None:
"""Best-effort warm pass: prime the freshly invalidated Data Cache for the
landing page and every group's default last-100 bundle, so the first human
request after an ingest is already hot. Each request is independent; one
failure does not abort the others."""
def warm(url: str) -> None:
try:
_http("GET", url, None, timeout)
except Exception as exc: # noqa: BLE001 -- warm is best-effort.
print(f"warning: warm {url} failed: {exc}", file=sys.stderr)
warm(f"{base}/")
try:
groups_body = _http("GET", f"{base}/api/groups", None, timeout)
slugs = [g["slug"] for g in json.loads(groups_body).get("groups", []) if "slug" in g]
except Exception as exc: # noqa: BLE001 -- group discovery is best-effort.
print(f"warning: warm group discovery failed: {exc}", file=sys.stderr)
return
# A whole-bundle recompute is a few seconds cold, so warm with bounded
# concurrency rather than one slow serial pass.
with ThreadPoolExecutor(max_workers=4) as pool:
pool.map(lambda s: warm(f"{base}/api/group/{s}?n=100"), slugs)
def refresh_site_cache(base_url: str, token: str, timeout: float) -> None:
"""Revalidate the site's Data Cache tag, then warm the default windows.
BEST-EFFORT: every failure is logged to stderr and swallowed so a cache
refresh can never change the ingest exit code. The warm pass is skipped
when revalidation fails: warming after a failed flush would repopulate the
Data Cache with stale data, which is the opposite of the intent.
"""
base = base_url.rstrip("/")
try:
_http("POST", f"{base}/api/revalidate", token, timeout)
except Exception as exc: # noqa: BLE001 -- refresh must never raise into ingest.
print(f"warning: cache revalidate failed: {exc}", file=sys.stderr)
return # Skip the warm pass: no point warming a cache that was not flushed.
_warm_default_windows(base, timeout)
def _main_postgres(args: argparse.Namespace) -> int:
records = read_records(args.jsonl_path)
# `build_commit` runs `git show <commit_sha>`, so the SHA must be in the runner's local git
# history. A shallow checkout missing the SHA fails before opening a database connection.
commit = build_commit(args.commit_sha, args.repo_url, args.git_dir)
conn = connect_postgres(args.postgres, args.region)
try:
inserted, updated = ingest_postgres(conn, commit, records)
finally:
conn.close()
print(
json.dumps(
{"records": len(records), "inserted": inserted, "updated": updated},
separators=(",", ":"),
)
)
# Best-effort site-cache refresh after a successful write. It runs only
# when both environment variables are configured and can never fail ingest.
base_url = os.environ.get("BENCH_SITE_BASE_URL")
revalidate_token = os.environ.get("BENCH_REVALIDATE_TOKEN")
if base_url and revalidate_token:
refresh_site_cache(base_url, revalidate_token, args.timeout)