qql 0.5.0

QQL runtime and executor for Qdrant REST and gRPC
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
use std::collections::HashMap;
use std::sync::{Arc, Mutex};

use crate::backend::CollectionInfo;
use crate::executor::response::{GroupedSearchResult, OnError, SearchHit};
use crate::executor::{ExecData, Executor};
use qql_plan::{PlanGroupId, PlanPointId};

use super::mock::{MockEmbedder, MockQdrantClient, collection_with_vectors, test_config};

#[tokio::test]
async fn test_batch_query_groups_same_collection() {
    let mut client = MockQdrantClient::default();
    client.info = Some(CollectionInfo::default()); // unnamed vector → passes check
    let batch_count = client.batch_call_count.clone();
    let searches_count = client.last_batch_searches_count.clone();

    let executor = Executor::new(Box::new(client), Some(test_config()));

    let resp = qql_core::parser::Parser::parse_all(
        "QUERY TEXT 'a' MODEL 'test-model' FROM docs USING dense AS DENSE LIMIT 1;\
         QUERY TEXT 'b' MODEL 'test-model' FROM docs USING dense AS DENSE LIMIT 1;\
         QUERY TEXT 'c' MODEL 'test-model' FROM docs USING dense AS DENSE LIMIT 1;",
    )
    .unwrap();
    let results = executor
        .execute_batch_nodes(resp, OnError::Continue)
        .await
        .unwrap();

    // 3 queries, 3 results, 1 batch call
    assert_eq!(results.len(), 3, "expected 3 results");
    for r in &results {
        assert!(r.ok, "result should be ok: {:?}", r);
    }

    let calls = *batch_count.lock().unwrap();
    assert_eq!(calls, 1, "expected 1 batch call, got {calls}");

    let count = *searches_count.lock().unwrap();
    assert_eq!(count, 3, "expected 3 searches in batch, got {count}");
}

#[tokio::test]
async fn test_batch_mutations_same_collection() {
    let client = MockQdrantClient::default();
    let update_count = client.update_batch_call_count.clone();
    let ops_count = client.last_update_batch_ops_count.clone();
    let route_count = client.last_planned.clone();

    let executor = Executor::new(Box::new(client), Some(test_config()));

    // Explicit `WAIT true` on the upserts: embedding-less upserts default to
    // `WAIT false`, which is a different ambient group than the waiting DELETE.
    let stmts = qql_core::parser::Parser::parse_all(
        "UPSERT INTO docs VALUES {id: 1, title: 'a'} WAIT true;\
         UPSERT INTO docs VALUES {id: 2, title: 'b'} WAIT true;\
         DELETE FROM docs WHERE id = 3;",
    )
    .unwrap();
    let results = executor
        .execute_batch_nodes(stmts, OnError::Continue)
        .await
        .unwrap();

    assert_eq!(
        results.len(),
        3,
        "expected 3 results, got {}",
        results.len()
    );
    for r in &results {
        assert!(r.ok, "result should be ok: {:?}", r);
    }

    let calls = *update_count.lock().unwrap();
    assert_eq!(calls, 1, "expected 1 update-batch call, got {calls}");

    let count = *ops_count.lock().unwrap();
    assert_eq!(count, 3, "expected 3 ops in batch, got {count}");

    // Individual routes should not have been used for these mutations
    assert!(
        route_count.lock().unwrap().is_none(),
        "mutations should go through update batch, not execute_route"
    );
}

