heeranjid 0.5.0

Rust Snowflake-style distributed ID generator: 64-bit sortable bigint IDs and UUIDv8-compatible 128-bit IDs for Postgres and MSSQL, with SQLx, Django, and cross-language ORM support.
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
//! Schema installation and seed tests for the `postgres` feature.
//!
//! Tests exercise `install_schema()` and `seed_default_node()` helpers
//! against a real Postgres instance, verifying that the DDL is idempotent
//! and that the seed creates the expected default node row.
//!
//! Requires a running Postgres instance reachable via the `DATABASE_URL`
//! environment variable. If unset, tests are skipped (printed to stderr).
//! The test suite uses `tokio::test` for async execution and `tokio-postgres`
//! with `NoTls` for the connection.
//!
//! Tests are compiled only when the `postgres` feature is enabled.

#![cfg(feature = "postgres")]

use std::env;
use tokio_postgres::NoTls;

async fn connect() -> Option<tokio_postgres::Client> {
    let url = env::var("DATABASE_URL").ok()?;
    let (client, conn) = tokio_postgres::connect(&url, NoTls).await.ok()?;
    tokio::spawn(async move {
        if let Err(e) = conn.await {
            eprintln!("postgres connection error: {e}");
        }
    });
    Some(client)
}

// ---------------------------------------------------------------------------
// Schema installation
// ---------------------------------------------------------------------------

#[tokio::test]
async fn install_schema_creates_tables() {
    let Some(client) = connect().await else {
        eprintln!("SKIP: DATABASE_URL not set; skipping live database test");
        return;
    };

    // Create an isolated schema for testing.
    let schema_name = "test_heeranjid_install";
    client
        .execute(&format!("DROP SCHEMA IF EXISTS {schema_name} CASCADE"), &[])
        .await
        .expect("drop test schema");
    client
        .execute(&format!("CREATE SCHEMA {schema_name}"), &[])
        .await
        .expect("create test schema");

    // Set search_path so subsequent DDL lands in our isolated schema.
    client
        .execute(&format!("SET search_path TO {schema_name}"), &[])
        .await
        .expect("set search_path");

    // Run install_schema.
    heeranjid::postgres_schema::install_schema(&client)
        .await
        .expect("install_schema should succeed");

    // Verify core tables exist.
    let tables: Vec<String> = client
        .query_opt(
            "SELECT tablename FROM pg_tables WHERE schemaname = $1 AND tablename = 'heer_nodes'",
            &[&schema_name],
        )
        .await
        .expect("query pg_tables")
        .iter()
        .map(|row| row.get(0))
        .collect();

    assert!(
        !tables.is_empty(),
        "heer_nodes table should exist after install"
    );

    // Re-run install_schema to verify idempotency.
    heeranjid::postgres_schema::install_schema(&client)
        .await
        .expect("install_schema should be idempotent");

    // Cleanup.
    client
        .execute(&format!("DROP SCHEMA {schema_name} CASCADE"), &[])
        .await
        .expect("drop test schema");
}

// ---------------------------------------------------------------------------
// Seed installation
// ---------------------------------------------------------------------------

#[tokio::test]
async fn seed_default_node_creates_row() {
    let Some(client) = connect().await else {
        eprintln!("SKIP: DATABASE_URL not set; skipping live database test");
        return;
    };

    // Create an isolated schema for testing.
    let schema_name = "test_heeranjid_seed";
    client
        .execute(&format!("DROP SCHEMA IF EXISTS {schema_name} CASCADE"), &[])
        .await
        .expect("drop test schema");
    client
        .execute(&format!("CREATE SCHEMA {schema_name}"), &[])
        .await
        .expect("create test schema");

    // Set search_path so subsequent DDL lands in our isolated schema.
    client
        .execute(&format!("SET search_path TO {schema_name}"), &[])
        .await
        .expect("set search_path");

    // Install schema first.
    heeranjid::postgres_schema::install_schema(&client)
        .await
        .expect("install_schema");

    // Seed default node.
    heeranjid::postgres_schema::seed_default_node(&client)
        .await
        .expect("seed_default_node should succeed");

    // Verify default node (node_id = 1) exists.
    let count: i64 = client
        .query_one("SELECT count(*) FROM heer_nodes WHERE node_id = 1", &[])
        .await
        .expect("query heer_nodes")
        .get(0);

    assert_eq!(
        count, 1,
        "default node (node_id = 1) should exist after seed"
    );

    // Re-run seed to verify idempotency.
    heeranjid::postgres_schema::seed_default_node(&client)
        .await
        .expect("seed_default_node should be idempotent");

    // Verify count is still 1 (not duplicated).
    let count_after_reseed: i64 = client
        .query_one("SELECT count(*) FROM heer_nodes WHERE node_id = 1", &[])
        .await
        .expect("query heer_nodes after reseed")
        .get(0);

    assert_eq!(
        count_after_reseed, 1,
        "default node should not be duplicated on re-seed"
    );

    // Cleanup.
    client
        .execute(&format!("DROP SCHEMA {schema_name} CASCADE"), &[])
        .await
        .expect("drop test schema");
}

// ---------------------------------------------------------------------------
// Desc flip round-trip (install_all_desc_support)
// ---------------------------------------------------------------------------

