sedona-testing 0.3.0

Apache SedonaDB Rust API
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
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.
//! Tools for generating random geometries
//!
//! The current options provided here were built to support basic correctness testing and
//! benchmarking algorithmic complexity of a large number of scalar functions, many of which
//! have various performance or correctness issues that arise from null features, empty features,
//! polygons with holes, or collections with various numbers of sub-geometries.
//! See <https://github.com/apache/sedona/pull/1680> for the Sedona/Java implementation of spider,
//! which implements a number of other strategies for generating various geometry types.

use arrow_array::{ArrayRef, RecordBatch, RecordBatchReader};
use arrow_array::{BinaryArray, BinaryViewArray};
use arrow_array::{Float64Array, Int32Array};
use arrow_schema::{ArrowError, DataType, Field, Schema, SchemaRef};
use datafusion_common::{exec_datafusion_err, plan_err, DataFusionError, Result};
use geo_types::{
    Coord, Geometry, GeometryCollection, LineString, MultiLineString, MultiPoint, MultiPolygon,
    Point, Polygon, Rect,
};
use rand::{distr::Uniform, rngs::StdRng, Rng, RngExt, SeedableRng};
use sedona_common::sedona_internal_err;
use sedona_geometry::types::GeometryTypeId;
use sedona_schema::datatypes::{SedonaType, WKB_GEOMETRY};
use std::f64::consts::PI;
use std::sync::Arc;
use wkb::writer::WriteOptions;
use wkb::Endianness;

/// Builder for generating test data partitions with random geometries.
///
/// This builder allows you to create deterministic test datasets with configurable
/// geometry types, data distribution, and partitioning for testing spatial operations.
///
/// The generated data includes:
///
/// - `id`: Unique integer identifier for each row
/// - `dist`: Random floating-point distance value (0.0 to 100.0)
/// - `geometry`: Random geometry data in the specified format (WKB or WKB View)
///
/// The strategy for generating geometries and their options are not stable and may change
/// as the needs of testing and benchmarking evolve or better strategies are discovered.
/// The strategy for generating random geometries is as follows:
///
/// - Points are uniformly distributed over the [Self::bounds] indicated
/// - Linestrings are generated by calculating the points in a circle of a randomly
///   chosen size (according to [Self::size_range]) with vertex count sampled using
///   [Self::vertices_per_linestring_range]. The start and end point of generated
///   linestrings are never connected.
/// - Polygons are generated using a closed version of the linestring generated.
///   They may or may not have a hole according to [Self::polygon_hole_rate].
/// - MultiPoint, MultiLinestring, and MultiPolygon geometries are constructed
///   with the number of parts sampled according to [Self::num_parts_range].
///   The size of the entire feature is constrained to [Self::size_range],
///   and this space is subdivided to obtain the exact number of spaces needed.
///   Child features are generated using the global options except with sizes
///   sampled to approach the space given to them.
///
/// # Example
///
/// ```rust
/// use sedona_testing::datagen::RandomPartitionedDataBuilder;
/// use sedona_geometry::types::GeometryTypeId;
/// use geo_types::{Coord, Rect};
///
/// let (schema, partitions) = RandomPartitionedDataBuilder::new()
///     .seed(42)
///     .num_partitions(4)
///     .rows_per_batch(1000)
///     .geometry_type(GeometryTypeId::Polygon)
///     .bounds(Rect::new(Coord { x: 0.0, y: 0.0 }, Coord { x: 100.0, y: 100.0 }))
///     .build()
///     .unwrap();
/// ```
#[derive(Debug, Clone)]
pub struct RandomPartitionedDataBuilder {
    pub seed: u64,
    pub num_partitions: usize,
    pub batches_per_partition: usize,
    pub rows_per_batch: usize,
    sedona_type: SedonaType,
    null_rate: f64,
    options: RandomGeometryOptions,
}

impl Default for RandomPartitionedDataBuilder {
    fn default() -> Self {
        let options = RandomGeometryOptions::new();

        Self {
            seed: 42,
            num_partitions: 1,
            batches_per_partition: 1,
            rows_per_batch: 10,
            sedona_type: WKB_GEOMETRY,
            null_rate: 0.0,
            options,
        }
    }
}

impl RandomPartitionedDataBuilder {
    /// Creates a new `RandomPartitionedDataBuilder` with default values.
    ///
    /// Default configuration:
    ///
    /// - seed: 42 (for deterministic results)
    /// - num_partitions: 1
    /// - batches_per_partition: 1
    /// - rows_per_batch: 10
    /// - geometry_type: Point
    /// - bounds: (0,0) to (100,100)
    /// - size_range: 1.0 to 10.0
    /// - null_rate: 0.0 (no nulls)
    /// - empty_rate: 0.0 (no empties)
    /// - vertices_per_linestring_range
    /// - num_parts_range: 1 to 3
    /// - polygon_hole_rate: 0.0 (no polygons with holes)
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets the random seed for deterministic data generation.
    ///
    /// Using the same seed will produce identical datasets, which is useful
    /// for reproducible tests.
    ///
    /// # Arguments
    ///
    /// * `seed` - The random seed value
    pub fn seed(mut self, seed: u64) -> Self {
        self.seed = seed;
        self
    }

    /// Sets the number of data partitions to generate.
    ///
    /// Each partition contains multiple batches of data. This is useful for
    /// testing distributed processing scenarios.
    ///
    /// # Arguments
    ///
    /// * `num_partitions` - Number of partitions to create
    pub fn num_partitions(mut self, num_partitions: usize) -> Self {
        self.num_partitions = num_partitions;
        self
    }

    /// Sets the number of batches per partition.
    ///
    /// Each batch is a `RecordBatch` containing the specified number of rows.
    ///
    /// # Arguments
    ///
    /// * `batches_per_partition` - Number of batches in each partition
    pub fn batches_per_partition(mut self, batches_per_partition: usize) -> Self {
        self.batches_per_partition = batches_per_partition;
        self
    }

    /// Sets the number of rows per batch.
    ///
    /// This determines the size of each `RecordBatch` that will be generated.
    ///
    /// # Arguments
    ///
    /// * `rows_per_batch` - Number of rows in each batch
    pub fn rows_per_batch(mut self, rows_per_batch: usize) -> Self {
        self.rows_per_batch = rows_per_batch;
        self
    }