#[tokio::test]
async fn test_delete_payload_batches_with_mutations() {
    // P1 full batch support: `DELETE PAYLOAD` has an `UpdateOperation` batch
    // form (`delete_payload`), so same-collection runs batch instead of
    // isolating. REST (`DeletePayloadOperation`) and gRPC
    // (`PointsUpdateOperation.delete_payload = 5`) both carry it.
    let client = MockQdrantClient::default();
    let update_count = client.update_batch_call_count.clone();
    let individual_calls = client.execute_planned_call_count.clone();

    let executor = Executor::new(Box::new(client), Some(test_config()));

    // Two DELETE PAYLOAD statements batch into one update-batch RPC.
    let stmts = qql_core::parser::Parser::parse_all(
        "DELETE PAYLOAD draft FROM docs WHERE id = 1;\
         DELETE PAYLOAD final FROM docs WHERE id = 2;",
    )
    .unwrap();
    let results = executor
        .execute_batch_nodes(stmts, OnError::Continue)
        .await
        .unwrap();
    assert_eq!(
        results.len(),
        2,
        "expected 2 results, got {}",
        results.len()
    );
    for r in &results {
        assert!(r.ok, "DELETE PAYLOAD should succeed: {:?}", r);
        assert_eq!(r.operation, "DELETE_PAYLOAD");
    }
    assert_eq!(
        *update_count.lock().unwrap(),
        1,
        "DELETE PAYLOAD run must use update batch"
    );
    assert_eq!(
        *individual_calls.lock().unwrap(),
        0,
        "batched DELETE PAYLOAD must not dispatch singly"
    );

    // UPSERT + DELETE PAYLOAD in one same-collection group batch together.
    let client = MockQdrantClient::default();
    let update_count = client.update_batch_call_count.clone();
    let ops_count = client.last_update_batch_ops_count.clone();
    let individual_calls = client.execute_planned_call_count.clone();
    let executor = Executor::new(Box::new(client), Some(test_config()));
    let stmts = qql_core::parser::Parser::parse_all(
        "UPSERT INTO docs VALUES {id: 1, title: 'a'} WAIT true;\
         DELETE PAYLOAD draft FROM docs WHERE id = 1;",
    )
    .unwrap();
    let results = executor
        .execute_batch_nodes(stmts, OnError::Continue)
        .await
        .unwrap();
    assert_eq!(results.len(), 2);
    assert!(results[0].ok, "UPSERT should succeed: {:?}", results[0]);
    assert_eq!(results[0].operation, "UPSERT");
    assert!(
        results[1].ok,
        "DELETE PAYLOAD should succeed: {:?}",
        results[1]
    );
    assert_eq!(results[1].operation, "DELETE_PAYLOAD");
    assert_eq!(
        *update_count.lock().unwrap(),
        1,
        "UPSERT + DELETE PAYLOAD must batch"
    );
    assert_eq!(*ops_count.lock().unwrap(), 2);
    assert_eq!(
        *individual_calls.lock().unwrap(),
        0,
        "batched run must not dispatch singly"
    );

    // DELETE PAYLOAD sandwiched between batchable mutations: the whole
    // same-collection run batches as one update batch, order preserved.
    let client = MockQdrantClient::default();
    let update_count = client.update_batch_call_count.clone();
    let ops_count = client.last_update_batch_ops_count.clone();
    let individual_calls = client.execute_planned_call_count.clone();
    let executor = Executor::new(Box::new(client), Some(test_config()));
    let stmts = qql_core::parser::Parser::parse_all(
        "UPSERT INTO docs VALUES {id: 1, title: 'a'} WAIT true;\
         DELETE PAYLOAD draft FROM docs WHERE id = 1;\
         DELETE FROM docs WHERE id = 2;\
         UPSERT INTO docs VALUES {id: 3, title: 'c'} WAIT true;",
    )
    .unwrap();
    let results = executor
        .execute_batch_nodes(stmts, OnError::Continue)
        .await
        .unwrap();
    assert_eq!(results.len(), 4);
    assert_eq!(results[0].operation, "UPSERT");
    assert_eq!(results[1].operation, "DELETE_PAYLOAD");
    assert_eq!(results[2].operation, "DELETE");
    assert_eq!(results[3].operation, "UPSERT");
    for r in &results {
        assert!(r.ok, "all statements should succeed: {:?}", r);
    }
    assert_eq!(
        *update_count.lock().unwrap(),
        1,
        "full same-collection run must batch once"
    );
    assert_eq!(*ops_count.lock().unwrap(), 4);
    assert_eq!(
        *individual_calls.lock().unwrap(),
        0,
        "batched run must not dispatch singly"
    );
}