#[tokio::test]
async fn desc_flip_round_trips_inside_postgres() {
    let Some(client) = connect().await else {
        eprintln!("SKIP: DATABASE_URL not set; skipping live database test");
        return;
    };

    // Create an isolated schema for testing.
    let schema_name = "test_heeranjid_desc_flip";
    client
        .execute(&format!("DROP SCHEMA IF EXISTS {schema_name} CASCADE"), &[])
        .await
        .expect("drop test schema");
    client
        .execute(&format!("CREATE SCHEMA {schema_name}"), &[])
        .await
        .expect("create test schema");

    // Set search_path so subsequent DDL lands in our isolated schema.
    client
        .execute(&format!("SET search_path TO {schema_name}"), &[])
        .await
        .expect("set search_path");

    // Install schema, seed, and all desc support.
    heeranjid::postgres_schema::install_schema(&client)
        .await
        .expect("install_schema");
    heeranjid::postgres_schema::seed_default_node(&client)
        .await
        .expect("seed_default_node");
    heeranjid::postgres_schema::install_all_desc_support(&client)
        .await
        .expect("install_all_desc_support");

    // heerid_to_asc(heerid_to_desc(1234567)) must round-trip.
    let row = client
        .query_one("SELECT heerid_to_asc(heerid_to_desc(1234567::bigint))", &[])
        .await
        .expect("round-trip query");
    let back: i64 = row.get(0);
    assert_eq!(back, 1_234_567, "heerid_to_asc(heerid_to_desc(x)) == x");

    // heerid_flip_mask() must equal the documented constant.
    let row = client
        .query_one("SELECT heerid_flip_mask()", &[])
        .await
        .expect("flip mask query");
    let mask: i64 = row.get(0);
    assert_eq!(
        mask, 9_223_372_036_850_589_695,
        "heerid_flip_mask() == documented constant"
    );

    // Cleanup.
    client
        .execute(&format!("DROP SCHEMA {schema_name} CASCADE"), &[])
        .await
        .expect("drop test schema");
}

// ---------------------------------------------------------------------------
// ID generation post-seed
// ---------------------------------------------------------------------------

#[tokio::test]
async fn generate_id_after_seed() {
    let Some(client) = connect().await else {
        eprintln!("SKIP: DATABASE_URL not set; skipping live database test");
        return;
    };

    // Create an isolated schema for testing.
    let schema_name = "test_heeranjid_genid";
    client
        .execute(&format!("DROP SCHEMA IF EXISTS {schema_name} CASCADE"), &[])
        .await
        .expect("drop test schema");
    client
        .execute(&format!("CREATE SCHEMA {schema_name}"), &[])
        .await
        .expect("create test schema");

    // Set search_path so subsequent DDL lands in our isolated schema.
    client
        .execute(&format!("SET search_path TO {schema_name}"), &[])
        .await
        .expect("set search_path");

    // Install schema and seed.
    heeranjid::postgres_schema::install_schema(&client)
        .await
        .expect("install_schema");
    heeranjid::postgres_schema::seed_default_node(&client)
        .await
        .expect("seed_default_node");

    // Set session node_id for generation.
    client
        .execute("SELECT set_heer_node_id(1)", &[])
        .await
        .expect("set session node_id");

    // Generate an ID.
    let id: i64 = client
        .query_one("SELECT generate_id()", &[])
        .await
        .expect("generate_id")
        .get(0);

    assert!(id > 0, "generated ID should be positive");

    // Cleanup.
    client
        .execute(&format!("DROP SCHEMA {schema_name} CASCADE"), &[])
        .await
        .expect("drop test schema");
}

// ---------------------------------------------------------------------------
// Per-table autofill trigger (Task 11)
// ---------------------------------------------------------------------------

