onetaskgraph-linear 0.14.20

A onetaskgraph source over the Linear 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
//! Many reads and many writes of one kind sent to Linear as one aliased document.
//!
//! [`graphql::aliased`] composes the document this source sends for one item into one that
//! carries every item, each under its own alias. Linear answers each alias as it answers the
//! document alone, so a batch costs one request where the items would each have cost theirs.
//!
//! **Where Linear fails a batch as a whole.** Every root this source batches is non-null, and
//! Linear applies an aliased document as one write: an alias it refuses — an id naming
//! nothing, an input it rejects, a create under an id a record holds — answers the whole
//! document with no `data` and one error whose `path` is that alias, and nothing of any alias
//! before or after it lands. Observed on the sandbox team on 2026-11-11: an aliased
//! `issueCreate` document whose second alias conflicted created neither the first nor the
//! third issue, and an aliased `issueUpdate` document whose second alias named no issue
//! updated neither the first nor the third. So one item's refusal never decides another's:
//!
//! - a **read** refused at one alias answers that item absent when the refusal says it names
//!   nothing — and otherwise fails as that item's own — and the rest are read together again;
//! - a **write** refused at one alias is sent again on its own, for its own answer, and the
//!   rest are sent together again. Nothing of the refused document landed, so no write — a
//!   comment included — is ever sent twice.
//!
//! A source the store's cache stands in front of reads with documents of their own, which this
//! does not batch: it answers each item as the single-item method does.

use onetaskgraph_plugin_api::{
    BatchAnswer, BatchComment, BatchUpdate, Comment, NativeId, Page, PageRequest, SourceError,
    Task, TaskDetailRead, TaskQuery, TaskUpdateOutcome, decided_on,
};
use serde_json::{Value, json};

use super::{
    Composed, LinearSource, MAX_PAGE_SIZE, MutationRoot, Read, Refusal, Under400, comment_page,
    connection, graphql, map_task, optional, optional_string, written_comment,
};

/// One issue as [`LinearSource::issue_held`] reads it: the task and its raw description.
type Held = (Task, Option<String>);

/// What Linear answered an aliased document with.
pub(crate) enum Aliased {
    /// Every alias's root value, in order.
    Answered(Vec<Value>),
    /// The alias at this index was refused, with this refusal; nothing was answered.
    Refused(usize, Refusal),
}

/// `value`, what one alias of an aliased read answered, when it is of `id` — or absent, which
/// that read answers on its own terms. An item that names another id is not that alias's answer,
/// so it is never taken for it. Project and document answers are matched by `id` alone, because
/// the store names them by no key.
fn of_asked(value: Value, id: &NativeId, doing: &str) -> Result<Value, SourceError> {
    match value.get("id").and_then(Value::as_str) {
        Some(answered) if answered != id.0 => Err(SourceError::Malformed {
            message: format!(
                "Linear answered the alias asking for {id} while {doing} with another item, \
                 {answered}"
            ),
        }),
        _ => Ok(value),
    }
}

/// [`of_asked`] for an issue, which Linear's `issue(id:)` resolves by its uuid or by its key
/// (`TEAM-101`) and answers with its uuid either way: an answer is the alias's own when its `id`
/// or its `identifier` is the id asked for.
fn issue_of_asked(value: Value, id: &NativeId, doing: &str) -> Result<Value, SourceError> {
    if value.get("identifier").and_then(Value::as_str) == Some(id.0.as_str()) {
        return Ok(value);
    }
    of_asked(value, id, doing)
}

/// What Linear answered an aliased document with, each alias on its own.
pub(crate) enum AliasedEach {
    /// Every alias's root value, in order — one the answer left out its own malformed answer.
    Answered(Vec<Result<Value, SourceError>>),
    /// The alias at this index was refused, with this refusal; nothing was answered.
    Refused(usize, Refusal),
}

/// The most creates one aliased `issueCreate` document carries.
pub(crate) const CREATE_BATCH: usize = 25;

/// One create `write_tasks` gathered: the write, the variables its `issueCreate` is sent, the
/// id it is sent under when its key chooses one, and the relations it writes once it exists.
pub(crate) struct QueuedCreate {
    pub(crate) write: onetaskgraph_plugin_api::ItemWrite<Task>,
    pub(crate) variables: Value,
    pub(crate) sent: Option<NativeId>,
    pub(crate) edges: Vec<onetaskgraph_plugin_api::DependencyEdge>,
}

impl LinearSource {
    /// Send `single` once per entry of `each` — its variables — as one aliased document.
    ///
    /// # Errors
    ///
    /// Whatever the request failed with, and a refusal naming no alias, which is Linear failing
    /// the whole request rather than one item of it.
    pub(crate) async fn send_aliased(
        &self,
        single: &str,
        each: &[Value],
    ) -> Result<Aliased, SourceError> {
        self.send_composed_of(&vec![single; each.len()], each).await
    }

    /// Send each of `singles` with its variables in `each` as one [`graphql::composed`]
    /// document, on the terms of [`Self::send_aliased`].
    ///
    /// # Errors
    ///
    /// As [`Self::send_aliased`].
    pub(crate) async fn send_composed_of(
        &self,
        singles: &[&str],
        each: &[Value],
    ) -> Result<Aliased, SourceError> {
        Ok(match self.send_composed_each(singles, each).await? {
            AliasedEach::Answered(values) => {
                Aliased::Answered(values.into_iter().collect::<Result<Vec<_>, _>>()?)
            }
            AliasedEach::Refused(at, refusal) => Aliased::Refused(at, refusal),
        })
    }