#[tokio::test]
async fn test_grouped_offset_applied_exactly_once() {
    // Regression (task 5): GROUP BY with OFFSET must apply the offset exactly
    // once. The planner sends `limit = user_limit + offset` and the executor
    // trims the returned groups client-side; `group_offset` has no wire
    // representation (serde-skipped, not in the gRPC QueryPointGroups proto),
    // so the backend never applies it. Simulate a server returning `limit`
    // groups and assert the result is exactly `user_limit` groups starting at
    // the offset — a double application would drop or duplicate groups.
    let group = |id: &str, point: u64, score: f64| GroupedSearchResult {
        group_id: PlanGroupId::Keyword(id.into()),
        hits: vec![SearchHit {
            id: PlanPointId::Number(point),
            score,
            payload: None,
            collection: None,
            vector: None,
        }],
    };
    let client = MockQdrantClient {
        info: Some(collection_with_vectors(&["dense"], &["sparse"])),
        point_map: Arc::new(Mutex::new(HashMap::from([(
            "docs".to_string(),
            ExecData::Groups(vec![
                group("a", 1, 1.0),
                group("b", 2, 0.9),
                group("c", 3, 0.8),
            ]),
        )]))),
        ..Default::default()
    };
    let executor = Executor::new(Box::new(client), Some(test_config()));
    let stmts = qql_core::parser::Parser::parse_all(
        "QUERY TEXT 'x' MODEL 'test-model' FROM docs USING dense AS DENSE GROUP BY category LIMIT 2 OFFSET 1;",
    )
    .unwrap();
    let results = executor
        .execute_batch_nodes(stmts, OnError::Continue)
        .await
        .unwrap();
    assert_eq!(results.len(), 1);
    let r = &results[0];
    assert!(r.ok, "grouped query should succeed: {:?}", r);
    assert_eq!(r.operation, "QUERY_GROUPS");
    assert_eq!(r.message, "Found 2 group(s)");
    let groups = r
        .data
        .as_ref()
        .and_then(ExecData::groups)
        .expect("grouped data is typed");
    assert_eq!(
        groups.len(),
        2,
        "must return exactly user_limit groups, got {}",
        groups.len()
    );
    assert_eq!(
        groups[0].group_id,
        PlanGroupId::Keyword("b".into()),
        "groups must start at the offset"
    );
    assert_eq!(groups[1].group_id, PlanGroupId::Keyword("c".into()));
}

#[tokio::test]
async fn test_batch_preserves_order_mixed_query_and_mutation() {
    let client = MockQdrantClient {
        info: Some(CollectionInfo::default()),
        ..Default::default()
    };
    let query_batch = client.batch_call_count.clone();
    let update_batch = client.update_batch_call_count.clone();

    let executor = Executor::new(Box::new(client), Some(test_config()));

    // Two mutations, then two queries — should batch each group separately
    let stmts = qql_core::parser::Parser::parse_all(
        "UPSERT INTO docs VALUES {id: 1} WAIT true;\
         DELETE FROM docs WHERE id = 2;\
         QUERY TEXT 'a' MODEL 'test-model' FROM docs USING dense AS DENSE LIMIT 1;\
         QUERY TEXT 'b' MODEL 'test-model' FROM docs USING dense AS DENSE LIMIT 1;",
    )
    .unwrap();
    let results = executor
        .execute_batch_nodes(stmts, OnError::Continue)
        .await
        .unwrap();

    assert_eq!(results.len(), 4);
    assert_eq!(results[0].operation, "UPSERT");
    assert_eq!(results[1].operation, "DELETE");
    assert_eq!(results[2].operation, "QUERY");
    assert_eq!(results[3].operation, "QUERY");

    assert_eq!(*update_batch.lock().unwrap(), 1);
    assert_eq!(*query_batch.lock().unwrap(), 1);
}