#[tokio::test]
async fn autofill_trigger_populates_desc_column_on_insert_and_update() {
    let Some(client) = connect().await else {
        eprintln!("SKIP: DATABASE_URL not set; skipping live database test");
        return;
    };

    // Create an isolated schema for testing.
    let schema_name = "test_heeranjid_autofill_trigger";
    client
        .execute(&format!("DROP SCHEMA IF EXISTS {schema_name} CASCADE"), &[])
        .await
        .expect("drop test schema");
    client
        .execute(&format!("CREATE SCHEMA {schema_name}"), &[])
        .await
        .expect("create test schema");

    // Pin search_path so all DDL and the trigger body resolve here.
    client
        .execute(&format!("SET search_path TO {schema_name}"), &[])
        .await
        .expect("set search_path");

    // Install schema + all desc support (flip fns are what the trigger calls).
    heeranjid::postgres_schema::install_schema(&client)
        .await
        .expect("install_schema");
    heeranjid::postgres_schema::seed_default_node(&client)
        .await
        .expect("seed_default_node");
    heeranjid::postgres_schema::install_all_desc_support(&client)
        .await
        .expect("install_all_desc_support");

    // Fixture table: plain int64 pk + a sibling desc column.
    client
        .batch_execute("CREATE TABLE trig_test (id bigint PRIMARY KEY, id_desc bigint)")
        .await
        .expect("create trig_test");

    // Install the per-table trigger (single pair, Heer kind).
    heeranjid::postgres_schema::install_autofill_trigger_for_table(
        &client,
        "trig_test",
        &[heeranjid::postgres_schema::ColumnPair {
            src: "id",
            dst: "id_desc",
        }],
        heeranjid::postgres_schema::IdKind::Heer,
    )
    .await
    .expect("install_autofill_trigger_for_table");

    // INSERT without populating id_desc — trigger must fill it.
    client
        .execute("INSERT INTO trig_test (id) VALUES ($1)", &[&1000_i64])
        .await
        .expect("insert row");

    let expected: i64 = client
        .query_one("SELECT heerid_to_desc($1::bigint)", &[&1000_i64])
        .await
        .expect("expected id_desc for 1000")
        .get(0);
    let got: i64 = client
        .query_one("SELECT id_desc FROM trig_test WHERE id = $1", &[&1000_i64])
        .await
        .expect("read id_desc after insert")
        .get(0);
    assert_eq!(
        got, expected,
        "INSERT trigger should populate id_desc via heerid_to_desc(id)"
    );

    // UPDATE the source — trigger must recompute id_desc.
    client
        .execute(
            "UPDATE trig_test SET id = $1 WHERE id = $2",
            &[&2000_i64, &1000_i64],
        )
        .await
        .expect("update row");

    let expected2: i64 = client
        .query_one("SELECT heerid_to_desc($1::bigint)", &[&2000_i64])
        .await
        .expect("expected id_desc for 2000")
        .get(0);
    let got2: i64 = client
        .query_one("SELECT id_desc FROM trig_test WHERE id = $1", &[&2000_i64])
        .await
        .expect("read id_desc after update")
        .get(0);
    assert_eq!(
        got2, expected2,
        "UPDATE trigger should recompute id_desc when source changes"
    );

    // Drop the trigger and confirm it's gone.
    heeranjid::postgres_schema::drop_autofill_trigger_for_table(&client, "trig_test")
        .await
        .expect("drop_autofill_trigger_for_table");

    let remaining: i64 = client
        .query_one(
            "SELECT count(*) FROM pg_trigger \
             WHERE tgname = 'zzz_trig_test_autofill_desc' AND NOT tgisinternal",
            &[],
        )
        .await
        .expect("check trigger removal")
        .get(0);
    assert_eq!(remaining, 0, "trigger should be gone after drop helper");

    // After drop, an UPDATE to id must NOT touch id_desc.
    client
        .execute(
            "UPDATE trig_test SET id = $1 WHERE id = $2",
            &[&3000_i64, &2000_i64],
        )
        .await
        .expect("update row post-drop");
    let stale: i64 = client
        .query_one("SELECT id_desc FROM trig_test WHERE id = $1", &[&3000_i64])
        .await
        .expect("read id_desc after post-drop update")
        .get(0);
    assert_eq!(
        stale, expected2,
        "after drop, id_desc must not be recomputed by a trigger"
    );

    // Cleanup.
    client
        .execute(&format!("DROP SCHEMA {schema_name} CASCADE"), &[])
        .await
        .expect("drop test schema");
}

// ---------------------------------------------------------------------------
// Bulk descending generators (v0.3.4)
// ---------------------------------------------------------------------------
//
// `generate_ids_desc(n)` and `generate_ranjids_desc(n)` are the batch
// counterparts to `heerid_next_desc()` / `ranjid_next_desc()`. They compose
// the existing asc allocator with the desc flip so callers get a column of
// descending-shape IDs in a single round-trip, without reaching for the
// flip primitives directly.
//
// These tests verify, for both HeerId and RanjId:
//   a) the function returns exactly the requested row count;
//   b) each returned desc-shape ID decodes back to a valid asc ID via the
//      matching `*_to_asc` primitive (self-inverse XOR);
//   c) the returned IDs are distinct.