    /// Sets the type of geometry to generate.
    ///
    /// Currently supports:
    /// - `GeometryTypeId::Point`: Random points within the specified bounds
    /// - `GeometryTypeId::Polygon`: Random diamond-shaped polygons
    /// - Other types default to point generation
    ///
    /// # Arguments
    ///
    /// * `geom_type` - The geometry type to generate
    pub fn geometry_type(mut self, geom_type: GeometryTypeId) -> Self {
        self.options.geom_type = geom_type;
        self
    }

    /// Sets the Sedona data type for the geometry column.
    ///
    /// This determines how the geometry data is stored (e.g., WKB or WKB View).
    ///
    /// # Arguments
    ///
    /// * `sedona_type` - The Sedona type for geometry storage
    pub fn sedona_type(mut self, sedona_type: SedonaType) -> Self {
        self.sedona_type = sedona_type;
        self
    }

    /// Sets the spatial bounds for geometry generation.
    ///
    /// All generated geometries will be positioned within these bounds.
    /// For polygons, the bounds are used to ensure the entire polygon fits within the area.
    ///
    /// # Arguments
    ///
    /// * `bounds` - Rectangle defining the spatial bounds (min_x, min_y, max_x, max_y)
    pub fn bounds(mut self, bounds: Rect) -> Self {
        self.options.bounds = bounds;
        self
    }

    /// Sets the size range for generated geometries.
    ///
    /// For polygons, this controls the radius of the generated shapes.
    /// For points, this parameter is not used.
    ///
    /// # Arguments
    ///
    /// * `size_range` - Tuple of (min_size, max_size) for geometry dimensions
    pub fn size_range(mut self, size_range: (f64, f64)) -> Self {
        self.options.size_range = size_range;
        self
    }

    /// Sets the rate of null values in the geometry column.
    ///
    /// # Arguments
    ///
    /// * `null_rate` - Fraction of rows that should have null geometry (0.0 to 1.0)
    pub fn null_rate(mut self, null_rate: f64) -> Self {
        self.null_rate = null_rate;
        self
    }

    /// Sets the rate of EMPTY geometries in the geometry column.
    ///
    /// # Arguments
    ///
    /// * `empty_rate` - Fraction of rows that should have empty geometry (0.0 to 1.0)
    pub fn empty_rate(mut self, empty_rate: f64) -> Self {
        self.options.empty_rate = empty_rate;
        self
    }

    /// Sets the vertex count range
    ///
    /// # Arguments
    ///
    /// * `vertices_per_linestring_range` - The minimum and maximum (inclusive) number of vertices
    ///   in linestring output. This also affects polygon output, although the actual number
    ///   of vertices in the polygon ring will be one more than the range indicated here to
    ///   close the polygon.
    pub fn vertices_per_linestring_range(
        mut self,
        vertices_per_linestring_range: (usize, usize),
    ) -> Self {
        self.options.vertices_per_linestring_range = vertices_per_linestring_range;
        self
    }

    /// Sets the number of parts range
    ///
    /// # Arguments
    ///
    /// * `num_parts_range` - The minimum and maximum (inclusive) number of parts
    ///   in multi geometry and/or collection output.
    pub fn num_parts_range(mut self, num_parts_range: (usize, usize)) -> Self {
        self.options.num_parts_range = num_parts_range;
        self
    }

    /// Sets the polygon hole rate
    ///
    /// # Arguments
    ///
    /// * `polygon_hole_rate` - Fraction of polygons that should have an interior
    ///   ring. Currently only a single interior ring is possible.
    pub fn polygon_hole_rate(mut self, polygon_hole_rate: f64) -> Self {
        self.options.polygon_hole_rate = polygon_hole_rate;
        self
    }

    /// The [SchemaRef] generated by this builder
    ///
    /// The resulting schema contains three columns:
    ///
    /// - `id`: Int32 - Unique sequential identifier for each row
    /// - `dist`: Float64 - Random distance value between 0.0 and 100.0
    /// - `geometry`: SedonaType - Random geometry data (WKB or WKB View format)
    pub fn schema(&self) -> SchemaRef {
        // Create schema
        Arc::new(Schema::new(vec![
            Field::new("id", DataType::Int32, false),
            Field::new("dist", DataType::Float64, false),
            self.sedona_type.to_storage_field("geometry", true).unwrap(),
        ]))
    }

    /// Builds the random partitioned dataset with the configured parameters.
    ///
    /// Generates a deterministic dataset based on the seed and configuration.
    /// The resulting schema contains three columns:
    /// - `id`: Int32 - Unique sequential identifier for each row
    /// - `dist`: Float64 - Random distance value between 0.0 and 100.0
    /// - `geometry`: SedonaType - Random geometry data (WKB or WKB View format)
    ///
    /// # Returns
    ///
    /// A tuple containing:
    /// - `SchemaRef`: Arrow schema for the generated data
    /// - `Vec<Vec<RecordBatch>>`: Vector of partitions, each containing a vector of record batches
    ///
    /// # Errors
    ///
    /// Returns a `datafusion_common::Result` error if:
    /// - RecordBatch creation fails
    /// - Array conversion fails
    /// - Schema creation fails
    pub fn build(&self) -> Result<(SchemaRef, Vec<Vec<RecordBatch>>)> {
        // Create a seeded random number generator for deterministic results
        let schema = self.schema();
        let mut result = Vec::with_capacity(self.num_partitions);

        for partition_idx in 0..self.num_partitions {
            let rng = Self::default_rng(self.seed + partition_idx as u64);
            let partition_batches = self
                .partition_reader(rng, partition_idx)
                .collect::<Result<Vec<_>, ArrowError>>()?;
            result.push(partition_batches);
        }

        Ok((schema, result))
    }

    /// Validate options
    ///
    /// This is called internally before generating batches to prevent panics from
    /// occurring while creating random output; however, it may also be called
    /// at a higher level to generate an error at a more relevant time.
    pub fn validate(&self) -> Result<()> {
        self.options.validate()?;

        if self.null_rate < 0.0 || self.null_rate > 1.0 {
            return plan_err!(
                "Expected null_rate between 0.0 and 1.0 but got {}",
                self.null_rate
            );
        }

        if self.rows_per_batch == 0 {
            return plan_err!("Expected rows_per_batch > 0 but got 0");
        }

        if self.num_partitions == 0 {
            return plan_err!("Expected num_partitions > 0 but got 0");
        }

        Ok(())
    }

    /// Generate a [Rng] based on a seed
    ///
    /// Callers can also supply their own [Rng].
    pub fn default_rng(seed: u64) -> impl Rng {
        StdRng::seed_from_u64(seed)
    }