#[tokio::test]
async fn test_single_mutation_not_batched() {
    let client = MockQdrantClient::default();
    let update_count = client.update_batch_call_count.clone();

    let executor = Executor::new(Box::new(client), Some(test_config()));
    let stmts = qql_core::parser::Parser::parse_all("DELETE FROM docs WHERE id = 1;").unwrap();
    let results = executor
        .execute_batch_nodes(stmts, OnError::Continue)
        .await
        .unwrap();

    assert_eq!(results.len(), 1);
    assert!(results[0].ok);
    assert_eq!(
        *update_count.lock().unwrap(),
        0,
        "single mutation must not use update batch"
    );
}

#[tokio::test]
async fn test_continue_preserves_failure_position_and_batch_boundary() {
    let client = MockQdrantClient::default();
    let update_batches = client.update_batch_call_count.clone();
    let individual_calls = client.execute_planned_call_count.clone();
    let executor = Executor::new(Box::new(client), Some(test_config()));
    let stmts = qql_core::parser::Parser::parse_all(
        "DELETE FROM docs WHERE id = 1;\
         QUERY TEXT 'missing schema' MODEL 'test-model' FROM docs LIMIT 1;\
         DELETE FROM docs WHERE id = 2;",
    )
    .unwrap();

    let results = executor
        .execute_batch_nodes(stmts, OnError::Continue)
        .await
        .unwrap();

    assert_eq!(results.len(), 3);
    assert_eq!(results[0].operation, "DELETE");
    assert!(results[0].ok);
    assert_eq!(results[1].operation, "PREPARE");
    assert!(!results[1].ok);
    assert_eq!(results[2].operation, "DELETE");
    assert!(results[2].ok);
    assert_eq!(*update_batches.lock().unwrap(), 0);
    assert_eq!(*individual_calls.lock().unwrap(), 2);
}

#[tokio::test]
async fn test_stop_dispatches_prior_statement_before_later_prepare_failure() {
    let client = MockQdrantClient::default();
    let individual_calls = client.execute_planned_call_count.clone();
    let executor = Executor::new(Box::new(client), Some(test_config()));
    let stmts = qql_core::parser::Parser::parse_all(
        "DELETE FROM docs WHERE id = 1;\
         QUERY TEXT 'missing schema' MODEL 'test-model' FROM docs LIMIT 1;",
    )
    .unwrap();

    let error = executor
        .execute_batch_nodes(stmts, OnError::Stop)
        .await
        .expect_err("the second statement should fail preparation");

    assert!(error.message.contains("no mock info set"));
    assert_eq!(*individual_calls.lock().unwrap(), 1);
}

#[tokio::test]
async fn test_batch_upserts_keep_single_statement_auto_create_semantics() {
    let client = MockQdrantClient::default();
    let creates = client.execute_planned_call_count.clone();
    let update_batches = client.update_batch_call_count.clone();
    let embedder = Arc::new(MockEmbedder {
        dense: vec![0.1, 0.2, 0.3],
        sparse_indices: Vec::new(),
        sparse_values: Vec::new(),
        multi: vec![vec![0.1, 0.2], vec![0.3, 0.4]],
    });
    let mut config = test_config();
    config.embedding_dimension = 3;
    let executor = Executor::with_embedder(Box::new(client), Some(config), Some(embedder));
    let stmts = qql_core::parser::Parser::parse_all(
        "UPSERT INTO docs VALUES {id: 1, text: 'a'} USING DENSE MODEL 'mock';\
         UPSERT INTO docs VALUES {id: 2, text: 'b'} USING DENSE MODEL 'mock';",
    )
    .unwrap();

    let results = executor
        .execute_batch_nodes(stmts, OnError::Stop)
        .await
        .unwrap();

    assert_eq!(results.len(), 2);
    assert!(results.iter().all(|result| result.ok));
    assert_eq!(*creates.lock().unwrap(), 1);
    assert_eq!(*update_batches.lock().unwrap(), 1);
}