#[tokio::test]
async fn generate_ids_desc_returns_flipped_batch() {
    let Some(client) = connect().await else {
        eprintln!("SKIP: DATABASE_URL not set; skipping live database test");
        return;
    };

    let schema_name = "test_heeranjid_bulk_heerid_desc";
    client
        .execute(&format!("DROP SCHEMA IF EXISTS {schema_name} CASCADE"), &[])
        .await
        .expect("drop test schema");
    client
        .execute(&format!("CREATE SCHEMA {schema_name}"), &[])
        .await
        .expect("create test schema");
    client
        .execute(&format!("SET search_path TO {schema_name}"), &[])
        .await
        .expect("set search_path");

    heeranjid::postgres_schema::install_schema(&client)
        .await
        .expect("install_schema");
    heeranjid::postgres_schema::seed_default_node(&client)
        .await
        .expect("seed_default_node");
    heeranjid::postgres_schema::install_all_desc_support(&client)
        .await
        .expect("install_all_desc_support");

    // Pin the session node so the `requested_count`-only overload resolves.
    client
        .execute("SELECT set_heer_node_id(1)", &[])
        .await
        .expect("set_heer_node_id");

    let requested: i32 = 8;

    // (a) Row count: the one-arg overload returns `requested` rows.
    let desc_rows = client
        .query(
            "SELECT id FROM generate_ids_desc($1::integer)",
            &[&requested],
        )
        .await
        .expect("bulk generate_ids_desc");
    assert_eq!(
        desc_rows.len(),
        requested as usize,
        "generate_ids_desc($1) must return exactly $1 rows"
    );

    let desc_ids: Vec<i64> = desc_rows.iter().map(|r| r.get::<_, i64>(0)).collect();

    // (b) Involutive property: heerid_to_desc(heerid_to_asc(d)) == d for every
    // returned id. Because both flip functions are the same XOR-mask operation,
    // applying them in sequence is a no-op on any value — this is a tautology
    // that documents the involutive (self-inverse) property of the flip
    // functions, NOT a check that the wrapper applied the flip. A wrapper that
    // returned raw asc IDs would still pass this assertion. The monotonicity
    // check in (c) is what actually catches a missed flip.
    for d in &desc_ids {
        let roundtrip_row = client
            .query_one("SELECT heerid_to_desc(heerid_to_asc($1::bigint))", &[d])
            .await
            .expect("heerid_to_desc(heerid_to_asc(d)) round-trip");
        let roundtrip: i64 = roundtrip_row.get(0);
        assert_eq!(
            *d, roundtrip,
            "heerid_to_desc(heerid_to_asc(d)) must equal d — wrapper must apply the flip"
        );
    }

    // (c) Flip is self-inverse: desc -> asc -> each asc value must decode
    // as a valid HeerId, and the asc sequence must be strictly monotonic
    // increasing (which would break if the wrapper returned already-flipped
    // values and heerid_to_asc then double-flipped them into non-monotonic
    // noise).
    let mut asc_ids: Vec<i64> = Vec::with_capacity(desc_ids.len());
    for d in &desc_ids {
        let asc_row = client
            .query_one("SELECT heerid_to_asc($1::bigint)", &[d])
            .await
            .expect("flip back to asc");
        let asc: i64 = asc_row.get(0);
        heeranjid::HeerId::from_i64(asc)
            .expect("asc-shape round-trip must parse as a valid HeerId");
        asc_ids.push(asc);
    }
    for window in asc_ids.windows(2) {
        assert!(
            window[0] < window[1],
            "asc-flipped sequence must be strictly monotonic increasing; \
             got {} then {} — wrapper may have skipped the desc flip",
            window[0],
            window[1],
        );
    }

    // (d) Distinctness: the batch must contain no duplicates.
    let mut sorted = desc_ids.clone();
    sorted.sort_unstable();
    sorted.dedup();
    assert_eq!(
        sorted.len(),
        desc_ids.len(),
        "generate_ids_desc must return distinct IDs"
    );

    // (e) Explicit-node overload (`(in_node_id, requested_count, spanning)`)
    // must honour the row count and apply the flip. Monotonicity of the
    // asc-flipped sequence is the real flip-detection: if the wrapper forgot
    // heerid_to_desc, heerid_to_asc would produce a *decreasing* sequence.
    let node_rows = client
        .query(
            "SELECT id FROM generate_ids_desc($1::integer, $2::integer, true)",
            &[&1_i32, &requested],
        )
        .await
        .expect("bulk generate_ids_desc with explicit node");
    assert_eq!(
        node_rows.len(),
        requested as usize,
        "generate_ids_desc(node, n, spanning) must return n rows"
    );
    let mut node_asc_ids: Vec<i64> = Vec::with_capacity(node_rows.len());
    for row in &node_rows {
        let d: i64 = row.get(0);
        let asc_row = client
            .query_one("SELECT heerid_to_asc($1::bigint)", &[&d])
            .await
            .expect("flip back to asc — explicit-node overload");
        let asc: i64 = asc_row.get(0);
        heeranjid::HeerId::from_i64(asc)
            .expect("asc-shape must parse as a valid HeerId — explicit-node overload");
        node_asc_ids.push(asc);
    }
    for window in node_asc_ids.windows(2) {
        assert!(
            window[0] < window[1],
            "explicit-node overload: asc-flipped sequence must be strictly monotonic increasing; \
             got {} then {} — wrapper may have skipped the desc flip",
            window[0],
            window[1],
        );
    }

    // (f) allow_spanning=false variant: 2-arg session-node overload.
    // Request enough IDs to verify monotonicity (a single ID cannot establish
    // ordering, so request `requested` IDs here too).
    let no_span_rows = client
        .query(
            "SELECT id FROM generate_ids_desc($1::integer, $2::boolean)",
            &[&requested, &false],
        )
        .await
        .expect("generate_ids_desc(n, false)");
    assert_eq!(
        no_span_rows.len(),
        requested as usize,
        "generate_ids_desc(n, false) must return n rows"
    );
    let mut no_span_asc_ids: Vec<i64> = Vec::with_capacity(no_span_rows.len());
    for row in &no_span_rows {
        let d: i64 = row.get(0);
        let asc_row = client
            .query_one("SELECT heerid_to_asc($1::bigint)", &[&d])
            .await
            .expect("flip back to asc — allow_spanning=false overload");
        let asc: i64 = asc_row.get(0);
        heeranjid::HeerId::from_i64(asc)
            .expect("asc-shape must parse as a valid HeerId — allow_spanning=false overload");
        no_span_asc_ids.push(asc);
    }
    for window in no_span_asc_ids.windows(2) {
        assert!(
            window[0] < window[1],
            "allow_spanning=false overload: asc-flipped sequence must be strictly monotonic \
             increasing; got {} then {} — wrapper may have skipped the desc flip",
            window[0],
            window[1],
        );
    }

    // (g) Zero-count propagates the underlying error.
    let zero_err = client
        .query("SELECT id FROM generate_ids_desc($1::integer)", &[&0_i32])
        .await;
    assert!(
        zero_err.is_err(),
        "generate_ids_desc(0) must propagate requested_count error"
    );
    let pg_err = zero_err.unwrap_err();
    let db_err = pg_err
        .as_db_error()
        .expect("generate_ids_desc(0) must raise a Postgres-level error");
    assert!(
        db_err
            .message()
            .contains("requested_count must be greater than zero"),
        "error message must mention requested_count; got: {}",
        db_err.message()
    );

    client
        .execute(&format!("DROP SCHEMA {schema_name} CASCADE"), &[])
        .await
        .expect("drop test schema");
}