    /// [`Self::send_aliased`], each alias answered on its own, as
    /// [`Self::send_composed_each`] answers it.
    ///
    /// # Errors
    ///
    /// As [`Self::send_aliased`].
    pub(crate) async fn send_aliased_each(
        &self,
        single: &str,
        each: &[Value],
    ) -> Result<AliasedEach, SourceError> {
        self.send_composed_each(&vec![single; each.len()], each)
            .await
    }

    /// [`Self::send_composed_of`], each alias answered on its own: one the answer leaves out is
    /// that alias's malformed answer beside every other's, where a write applied whole still
    /// needs every answer it can read.
    ///
    /// # Errors
    ///
    /// As [`Self::send_aliased`].
    async fn send_composed_each(
        &self,
        singles: &[&str],
        each: &[Value],
    ) -> Result<AliasedEach, SourceError> {
        let document = graphql::composed(singles);
        match self
            .answer_with(
                &document,
                graphql::aliased_variables(each),
                Under400::Unavailable,
            )
            .await?
        {
            Ok(data) => Ok(AliasedEach::Answered(
                (0..each.len())
                    .map(|at| {
                        data.get(format!("a{at}"))
                            .cloned()
                            .ok_or_else(|| SourceError::Malformed {
                                message: format!(
                                    "Linear answered a batch of {} without alias a{at}; what that \
                                 alias asked may have been done, so read it before sending it \
                                 again",
                                    each.len()
                                ),
                            })
                    })
                    .collect(),
            )),
            Err(refusal) => match refusal.alias() {
                Some(at) if at < each.len() => Ok(AliasedEach::Refused(at, refusal)),
                _ => Err(refusal.into_error()),
            },
        }
    }

    /// Whether this source batches reads with `single` as it is — not when the store's cache
    /// stands in front of it and reads with documents of its own.
    fn batches(&self, single: &'static str) -> bool {
        self.read_document(single) == single
    }

    /// Each of `ids` read as [`Self::issue_held`] reads it — the issue and its raw description,
    /// `None` for one this source does not hold — in as few aliased reads as Linear answers,
    /// each answered on its own: one Linear refuses, or answers malformed, fails that issue's
    /// read alone, and the rest are read together again.
    ///
    /// # Errors
    ///
    /// What the whole request failed with, which answers no issue.
    pub(crate) async fn issues_held(
        &self,
        ids: &[NativeId],
    ) -> Result<Vec<Result<Option<Held>, SourceError>>, SourceError> {
        if ids.len() < 2 || !self.batches(graphql::ISSUE) {
            let mut read = Vec::with_capacity(ids.len());
            for id in ids {
                read.push(self.issue_held(id, Read::Load).await);
            }
            return Ok(read);
        }
        let mut read: Vec<Option<Result<Option<Held>, SourceError>>> =
            (0..ids.len()).map(|_| None).collect();
        let mut pending: Vec<usize> = (0..ids.len()).collect();
        while !pending.is_empty() {
            let each: Vec<Value> = pending.iter().map(|at| json!({"id": ids[*at].0})).collect();
            match self.send_aliased_each(graphql::ISSUE, &each).await? {
                AliasedEach::Answered(values) => {
                    for (at, value) in pending.iter().zip(values) {
                        read[*at] = Some(
                            value
                                .and_then(|value| {
                                    issue_of_asked(value, &ids[*at], "reading issues together")
                                })
                                .and_then(|value| {
                                    Ok(optional(&json!({"issue": value}), "issue", |v| {
                                        Ok((
                                            map_task(
                                                v,
                                                &self.name,
                                                &self.statuses,
                                                self.spelling(),
                                                self.assignees,
                                            )?,
                                            optional_string(v, "description")?,
                                        ))
                                    })?
                                    .filter(|(task, _)| self.in_scope(task.project.as_ref())))
                                }),
                        );
                    }
                    pending.clear();
                }
                AliasedEach::Refused(refused, refusal) => {
                    let at = pending.remove(refused);
                    read[at] = Some(if refusal.entity_missing() {
                        Ok(None)
                    } else {
                        Err(refusal.into_error())
                    });
                }
            }
        }
        Ok(read
            .into_iter()
            .map(|held| {
                held.unwrap_or_else(|| {
                    Err(SourceError::Malformed {
                        message: "an issue of the batch was given no answer".to_owned(),
                    })
                })
            })
            .collect())
    }

    /// One held comment of a batch made on its own after the rest: the issue read as it now
    /// stands, the hold decided on that read, and the comment added as `add_comment` adds it.
    async fn comment_after(
        &self,
        each: &BatchComment,
    ) -> Result<BatchAnswer<Comment>, SourceError> {
        use onetaskgraph_plugin_api::TaskSource as _;
        let now = self.issue_held(&each.task, Read::Load).await?;
        if let Some(answer) = decided_on(
            self,
            now.as_ref().map(|(task, _)| task),
            each.if_version.as_deref(),
            &[],
            None,
        ) {
            return Ok(answer);
        }
        Ok(self
            .add_comment(&each.task, &each.comment)
            .await?
            .map_or(BatchAnswer::Missing, BatchAnswer::Written))
    }

    /// One update of a batch made on its own after the rest: the issue read as it now stands,
    /// the update decided on that read, and written as `update_task` writes it.
    async fn update_after(
        &self,
        each: &BatchUpdate,
    ) -> Result<BatchAnswer<TaskUpdateOutcome>, SourceError> {
        use onetaskgraph_plugin_api::TaskSource as _;
        let now = self.issue_held(&each.id, Read::Load).await?;
        if let Some(answer) = decided_on(
            self,
            now.as_ref().map(|(task, _)| task),
            each.if_version.as_deref(),
            &each.when_priority,
            each.when_assignees.as_deref(),
        ) {
            return Ok(answer);
        }
        Ok(self
            .update_task(&each.id, &each.update)
            .await?
            .map_or(BatchAnswer::Missing, BatchAnswer::Written))
    }