    /// Create a [RecordBatchReader] that reads a single partition
    pub fn partition_reader<R: Rng + Send + 'static>(
        &self,
        rng: R,
        partition_idx: usize,
    ) -> Box<dyn RecordBatchReader + Send> {
        let reader = RandomPartitionedDataReader {
            builder: self.clone(),
            schema: self.schema(),
            partition_idx,
            batch_idx: 0,
            rng,
        };

        Box::new(reader)
    }

    /// Generate a single batch
    fn generate_batch<R: Rng>(
        &self,
        rng: &mut R,
        schema: &SchemaRef,
        partition_idx: usize,
        batch_idx: usize,
    ) -> Result<RecordBatch> {
        // Check for valid ranges to avoid panic in generation
        self.validate()?;

        // Generate IDs - make them unique across partitions and batches
        let id_start =
            (partition_idx * self.batches_per_partition + batch_idx) * self.rows_per_batch;
        let ids: Vec<i32> = (0..self.rows_per_batch)
            .map(|i| (id_start + i) as i32)
            .collect();

        // Generate random distances relevant to the bounds (0.0 and 100.0 by default)
        let max_dist = self
            .options
            .bounds
            .width()
            .min(self.options.bounds.height());
        let distance_dist = Uniform::new(0.0, max_dist).expect("valid input to Uniform::new()");
        let distances: Vec<f64> = (0..self.rows_per_batch)
            .map(|_| rng.sample(distance_dist))
            .collect();

        // Generate random geometries based on the geometry type
        let wkb_geometries = (0..self.rows_per_batch)
            .map(|_| -> Result<Option<Vec<u8>>> {
                if rng.random_bool(self.null_rate) {
                    Ok(None)
                } else {
                    Ok(Some(generate_random_wkb(rng, &self.options)?))
                }
            })
            .collect::<Result<Vec<Option<Vec<u8>>>>>()?;

        // Create Arrow arrays
        let id_array = Arc::new(Int32Array::from(ids));
        let dist_array = Arc::new(Float64Array::from(distances));
        let geometry_array = create_wkb_array(wkb_geometries, &self.sedona_type)?;

        // Create RecordBatch
        Ok(RecordBatch::try_new(
            schema.clone(),
            vec![id_array, dist_array, geometry_array],
        )?)
    }
}

/// Create an ArrayRef from a vector of WKB bytes based on the sedona type
fn create_wkb_array(
    wkb_values: Vec<Option<Vec<u8>>>,
    sedona_type: &SedonaType,
) -> Result<ArrayRef> {
    match sedona_type {
        SedonaType::Wkb(_, _) => Ok(Arc::new(BinaryArray::from_iter(wkb_values))),
        SedonaType::WkbView(_, _) => Ok(Arc::new(BinaryViewArray::from_iter(wkb_values))),
        _ => sedona_internal_err!("create_wkb_array not implemented for {sedona_type:?}"),
    }
}

struct RandomPartitionedDataReader<R> {
    builder: RandomPartitionedDataBuilder,
    schema: SchemaRef,
    partition_idx: usize,
    batch_idx: usize,
    rng: R,
}

impl<R: Rng> RecordBatchReader for RandomPartitionedDataReader<R> {
    fn schema(&self) -> SchemaRef {
        self.builder.schema()
    }
}

impl<R: Rng> Iterator for RandomPartitionedDataReader<R> {
    type Item = std::result::Result<RecordBatch, ArrowError>;

    fn next(&mut self) -> Option<Self::Item> {
        if self.batch_idx == self.builder.batches_per_partition {
            return None;
        }

        let maybe_batch = self
            .builder
            .generate_batch(
                &mut self.rng,
                &self.schema,
                self.partition_idx,
                self.batch_idx,
            )
            .map_err(|e| ArrowError::ExternalError(Box::new(e)));
        self.batch_idx += 1;
        Some(maybe_batch)
    }
}

/// Options for the current strategy influencing individual geometry constructors
#[derive(Debug, Clone)]
struct RandomGeometryOptions {
    geom_type: GeometryTypeId,
    bounds: Rect,
    size_range: (f64, f64),
    vertices_per_linestring_range: (usize, usize),
    empty_rate: f64,
    polygon_hole_rate: f64,
    num_parts_range: (usize, usize),
}

impl RandomGeometryOptions {
    fn new() -> Self {
        Self {
            geom_type: GeometryTypeId::Point,
            empty_rate: 0.0,
            bounds: Rect::new(Coord { x: 0.0, y: 0.0 }, Coord { x: 100.0, y: 100.0 }),
            size_range: (1.0, 10.0),
            vertices_per_linestring_range: (4, 4),
            polygon_hole_rate: 0.0,
            num_parts_range: (1, 3),
        }
    }

    fn validate(&self) -> Result<()> {
        if self.bounds.width() <= 0.0 || self.bounds.height() <= 0.0 {
            return plan_err!("Expected valid bounds but got {:?}", self.bounds);
        }

        if self.size_range.0 <= 0.0 || self.size_range.0 > self.size_range.1 {
            return plan_err!("Expected valid size_range but got {:?}", self.size_range);
        }

        if self.vertices_per_linestring_range.0 == 0
            || self.vertices_per_linestring_range.0 > self.vertices_per_linestring_range.1
        {
            return plan_err!(
                "Expected valid vertices_per_linestring_range but got {:?}",
                self.vertices_per_linestring_range
            );
        }

        if !(0.0..=1.0).contains(&self.empty_rate) {
            return plan_err!(
                "Expected empty_rate between 0.0 and 1.0 but got {}",
                self.empty_rate
            );
        }

        if !(0.0..=1.0).contains(&self.polygon_hole_rate) {
            return plan_err!(
                "Expected polygon_hole_rate between 0.0 and 1.0 but got {}",
                self.polygon_hole_rate
            );
        }

        if self.num_parts_range.0 == 0 || self.num_parts_range.0 > self.num_parts_range.1 {
            return plan_err!(
                "Expected valid num_parts_range but got {:?}",
                self.num_parts_range
            );
        }

        Ok(())
    }
}

impl Default for RandomGeometryOptions {
    fn default() -> Self {
        Self::new()
    }
}