#[tokio::test]
async fn generate_ranjids_desc_returns_flipped_batch() {
    let Some(client) = connect().await else {
        eprintln!("SKIP: DATABASE_URL not set; skipping live database test");
        return;
    };

    let schema_name = "test_heeranjid_bulk_ranjid_desc";
    client
        .execute(&format!("DROP SCHEMA IF EXISTS {schema_name} CASCADE"), &[])
        .await
        .expect("drop test schema");
    client
        .execute(&format!("CREATE SCHEMA {schema_name}"), &[])
        .await
        .expect("create test schema");
    client
        .execute(&format!("SET search_path TO {schema_name}"), &[])
        .await
        .expect("set search_path");

    heeranjid::postgres_schema::install_schema(&client)
        .await
        .expect("install_schema");
    heeranjid::postgres_schema::seed_default_node(&client)
        .await
        .expect("seed_default_node");
    heeranjid::postgres_schema::install_all_desc_support(&client)
        .await
        .expect("install_all_desc_support");

    // Pin the session ranj node so the one-arg overload resolves.
    client
        .execute("SELECT set_heer_ranj_node_id(1)", &[])
        .await
        .expect("set_heer_ranj_node_id");

    let requested: i32 = 8;

    // (a) Row count.
    let desc_rows = client
        .query(
            "SELECT id FROM generate_ranjids_desc($1::integer)",
            &[&requested],
        )
        .await
        .expect("bulk generate_ranjids_desc");
    assert_eq!(
        desc_rows.len(),
        requested as usize,
        "generate_ranjids_desc($1) must return exactly $1 rows"
    );

    let desc_ids: Vec<uuid::Uuid> = desc_rows
        .iter()
        .map(|r| r.get::<_, uuid::Uuid>(0))
        .collect();

    // (b) Involutive property: ranjid_to_desc(ranjid_to_asc(d)) == d for every
    // returned id. Because both flip functions apply the same XOR-mask, applying
    // them in sequence is a no-op on any value — this is a tautology documenting
    // the involutive (self-inverse) property of the flip functions, NOT a check
    // that the wrapper applied the flip. A wrapper that returned raw asc IDs
    // would still pass. The monotonicity check in (c) is what catches a missed
    // flip.
    for d in &desc_ids {
        let roundtrip_row = client
            .query_one("SELECT ranjid_to_desc(ranjid_to_asc($1::uuid))", &[d])
            .await
            .expect("ranjid_to_desc(ranjid_to_asc(d)) round-trip");
        let roundtrip: uuid::Uuid = roundtrip_row.get(0);
        assert_eq!(
            *d, roundtrip,
            "ranjid_to_desc(ranjid_to_asc(d)) must equal d — wrapper must apply the flip"
        );
    }

    // (c) Flip is self-inverse: desc -> asc -> each asc value must decode as
    // a valid RanjId, and the asc sequence must be strictly monotonic
    // increasing (catches a wrapper that double-flips into non-monotonic noise).
    let mut asc_ids: Vec<uuid::Uuid> = Vec::with_capacity(desc_ids.len());
    for d in &desc_ids {
        let asc_row = client
            .query_one("SELECT ranjid_to_asc($1::uuid)", &[d])
            .await
            .expect("flip back to asc");
        let asc: uuid::Uuid = asc_row.get(0);
        heeranjid::RanjId::from_uuid(asc)
            .expect("asc-shape round-trip must parse as a valid RanjId");
        asc_ids.push(asc);
    }
    for window in asc_ids.windows(2) {
        assert!(
            window[0] < window[1],
            "asc-flipped sequence must be strictly monotonic increasing; \
             got {} then {} — wrapper may have skipped the desc flip",
            window[0],
            window[1],
        );
    }

    // (d) Distinctness.
    let mut sorted = desc_ids.clone();
    sorted.sort();
    sorted.dedup();
    assert_eq!(
        sorted.len(),
        desc_ids.len(),
        "generate_ranjids_desc must return distinct IDs"
    );

    // (e) Explicit-node overload (`(in_node_id, requested_count, spanning)`)
    // must honour the row count and apply the flip. Monotonicity of the
    // asc-flipped sequence is the real flip-detection: if the wrapper forgot
    // ranjid_to_desc, ranjid_to_asc would produce a *decreasing* sequence.
    let node_rows = client
        .query(
            "SELECT id FROM generate_ranjids_desc($1::integer, $2::integer, true)",
            &[&1_i32, &requested],
        )
        .await
        .expect("bulk generate_ranjids_desc with explicit node");
    assert_eq!(
        node_rows.len(),
        requested as usize,
        "generate_ranjids_desc(node, n, spanning) must return n rows"
    );
    let mut node_asc_ids: Vec<uuid::Uuid> = Vec::with_capacity(node_rows.len());
    for row in &node_rows {
        let d: uuid::Uuid = row.get(0);
        let asc_row = client
            .query_one("SELECT ranjid_to_asc($1::uuid)", &[&d])
            .await
            .expect("flip back to asc — explicit-node overload");
        let asc: uuid::Uuid = asc_row.get(0);
        heeranjid::RanjId::from_uuid(asc)
            .expect("asc-shape must parse as a valid RanjId — explicit-node overload");
        node_asc_ids.push(asc);
    }
    for window in node_asc_ids.windows(2) {
        assert!(
            window[0] < window[1],
            "explicit-node overload: asc-flipped sequence must be strictly monotonic increasing; \
             got {} then {} — wrapper may have skipped the desc flip",
            window[0],
            window[1],
        );
    }

    // (f) allow_spanning=false variant: 2-arg session-node overload.
    // Request enough IDs to verify monotonicity (a single ID cannot establish
    // ordering, so request `requested` IDs here too).
    let no_span_rows = client
        .query(
            "SELECT id FROM generate_ranjids_desc($1::integer, $2::boolean)",
            &[&requested, &false],
        )
        .await
        .expect("generate_ranjids_desc(n, false)");
    assert_eq!(
        no_span_rows.len(),
        requested as usize,
        "generate_ranjids_desc(n, false) must return n rows"
    );
    let mut no_span_asc_ids: Vec<uuid::Uuid> = Vec::with_capacity(no_span_rows.len());
    for row in &no_span_rows {
        let d: uuid::Uuid = row.get(0);
        let asc_row = client
            .query_one("SELECT ranjid_to_asc($1::uuid)", &[&d])
            .await
            .expect("flip back to asc — allow_spanning=false overload");
        let asc: uuid::Uuid = asc_row.get(0);
        heeranjid::RanjId::from_uuid(asc)
            .expect("asc-shape must parse as a valid RanjId — allow_spanning=false overload");
        no_span_asc_ids.push(asc);
    }
    for window in no_span_asc_ids.windows(2) {
        assert!(
            window[0] < window[1],
            "allow_spanning=false overload: asc-flipped sequence must be strictly monotonic \
             increasing; got {} then {} — wrapper may have skipped the desc flip",
            window[0],
            window[1],
        );
    }

    // (g) Zero-count propagates the underlying error.
    let zero_err = client
        .query(
            "SELECT id FROM generate_ranjids_desc($1::integer)",
            &[&0_i32],
        )
        .await;
    assert!(
        zero_err.is_err(),
        "generate_ranjids_desc(0) must propagate requested_count error"
    );
    let pg_err = zero_err.unwrap_err();
    let db_err = pg_err
        .as_db_error()
        .expect("generate_ranjids_desc(0) must raise a Postgres-level error");
    assert!(
        db_err
            .message()
            .contains("requested_count must be greater than zero"),
        "error message must mention requested_count; got: {}",
        db_err.message()
    );

    client
        .execute(&format!("DROP SCHEMA {schema_name} CASCADE"), &[])
        .await
        .expect("drop test schema");
}