    /// [`TaskSource::update_tasks`](onetaskgraph_plugin_api::TaskSource::update_tasks): every
    /// issue read in one aliased read, each decided against its hold and its guard, and every
    /// update that changes something sent in one aliased `issueUpdate` document; see the module
    /// documentation for where an item is sent on its own.
    pub(crate) async fn update_batched(
        &self,
        updates: &[BatchUpdate],
    ) -> Vec<Result<BatchAnswer<TaskUpdateOutcome>, SourceError>> {
        let mut answers: Vec<Option<Result<BatchAnswer<TaskUpdateOutcome>, SourceError>>> =
            updates.iter().map(|_| None).collect();
        // Refused before anything is read, as `update_task` refuses it.
        for (at, each) in updates.iter().enumerate() {
            if let Err(error) = self.update_checked(&each.id, &each.update) {
                answers[at] = Some(Err(error));
            }
        }
        // A later update of an issue an earlier update of this batch names is made after the
        // batch, on its own, decided on what the earlier one left: composed beside it on the
        // same read, the later write would put back what the earlier one changed.
        let mut wanted: Vec<usize> = Vec::new();
        let mut later: Vec<usize> = Vec::new();
        for at in (0..updates.len()).filter(|at| answers[*at].is_none()) {
            if wanted
                .iter()
                .any(|earlier| updates[*earlier].id == updates[at].id)
            {
                later.push(at);
            } else {
                wanted.push(at);
            }
        }
        let ids: Vec<NativeId> = wanted.iter().map(|at| updates[*at].id.clone()).collect();
        let read = match self.issues_held(&ids).await {
            Ok(read) => read,
            Err(error) => {
                for at in wanted.iter().chain(&later) {
                    answers[*at] = Some(Err(error.clone()));
                }
                return answers.into_iter().flatten().collect();
            }
        };
        let mut deciding: Vec<(usize, Held)> = Vec::new();
        for (at, held) in wanted.into_iter().zip(read) {
            let each = &updates[at];
            let held = match held {
                Ok(held) => held,
                Err(error) => {
                    answers[at] = Some(Err(error));
                    continue;
                }
            };
            if let Some(answer) = decided_on(
                self,
                held.as_ref().map(|(task, _)| task),
                each.if_version.as_deref(),
                &each.when_priority,
                each.when_assignees.as_deref(),
            ) {
                answers[at] = Some(Ok(answer));
                continue;
            }
            let Some(held) = held else {
                answers[at] = Some(Ok(BatchAnswer::Missing));
                continue;
            };
            deciding.push((at, held));
        }
        // Every person the updates to be written assign, resolved in one request — the later
        // updates of an issue too, which are made after the batch and would otherwise each
        // resolve their own; a failure here is each such update's own when it is composed. A
        // first update naming exactly the people its issue holds writes none, so asks for none.
        let firsts = deciding.iter().filter_map(|(at, (before, _))| {
            updates[*at]
                .update
                .assignees
                .as_deref()
                .filter(|people| *people != before.assignees.as_deref().unwrap_or_default())
        });
        let afterwards = later
            .iter()
            .filter(|at| answers[**at].is_none())
            .filter_map(|at| updates[*at].update.assignees.as_deref());
        let people =
            super::assignees::named(firsts.chain(afterwards).filter(|people| !people.is_empty()));
        if !people.is_empty() {
            let _ = self.resolve_people(&people).await;
        }
        let mut sending: Vec<(usize, Composed)> = Vec::new();
        for (at, (before, description)) in deciding {
            let each = &updates[at];
            match self.compose_update(&each.update, before, description).await {
                Ok(composed) if composed.relations.is_some() => {
                    // An update writing relations sends them after its issue's own write, so it
                    // is sent as `update_task` sends it.
                    answers[at] = Some(
                        self.send_composed(&each.id, &each.update, composed)
                            .await
                            .map(|outcome| {
                                outcome.map_or(BatchAnswer::Missing, BatchAnswer::Written)
                            }),
                    );
                }
                Ok(composed) if composed.input.is_empty() => {
                    let written = each.update.changed(&composed.before, &composed.before);
                    answers[at] = Some(Ok(BatchAnswer::Written(TaskUpdateOutcome {
                        delivers_before: composed.before.delivers.clone(),
                        task: composed.before,
                        written,
                    })));
                }
                Ok(composed) => sending.push((at, composed)),
                Err(error) => answers[at] = Some(Err(error)),
            }
        }
        while !sending.is_empty() {
            let each: Vec<Value> = sending
                .iter()
                .map(|(_, composed)| {
                    json!({"id": composed.before.id.0,
                           "input": Value::Object(composed.input.clone())})
                })
                .collect();
            let carries_state = sending
                .iter()
                .any(|(_, composed)| composed.input.contains_key("stateId"));
            let answered = if each.len() == 1 {
                // One update alone is sent as `update_task` sends it.
                self.send(graphql::ISSUE_UPDATE_READ, each[0].clone())
                    .await
                    .map(|data| AliasedEach::Answered(vec![Ok(data["issueUpdate"].clone())]))
            } else {
                self.send_aliased_each(graphql::ISSUE_UPDATE_READ, &each)
                    .await
            };
            match answered {
                Ok(AliasedEach::Answered(values)) => {
                    for ((at, composed), value) in sending.drain(..).zip(values) {
                        let id = composed.before.id.clone();
                        answers[at] = Some(
                            value
                                .and_then(|value| {
                                    self.updated_issue(&json!({"issueUpdate": value}), &id)
                                })
                                .and_then(|task| {
                                    task.ok_or_else(|| SourceError::Malformed {
                                        message: format!(
                                            "task {id} was updated and then answered as no issue"
                                        ),
                                    })
                                })
                                .and_then(|task| {
                                    self.assigned_as(
                                        &id,
                                        updates[at].update.assignees.as_deref(),
                                        &task,
                                    )?;
                                    Ok(task)
                                })
                                .map(|task| {
                                    BatchAnswer::Written(TaskUpdateOutcome {
                                        written: updates[at]
                                            .update
                                            .changed(&composed.before, &task),
                                        delivers_before: composed.before.delivers.clone(),
                                        task,
                                    })
                                }),
                        );
                    }
                }
                Ok(AliasedEach::Refused(refused, _)) => {
                    // That one alone, for its own answer; the rest together again.
                    let (at, composed) = sending.remove(refused);
                    let id = updates[at].id.clone();
                    answers[at] = Some(
                        self.send_composed(&id, &updates[at].update, composed)
                            .await
                            .map(|outcome| {
                                outcome.map_or(BatchAnswer::Missing, BatchAnswer::Written)
                            }),
                    );
                }
                Err(error) => {
                    if carries_state {
                        self.forget_vocabulary();
                    }
                    for (at, _) in sending.drain(..) {
                        answers[at] = Some(Err(error.clone()));
                    }
                }
            }
        }
        for at in later {
            answers[at] = Some(self.update_after(&updates[at]).await);
        }
        answers
            .into_iter()
            .map(|answer| {
                answer.unwrap_or_else(|| {
                    Err(SourceError::Malformed {
                        message: "an update of the batch was given no answer".to_owned(),
                    })
                })
            })
            .collect()
    }