/// Generate random geometry WKB bytes based on the geometry type
fn generate_random_wkb<R: rand::Rng>(
    rng: &mut R,
    options: &RandomGeometryOptions,
) -> Result<Vec<u8>> {
    let geometry = generate_random_geometry(rng, options)?;

    // Convert geometry to WKB
    let mut out: Vec<u8> = vec![];
    wkb::writer::write_geometry(
        &mut out,
        &geometry,
        &WriteOptions {
            endianness: Endianness::LittleEndian,
        },
    )
    .map_err(|e| DataFusionError::External(Box::new(e)))?;
    Ok(out)
}

fn generate_random_geometry<R: rand::Rng>(
    rng: &mut R,
    options: &RandomGeometryOptions,
) -> Result<Geometry> {
    Ok(match options.geom_type {
        GeometryTypeId::Point => Geometry::Point(generate_random_point(rng, options)?),
        GeometryTypeId::LineString => {
            Geometry::LineString(generate_random_linestring(rng, options)?)
        }
        GeometryTypeId::Polygon => Geometry::Polygon(generate_random_polygon(rng, options)?),
        GeometryTypeId::MultiPoint => {
            Geometry::MultiPoint(generate_random_multipoint(rng, options)?)
        }
        GeometryTypeId::MultiLineString => {
            Geometry::MultiLineString(generate_random_multilinestring(rng, options)?)
        }
        GeometryTypeId::MultiPolygon => {
            Geometry::MultiPolygon(generate_random_multipolygon(rng, options)?)
        }
        GeometryTypeId::GeometryCollection => {
            Geometry::GeometryCollection(generate_random_geometrycollection(rng, options)?)
        }
        GeometryTypeId::Geometry => {
            let mut copy_options = options.clone();
            copy_options.geom_type = pick_random_geometry_type(rng);
            generate_random_geometry(rng, &copy_options)?
        }
    })
}

fn generate_random_point<R: rand::Rng>(
    rng: &mut R,
    options: &RandomGeometryOptions,
) -> Result<Point> {
    if rng.random_bool(options.empty_rate) {
        // This is a bit of a hack because geo-types doesn't support empty point; however,
        // this does work with respect to sending this directly to the WKB reader and getting
        // the WKB result we want
        Ok(Point::new(f64::NAN, f64::NAN))
    } else {
        // Generate random points within the specified bounds
        let x_dist = Uniform::new(options.bounds.min().x, options.bounds.max().x)
            .map_err(|e| exec_datafusion_err!("Invalid x bounds for random point: {e}"))?;
        let y_dist = Uniform::new(options.bounds.min().y, options.bounds.max().y)
            .map_err(|e| exec_datafusion_err!("Invalid y bounds for random point: {e}"))?;
        let x = rng.sample(x_dist);
        let y = rng.sample(y_dist);
        Ok(Point::new(x, y))
    }
}

fn generate_random_linestring<R: rand::Rng>(
    rng: &mut R,
    options: &RandomGeometryOptions,
) -> Result<LineString> {
    if rng.random_bool(options.empty_rate) {
        Ok(LineString::new(vec![]))
    } else {
        let (center_x, center_y, half_size) = generate_random_circle(rng, options)?;
        let vertices_dist = Uniform::new_inclusive(
            options.vertices_per_linestring_range.0,
            options.vertices_per_linestring_range.1,
        )
        .map_err(|e| exec_datafusion_err!("Invalid vertex count range for linestring: {e}"))?;
        // Always sample in such a way that we end up with a valid linestring
        let num_vertices = rng.sample(vertices_dist).max(2);
        // Randomize starting angle (0 to 2 * PI)
        let angle = rng.random_range(0.0..(2.0 * PI));
        let coords =
            generate_circular_vertices(angle, center_x, center_y, half_size, num_vertices, false)?;
        Ok(LineString::from(coords))
    }
}

fn generate_random_polygon<R: rand::Rng>(
    rng: &mut R,
    options: &RandomGeometryOptions,
) -> Result<Polygon> {
    if rng.random_bool(options.empty_rate) {
        Ok(Polygon::new(LineString::new(vec![]), vec![]))
    } else {
        let (center_x, center_y, half_size) = generate_random_circle(rng, options)?;
        let vertices_dist = Uniform::new_inclusive(
            options.vertices_per_linestring_range.0,
            options.vertices_per_linestring_range.1,
        )
        .map_err(|e| exec_datafusion_err!("Invalid vertex count range for polygon: {e}"))?;
        // Always sample in such a way that we end up with a valid Polygon
        let num_vertices = rng.sample(vertices_dist).max(3);

        // Randomize starting angle (but use the same starting angle for both the shell
        // and the hole to ensure a non-intersecting interior)
        let angle = rng.random_range(0.0..=(2.0 * PI));
        let coords =
            generate_circular_vertices(angle, center_x, center_y, half_size, num_vertices, true)?;
        let shell = LineString::from(coords);
        let mut holes = Vec::new();

        // Potentially add a hole based on probability
        let add_hole = rng.random_bool(options.polygon_hole_rate);
        let hole_scale_factor = rng.random_range(0.1..0.5);
        if add_hole {
            let new_size = half_size * hole_scale_factor;
            let mut coords = generate_circular_vertices(
                angle,
                center_x,
                center_y,
                new_size,
                num_vertices,
                true,
            )?;
            coords.reverse();
            holes.push(LineString::from(coords));
        }

        Ok(Polygon::new(shell, holes))
    }
}

fn generate_random_multipoint<R: rand::Rng>(
    rng: &mut R,
    options: &RandomGeometryOptions,
) -> Result<MultiPoint> {
    if rng.random_bool(options.empty_rate) {
        Ok(MultiPoint::new(vec![]))
    } else {
        let children = generate_random_children(rng, options, generate_random_point)?;
        Ok(MultiPoint::new(children))
    }
}

fn generate_random_multilinestring<R: rand::Rng>(
    rng: &mut R,
    options: &RandomGeometryOptions,
) -> Result<MultiLineString> {
    if rng.random_bool(options.empty_rate) {
        Ok(MultiLineString::new(vec![]))
    } else {
        let children = generate_random_children(rng, options, generate_random_linestring)?;
        Ok(MultiLineString::new(children))
    }
}

fn generate_random_multipolygon<R: rand::Rng>(
    rng: &mut R,
    options: &RandomGeometryOptions,
) -> Result<MultiPolygon> {
    if rng.random_bool(options.empty_rate) {
        Ok(MultiPolygon::new(vec![]))
    } else {
        let children = generate_random_children(rng, options, generate_random_polygon)?;
        Ok(MultiPolygon::new(children))
    }
}