// ---------------------------------------------------------------------------
// install_configure / heer_configure() (issue #40)
// ---------------------------------------------------------------------------
//
// Verifies that `install_configure()` installs the `heer_configure()` stored
// procedure and that calling it succeeds end-to-end without error.  Requires a
// live `heer_config` row so the smoke test inside `heer_configure()` can run
// `generate_id(1)` / `generate_ranjid(1)`.

#[tokio::test]
async fn install_configure_and_call_heer_configure() {
    let Some(client) = connect().await else {
        eprintln!("SKIP: DATABASE_URL not set; skipping live database test");
        return;
    };

    let schema_name = "test_heeranjid_configure";
    client
        .execute(&format!("DROP SCHEMA IF EXISTS {schema_name} CASCADE"), &[])
        .await
        .expect("drop test schema");
    client
        .execute(&format!("CREATE SCHEMA {schema_name}"), &[])
        .await
        .expect("create test schema");
    client
        .execute(&format!("SET search_path TO {schema_name}"), &[])
        .await
        .expect("set search_path");

    // Base schema + functions.
    heeranjid::postgres_schema::install_schema(&client)
        .await
        .expect("install_schema");

    // Manual seed — avoids the ON CONFLICT DO NOTHING in seed_default_node()
    // conflicting with the precision-specific epoch row inserted below.
    client
        .execute(
            "INSERT INTO heer_config (id, epoch, precision) \
             VALUES (1, CURRENT_TIMESTAMP - INTERVAL '1 day', 'us')",
            &[],
        )
        .await
        .expect("insert heer_config");
    client
        .execute(
            "INSERT INTO heer_nodes (node_id, name, description, is_active) \
             VALUES (1, 'default', 'Default single-node instance', true)",
            &[],
        )
        .await
        .expect("insert heer_nodes");
    client
        .execute("INSERT INTO heer_node_state (node_id) VALUES (1)", &[])
        .await
        .expect("insert heer_node_state");
    client
        .execute("INSERT INTO heer_ranj_node_state (node_id) VALUES (1)", &[])
        .await
        .expect("insert heer_ranj_node_state");

    // Install the heer_configure() stored procedure.
    heeranjid::postgres_schema::install_configure(&client)
        .await
        .expect("install_configure should succeed");

    // Call heer_configure() — this validates config, regenerates generate_ids /
    // generate_ranjids with baked-in constants, resets node state, and runs a
    // smoke test.  Any error here indicates a bug in configure.sql.
    client
        .execute("SELECT heer_configure()", &[])
        .await
        .expect("heer_configure() should succeed without error");

    // Cleanup.
    client
        .execute(&format!("DROP SCHEMA {schema_name} CASCADE"), &[])
        .await
        .expect("drop test schema (configure)");
}

// ---------------------------------------------------------------------------
// Decoded RanjId timestamp (issue #40 / issue #33)
// ---------------------------------------------------------------------------
//
// Generates a RanjId via the embedded SQL path (`generate_ranjid(1)`), then
// decodes it with `RanjId::from_uuid()` / `RanjId::timestamp_micros()` and
// asserts that the decoded timestamp is within 5 seconds of the current wall
// clock.  Before the precision_bits fix in issue #33 the decoded timestamp was
// 1000x too small (nanoseconds stored as microseconds), so this test would
// have failed with a value close to `now / 1000`.