    /// [`TaskSource::add_comments`](onetaskgraph_plugin_api::TaskSource::add_comments): every
    /// issue read in one aliased read — which finds each and decides each hold — and every
    /// comment then created in one aliased `commentCreate` document; see the module
    /// documentation.
    pub(crate) async fn comment_batched(
        &self,
        comments: &[BatchComment],
    ) -> Vec<Result<BatchAnswer<Comment>, SourceError>> {
        let mut answers: Vec<Option<Result<BatchAnswer<Comment>, SourceError>>> =
            comments.iter().map(|_| None).collect();
        for (at, each) in comments.iter().enumerate() {
            if let Some(author) = &each.comment.author {
                answers[at] = Some(Err(SourceError::Refused {
                    message: format!(
                        "source {} cannot post a comment as {author:?}, because Linear records \
                         the user whose API key makes the request as the author of every \
                         comment; leave the author out to post as that user",
                        self.name
                    ),
                }));
            }
        }
        // A held comment on an issue an earlier comment of this batch names is decided only
        // once that one is answered, on a read made then: whether a comment moves its issue's
        // version is the version's own — a `lin1` token counts comments, `updatedAt` does not.
        let mut wanted: Vec<usize> = Vec::new();
        let mut later: Vec<usize> = Vec::new();
        for at in (0..comments.len()).filter(|at| answers[*at].is_none()) {
            if comments[at].if_version.is_some()
                && wanted
                    .iter()
                    .any(|earlier| comments[*earlier].task == comments[at].task)
            {
                later.push(at);
            } else {
                wanted.push(at);
            }
        }
        let ids: Vec<NativeId> = wanted.iter().map(|at| comments[*at].task.clone()).collect();
        let read = match self.issues_held(&ids).await {
            Ok(read) => read,
            Err(error) => {
                for at in wanted.iter().chain(&later) {
                    answers[*at] = Some(Err(error.clone()));
                }
                return answers.into_iter().flatten().collect();
            }
        };
        let mut sending: Vec<(usize, NativeId)> = Vec::new();
        for (at, held) in wanted.into_iter().zip(read) {
            let each = &comments[at];
            let held = match held {
                Ok(held) => held,
                Err(error) => {
                    answers[at] = Some(Err(error));
                    continue;
                }
            };
            if let Some(answer) = decided_on(
                self,
                held.as_ref().map(|(task, _)| task),
                each.if_version.as_deref(),
                &[],
                None,
            ) {
                answers[at] = Some(Ok(answer));
                continue;
            }
            if let Some((task, _)) = held {
                sending.push((at, task.id));
            }
        }
        while !sending.is_empty() {
            let each: Vec<Value> = sending
                .iter()
                .map(|(at, issue)| {
                    json!({"input": {"issueId": issue.0,
                                     "body": comments[*at].comment.body.as_str()}})
                })
                .collect();
            let answered = if each.len() == 1 {
                self.send(graphql::COMMENT_CREATE, each[0].clone())
                    .await
                    .map(|data| AliasedEach::Answered(vec![Ok(data["commentCreate"].clone())]))
            } else {
                self.send_aliased_each(graphql::COMMENT_CREATE, &each).await
            };
            match answered {
                Ok(AliasedEach::Answered(values)) => {
                    for ((at, _), value) in sending.drain(..).zip(values) {
                        answers[at] = Some(
                            value
                                .and_then(|value| {
                                    written_comment(
                                        &json!({"commentCreate": value}),
                                        MutationRoot::CommentCreate,
                                    )
                                })
                                .map(BatchAnswer::Written),
                        );
                    }
                }
                Ok(AliasedEach::Refused(refused, _)) => {
                    // Nothing of the document landed: that one alone, for its own answer, and
                    // the rest together again.
                    let (at, issue) = sending.remove(refused);
                    answers[at] = Some(
                        self.send(
                            graphql::COMMENT_CREATE,
                            json!({"input": {"issueId": issue.0,
                                             "body": comments[at].comment.body.as_str()}}),
                        )
                        .await
                        .and_then(|data| written_comment(&data, MutationRoot::CommentCreate))
                        .map(BatchAnswer::Written),
                    );
                }
                Err(error) => {
                    for (at, _) in sending.drain(..) {
                        answers[at] = Some(Err(error.clone()));
                    }
                }
            }
        }
        for at in later {
            answers[at] = Some(self.comment_after(&comments[at]).await);
        }
        answers
            .into_iter()
            .map(|answer| {
                answer.unwrap_or_else(|| {
                    Err(SourceError::Malformed {
                        message: "a comment of the batch was given no answer".to_owned(),
                    })
                })
            })
            .collect()
    }