fn generate_random_geometrycollection<R: rand::Rng>(
    rng: &mut R,
    options: &RandomGeometryOptions,
) -> Result<GeometryCollection> {
    if rng.random_bool(options.empty_rate) {
        Ok(GeometryCollection::new_from(vec![]))
    } else {
        let children = generate_random_children(rng, options, generate_random_geometry)?;
        Ok(GeometryCollection::new_from(children))
    }
}

fn generate_random_children<R: Rng, T, F: Fn(&mut R, &RandomGeometryOptions) -> Result<T>>(
    rng: &mut R,
    options: &RandomGeometryOptions,
    func: F,
) -> Result<Vec<T>> {
    let num_parts_dist =
        Uniform::new_inclusive(options.num_parts_range.0, options.num_parts_range.1)
            .map_err(|e| exec_datafusion_err!("Invalid part count range: {e}"))?;
    let num_parts = rng.sample(num_parts_dist);

    // Constrain this feature to the size range indicated in the option
    let (center_x, center_y, half_width) = generate_random_circle(rng, options)?;
    let feature_bounds = Rect::new(
        Coord {
            x: center_x - half_width,
            y: center_y - half_width,
        },
        Coord {
            x: center_x + half_width,
            y: center_y + half_width,
        },
    );

    let child_bounds = generate_non_overlapping_sub_rectangles(num_parts, &feature_bounds);
    let mut child_options = options.clone();
    child_options.empty_rate = 0.0;

    let mut children = Vec::new();
    for bounds in child_bounds {
        child_options.bounds = bounds;
        let child_size = bounds.height().min(bounds.width());
        child_options.size_range = (child_size * 0.9, child_size);

        // If GeometryCollection, pick a random geometry type
        // Don't support nested GeometryCollection for now to avoid too much recursion
        if options.geom_type == GeometryTypeId::GeometryCollection {
            child_options.geom_type = pick_random_geometry_type(rng);
        }
        children.push(func(rng, &child_options)?);
    }

    Ok(children)
}

fn pick_random_geometry_type<R: Rng>(rng: &mut R) -> GeometryTypeId {
    [
        GeometryTypeId::Point,
        GeometryTypeId::LineString,
        GeometryTypeId::Polygon,
        GeometryTypeId::MultiPoint,
        GeometryTypeId::MultiLineString,
        GeometryTypeId::MultiPolygon,
    ][rng.random_range(0..6)]
}

fn generate_random_circle<R: rand::Rng>(
    rng: &mut R,
    options: &RandomGeometryOptions,
) -> Result<(f64, f64, f64)> {
    // Generate random circular polygons
    let size_dist = Uniform::new_inclusive(options.size_range.0, options.size_range.1)
        .map_err(|e| exec_datafusion_err!("Invalid size range for random region: {e}"))?;
    let size = rng.sample(size_dist);
    let half_size = size / 2.0;
    let height = options.bounds.height();
    let width = options.bounds.width();

    // Ensure circle fits within bounds by constraining center position
    let center_x = if width >= size {
        let center_x_dist = Uniform::new(
            options.bounds.min().x + half_size,
            options.bounds.max().x - half_size,
        )
        .map_err(|e| exec_datafusion_err!("Invalid x bounds for random circle center: {e}"))?;

        rng.sample(center_x_dist)
    } else {
        options.bounds.min().x + width / 2.0
    };

    let center_y = if height >= size {
        let center_y_dist = Uniform::new(
            options.bounds.min().y + half_size,
            options.bounds.max().y - half_size,
        )
        .map_err(|e| exec_datafusion_err!("Invalid y bounds for random circle center: {e}"))?;

        rng.sample(center_y_dist)
    } else {
        options.bounds.min().y + height / 2.0
    };

    Ok((
        center_x,
        center_y,
        half_size.min(height / 2.0).min(width / 2.0),
    ))
}

fn generate_non_overlapping_sub_rectangles(num_parts: usize, bounds: &Rect) -> Vec<Rect> {
    let mut tiles = vec![*bounds];
    let mut n = 0;
    while tiles.len() < num_parts {
        // Find the largest rectangle
        let (largest_idx, _) = tiles
            .iter()
            .enumerate()
            .map(|(i, rect)| (i, rect.height() * rect.width()))
            .max_by(|(_, a1), (_, a2)| a1.partial_cmp(a2).unwrap())
            .unwrap_or((0, 0.0));

        // Mix up subdividing by x and y
        let new_rects = if (n % 2) == 0 {
            tiles[largest_idx].split_x()
        } else {
            tiles[largest_idx].split_y()
        };

        // Remove the largest rectangle and add its subdivisions
        tiles.remove(largest_idx);
        tiles.insert(largest_idx, new_rects[0]);
        tiles.insert(largest_idx, new_rects[1]);
        n += 1;
    }

    tiles
}

fn generate_circular_vertices(
    mut angle: f64,
    center_x: f64,
    center_y: f64,
    radius: f64,
    num_vertices: usize,
    closed: bool,
) -> Result<Vec<Coord>> {
    let mut out = Vec::new();

    let dangle = 2.0 * PI / (num_vertices as f64).max(3.0);
    for _ in 0..num_vertices {
        out.push(Coord {
            x: angle.cos() * radius + center_x,
            y: angle.sin() * radius + center_y,
        });
        angle += dangle;
    }

    if closed {
        out.push(out[0]);
    }

    Ok(out)
}

#[cfg(test)]
mod tests {
    use super::*;
    use arrow_schema::DataType;
    use geo_traits::{MultiLineStringTrait, MultiPolygonTrait};
    use geo_types::Coord;
    use rand::rngs::StdRng;
    use rand::SeedableRng;
    use rstest::rstest;
    use sedona_geometry::{
        analyze::analyze_geometry, bounds::wkb_bounds_xy, interval::IntervalTrait,
    };