#[tokio::test]
async fn decoded_ranjid_timestamp_is_current() {
    let Some(client) = connect().await else {
        eprintln!("SKIP: DATABASE_URL not set; skipping live database test");
        return;
    };

    let schema_name = "test_heeranjid_ranjid_ts";
    client
        .execute(&format!("DROP SCHEMA IF EXISTS {schema_name} CASCADE"), &[])
        .await
        .expect("drop test schema");
    client
        .execute(&format!("CREATE SCHEMA {schema_name}"), &[])
        .await
        .expect("create test schema");
    client
        .execute(&format!("SET search_path TO {schema_name}"), &[])
        .await
        .expect("set search_path");

    heeranjid::postgres_schema::install_schema(&client)
        .await
        .expect("install_schema");

    // Manual seed — precision 'us' is required for the timestamp decode check;
    // seed_default_node() inserts 'ns' and ON CONFLICT DO NOTHING would silently
    // leave the wrong precision, or a plain INSERT would fail with a duplicate key.
    client
        .execute(
            "INSERT INTO heer_config (id, epoch, precision) \
             VALUES (1, CURRENT_TIMESTAMP - INTERVAL '1 day', 'us')",
            &[],
        )
        .await
        .expect("insert heer_config");
    client
        .execute(
            "INSERT INTO heer_nodes (node_id, name, description, is_active) \
             VALUES (1, 'default', 'Default single-node instance', true)",
            &[],
        )
        .await
        .expect("insert heer_nodes");
    client
        .execute("INSERT INTO heer_node_state (node_id) VALUES (1)", &[])
        .await
        .expect("insert heer_node_state");
    client
        .execute("INSERT INTO heer_ranj_node_state (node_id) VALUES (1)", &[])
        .await
        .expect("insert heer_ranj_node_state");

    // Capture wall time just before generation so we can bound the timestamp.
    let before_micros = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .expect("system time is after epoch")
        .as_micros();

    // Generate via the embedded SQL path.
    let uuid: uuid::Uuid = client
        .query_one("SELECT generate_ranjid(1)", &[])
        .await
        .expect("generate_ranjid(1)")
        .get(0);

    let after_micros = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .expect("system time is after epoch")
        .as_micros();

    let ranj = heeranjid::RanjId::from_uuid(uuid).expect("database returned a valid RanjId UUID");

    // The RanjId tick counts microseconds since the configured epoch
    // (CURRENT_TIMESTAMP - 1 day).  Convert to Unix microseconds by adding
    // the epoch offset.
    let epoch_micros: u128 = client
        .query_one(
            "SELECT FLOOR(EXTRACT(EPOCH FROM epoch) * 1000000)::BIGINT \
             FROM heer_config WHERE id = 1",
            &[],
        )
        .await
        .expect("fetch epoch_micros")
        .get::<_, i64>(0) as u128;

    let decoded_unix_micros = epoch_micros + ranj.timestamp_micros();

    const TOLERANCE_MICROS: u128 = 5_000_000; // 5 seconds
    assert!(
        decoded_unix_micros >= before_micros.saturating_sub(TOLERANCE_MICROS),
        "decoded timestamp {} µs is more than 5 s before generation start {} µs",
        decoded_unix_micros,
        before_micros,
    );
    assert!(
        decoded_unix_micros <= after_micros + TOLERANCE_MICROS,
        "decoded timestamp {} µs is more than 5 s after generation end {} µs",
        decoded_unix_micros,
        after_micros,
    );

    // Cleanup.
    client
        .execute(&format!("DROP SCHEMA {schema_name} CASCADE"), &[])
        .await
        .expect("drop test schema (ranjid_ts)");
}

// ---------------------------------------------------------------------------
// Configured-path rollback SQLSTATE (issue #40)
// ---------------------------------------------------------------------------
//
// After `heer_configure()` activates the configured generation path, seeding
// `last_id_time` far in the future must still surface the typed
// `HardClockRollback` error.  This is the configured-path parallel of the
// existing `generate_heerid_surfaces_typed_rollback` /
// `generate_ranjid_surfaces_hard_clock_rollback` tests in
// `postgres_generate.rs`.