#[tokio::test]
async fn test_execute_batch_continue_collects_parse_errors_in_order() {
    let client = MockQdrantClient::default();
    let executor = Executor::new(Box::new(client), Some(test_config()));

    let report = executor
        .execute_batch(
            &[
                "DELETE FROM docs WHERE id = 1",
                "not qql",
                "DELETE FROM docs WHERE id = 2",
            ],
            OnError::Continue,
        )
        .await
        .unwrap();

    assert!(!report.ok);
    assert_eq!(report.succeeded, 2);
    assert_eq!(report.failed, 1);
    assert_eq!(report.results[0].operation, "DELETE");
    assert_eq!(report.results[1].operation, "PARSE");
    assert_eq!(report.results[2].operation, "DELETE");
}

#[tokio::test]
async fn test_execute_batch_stop_dispatches_prior_entries_before_parse_failure() {
    let client = MockQdrantClient::default();
    let individual_calls = client.execute_planned_call_count.clone();
    let executor = Executor::new(Box::new(client), Some(test_config()));

    let error = executor
        .execute_batch(&["DELETE FROM docs WHERE id = 1", "not qql"], OnError::Stop)
        .await
        .expect_err("the second entry should fail parsing");

    assert_eq!(error.code, "QQL-PARSE-STATEMENT");
    assert_eq!(*individual_calls.lock().unwrap(), 1);
}

#[tokio::test]
async fn test_execute_continue_returns_parse_failure_report() {
    let executor = Executor::new(Box::new(MockQdrantClient::default()), Some(test_config()));

    let report = executor
        .execute("not qql", OnError::Continue)
        .await
        .expect("continue mode should report parse failures");

    assert!(!report.ok);
    assert_eq!(report.succeeded, 0);
    assert_eq!(report.failed, 1);
    assert_eq!(report.results[0].operation, "PARSE");
}

#[tokio::test]
async fn test_execute_continue_returns_single_preparation_failure_report() {
    let executor = Executor::new(Box::new(MockQdrantClient::default()), Some(test_config()));

    let report = executor
        .execute(
            "QUERY TEXT 'missing schema' MODEL 'test-model' FROM docs LIMIT 1",
            OnError::Continue,
        )
        .await
        .expect("continue mode should report preparation failures");

    assert!(!report.ok);
    assert_eq!(report.succeeded, 0);
    assert_eq!(report.failed, 1);
    assert_eq!(report.results[0].operation, "PREPARE");
}

#[tokio::test]
async fn empty_script_fails_closed_like_double_semicolon() {
    let executor = Executor::new(Box::new(MockQdrantClient::default()), Some(test_config()));
    let err = executor
        .execute("   ", OnError::Stop)
        .await
        .expect_err("empty script must fail");
    assert_eq!(err.code, "QQL-VALIDATION-EMPTY-SCRIPT");

    let err = executor
        .execute_batch(&[], OnError::Stop)
        .await
        .expect_err("empty batch must fail");
    assert_eq!(err.code, "QQL-VALIDATION-EMPTY-SCRIPT");

    // Parity: `";;"` was already a parse error.
    let err = executor.execute(";;", OnError::Stop).await.unwrap_err();
    assert!(err.code.starts_with("QQL-PARSE"), "{err:?}");
}

#[tokio::test]
async fn close_reaches_backend_close_once() {
    let mock = MockQdrantClient::default();
    let close_calls = Arc::clone(&mock.close_call_count);
    let executor = Executor::new(Box::new(mock), Some(test_config()));
    executor
        .close()
        .await
        .expect("close forwards to the backend");
    assert_eq!(*close_calls.lock().unwrap(), 1);
    executor.close().await.expect("close twice is fine");
    assert_eq!(
        *close_calls.lock().unwrap(),
        1,
        "the backend is closed exactly once"
    );
}

#[tokio::test]
async fn closed_client_fails_every_execution_entry_point() {
    let executor = Executor::new(Box::new(MockQdrantClient::default()), Some(test_config()));
    executor.close().await.expect("close is idempotent");
    assert!(executor.is_closed());
    executor.close().await.expect("close twice is fine");

    let err = executor
        .execute("QUERY VECTOR [0.1] FROM docs", OnError::Stop)
        .await
        .expect_err("execute must fail after close");
    assert_eq!(err.code, "QQL-CLIENT-CLOSED");

    let err = executor
        .execute_batch(&["QUERY VECTOR [0.1] FROM docs"], OnError::Stop)
        .await
        .expect_err("execute_batch must fail after close");
    assert_eq!(err.code, "QQL-CLIENT-CLOSED");

    let stmt = qql_core::parser::Parser::parse("QUERY VECTOR [0.1] FROM docs").unwrap();
    let err = executor
        .execute_node(stmt)
        .await
        .expect_err("execute_node must fail after close");
    assert_eq!(err.code, "QQL-CLIENT-CLOSED");
}