    #[test]
    fn test_generate_random_geometry_produces_valid_wkb() {
        let bounds = Rect::new(Coord { x: 10.0, y: 10.0 }, Coord { x: 90.0, y: 90.0 });
        let size_range = (1.0, 10.0);

        // Test both Point and Polygon geometry types
        let test_cases = vec![
            (GeometryTypeId::Point, 42, 100, 20, 50), // (type, seed, iterations, min_size, max_size)
            (GeometryTypeId::Polygon, 123, 50, 80, 200),
        ];

        for (geom_type, seed, iterations, min_size, max_size) in test_cases {
            let mut rng = StdRng::seed_from_u64(seed);
            let options = RandomGeometryOptions {
                geom_type,
                bounds,
                size_range,
                ..Default::default()
            };

            for _ in 0..iterations {
                let wkb_bytes = generate_random_wkb(&mut rng, &options).unwrap();

                // Verify WKB is not empty and has reasonable size
                assert!(!wkb_bytes.is_empty());
                assert!(
                    wkb_bytes.len() >= min_size,
                    "WKB size {} is smaller than expected minimum {} for {:?}",
                    wkb_bytes.len(),
                    min_size,
                    geom_type
                );
                assert!(
                    wkb_bytes.len() <= max_size,
                    "WKB size {} is larger than expected maximum {} for {:?}",
                    wkb_bytes.len(),
                    max_size,
                    geom_type
                );

                // Verify WKB can be parsed without error
                wkb::reader::read_wkb(&wkb_bytes).unwrap();
            }
        }
    }

    #[test]
    fn test_generate_random_geometry_deterministic() {
        let bounds = Rect::new(Coord { x: 0.0, y: 0.0 }, Coord { x: 100.0, y: 100.0 });
        let size_range = (1.0, 10.0);

        let geom_types = [GeometryTypeId::Point, GeometryTypeId::Polygon];

        // Generate with same seed twice
        let mut rng1 = StdRng::seed_from_u64(42);
        let mut rng2 = StdRng::seed_from_u64(42);

        for geom_type in geom_types {
            let options = RandomGeometryOptions {
                geom_type,
                bounds,
                size_range,
                ..Default::default()
            };
            let wkb1 = generate_random_wkb(&mut rng1, &options).unwrap();
            let wkb2 = generate_random_wkb(&mut rng2, &options).unwrap();

            // Should generate identical results
            assert_eq!(wkb1, wkb2);
        }
    }

    #[test]
    fn test_random_partitioned_data_builder_build_basic() {
        let (schema, partitions) = RandomPartitionedDataBuilder::new()
            .num_partitions(2)
            .batches_per_partition(3)
            .rows_per_batch(4)
            .null_rate(0.0) // No nulls for easier testing
            .build()
            .unwrap();

        // Verify schema
        assert_eq!(schema.fields().len(), 3);
        assert_eq!(schema.field(0).name(), "id");
        assert_eq!(schema.field(0).data_type(), &DataType::Int32);
        assert_eq!(schema.field(1).name(), "dist");
        assert_eq!(schema.field(1).data_type(), &DataType::Float64);
        assert_eq!(schema.field(2).name(), "geometry");

        // Verify partitions structure
        assert_eq!(partitions.len(), 2); // num_partitions

        for partition in &partitions {
            assert_eq!(partition.len(), 3); // batches_per_partition

            for batch in partition {
                assert_eq!(batch.num_rows(), 4); // rows_per_batch
                assert_eq!(batch.num_columns(), 3);
            }
        }
    }

    #[test]
    fn test_random_partitioned_data_builder_unique_ids() {
        let (_, partitions) = RandomPartitionedDataBuilder::new()
            .num_partitions(2)
            .batches_per_partition(2)
            .rows_per_batch(3)
            .build()
            .unwrap();

        let mut all_ids = Vec::new();

        for partition in &partitions {
            for batch in partition {
                let id_array = batch
                    .column(0)
                    .as_any()
                    .downcast_ref::<Int32Array>()
                    .unwrap();
                for i in 0..id_array.len() {
                    all_ids.push(id_array.value(i));
                }
            }
        }

        // Verify all IDs are unique
        all_ids.sort();
        for i in 1..all_ids.len() {
            assert_ne!(
                all_ids[i - 1],
                all_ids[i],
                "Found duplicate ID: {}",
                all_ids[i]
            );
        }

        // Verify IDs are sequential starting from 0
        for (i, &id) in all_ids.iter().enumerate() {
            assert_eq!(id, i as i32);
        }
    }

    #[test]
    fn test_random_partitioned_data_builder_null_rate() {
        let (_, partitions) = RandomPartitionedDataBuilder::new()
            .rows_per_batch(100)
            .null_rate(0.5) // 50% null rate
            .build()
            .unwrap();

        let batch = &partitions[0][0];
        let geometry_array = batch.column(2);

        let null_count = geometry_array.null_count();
        let total_count = geometry_array.len();
        let null_rate = null_count as f64 / total_count as f64;

        // Allow some variance due to randomness (±20%)
        assert!(
            (0.3..=0.7).contains(&null_rate),
            "Expected null rate around 0.5, got {null_rate}"
        );
    }

    #[test]
    fn test_random_partitioned_data_builder_deterministic() {
        let bounds = Rect::new(Coord { x: 0.0, y: 0.0 }, Coord { x: 100.0, y: 100.0 });

        let (schema1, partitions1) = RandomPartitionedDataBuilder::new()
            .seed(999)
            .num_partitions(2)
            .batches_per_partition(2)
            .rows_per_batch(5)
            .bounds(bounds)
            .build()
            .unwrap();

        let (schema2, partitions2) = RandomPartitionedDataBuilder::new()
            .seed(999) // Same seed
            .num_partitions(2)
            .batches_per_partition(2)
            .rows_per_batch(5)
            .bounds(bounds)
            .build()
            .unwrap();

        // Schemas should be identical
        assert_eq!(schema1, schema2);

        // All data should be identical
        assert_eq!(partitions1.len(), partitions2.len());
        for (partition1, partition2) in partitions1.iter().zip(partitions2.iter()) {
            assert_eq!(partition1.len(), partition2.len());
            for (batch1, batch2) in partition1.iter().zip(partition2.iter()) {
                // Compare IDs
                let ids1 = batch1
                    .column(0)
                    .as_any()
                    .downcast_ref::<Int32Array>()
                    .unwrap();
                let ids2 = batch2
                    .column(0)
                    .as_any()
                    .downcast_ref::<Int32Array>()
                    .unwrap();
                assert_eq!(ids1, ids2);

                // Compare distances
                let dists1 = batch1
                    .column(1)
                    .as_any()
                    .downcast_ref::<Float64Array>()
                    .unwrap();
                let dists2 = batch2
                    .column(1)
                    .as_any()
                    .downcast_ref::<Float64Array>()
                    .unwrap();
                assert_eq!(dists1, dists2);
            }
        }
    }

