-
Notifications
You must be signed in to change notification settings - Fork 244
/
Copy pathmod.rs
3025 lines (2786 loc) · 135 KB
/
mod.rs
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
use petgraph::graph::NodeIndex;
use std::borrow::Cow;
use std::cell;
use std::cmp;
use std::collections::{HashMap, HashSet, VecDeque};
use std::mem;
use std::net::SocketAddr;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
use std::time;
use crate::group_commit::GroupCommitQueueSet;
use crate::payload::{ControlReplyPacket, ReplayPieceContext, SourceSelection};
use crate::prelude::*;
use ahash::RandomState;
use futures_util::{future::FutureExt, stream::StreamExt};
use noria::channel::{self, TcpSender};
pub use noria::internal::DomainIndex as Index;
use slog::Logger;
use stream_cancel::Valve;
use crate::Readers;
use timekeeper::{RealTime, SimpleTracker, ThreadTime, Timer, TimerSet};
use tokio;
#[derive(Debug)]
pub enum PollEvent {
ResumePolling,
Process(Box<Packet>),
Timeout,
}
#[derive(Debug)]
pub enum ProcessResult {
KeepPolling(Option<time::Duration>),
Processed,
StopPolling,
}
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct Config {
pub concurrent_replays: usize,
pub replay_batch_timeout: time::Duration,
}
const BATCH_SIZE: usize = 256;
#[derive(Debug)]
enum DomainMode {
Forwarding,
Replaying {
to: LocalNodeIndex,
buffered: VecDeque<Box<Packet>>,
passes: usize,
},
}
impl PartialEq for DomainMode {
fn eq(&self, other: &Self) -> bool {
match (self, other) {
(&DomainMode::Forwarding, &DomainMode::Forwarding) => true,
_ => false,
}
}
}
enum TriggerEndpoint {
None,
Start(Vec<usize>),
End {
source: SourceSelection,
options: Vec<Box<dyn channel::Sender<Item = Box<Packet>> + Send>>,
},
Local(Vec<usize>),
}
pub(crate) struct ReplayPath {
source: Option<LocalNodeIndex>,
path: Vec<ReplayPathSegment>,
notify_done: bool,
pub(crate) partial_unicast_sharder: Option<NodeIndex>,
trigger: TriggerEndpoint,
}
type Hole = (Vec<usize>, Vec<DataType>);
#[derive(Debug, Eq, PartialEq, Hash, Clone)]
struct Redo {
tag: Tag,
replay_key: Vec<DataType>,
unishard: bool,
requesting_shard: usize,
}
/// When a replay misses while being processed, it triggers a replay to backfill the hole that it
/// missed in. We need to ensure that when this happens, we re-run the original replay to fill the
/// hole we *originally* were trying to fill.
///
/// This comes with some complexity:
///
/// - If two replays both hit the *same* hole, we should only request a backfill of it once, but
/// need to re-run *both* replays when the hole is filled.
/// - If one replay hits two *different* holes, we should backfill both holes, but we must ensure
/// that we only re-run the replay once when both holes have been filled.
///
/// To keep track of this, we use the `Waiting` structure below. One is created for every node with
/// at least one outstanding backfill, and contains the necessary bookkeeping to ensure the two
/// behaviors outlined above.
///
/// Note that in the type aliases above, we have chosen to use Vec<usize> instead of Tag to
/// identify a hole. This is because there may be more than one Tag used to fill a given hole, and
/// the set of columns uniquely identifies the set of tags.
#[derive(Debug, Default)]
struct Waiting {
/// For each eventual redo, how many holes are we waiting for?
holes: HashMap<Redo, usize>,
/// For each hole, which redos do we expect we'll have to do?
redos: HashMap<Hole, HashSet<Redo>>,
}
/// Struct sent to a worker to start a domain.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct DomainBuilder {
/// The domain's index.
pub index: Index,
/// The shard ID represented by this `DomainBuilder`.
pub shard: Option<usize>,
/// The number of shards in the domain.
pub nshards: usize,
/// The nodes in the domain.
pub nodes: DomainNodes,
/// The domain's persistence setting.
pub persistence_parameters: PersistenceParameters,
/// Configuration parameters for the domain.
pub config: Config,
}
unsafe impl Send for DomainBuilder {}
impl DomainBuilder {
/// Starts up the domain represented by this `DomainBuilder`.
pub fn build(
self,
log: Logger,
readers: Readers,
channel_coordinator: Arc<ChannelCoordinator>,
control_addr: SocketAddr,
shutdown_valve: &Valve,
state_size: Arc<AtomicUsize>,
) -> Domain {
// initially, all nodes are not ready
let not_ready = self
.nodes
.values()
.map(|n| n.borrow().local_addr())
.collect();
let log = log.new(o!("domain" => self.index.index(), "shard" => self.shard.unwrap_or(0)));
let control_reply_tx = TcpSender::connect(&control_addr).unwrap();
let group_commit_queues = GroupCommitQueueSet::new(&self.persistence_parameters);
Domain {
index: self.index,
shard: self.shard,
_nshards: self.nshards,
persistence_parameters: self.persistence_parameters,
nodes: self.nodes,
state: StateMap::default(),
log,
not_ready,
mode: DomainMode::Forwarding,
waiting: Default::default(),
reader_triggered: Default::default(),
replay_paths: Default::default(),
replay_paths_by_dst: Default::default(),
ingress_inject: Default::default(),
shutdown_valve: shutdown_valve.clone(),
readers,
control_reply_tx,
channel_coordinator,
buffered_replay_requests: Default::default(),
replay_batch_timeout: self.config.replay_batch_timeout,
timed_purges: Default::default(),
concurrent_replays: 0,
max_concurrent_replays: self.config.concurrent_replays,
replay_request_queue: Default::default(),
delayed_for_self: Default::default(),
group_commit_queues,
state_size,
total_time: Timer::new(),
total_ptime: Timer::new(),
wait_time: Timer::new(),
process_times: TimerSet::new(),
process_ptimes: TimerSet::new(),
total_replay_time: Timer::new(),
total_forward_time: Timer::new(),
}
}
}
#[derive(Clone, Debug)]
struct TimedPurge {
time: time::Instant,
view: LocalNodeIndex,
tag: Tag,
keys: HashSet<Vec<DataType>>,
}
pub struct Domain {
index: Index,
shard: Option<usize>,
_nshards: usize,
nodes: DomainNodes,
state: StateMap,
log: Logger,
not_ready: HashSet<LocalNodeIndex>,
ingress_inject: Map<(usize, Vec<DataType>)>,
persistence_parameters: PersistenceParameters,
mode: DomainMode,
waiting: Map<Waiting>,
replay_paths: HashMap<Tag, ReplayPath>,
reader_triggered: Map<HashSet<Vec<DataType>, RandomState>>,
timed_purges: VecDeque<TimedPurge>,
replay_paths_by_dst: Map<HashMap<Vec<usize>, Vec<Tag>>>,
concurrent_replays: usize,
max_concurrent_replays: usize,
replay_request_queue: VecDeque<(Tag, Vec<Vec<DataType>>)>,
shutdown_valve: Valve,
readers: Readers,
control_reply_tx: TcpSender<ControlReplyPacket>,
channel_coordinator: Arc<ChannelCoordinator>,
buffered_replay_requests: HashMap<(Tag, usize), (time::Instant, HashSet<Vec<DataType>>, bool)>,
replay_batch_timeout: time::Duration,
delayed_for_self: VecDeque<Box<Packet>>,
group_commit_queues: GroupCommitQueueSet,
state_size: Arc<AtomicUsize>,
total_time: Timer<SimpleTracker, RealTime>,
total_ptime: Timer<SimpleTracker, ThreadTime>,
wait_time: Timer<SimpleTracker, RealTime>,
process_times: TimerSet<LocalNodeIndex, SimpleTracker, RealTime>,
process_ptimes: TimerSet<LocalNodeIndex, SimpleTracker, ThreadTime>,
/// time spent processing replays
total_replay_time: Timer<SimpleTracker, RealTime>,
/// time spent processing ordinary, forward updates
total_forward_time: Timer<SimpleTracker, RealTime>,
}
impl Domain {
fn find_tags_and_replay(
&mut self,
miss_keys: Vec<Vec<DataType>>,
miss_columns: &[usize],
miss_in: LocalNodeIndex,
) {
let mut tags = Vec::new();
if let Some(ref candidates) = self.replay_paths_by_dst.get(miss_in) {
if let Some(ts) = candidates.get(miss_columns) {
// the clone is a bit sad; self.request_partial_replay doesn't use
// self.replay_paths_by_dst.
tags = ts.clone();
}
}
for &tag in &tags {
// send a message to the source domain(s) responsible
// for the chosen tag so they'll start replay.
let keys = miss_keys.clone(); // :(
if let TriggerEndpoint::Local(..) = self.replay_paths[&tag].trigger {
// *in theory* we could just call self.seed_replay, and everything would be good.
// however, then we start recursing, which could get us into sad situations where
// we break invariants where some piece of code is assuming that it is the only
// thing processing at the time (think, e.g., borrow_mut()).
//
// for example, consider the case where two misses occurred on the same key.
// normally, those requests would be deduplicated so that we don't get two replay
// responses for the same key later. however, the way we do that is by tracking
// keys we have requested in self.waiting.redos (see `redundant` in
// `on_replay_miss`). in particular, on_replay_miss is called while looping over
// all the misses that need replays, and while the first miss of a given key will
// trigger a replay, the second will not. if we call `seed_replay` directly here,
// that might immediately fill in this key and remove the entry. when the next miss
// (for the same key) is then hit in the outer iteration, it will *also* request a
// replay of that same key, which gets us into trouble with `State::mark_filled`.
//
// so instead, we simply keep track of the fact that we have a replay to handle,
// and then get back to it after all processing has finished (at the bottom of
// `Self::handle()`)
self.delayed_for_self
.push_back(Box::new(Packet::RequestPartialReplay {
tag,
keys,
unishard: true, // local replays are necessarily single-shard
requesting_shard: self.shard.unwrap_or(0),
}));
continue;
}
// NOTE: due to max_concurrent_replays, it may be that we only replay from *some* of
// these ancestors now, and some later. this will cause more of the replay to be
// buffered up at the union above us, but that's probably fine.
self.request_partial_replay(tag, keys);
}
if tags.is_empty() {
unreachable!(format!(
"no tag found to fill missing value {:?} in {}.{:?}",
miss_keys, miss_in, miss_columns
));
}
}
fn on_replay_miss(
&mut self,
miss_in: LocalNodeIndex,
miss_columns: &[usize],
replay_key: Vec<DataType>,
miss_key: Vec<DataType>,
was_single_shard: bool,
requesting_shard: usize,
needed_for: Tag,
) {
use std::collections::hash_map::Entry;
use std::ops::AddAssign;
// when the replay eventually succeeds, we want to re-do the replay.
let mut w = self.waiting.remove(miss_in).unwrap_or_default();
let mut redundant = false;
let redo = Redo {
tag: needed_for,
replay_key: replay_key.clone(),
unishard: was_single_shard,
requesting_shard,
};
match w.redos.entry((Vec::from(miss_columns), miss_key.clone())) {
Entry::Occupied(e) => {
// we have already requested backfill of this key
// remember to notify this Redo when backfill completes
if e.into_mut().insert(redo.clone()) {
// this Redo should wait for this backfill to complete before redoing
w.holes.entry(redo).or_default().add_assign(1);
}
redundant = true;
}
Entry::Vacant(e) => {
// we haven't already requested backfill of this key
let mut redos = HashSet::new();
// remember to notify this Redo when backfill completes
redos.insert(redo.clone());
e.insert(redos);
// this Redo should wait for this backfill to complete before redoing
w.holes.entry(redo).or_default().add_assign(1);
}
}
self.waiting.insert(miss_in, w);
if redundant {
return;
}
self.find_tags_and_replay(vec![miss_key], miss_columns, miss_in);
}
fn send_partial_replay_request(&mut self, tag: Tag, keys: Vec<Vec<DataType>>) {
debug_assert!(self.concurrent_replays < self.max_concurrent_replays);
if let TriggerEndpoint::End {
source,
ref mut options,
} = self.replay_paths.get_mut(&tag).unwrap().trigger
{
let ask_shard_by_key_i = match source {
SourceSelection::AllShards(_) => None,
SourceSelection::SameShard => {
// note that we "ask all" here because we're not indexing the vector by the
// key's shard index. unipath will still be set to true though, since
// options.len() == 1.
None
}
SourceSelection::KeyShard { key_i_to_shard, .. } => Some(key_i_to_shard),
};
if ask_shard_by_key_i.is_none() && options.len() != 1 {
// source is sharded by a different key than we are doing lookups for,
// so we need to trigger on all the shards.
self.concurrent_replays += 1;
trace!(self.log, "sending shuffled shard replay request";
"tag" => ?tag,
"keys" => ?keys,
"buffered" => self.replay_request_queue.len(),
"concurrent" => self.concurrent_replays,
);
for trigger in options {
if trigger
.send(Box::new(Packet::RequestPartialReplay {
tag,
unishard: false, // ask_all is true, so replay is sharded
keys: keys.clone(), // sad to clone here
requesting_shard: self.shard.unwrap_or(0),
}))
.is_err()
{
// we're shutting down -- it's fine.
}
}
return;
}
self.concurrent_replays += 1;
trace!(self.log, "sending replay request";
"tag" => ?tag,
"keys" => ?keys,
"buffered" => self.replay_request_queue.len(),
"concurrent" => self.concurrent_replays,
);
if options.len() == 1 {
if options[0]
.send(Box::new(Packet::RequestPartialReplay {
tag,
keys,
unishard: true, // only one option, so only one path
requesting_shard: self.shard.unwrap_or(0),
}))
.is_err()
{
// we're shutting down -- it's fine.
}
} else if let Some(key_shard_i) = ask_shard_by_key_i {
let mut shards = HashMap::new();
for key in keys {
let shard = crate::shard_by(&key[key_shard_i], options.len());
shards.entry(shard).or_insert_with(Vec::new).push(key);
}
for (shard, keys) in shards {
if options[shard]
.send(Box::new(Packet::RequestPartialReplay {
tag,
keys,
unishard: true, // !ask_all, so only one path
requesting_shard: self.shard.unwrap_or(0),
}))
.is_err()
{
// we're shutting down -- it's fine.
}
}
} else {
// would have hit the if further up
unreachable!();
};
} else {
unreachable!("asked to replay along non-existing path")
}
}
fn request_partial_replay(&mut self, tag: Tag, keys: Vec<Vec<DataType>>) {
if self.concurrent_replays < self.max_concurrent_replays {
assert_eq!(self.replay_request_queue.len(), 0);
self.send_partial_replay_request(tag, keys);
} else {
trace!(self.log, "buffering replay request";
"tag" => ?tag,
"keys" => ?keys,
"buffered" => self.replay_request_queue.len(),
);
self.replay_request_queue.push_back((tag, keys));
}
}
fn finished_partial_replay(&mut self, tag: Tag, num: usize) {
match self.replay_paths[&tag].trigger {
TriggerEndpoint::End { .. } => {
// A backfill request we made to another domain was just satisfied!
// We can now issue another request from the concurrent replay queue.
// However, since unions require multiple backfill requests, but produce only one
// backfill reply, we need to check how many requests we're now free to issue. If
// we just naively release one slot here, a union with two parents would mean that
// `self.concurrent_replays` constantly grows by +1 (+2 for the backfill requests,
// -1 when satisfied), which would lead to a deadlock!
let mut requests_satisfied = 0;
let last = self.replay_paths[&tag].path.last().unwrap();
if let Some(ref cs) = self.replay_paths_by_dst.get(last.node) {
if let Some(ref tags) = cs.get(last.partial_key.as_ref().unwrap()) {
requests_satisfied = tags
.iter()
.filter(|tag| {
if let TriggerEndpoint::End { .. } = self.replay_paths[tag].trigger
{
true
} else {
false
}
})
.count();
}
}
// we also sent that many requests *per key*.
requests_satisfied *= num;
// TODO: figure out why this can underflow
self.concurrent_replays =
self.concurrent_replays.saturating_sub(requests_satisfied);
trace!(self.log, "notified of finished replay";
"#done" => requests_satisfied,
"ongoing" => self.concurrent_replays,
);
debug_assert!(self.concurrent_replays < self.max_concurrent_replays);
let mut per_tag = HashMap::new();
while self.concurrent_replays < self.max_concurrent_replays {
if let Some((tag, mut keys)) = self.replay_request_queue.pop_front() {
per_tag
.entry(tag)
.or_insert_with(Vec::new)
.append(&mut keys);
} else {
break;
}
}
for (tag, keys) in per_tag {
trace!(self.log, "releasing replay request";
"tag" => ?tag,
"keys" => ?keys,
"left" => self.replay_request_queue.len(),
"ongoing" => self.concurrent_replays,
);
self.send_partial_replay_request(tag, keys);
}
}
TriggerEndpoint::Local(..) => {
// didn't count against our quote, so we're also not decementing
}
TriggerEndpoint::Start(..) | TriggerEndpoint::None => {
unreachable!();
}
}
}
fn dispatch(&mut self, m: Box<Packet>, executor: &mut dyn Executor) {
let src = m.src();
let me = m.dst();
match self.mode {
DomainMode::Forwarding => (),
DomainMode::Replaying {
ref to,
ref mut buffered,
..
} if to == &me => {
buffered.push_back(m);
return;
}
DomainMode::Replaying { .. } => (),
}
if !self.not_ready.is_empty() && self.not_ready.contains(&me) {
return;
}
let (mut m, evictions) = {
let mut n = self.nodes[me].borrow_mut();
self.process_times.start(me);
self.process_ptimes.start(me);
let mut m = Some(m);
let (misses, _, captured) = n.process(
&mut m,
None,
&mut self.state,
&self.nodes,
self.shard,
true,
None,
executor,
&self.log,
);
assert_eq!(captured.len(), 0);
self.process_ptimes.stop();
self.process_times.stop();
if m.is_none() {
// no need to deal with our children if we're not sending them anything
return;
}
// normally, we ignore misses during regular forwarding.
// however, we have to be a little careful in the case of joins.
let evictions = if n.is_internal() && n.is_join() && !misses.is_empty() {
// there are two possible cases here:
//
// - this is a write that will hit a hole in every downstream materialization.
// dropping it is totally safe!
// - this is a write that will update an entry in some downstream materialization.
// this is *not* allowed! we *must* ensure that downstream remains up to date.
// but how can we? we missed in the other side of the join, so we can't produce
// the necessary output record... what we *can* do though is evict from any
// downstream, and then we guarantee that we're in case 1!
//
// if you're curious about how we may have ended up in case 2 above, here are two
// ways:
//
// - some downstream view is partial over the join key. some time in the past, it
// requested a replay of key k. that replay produced *no* rows from the side
// that was replayed. this in turn means that no lookup was performed on the
// other side of the join, and so k wasn't replayed to that other side (which
// then still has a hole!). in that case, any subsequent write with k in the
// join column from the replay side will miss in the other side.
// - some downstream view is partial over a column that is *not* the join key. in
// the past, it replayed some key k, which means that we aren't allowed to drop
// any write with k in that column. now, a write comes along with k in that
// replay column, but with some hitherto unseen key z in the join column. if the
// replay of k never caused a lookup of z in the other side of the join, then
// the other side will have a hole. thus, we end up in the situation where we
// need to forward a write through the join, but we miss.
//
// unfortunately, we can't easily distinguish between the case where we have to
// evict and the case where we don't (at least not currently), so we *always* need
// to evict when this happens. this shouldn't normally be *too* bad, because writes
// are likely to be dropped before they even reach the join in most benign cases
// (e.g., in an ingress). this can be remedied somewhat in the future by ensuring
// that the first of the two causes outlined above can't happen (by always doing a
// lookup on the replay key, even if there are now rows). then we know that the
// *only* case where we have to evict is when the replay key != the join key.
//
// but, for now, here we go:
// first, what partial replay paths go through this node?
let from = self.nodes[src].borrow().global_addr();
// TODO: this is a linear walk of replay paths -- we should make that not linear
let deps: Vec<_> = self
.replay_paths
.iter()
.filter_map(|(&tag, rp)| {
rp.path
.iter()
.find(|rps| rps.node == me)
.and_then(|rps| rps.partial_key.as_ref())
.and_then(|keys| {
// we need to find the *input* column that produces that output.
//
// if one of the columns for this replay path's keys does not
// resolve into the ancestor we got the update from, we don't need
// to issue an eviction for that path. this is because we *missed*
// on the join column in the other side, so we *know* it can't have
// forwarded anything related to the write we're now handling.
keys.iter()
.map(|&k| {
n.parent_columns(k)
.into_iter()
.find(|&(ni, _)| ni == from)
.ok_or(())
.map(|k| k.1.unwrap())
})
.collect::<Result<Vec<_>, _>>()
.ok()
})
.map(move |k| (tag, k))
})
.collect();
let mut evictions = HashMap::new();
for miss in misses {
for &(tag, ref keys) in &deps {
evictions
.entry(tag)
.or_insert_with(HashSet::new)
.insert(keys.iter().map(|&key| miss.record[key].clone()).collect());
}
}
Some(evictions)
} else {
None
};
(m, evictions)
};
if let Some(evictions) = evictions {
// now send evictions for all the (tag, [key]) things in evictions
for (tag, keys) in evictions {
self.handle_eviction(
Box::new(Packet::EvictKeys {
keys: keys.into_iter().collect(),
link: Link::new(src, me),
tag,
}),
executor,
);
}
}
match &**m.as_ref().unwrap() {
m @ &Packet::Message { .. } if m.is_empty() => {
// no need to deal with our children if we're not sending them anything
return;
}
&Packet::Message { .. } => {}
&Packet::ReplayPiece { .. } => {
unreachable!("replay should never go through dispatch");
}
m => unreachable!("dispatch process got {:?}", m),
}
// NOTE: we can't directly iterate over .children due to self.dispatch in the loop
let nchildren = self.nodes[me].borrow().children().len();
for i in 0..nchildren {
// avoid cloning if we can
let mut m = if i == nchildren - 1 {
m.take().unwrap()
} else {
m.as_ref().map(|m| Box::new(m.clone_data())).unwrap()
};
let childi = self.nodes[me].borrow().children()[i];
let child_is_merger = {
// XXX: shouldn't NLL make this unnecessary?
let c = self.nodes[childi].borrow();
c.is_shard_merger()
};
if child_is_merger {
// we need to preserve the egress src (which includes shard identifier)
} else {
m.link_mut().src = me;
}
m.link_mut().dst = childi;
self.dispatch(m, executor);
}
}
#[allow(clippy::cognitive_complexity)]
fn handle(&mut self, m: Box<Packet>, executor: &mut dyn Executor, top: bool) {
if self.wait_time.is_running() {
self.wait_time.stop();
}
match *m {
Packet::Message { .. } | Packet::Input { .. } => {
// WO for https://github.com/rust-lang/rfcs/issues/1403
self.total_forward_time.start();
self.dispatch(m, executor);
self.total_forward_time.stop();
}
Packet::ReplayPiece { .. } => {
self.total_replay_time.start();
self.handle_replay(m, executor);
self.total_replay_time.stop();
}
Packet::Evict { .. } | Packet::EvictKeys { .. } => {
self.handle_eviction(m, executor);
}
consumed => {
match consumed {
// workaround #16223
Packet::AddNode { node, parents } => {
let addr = node.local_addr();
self.not_ready.insert(addr);
for p in parents {
self.nodes
.get_mut(p)
.unwrap()
.borrow_mut()
.add_child(node.local_addr());
}
self.nodes.insert(addr, cell::RefCell::new(node));
trace!(self.log, "new node incorporated"; "local" => addr.id());
}
Packet::RemoveNodes { nodes } => {
for &node in &nodes {
self.nodes[node].borrow_mut().remove();
self.state.remove(node);
trace!(self.log, "node removed"; "local" => node.id());
}
for node in nodes {
for cn in self.nodes.iter_mut() {
cn.1.borrow_mut().try_remove_child(node);
// NOTE: since nodes are always removed leaves-first, it's not
// important to update parent pointers here
}
}
}
Packet::AddBaseColumn {
node,
field,
default,
} => {
let mut n = self.nodes[node].borrow_mut();
n.add_column(&field);
if let Some(b) = n.get_base_mut() {
b.add_column(default);
} else if n.is_ingress() {
self.ingress_inject
.entry(node)
.or_insert_with(|| (n.fields().len(), Vec::new()))
.1
.push(default);
} else {
unreachable!("node unrelated to base got AddBaseColumn");
}
self.control_reply_tx
.send(ControlReplyPacket::ack())
.unwrap();
}
Packet::DropBaseColumn { node, column } => {
let mut n = self.nodes[node].borrow_mut();
n.get_base_mut()
.expect("told to drop base column from non-base node")
.drop_column(column);
self.control_reply_tx
.send(ControlReplyPacket::ack())
.unwrap();
}
Packet::UpdateEgress {
node,
new_tx,
new_tag,
} => {
let mut n = self.nodes[node].borrow_mut();
n.with_egress_mut(move |e| {
if let Some((node, local, addr)) = new_tx {
e.add_tx(node, local, addr);
}
if let Some(new_tag) = new_tag {
e.add_tag(new_tag.0, new_tag.1);
}
});
}
Packet::UpdateSharder { node, new_txs } => {
let mut n = self.nodes[node].borrow_mut();
n.with_sharder_mut(move |s| {
s.add_sharded_child(new_txs.0, new_txs.1);
});
}
Packet::StateSizeProbe { node } => {
let row_count = self.state.get(node).map(|r| r.rows()).unwrap_or(0);
let mem_size = self.state.get(node).map(|s| s.deep_size_of()).unwrap_or(0);
self.control_reply_tx
.send(ControlReplyPacket::StateSize(row_count, mem_size))
.unwrap();
}
Packet::PrepareState { node, state } => {
use crate::payload::InitialState;
match state {
InitialState::PartialLocal(index) => {
if !self.state.contains_key(node) {
self.state.insert(node, Box::new(MemoryState::default()));
}
let state = self.state.get_mut(node).unwrap();
for (key, tags) in index {
info!(self.log, "told to prepare partial state";
"key" => ?key,
"tags" => ?tags);
state.add_key(&key[..], Some(tags));
}
}
InitialState::IndexedLocal(index) => {
if !self.state.contains_key(node) {
self.state.insert(node, Box::new(MemoryState::default()));
}
let state = self.state.get_mut(node).unwrap();
for idx in index {
info!(self.log, "told to prepare full state";
"key" => ?idx);
state.add_key(&idx[..], None);
}
}
InitialState::PartialGlobal {
gid,
cols,
key,
trigger_domain: (trigger_domain, shards),
} => {
use crate::backlog;
let k = key.clone(); // ugh
let txs = (0..shards)
.map(|shard| {
let key = key.clone();
let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
let sender = self
.channel_coordinator
.builder_for(&(trigger_domain, shard))
.unwrap()
.build_async()
.unwrap();
tokio::spawn(
self.shutdown_valve
.wrap(rx)
.map(move |misses| {
Box::new(Packet::RequestReaderReplay {
keys: misses,
cols: key.clone(),
node,
})
})
.map(Ok)
.forward(sender)
.map(|r| {
if let Err(e) = r {
// domain went away?
eprintln!(
"replay source went away: {:?}",
e
);
}
}),
);
tx
})
.collect::<Vec<_>>();
let (r_part, w_part) = backlog::new_partial(
cols,
&k[..],
move |misses: &mut dyn Iterator<Item = &[DataType]>| {
let n = txs.len();
if n == 1 {
use std::iter::FromIterator;
let misses = Vec::from_iter(misses.map(Vec::from));
if misses.is_empty() {
return true;
}
txs[0].send(misses).is_ok()
} else {
// TODO: compound reader
let mut per_shard = HashMap::new();
for miss in misses {
assert_eq!(miss.len(), 1);
let shard = crate::shard_by(&miss[0], n);
per_shard
.entry(shard)
.or_insert_with(Vec::new)
.push(Vec::from(miss));
}
if per_shard.is_empty() {
return true;
}
per_shard
.into_iter()
.all(|(shard, keys)| txs[shard].send(keys).is_ok())
}
},
);
let mut n = self.nodes[node].borrow_mut();
tokio::task::block_in_place(|| {
n.with_reader_mut(|r| {
assert!(self
.readers
.lock()
.unwrap()
.insert(
(gid, *self.shard.as_ref().unwrap_or(&0)),
r_part
)
.is_none());
// make sure Reader is actually prepared to receive state
r.set_write_handle(w_part)
})
})
.unwrap();
}
InitialState::Global { gid, cols, key } => {
use crate::backlog;
let (r_part, w_part) = backlog::new(cols, &key[..]);
let mut n = self.nodes[node].borrow_mut();
tokio::task::block_in_place(|| {
n.with_reader_mut(|r| {
assert!(self
.readers
.lock()
.unwrap()
.insert(
(gid, *self.shard.as_ref().unwrap_or(&0)),
r_part