#[tokio::test]
async fn query_batch_failure_with_continue_retries_individually() {
    // Two same-collection QUERY statements batch into one RPC. When the batch
    // RPC fails and on_error = continue, the group is retried one-by-one so
    // the first statement's success is preserved and the failed one is
    // reported at its own index.
    let client = MockQdrantClient {
        info: Some(collection_with_vectors(&["dense"], &[])),
        ..Default::default()
    };
    *client.fail_query_batch.lock().unwrap() = true;
    // On the per-op retry, statement 1 (the second execute_planned call) fails.
    *client.fail_execute_planned_call.lock().unwrap() = 2;
    let executor = Executor::new(Box::new(client), Some(test_config()));

    let report = executor
        .execute_batch(
            &[
                "QUERY VECTOR [0.1] FROM docs USING dense",
                "QUERY VECTOR [0.2] FROM docs USING dense",
            ],
            OnError::Continue,
        )
        .await
        .expect("continue mode must return a report");
    assert!(!report.ok);
    assert_eq!(report.succeeded, 1);
    assert_eq!(report.failed, 1);
    assert!(
        report.results[0].ok,
        "first statement must keep its success"
    );
    assert!(
        !report.results[1].ok,
        "second statement must be the failure"
    );
    assert_eq!(
        report.results.len(),
        2,
        "one response per statement, in order"
    );
}

#[tokio::test]
async fn conditional_upserts_are_not_retried_after_batch_transport_failure() {
    // A transport failure on a mutation batch re-runs only set-semantics
    // members one-by-one. Conditional upserts (`update_filter` /
    // `update_mode`) must surface the original batch error instead of
    // executing again against different state.
    let client = MockQdrantClient::default();
    *client.fail_update_batch.lock().unwrap() = true;
    let update_calls = client.update_batch_call_count.clone();
    let individual_calls = client.execute_planned_call_count.clone();
    let executor = Executor::new(Box::new(client), Some(test_config()));

    let stmts = qql_core::parser::Parser::parse_all(
        "UPSERT INTO docs VALUES {id: 1, vector: [0.1], status: 'active'} \
             UPDATE FILTER status = 'active' WAIT true;\
         UPSERT INTO docs VALUES {id: 2, vector: [0.2]} UPDATE MODE insert_only WAIT true;\
         UPSERT INTO docs VALUES {id: 3, vector: [0.3]} WAIT true;",
    )
    .unwrap();
    let results = executor
        .execute_batch_nodes(stmts, OnError::Continue)
        .await
        .expect("continue mode must return a report");

    assert_eq!(results.len(), 3, "one response per statement: {results:?}");
    assert!(
        !results[0].ok,
        "an update_filter upsert must not be retried: {results:?}"
    );
    assert!(
        !results[1].ok,
        "an insert_only upsert must not be retried: {results:?}"
    );
    assert!(
        results[1].message.contains("batch rejected"),
        "the original transport error is surfaced: {:?}",
        results[1]
    );
    assert!(
        results[2].ok,
        "the set-semantics upsert is retried individually: {results:?}"
    );
    assert_eq!(*update_calls.lock().unwrap(), 1, "exactly one batch RPC");
    assert_eq!(
        *individual_calls.lock().unwrap(),
        1,
        "only the retry-safe member re-runs"
    );
}