    #[test]
    fn test_random_partitioned_data_builder_different_seeds() {
        let bounds = Rect::new(Coord { x: 0.0, y: 0.0 }, Coord { x: 100.0, y: 100.0 });

        let (_, partitions1) = RandomPartitionedDataBuilder::new()
            .seed(111)
            .rows_per_batch(10)
            .bounds(bounds)
            .build()
            .unwrap();

        let (_, partitions2) = RandomPartitionedDataBuilder::new()
            .seed(222) // Different seed
            .rows_per_batch(10)
            .bounds(bounds)
            .build()
            .unwrap();

        // Data should be different (distances should differ)
        let dists1 = partitions1[0][0]
            .column(1)
            .as_any()
            .downcast_ref::<Float64Array>()
            .unwrap();
        let dists2 = partitions2[0][0]
            .column(1)
            .as_any()
            .downcast_ref::<Float64Array>()
            .unwrap();

        // At least some distances should be different
        let mut found_difference = false;
        for i in 0..dists1.len() {
            if (dists1.value(i) - dists2.value(i)).abs() > f64::EPSILON {
                found_difference = true;
                break;
            }
        }
        assert!(
            found_difference,
            "Expected different random data with different seeds"
        );
    }

    #[test]
    fn test_random_linestring_num_vertices() {
        let mut rng = StdRng::seed_from_u64(123);
        let mut options = RandomGeometryOptions::new();
        options.vertices_per_linestring_range = (3, 3);
        for _ in 0..100 {
            let geom = generate_random_linestring(&mut rng, &options).unwrap();
            assert_eq!(geom.coords().count(), 3);
        }

        options.vertices_per_linestring_range = (50, 50);
        for _ in 0..100 {
            let geom = generate_random_linestring(&mut rng, &options).unwrap();
            assert_eq!(geom.coords().count(), 50);
        }
    }

    #[test]
    fn test_random_polygon_has_hole() {
        let mut rng = StdRng::seed_from_u64(123);
        let mut options = RandomGeometryOptions::new();

        options.polygon_hole_rate = 0.0;
        for _ in 0..100 {
            let geom = generate_random_polygon(&mut rng, &options).unwrap();
            assert_eq!(geom.interiors().len(), 0);
        }

        options.polygon_hole_rate = 1.0;
        for _ in 0..100 {
            let geom = generate_random_polygon(&mut rng, &options).unwrap();
            assert!(!geom.interiors().is_empty());
        }
    }

    #[test]
    fn test_random_multipoint_part_count() {
        let mut rng = StdRng::seed_from_u64(123);
        let mut options = RandomGeometryOptions::new();

        options.num_parts_range = (3, 3);
        for _ in 0..100 {
            let geom = generate_random_multipoint(&mut rng, &options).unwrap();
            assert_eq!(geom.len(), 3);
        }

        options.num_parts_range = (10, 10);
        for _ in 0..100 {
            let geom = generate_random_multipoint(&mut rng, &options).unwrap();
            assert_eq!(geom.len(), 10);
        }
    }

    #[test]
    fn test_random_multilinestring_part_count() {
        let mut rng = StdRng::seed_from_u64(123);
        let mut options = RandomGeometryOptions::new();

        options.num_parts_range = (3, 3);
        for _ in 0..100 {
            let geom = generate_random_multilinestring(&mut rng, &options).unwrap();
            assert_eq!(geom.num_line_strings(), 3);
        }

        options.num_parts_range = (10, 10);
        for _ in 0..100 {
            let geom = generate_random_multilinestring(&mut rng, &options).unwrap();
            assert_eq!(geom.num_line_strings(), 10);
        }
    }

    #[test]
    fn test_random_multipolygon_part_count() {
        let mut rng = StdRng::seed_from_u64(123);
        let mut options = RandomGeometryOptions::new();

        options.num_parts_range = (3, 3);
        for _ in 0..100 {
            let geom = generate_random_multipolygon(&mut rng, &options).unwrap();
            assert_eq!(geom.num_polygons(), 3);
        }

        options.num_parts_range = (10, 10);
        for _ in 0..100 {
            let geom = generate_random_multipolygon(&mut rng, &options).unwrap();
            assert_eq!(geom.num_polygons(), 10);
        }
    }

    #[test]
    fn test_random_geometrycollection_part_count() {
        let mut rng = StdRng::seed_from_u64(123);
        let mut options = RandomGeometryOptions::new();

        options.num_parts_range = (3, 3);
        for _ in 0..100 {
            let geom = generate_random_geometrycollection(&mut rng, &options).unwrap();
            assert_eq!(geom.len(), 3);
        }

        options.num_parts_range = (10, 10);
        for _ in 0..100 {
            let geom = generate_random_geometrycollection(&mut rng, &options).unwrap();
            assert_eq!(geom.len(), 10);
        }
    }