    /// Queue the create `write_task` composed — `input`, with the team and the id its key
    /// derives — for the `write_tasks` gathering it; nothing is sent.
    pub(crate) fn create_queued(
        &self,
        write: &onetaskgraph_plugin_api::ItemWrite<Task>,
        mut input: Value,
        team: NativeId,
        create: &super::CreateId,
        edges: Vec<onetaskgraph_plugin_api::DependencyEdge>,
    ) -> Result<(), SourceError> {
        input["teamId"] = Value::String(team.0);
        let sent = match create {
            super::CreateId::Unchosen => None,
            super::CreateId::Keyed(key) | super::CreateId::Origin { key, .. } => {
                let ids = super::linear_ids_of_key(&key.hyphenated().to_string())?;
                ids.into_iter().next().map(NativeId)
            }
        };
        if let Some(id) = &sent {
            input["id"] = Value::String(id.0.clone());
        }
        self.queued_creates
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .push(QueuedCreate {
                write: write.clone(),
                variables: json!({"input": input}),
                sent,
                edges,
            });
        Ok(())
    }

    /// [`TaskSource::write_tasks`](onetaskgraph_plugin_api::TaskSource::write_tasks): every create
    /// composed as `write_task` composes it and sent in one aliased `issueCreate` document, each
    /// answered — its id, the content Linear stored and its location — as a create alone is.
    ///
    /// Linear applies the document as one write, so one it refuses lands nothing: that create is
    /// made on its own, as `write_task` makes it — a create under an id a record holds finding
    /// the issue an earlier attempt made there — and the rest are sent together again. All of
    /// them or none, as the contract asks: one refused alone takes back every create made.
    pub(crate) async fn create_batched(
        &self,
        writes: &[onetaskgraph_plugin_api::ItemWrite<Task>],
    ) -> Result<Vec<NativeId>, SourceError> {
        if let Some(write) = writes.iter().find(|write| write.target.is_some()) {
            return Err(SourceError::Refused {
                message: format!(
                    "write_tasks creates tasks, and the write of {} names an existing target; \
                     next: update it with write_task",
                    write.item.id
                ),
            });
        }
        // Every person the creates name resolved in one request, before any is composed.
        if self.assignees {
            let people = super::assignees::named(
                writes
                    .iter()
                    .filter_map(|write| write.item.assignees.as_deref()),
            );
            if !people.is_empty() {
                self.resolve_people(&people).await?;
            }
        }
        self.deferring_creates
            .store(true, std::sync::atomic::Ordering::SeqCst);
        let mut composed = Ok(());
        for write in writes {
            match self.write_or_queue(write).await {
                Ok(super::Landed::Queued) => {}
                Ok(super::Landed::At(id)) => {
                    composed = Err(SourceError::Malformed {
                        message: format!(
                            "the create of {} was written rather than queued as {id}",
                            write.item.id
                        ),
                    });
                    break;
                }
                Err(error) => {
                    composed = Err(error);
                    break;
                }
            }
        }
        self.deferring_creates
            .store(false, std::sync::atomic::Ordering::SeqCst);
        let mut queued: Vec<(usize, QueuedCreate)> = std::mem::take(
            &mut *self
                .queued_creates
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner),
        )
        .into_iter()
        .enumerate()
        .collect();
        composed?;
        let mut landed: Vec<Option<NativeId>> = writes.iter().map(|_| None).collect();
        let outcome = self.send_queued(&mut queued, &mut landed).await;
        if let Err(error) = outcome {
            // The caller is never handed these ids, so one Linear will not take back is named
            // here or by nobody — as the default `write_tasks` names it.
            let mut left: Vec<&str> = Vec::new();
            for id in landed.iter().flatten() {
                if <Self as onetaskgraph_plugin_api::TaskSource>::delete_task(self, id)
                    .await
                    .is_err()
                {
                    left.push(id.0.as_str());
                }
            }
            if left.is_empty() {
                return Err(error);
            }
            let message = format!(
                "{error}; Linear then refused to take back {}, which this write created or \
                 brought in step and which it still holds; next: delete {} before writing again",
                left.join(", "),
                if left.len() == 1 { "it" } else { "them" }
            );
            // A malformed answer stays one, so the caller still knows a create it cannot name
            // may have landed.
            return Err(match error {
                SourceError::Malformed { .. } => SourceError::Malformed { message },
                _ => SourceError::Refused { message },
            });
        }
        landed
            .into_iter()
            .map(|id| {
                id.ok_or_else(|| SourceError::Malformed {
                    message: "a create of the batch was given no id".to_owned(),
                })
            })
            .collect()
    }

    /// Send every queued create, recording at its index in `landed` the id of the issue it
    /// left — one it created, or one an earlier attempt made under its id and this write
    /// brought in step — so a write that cannot finish takes each back.
    async fn send_queued(
        &self,
        queued: &mut Vec<(usize, QueuedCreate)>,
        landed: &mut [Option<NativeId>],
    ) -> Result<(), SourceError> {
        while !queued.is_empty() {
            if queued.len() == 1 {
                let (at, alone) = queued.remove(0);
                landed[at] = Some(
                    <Self as onetaskgraph_plugin_api::TaskSource>::write_task(self, &alone.write)
                        .await?,
                );
                continue;
            }
            let each: Vec<Value> = queued
                .iter()
                .map(|(_, create)| {
                    json!({"input": super::assignees::create_input(create.variables["input"].clone())})
                })
                .collect();
            let singles = vec![graphql::ISSUE_CREATE; each.len()];
            match self.send_composed_each(&singles, &each).await? {
                AliasedEach::Answered(values) => {
                    // Linear applied the whole document, so every create in it that its answer
                    // names is recorded to be taken back before any answer is refused as
                    // malformed — one malformed answer leaves the others nameable.
                    let mut answered = Vec::with_capacity(values.len());
                    let mut malformed = None;
                    for ((at, create), value) in queued.drain(..).zip(values) {
                        let named = value
                            .and_then(|value| {
                                let answered = json!({"issueCreate": value});
                                super::mutation_payload(&answered, MutationRoot::IssueCreate)
                                    .cloned()
                            })
                            .and_then(|payload| {
                                payload.get("issue").cloned().ok_or_else(|| {
                                    SourceError::Malformed {
                                        message: "missing issueCreate.issue".to_owned(),
                                    }
                                })
                            })
                            .and_then(|issue| {
                                let id = super::created_as(
                                    NativeId(super::backend_id(&issue, "id")?.into()),
                                    create.sent.as_ref(),
                                    "issue",
                                )?;
                                Ok((id, issue))
                            });
                        match named {
                            Ok((id, issue)) => {
                                landed[at] = Some(id.clone());
                                answered.push((id, issue, create));
                            }
                            Err(error) => {
                                malformed.get_or_insert(error);
                            }
                        }
                    }
                    if let Some(error) = malformed {
                        return Err(error);
                    }
                    for (id, issue, create) in answered {
                        if self.assignees {
                            self.answered_as(
                                &id,
                                super::assignees::asked(
                                    create.write.item.assignees.as_deref(),
                                    true,
                                ),
                                &super::assignees::read(&issue)?,
                            )?;
                        }
                        self.hold_stored(
                            onetaskgraph_plugin_api::MetadataRecord::Task,
                            &id,
                            &issue,
                        )?;
                        let mut sent = create.variables["input"].clone();
                        if let Some(input) = sent.as_object_mut() {
                            input.remove("teamId");
                            input.remove("id");
                        }
                        self.created_inputs
                            .lock()
                            .unwrap_or_else(std::sync::PoisonError::into_inner)
                            .insert(id.clone(), sent);
                        self.write_relations(
                            &id,
                            &create.edges,
                            super::WriteKind::Task,
                            super::HeldRelations::None,
                        )
                        .await?;
                    }
                }
                AliasedEach::Refused(refused, _) => {
                    // Nothing of the document landed: that one on its own, the rest together.
                    let (at, alone) = queued.remove(refused);
                    landed[at] = Some(
                        <Self as onetaskgraph_plugin_api::TaskSource>::write_task(
                            self,
                            &alone.write,
                        )
                        .await?,
                    );
                }
            }
        }
        Ok(())
    }

    /// Whether the issue `id`, which `write_tasks` created in this command, was created saying
    /// exactly `input` — the write a copy then makes of it, naming no edge, writes nothing — and,
    /// when it was, the content Linear stored it with held again as that write's answer.
    pub(crate) fn just_created_as(
        &self,
        id: &NativeId,
        input: &Value,
    ) -> Result<bool, SourceError> {
        let sent = self
            .created_inputs
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .remove(id);
        if sent.as_ref() != Some(input) {
            return Ok(false);
        }
        let held = self
            .written
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .get(&(onetaskgraph_plugin_api::MetadataRecord::Task, id.clone()))
            .cloned();
        // One brought in step by a compared update holds no create's answer: what it stores was
        // read rather than sent, so there is no stored content to report for it.
        if let Some(issue) = held {
            self.hold_stored(onetaskgraph_plugin_api::MetadataRecord::Task, id, &issue)?;
        }
        Ok(true)
    }

    /// Bring the issue `held` — one an earlier attempt of this create made under the same id —
    /// in step with `write`, as a create would have written it, by a compared update: only the
    /// title, the description, the state, the priority and the labels that differ are sent, the
    /// metadata the write names laid over what the issue's slot holds so a key a person added
    /// there since is kept, and its relations reconciled with the write's edges. Its assignee is
    /// left as the issue holds it.
    pub(crate) async fn bring_in_step(
        &self,
        held: &NativeId,
        write: &onetaskgraph_plugin_api::ItemWrite<Task>,
        state: &NativeId,
        labels: &[NativeId],
        description: Option<&str>,
        edges: &[onetaskgraph_plugin_api::DependencyEdge],
    ) -> Result<(), SourceError> {
        let Some((before, raw)) = self.issue_held(held, Read::Load).await? else {
            return Err(SourceError::Unavailable {
                message: format!(
                    "Linear refused a create under {held} as held by an issue, and then read                      none there; copy again"
                ),
            });
        };
        let (content, wanted) = super::metadata_description(description.map(str::to_owned))?;
        let (_, mut slot) = super::metadata_description(raw.clone())?;
        slot.extend(wanted);
        let merged = Self::described(content.as_deref(), &slot)?;
        let mut input = serde_json::Map::new();
        if before.title != write.item.title {
            input.insert("title".into(), json!(write.item.title));
        }
        if merged != raw {
            input.insert("description".into(), json!(merged));
        }
        if before.status.category != write.item.status.category {
            input.insert("stateId".into(), json!(state.0));
        }
        if before.priority != write.item.priority {
            input.insert(
                "priority".into(),
                json!(super::linear_priority(write.item.priority)),
            );
        }
        let mut held_labels: Vec<&str> = before
            .labels
            .iter()
            .map(|label| label.id.as_str())
            .collect();
        let mut sent_labels: Vec<&str> = labels.iter().map(|label| label.0.as_str()).collect();
        held_labels.sort_unstable();
        sent_labels.sort_unstable();
        if held_labels != sent_labels {
            input.insert("labelIds".into(), json!(labels));
        }
        // No assignee: the create the earlier attempt sent carried it already, so the issue
        // holds another person only when somebody reassigned it since — and a person's own
        // assignment stands, as it does over every existing item a copy updates.
        if !input.is_empty() {
            let data = self
                .send(
                    graphql::ISSUE_UPDATE_READ,
                    json!({"id": held.0, "input": Value::Object(input)}),
                )
                .await?;
            self.updated_issue(&data, held)?;
        }
        self.write_relations(
            held,
            edges,
            super::WriteKind::Task,
            super::HeldRelations::Unread,
        )
        .await
    }

    /// [`TaskSource::get_task_details`](onetaskgraph_plugin_api::TaskSource::get_task_details)
    /// with a page of comments: every issue and its page in one aliased read.
    pub(crate) async fn details_batched(
        &self,
        ids: &[NativeId],
        page: &PageRequest,
    ) -> Option<Vec<Result<Option<TaskDetailRead>, SourceError>>> {
        if ids.len() < 2 || !self.batches(graphql::ISSUE_DETAIL) || page.limit == 0 {
            return None;
        }
        let mut read: Vec<Option<Result<Option<TaskDetailRead>, SourceError>>> =
            ids.iter().map(|_| None).collect();
        let mut pending: Vec<usize> = (0..ids.len()).collect();
        while !pending.is_empty() {
            let each: Vec<Value> = pending
                .iter()
                .map(|at| {
                    json!({"id": ids[*at].0, "last": page.limit.min(MAX_PAGE_SIZE),
                           "before": page.cursor.as_ref().map(|cursor| &cursor.0)})
                })
                .collect();
            match self.send_aliased(graphql::ISSUE_DETAIL, &each).await {
                Ok(Aliased::Answered(values)) => {
                    for (at, value) in pending.drain(..).zip(values) {
                        read[at] = Some(
                            issue_of_asked(value, &ids[at], "reading issues with their comments")
                                .and_then(|value| self.detail_of(&value, page)),
                        );
                    }
                }
                Ok(Aliased::Refused(refused, refusal)) => {
                    let at = pending.remove(refused);
                    read[at] = Some(if refusal.entity_missing() {
                        Ok(None)
                    } else {
                        Err(refusal.into_error())
                    });
                }
                Err(error) => {
                    for at in pending.drain(..) {
                        read[at] = Some(Err(error.clone()));
                    }
                }
            }
        }
        Some(read.into_iter().flatten().collect())
    }

    /// One issue and its page of comments as an aliased detail read answered it.
    fn detail_of(
        &self,
        value: &Value,
        page: &PageRequest,
    ) -> Result<Option<TaskDetailRead>, SourceError> {
        Ok(optional(&json!({"issue": value}), "issue", |v| {
            let mut task = map_task(
                v,
                &self.name,
                &self.statuses,
                self.spelling(),
                self.assignees,
            )?;
            if self.attached() && page.cursor.is_some() {
                task.version = None;
            }
            Ok((task, comment_page(v)?))
        })?
        .filter(|(task, _)| self.in_scope(task.project.as_ref()))
        .map(|(task, comments)| TaskDetailRead {
            task,
            comments: Some(Ok(Some(comments))),
        }))
    }

    /// [`TaskSource::read_ahead_records_for_copy`](onetaskgraph_plugin_api::TaskSource::read_ahead_records_for_copy):
    /// every task and project the copy names read beside the first page of its forward
    /// relations, and every document, in one composed read, each held for the next read of it.
    /// An item Linear says is not there is left to its own read, which answers it absent, and
    /// the rest are read together again.
    pub(crate) async fn read_ahead_batched(
        &self,
        records: &[(onetaskgraph_plugin_api::MetadataRecord, NativeId)],
    ) -> Result<(), SourceError> {
        use onetaskgraph_plugin_api::MetadataRecord;
        if records.len() < 2
            || !self.batches(graphql::ISSUE)
            || !self.batches(graphql::PROJECT)
            || !self.batches(graphql::ISSUE_DEPENDS_ON)
        {
            return Ok(());
        }
        let mut pending: Vec<&(MetadataRecord, NativeId)> = records.iter().collect();
        while !pending.is_empty() {
            let mut singles = Vec::new();
            let mut each = Vec::new();
            let mut owners = Vec::new();
            for (at, (record, id)) in pending.iter().enumerate() {
                let reads: &[&'static str] = match record {
                    MetadataRecord::Task => &[graphql::ISSUE, graphql::ISSUE_DEPENDS_ON],
                    MetadataRecord::Project => &[graphql::PROJECT, graphql::PROJECT_DEPENDS_ON],
                    MetadataRecord::Document => &[graphql::DOCUMENT],
                };
                for (part, single) in reads.iter().enumerate() {
                    singles.push(*single);
                    each.push(if part == 0 {
                        json!({"id": id.0})
                    } else {
                        json!({"id": id.0, "first": MAX_PAGE_SIZE, "after": null})
                    });
                    owners.push((at, part));
                }
            }
            match self.send_composed_of(&singles, &each).await? {
                Aliased::Answered(values) => {
                    let mut ahead = self
                        .ahead
                        .lock()
                        .unwrap_or_else(std::sync::PoisonError::into_inner);
                    let mut edges = self
                        .edges_ahead
                        .lock()
                        .unwrap_or_else(std::sync::PoisonError::into_inner);
                    for ((at, part), value) in owners.into_iter().zip(values) {
                        let (record, id) = pending[at];
                        let doing = "reading a copy's records ahead";
                        let value = match record {
                            MetadataRecord::Task => issue_of_asked(value, id, doing),
                            MetadataRecord::Project | MetadataRecord::Document => {
                                of_asked(value, id, doing)
                            }
                        }?;
                        let key = (*record, id.clone());
                        if part == 0 {
                            ahead.insert(key, value);
                        } else {
                            edges.insert(key, value);
                        }
                    }
                    pending.clear();
                }
                Aliased::Refused(refused, refusal)
                    if refusal.entity_missing()
                        || refusal.project_missing()
                        || refusal.document_missing() =>
                {
                    let (at, _) = owners[refused];
                    pending.remove(at);
                }
                Aliased::Refused(_, refusal) => return Err(refusal.into_error()),
            }
        }
        Ok(())
    }

    /// Create every relation held back for `finish_writes` in one aliased `issueRelationCreate`
    /// document. One Linear refuses fails the whole write — the copy then takes back what it
    /// made — since a relation create is not safe to send twice.
    pub(crate) async fn finish_relations(&self) -> Result<(), SourceError> {
        let held: Vec<(NativeId, Value)> = std::mem::take(
            &mut *self
                .deferred_relations
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner),
        );
        if held.is_empty() {
            return Ok(());
        }
        let each: Vec<Value> = held
            .iter()
            .map(|(_, variables)| variables.clone())
            .collect();
        let values = if each.len() == 1 {
            vec![
                self.send(graphql::ISSUE_RELATION_CREATE, each[0].clone())
                    .await?["issueRelationCreate"]
                    .clone(),
            ]
        } else {
            match self
                .send_aliased(graphql::ISSUE_RELATION_CREATE, &each)
                .await?
            {
                Aliased::Answered(values) => values,
                Aliased::Refused(_, refusal) => return Err(refusal.into_error()),
            }
        };
        for ((near, _), value) in held.iter().zip(values) {
            self.unknown_version(near);
            let answered = json!({"issueRelationCreate": value});
            let payload = super::mutation_payload(&answered, MutationRoot::IssueRelationCreate)?;
            let relation = payload
                .get("issueRelation")
                .ok_or_else(|| SourceError::Malformed {
                    message: "missing issueRelationCreate relation".to_owned(),
                })?;
            super::backend_id(relation, "id")?;
        }
        Ok(())
    }

    /// [`TaskSource::query_tasks_batch`](onetaskgraph_plugin_api::TaskSource::query_tasks_batch):
    /// every query as one aliased `issues` read per round, each query's page confirmed as
    /// `query_tasks` confirms it, and a query whose page Linear refuses answered that refusal
    /// alone. A search is not a copy's lookup, so a query by origin listing nothing reads no id
    /// its origin's key derives.
    pub(crate) async fn query_batched(
        &self,
        asks: &[(TaskQuery, PageRequest)],
    ) -> Vec<Result<Page<Task>, SourceError>> {
        let mut answers: Vec<Option<Result<Page<Task>, SourceError>>> =
            asks.iter().map(|_| None).collect();
        let mut pending = Vec::new();
        for (at, (query, page)) in asks.iter().enumerate() {
            if !self.batches(graphql::ISSUES) {
                answers[at] = Some(
                    <Self as onetaskgraph_plugin_api::TaskSource>::query_tasks(self, query, page)
                        .await,
                );
                continue;
            }
            match self.issue_filter(query) {
                Ok(filter) => pending.push((at, filter)),
                Err(error) => answers[at] = Some(Err(error)),
            }
        }
        while !pending.is_empty() {
            let each: Vec<Value> = pending
                .iter()
                .map(|(at, filter)| {
                    let page = &asks[*at].1;
                    json!({"first": page.limit.min(MAX_PAGE_SIZE),
                           "after": page.cursor.as_ref().map(|cursor| &cursor.0),
                           "filter": filter})
                })
                .collect();
            let answered = if each.len() == 1 {
                self.send(graphql::ISSUES, each[0].clone())
                    .await
                    .map(|data| Aliased::Answered(vec![data["issues"].clone()]))
            } else {
                self.send_aliased(graphql::ISSUES, &each).await
            };
            match answered {
                Ok(Aliased::Answered(values)) => {
                    for ((at, _), value) in pending.drain(..).zip(values) {
                        let query = &asks[at].0;
                        answers[at] = Some(
                            connection(&json!({"issues": value}), "issues", |v| {
                                map_task(
                                    v,
                                    &self.name,
                                    &self.statuses,
                                    self.spelling(),
                                    self.assignees,
                                )
                            })
                            .map(|listed| Page {
                                items: listed
                                    .items
                                    .into_iter()
                                    .filter(|task| Self::confirms(query, task))
                                    .collect(),
                                next: listed.next,
                            }),
                        );
                    }
                }
                Ok(Aliased::Refused(refused, refusal)) => {
                    let (at, _) = pending.remove(refused);
                    answers[at] = Some(Err(refusal.into_error()));
                }
                Err(error) => {
                    for (at, _) in pending.drain(..) {
                        answers[at] = Some(Err(error.clone()));
                    }
                }
            }
        }
        answers
            .into_iter()
            .map(|answer| {
                answer.unwrap_or_else(|| {
                    Err(SourceError::Malformed {
                        message: "a query of the batch was given no answer".to_owned(),
                    })
                })
            })
            .collect()
    }
}