#[tokio::test]
async fn same_collection_query_batch_yields_per_statement_hits() {
    // N1: two same-collection QUERY statements batch into ONE
    // /points/query/batch RPC. The upstream per-item shape (OpenAPI
    // QueryResponse) is {"points": [...]} — the extraction must map each
    // item to its own statement's hits instead of silently returning [].
    let client = MockQdrantClient {
        info: Some(collection_with_vectors(&["dense"], &[])),
        ..Default::default()
    };
    let executor = Executor::new(Box::new(client), Some(test_config()));

    // Per-item strict parsing (each `QueryResponse` carries `points` at its
    // top level) lives in `rest_response::tests`; here we pin the end-to-end
    // executor behavior: one response per statement, in order.
    let report = executor
        .execute_batch(
            &[
                "QUERY VECTOR [0.1] FROM docs USING dense LIMIT 2",
                "QUERY VECTOR [0.2] FROM docs USING dense LIMIT 1",
            ],
            OnError::Stop,
        )
        .await
        .expect("same-collection batch must succeed");
    assert!(report.ok, "{report:?}");
    assert_eq!(report.results.len(), 2, "one response per statement");
    for r in &report.results {
        assert!(r.ok, "every batched statement must succeed: {r:?}");
    }
}

#[tokio::test]
async fn test_explicit_batch_forces_single_group_with_header_opts() {
    let mut client = MockQdrantClient::default();
    client.info = Some(CollectionInfo::default());
    let update_calls = client.update_batch_call_count.clone();
    let last_wait = client.last_update_batch_wait.clone();

    let executor = Executor::new(Box::new(client), Some(test_config()));
    let stmts = qql_core::parser::Parser::parse_all(
        "SHOW COLLECTIONS; BATCH { DELETE FROM docs WHERE id = 1; DELETE FROM docs WHERE id = 2; } WAIT false; SHOW COLLECTIONS;",
    )
    .unwrap();
    let results = executor
        .execute_batch_nodes(stmts, OnError::Continue)
        .await
        .unwrap();

    // SHOW barriers flank the block, yet members stay one forced group.
    assert_eq!(results.len(), 4, "one response per statement: {results:?}");
    assert_eq!(*update_calls.lock().unwrap(), 1, "exactly one batch RPC");
    assert_eq!(
        *last_wait.lock().unwrap(),
        Some(false),
        "header WAIT reaches the backend"
    );
    for r in &results {
        assert!(r.ok, "every statement must succeed: {r:?}");
    }
}

#[tokio::test]
async fn test_explicit_query_batch_carries_timeout() {
    let mut client = MockQdrantClient::default();
    client.info = Some(CollectionInfo::default());
    let batch_calls = client.batch_call_count.clone();
    let last_timeout = client.last_batch_timeout.clone();

    let executor = Executor::new(Box::new(client), Some(test_config()));
    let stmts = qql_core::parser::Parser::parse_all(
        "BATCH { QUERY [0.1] FROM docs LIMIT 1; QUERY [0.2] FROM docs LIMIT 1; } PARAMS (timeout = 30)",
    )
    .unwrap();
    let results = executor
        .execute_batch_nodes(stmts, OnError::Continue)
        .await
        .unwrap();

    assert_eq!(results.len(), 2, "one response per member: {results:?}");
    assert_eq!(*batch_calls.lock().unwrap(), 1, "exactly one batch RPC");
    assert_eq!(
        *last_timeout.lock().unwrap(),
        Some(30),
        "header timeout reaches the backend"
    );
}