    #[rstest]
    fn test_random_geometry_type(
        #[values(
            GeometryTypeId::Point,
            GeometryTypeId::LineString,
            GeometryTypeId::Polygon,
            GeometryTypeId::MultiPoint,
            GeometryTypeId::MultiLineString,
            GeometryTypeId::MultiPolygon,
            GeometryTypeId::GeometryCollection
        )]
        geom_type: GeometryTypeId,
    ) {
        let mut rng = StdRng::seed_from_u64(123);
        let mut options = RandomGeometryOptions::new();
        options.geom_type = geom_type;

        options.empty_rate = 0.0;
        for _ in 0..100 {
            let geom = generate_random_wkb(&mut rng, &options).unwrap();
            let wkb = wkb::reader::read_wkb(&geom).unwrap();
            let analysis = analyze_geometry(&wkb).unwrap();
            assert_eq!(analysis.geometry_type.geometry_type(), geom_type);
        }
    }

    #[rstest]
    fn test_random_emptiness(
        #[values(
            GeometryTypeId::Point,
            GeometryTypeId::LineString,
            GeometryTypeId::Polygon,
            GeometryTypeId::MultiPoint,
            GeometryTypeId::MultiLineString,
            GeometryTypeId::MultiPolygon,
            GeometryTypeId::GeometryCollection
        )]
        geom_type: GeometryTypeId,
    ) {
        let mut rng = StdRng::seed_from_u64(123);
        let mut options = RandomGeometryOptions::new();
        options.geom_type = geom_type;

        options.empty_rate = 0.0;
        for _ in 0..100 {
            let geom = generate_random_wkb(&mut rng, &options).unwrap();
            let bounds = wkb_bounds_xy(&geom).unwrap();
            assert!(!bounds.x().is_empty());
            assert!(!bounds.y().is_empty());

            assert!(
                bounds.x().lo() >= options.bounds.min().x
                    && bounds.y().lo() >= options.bounds.min().y
                    && bounds.x().hi() <= options.bounds.max().x
                    && bounds.y().hi() <= options.bounds.max().y
            );
        }

        options.empty_rate = 1.0;
        for _ in 0..100 {
            let geom = generate_random_wkb(&mut rng, &options).unwrap();
            let bounds = wkb_bounds_xy(&geom).unwrap();
            assert!(bounds.x().is_empty());
            assert!(bounds.y().is_empty());
        }
    }

    #[test]
    fn test_random_partitioned_data_builder_validation() {
        // Test invalid null_rate (< 0.0)
        let err = RandomPartitionedDataBuilder::new()
            .null_rate(-0.1)
            .validate()
            .unwrap_err();
        assert_eq!(
            err.to_string(),
            "Error during planning: Expected null_rate between 0.0 and 1.0 but got -0.1"
        );

        // Test invalid null_rate (> 1.0)
        let err = RandomPartitionedDataBuilder::new()
            .null_rate(1.5)
            .validate()
            .unwrap_err();
        assert_eq!(
            err.to_string(),
            "Error during planning: Expected null_rate between 0.0 and 1.0 but got 1.5"
        );

        // Test invalid rows_per_batch (0)
        let err = RandomPartitionedDataBuilder::new()
            .rows_per_batch(0)
            .validate()
            .unwrap_err();
        assert_eq!(
            err.to_string(),
            "Error during planning: Expected rows_per_batch > 0 but got 0"
        );

        // Test invalid num_partitions (0)
        let err = RandomPartitionedDataBuilder::new()
            .num_partitions(0)
            .validate()
            .unwrap_err();
        assert_eq!(
            err.to_string(),
            "Error during planning: Expected num_partitions > 0 but got 0"
        );

        // Test invalid empty_rate (< 0.0)
        let err = RandomPartitionedDataBuilder::new()
            .empty_rate(-0.1)
            .validate()
            .unwrap_err();
        assert_eq!(
            err.to_string(),
            "Error during planning: Expected empty_rate between 0.0 and 1.0 but got -0.1"
        );

        // Test invalid empty_rate (> 1.0)
        let err = RandomPartitionedDataBuilder::new()
            .empty_rate(1.5)
            .validate()
            .unwrap_err();
        assert_eq!(
            err.to_string(),
            "Error during planning: Expected empty_rate between 0.0 and 1.0 but got 1.5"
        );

        // Test invalid polygon_hole_rate (< 0.0)
        let err = RandomPartitionedDataBuilder::new()
            .polygon_hole_rate(-0.1)
            .validate()
            .unwrap_err();
        assert_eq!(
            err.to_string(),
            "Error during planning: Expected polygon_hole_rate between 0.0 and 1.0 but got -0.1"
        );

        // Test invalid polygon_hole_rate (> 1.0)
        let err = RandomPartitionedDataBuilder::new()
            .polygon_hole_rate(1.5)
            .validate()
            .unwrap_err();
        assert_eq!(
            err.to_string(),
            "Error during planning: Expected polygon_hole_rate between 0.0 and 1.0 but got 1.5"
        );

        // Test invalid size_range (min <= 0)
        let err = RandomPartitionedDataBuilder::new()
            .size_range((0.0, 10.0))
            .validate()
            .unwrap_err();
        assert_eq!(
            err.to_string(),
            "Error during planning: Expected valid size_range but got (0.0, 10.0)"
        );

        // Test invalid size_range (max <= 0)
        let err = RandomPartitionedDataBuilder::new()
            .size_range((5.0, -1.0))
            .validate()
            .unwrap_err();
        assert_eq!(
            err.to_string(),
            "Error during planning: Expected valid size_range but got (5.0, -1.0)"
        );

        // Test invalid size_range (min > max)
        let err = RandomPartitionedDataBuilder::new()
            .size_range((10.0, 5.0))
            .validate()
            .unwrap_err();
        assert_eq!(
            err.to_string(),
            "Error during planning: Expected valid size_range but got (10.0, 5.0)"
        );

        // Test invalid vertices_per_linestring_range (min == 0)
        let err = RandomPartitionedDataBuilder::new()
            .vertices_per_linestring_range((0, 5))
            .validate()
            .unwrap_err();
        assert_eq!(
            err.to_string(),
            "Error during planning: Expected valid vertices_per_linestring_range but got (0, 5)"
        );

        // Test invalid vertices_per_linestring_range (min > max)
        let err = RandomPartitionedDataBuilder::new()
            .vertices_per_linestring_range((10, 5))
            .validate()
            .unwrap_err();
        assert_eq!(
            err.to_string(),
            "Error during planning: Expected valid vertices_per_linestring_range but got (10, 5)"
        );

        // Test invalid num_parts_range (min == 0)
        let err = RandomPartitionedDataBuilder::new()
            .num_parts_range((0, 5))
            .validate()
            .unwrap_err();
        assert_eq!(
            err.to_string(),
            "Error during planning: Expected valid num_parts_range but got (0, 5)"
        );

        // Test invalid num_parts_range (min > max)
        let err = RandomPartitionedDataBuilder::new()
            .num_parts_range((10, 5))
            .validate()
            .unwrap_err();
        assert_eq!(
            err.to_string(),
            "Error during planning: Expected valid num_parts_range but got (10, 5)"
        );

        // Test invalid bounds (zero width)
        let err = RandomPartitionedDataBuilder::new()
            .bounds(Rect::new(
                Coord { x: 10.0, y: 10.0 },
                Coord { x: 10.0, y: 20.0 },
            ))
            .validate()
            .unwrap_err();
        assert_eq!(
            err.to_string(),
            "Error during planning: Expected valid bounds but got RECT(10.0 10.0,10.0 20.0)"
        );

        // Test invalid bounds (zero height)
        let err = RandomPartitionedDataBuilder::new()
            .bounds(Rect::new(
                Coord { x: 10.0, y: 10.0 },
                Coord { x: 20.0, y: 10.0 },
            ))
            .validate()
            .unwrap_err();
        assert_eq!(
            err.to_string(),
            "Error during planning: Expected valid bounds but got RECT(10.0 10.0,20.0 10.0)"
        );
    }
}