#[tokio::test]
async fn configured_ranjid_path_surfaces_hard_clock_rollback() {
    let Some(client) = connect().await else {
        eprintln!("SKIP: DATABASE_URL not set; skipping live database test");
        return;
    };

    let schema_name = "test_heeranjid_configured_rollback";
    client
        .execute(&format!("DROP SCHEMA IF EXISTS {schema_name} CASCADE"), &[])
        .await
        .expect("drop test schema");
    client
        .execute(&format!("CREATE SCHEMA {schema_name}"), &[])
        .await
        .expect("create test schema");
    client
        .execute(&format!("SET search_path TO {schema_name}"), &[])
        .await
        .expect("set search_path");

    heeranjid::postgres_schema::install_schema(&client)
        .await
        .expect("install_schema");

    // Manual seed — avoids the ON CONFLICT DO NOTHING in seed_default_node()
    // conflicting with the precision-specific epoch row inserted below.
    client
        .execute(
            "INSERT INTO heer_config (id, epoch, precision) \
             VALUES (1, CURRENT_TIMESTAMP - INTERVAL '1 day', 'us')",
            &[],
        )
        .await
        .expect("insert heer_config");
    client
        .execute(
            "INSERT INTO heer_nodes (node_id, name, description, is_active) \
             VALUES (1, 'default', 'Default single-node instance', true)",
            &[],
        )
        .await
        .expect("insert heer_nodes");
    client
        .execute("INSERT INTO heer_node_state (node_id) VALUES (1)", &[])
        .await
        .expect("insert heer_node_state");
    client
        .execute("INSERT INTO heer_ranj_node_state (node_id) VALUES (1)", &[])
        .await
        .expect("insert heer_ranj_node_state");

    // Activate the configured path.
    heeranjid::postgres_schema::install_configure(&client)
        .await
        .expect("install_configure");
    client
        .execute("SELECT heer_configure()", &[])
        .await
        .expect("heer_configure() should succeed");

    // Seed last_id_time far in the future (999 trillion ticks) to trigger hard
    // clock rollback on the next generation call, regardless of execution latency.
    client
        .execute(
            "INSERT INTO heer_ranj_node_state (node_id, last_id_time, last_sequence) \
             VALUES (1, 999999999999999, 0) \
             ON CONFLICT (node_id) DO UPDATE \
             SET last_id_time = EXCLUDED.last_id_time, \
                 last_sequence = EXCLUDED.last_sequence",
            &[],
        )
        .await
        .expect("seed heer_ranj_node_state with future timestamp");

    // The typed generate helper must surface HardClockRollback.
    let error = heeranjid::postgres_generate::generate_ranjid(&client, 1)
        .await
        .unwrap_err();

    assert!(
        matches!(
            error,
            heeranjid::postgres_generate::GenerateError::HardClockRollback { .. }
        ),
        "expected HardClockRollback on configured path, got {:?}",
        error,
    );

    // Cleanup.
    client
        .execute(&format!("DROP SCHEMA {schema_name} CASCADE"), &[])
        .await
        .expect("drop test schema (configured_rollback)");
}

// ---------------------------------------------------------------------------
// Upgrade identity hazard: old zero-arg overload is dropped by install_configure
// ---------------------------------------------------------------------------
//
// When upgrading from a schema that has an old zero-arg `heer_configure()`
// (pre-BOOLEAN-parameter version), `install_configure()` must drop that overload
// before creating the new one.  Without the DROP FUNCTION IF EXISTS line in
// configure.sql, the old overload would shadow or conflict with the new one.
//
// Steps:
//   1. Fresh schema + install_schema() + manual seed.
//   2. Create the old zero-arg overload manually (raises an exception if called).
//   3. Call install_configure() — the DROP FUNCTION IF EXISTS heer_configure()
//      line in configure.sql must remove the old overload first.
//   4. Call SELECT heer_configure() — must succeed (new BOOLEAN overload with
//      default), not raise 'old overload still present'.
//   5. Call SELECT heer_configure(false) — must also succeed.

#[tokio::test]
async fn heer_configure_upgrade_drops_old_overload() {
    let Some(client) = connect().await else {
        eprintln!("SKIP: DATABASE_URL not set; skipping live database test");
        return;
    };

    let schema_name = "test_heeranjid_configure_upgrade";
    client
        .execute(&format!("DROP SCHEMA IF EXISTS {schema_name} CASCADE"), &[])
        .await
        .expect("drop test schema");
    client
        .execute(&format!("CREATE SCHEMA {schema_name}"), &[])
        .await
        .expect("create test schema");
    client
        .execute(&format!("SET search_path TO {schema_name}"), &[])
        .await
        .expect("set search_path");

    // Step 1: Install base schema.
    heeranjid::postgres_schema::install_schema(&client)
        .await
        .expect("install_schema");

    // Manual seed.
    client
        .execute(
            "INSERT INTO heer_config (id, epoch, precision) \
             VALUES (1, CURRENT_TIMESTAMP - INTERVAL '1 day', 'us')",
            &[],
        )
        .await
        .expect("insert heer_config");
    client
        .execute(
            "INSERT INTO heer_nodes (node_id, name, description, is_active) \
             VALUES (1, 'default', 'Default single-node instance', true)",
            &[],
        )
        .await
        .expect("insert heer_nodes");
    client
        .execute("INSERT INTO heer_node_state (node_id) VALUES (1)", &[])
        .await
        .expect("insert heer_node_state");
    client
        .execute("INSERT INTO heer_ranj_node_state (node_id) VALUES (1)", &[])
        .await
        .expect("insert heer_ranj_node_state");

    // Step 2: Create the old zero-arg overload that would exist in a pre-upgrade schema.
    client
        .batch_execute(
            "CREATE FUNCTION heer_configure() RETURNS VOID LANGUAGE plpgsql AS $$ \
             BEGIN RAISE EXCEPTION 'old overload still present'; END; $$",
        )
        .await
        .expect("create old zero-arg heer_configure overload");

    // Step 3: install_configure() must DROP the old overload before creating the new one.
    heeranjid::postgres_schema::install_configure(&client)
        .await
        .expect("install_configure should succeed and drop the old overload");

    // Step 4: Calling heer_configure() (zero args, resolved via default) must invoke
    // the new BOOLEAN overload, not raise 'old overload still present'.
    client
        .execute("SELECT heer_configure()", &[])
        .await
        .expect("heer_configure() must call the new overload, not the old zero-arg one");

    // Step 5: Explicit-false variant must also succeed.
    client
        .execute("SELECT heer_configure(false)", &[])
        .await
        .expect("heer_configure(false) should succeed");

    // Cleanup.
    client
        .execute(&format!("DROP SCHEMA {schema_name} CASCADE"), &[])
        .await
        .expect("drop test schema (configure_upgrade)");
}