#[tokio::test]
async fn test_ambient_query_groups_execute_with_their_own_read_opts() {
    // P0: differing per-statement read opts must split into separate ambient
    // groups, and each group must execute with its own header opts — never the
    // neighbor's.
    let mut client = MockQdrantClient::default();
    client.info = Some(CollectionInfo::default());
    let batch_calls = client.batch_call_count.clone();
    let last_timeout = client.last_batch_timeout.clone();
    let last_consistency = client.last_batch_consistency.clone();

    let executor = Executor::new(Box::new(client), Some(test_config()));
    let stmts = qql_core::parser::Parser::parse_all(
        "QUERY TEXT 'a' MODEL 'test-model' FROM docs USING dense AS DENSE PARAMS (timeout = 5) LIMIT 1;\
         QUERY TEXT 'b' MODEL 'test-model' FROM docs USING dense AS DENSE PARAMS (timeout = 5) LIMIT 1;\
         QUERY TEXT 'c' MODEL 'test-model' FROM docs USING dense AS DENSE PARAMS (timeout = 30, consistency = all) LIMIT 1;",
    )
    .unwrap();
    let results = executor
        .execute_batch_nodes(stmts, OnError::Continue)
        .await
        .unwrap();

    assert_eq!(results.len(), 3, "one response per statement: {results:?}");
    for r in &results {
        assert!(r.ok, "every statement must succeed: {r:?}");
    }
    assert_eq!(
        *batch_calls.lock().unwrap(),
        1,
        "only the two same-opt queries co-group; the differing one dispatches singly"
    );
    assert_eq!(
        *last_timeout.lock().unwrap(),
        Some(5),
        "the group executes with its own timeout"
    );
    assert_eq!(
        *last_consistency.lock().unwrap(),
        None,
        "the group executes with its own consistency"
    );
}

#[tokio::test]
async fn test_ambient_mutation_groups_execute_with_their_own_wait() {
    // P0: two `WAIT false` upserts co-group and execute with `wait=false`
    // (previously hardcoded `wait=true`); a `WAIT true` neighbor splits.
    let client = MockQdrantClient::default();
    let update_calls = client.update_batch_call_count.clone();
    let last_wait = client.last_update_batch_wait.clone();

    let executor = Executor::new(Box::new(client), Some(test_config()));
    let stmts = qql_core::parser::Parser::parse_all(
        "UPSERT INTO docs VALUES {id: 1, vector: [0.1, 0.2]} WAIT false;\
         UPSERT INTO docs VALUES {id: 2, vector: [0.1, 0.2]} WAIT false;",
    )
    .unwrap();
    let results = executor
        .execute_batch_nodes(stmts, OnError::Continue)
        .await
        .unwrap();

    assert_eq!(results.len(), 2);
    assert_eq!(*update_calls.lock().unwrap(), 1, "same wait must co-group");
    assert_eq!(
        *last_wait.lock().unwrap(),
        Some(false),
        "explicit WAIT false must reach the backend"
    );

    // `WAIT false` next to `WAIT true` is two groups, each with its own wait.
    let client = MockQdrantClient::default();
    let update_calls = client.update_batch_call_count.clone();
    let last_wait = client.last_update_batch_wait.clone();

    let executor = Executor::new(Box::new(client), Some(test_config()));
    let stmts = qql_core::parser::Parser::parse_all(
        "UPSERT INTO docs VALUES {id: 1, vector: [0.1, 0.2]} WAIT false;\
         UPSERT INTO docs VALUES {id: 2, vector: [0.1, 0.2]} WAIT false;\
         UPSERT INTO docs VALUES {id: 3, vector: [0.1, 0.2]} WAIT true;\
         UPSERT INTO docs VALUES {id: 4, vector: [0.1, 0.2]} WAIT true;",
    )
    .unwrap();
    let results = executor
        .execute_batch_nodes(stmts, OnError::Continue)
        .await
        .unwrap();

    assert_eq!(results.len(), 4);
    assert_eq!(
        *update_calls.lock().unwrap(),
        2,
        "differing wait must split into two groups"
    );
    assert_eq!(*last_wait.lock().unwrap(), Some(true));
}

#[tokio::test]
async fn test_execute_node_batch_returns_summary() {
    let mut client = MockQdrantClient::default();
    client.info = Some(CollectionInfo::default());

    let executor = Executor::new(Box::new(client), Some(test_config()));
    let stmt = qql_core::parser::Parser::parse(
        "BATCH { DELETE FROM docs WHERE id = 1; DELETE FROM docs WHERE id = 2; }",
    )
    .unwrap();
    let resp = executor.execute_node(stmt).await.unwrap();

    assert!(resp.ok, "{resp:?}");
    assert_eq!(resp.operation, "BATCH");
    assert!(resp.message.contains("2/2"), "{resp:?}");
}