1use std::rc::Rc;
9use std::cell::RefCell;
10use std::collections::BinaryHeap;
11use std::cmp::Reverse;
12
13use crate::logging::TimelyLogger as Logger;
14use crate::logging::TimelySummaryLogger as SummaryLogger;
15
16use crate::scheduling::Schedule;
17use crate::scheduling::activate::Activations;
18
19use crate::progress::frontier::{MutableAntichain, MutableAntichainFilter};
20use crate::progress::{Timestamp, Operate, operate::SharedProgress};
21use crate::progress::{Location, Port, Source, Target};
22use crate::progress::operate::{Connectivity, PortConnectivity};
23use crate::progress::ChangeBatch;
24use crate::progress::broadcast::Progcaster;
25use crate::progress::reachability;
26use crate::progress::timestamp::Refines;
27
28use crate::worker::ProgressMode;
29
30pub struct SubgraphBuilder<TOuter, TInner>
40where
41 TOuter: Timestamp,
42 TInner: Timestamp,
43{
44 pub name: String,
46
47 pub path: Rc<[usize]>,
49
50 index: usize,
52
53 identifier: usize,
55
56 children: Vec<PerOperatorState<TInner>>,
58 child_count: usize,
59
60 edge_stash: Vec<(Source, Target)>,
61
62 input_messages: Vec<Rc<RefCell<ChangeBatch<TInner>>>>,
64
65 output_capabilities: Vec<MutableAntichain<TOuter>>,
67
68 logging: Option<Logger>,
70 summary_logging: Option<SummaryLogger<TInner::Summary>>,
72}
73
74impl<TOuter, TInner> SubgraphBuilder<TOuter, TInner>
75where
76 TOuter: Timestamp,
77 TInner: Timestamp+Refines<TOuter>,
78{
79 pub fn new_input(&mut self, shared_counts: Rc<RefCell<ChangeBatch<TInner>>>) -> Target {
81 self.input_messages.push(shared_counts);
82 Target::new(self.index, self.input_messages.len() - 1)
83 }
84
85 pub fn new_output(&mut self) -> Source {
87 self.output_capabilities.push(MutableAntichain::new());
88 Source::new(self.index, self.output_capabilities.len() - 1)
89 }
90
91 pub fn connect(&mut self, source: Source, target: Target) {
96 self.edge_stash.push((source, target));
97 }
98
99 pub fn new_from(
102 path: Rc<[usize]>,
103 identifier: usize,
104 logging: Option<Logger>,
105 summary_logging: Option<SummaryLogger<TInner::Summary>>,
106 name: &str,
107 )
108 -> SubgraphBuilder<TOuter, TInner>
109 {
110 let children = vec![PerOperatorState::empty(0, 0)];
112 let index = path[path.len() - 1];
113
114 SubgraphBuilder {
115 name: name.to_owned(),
116 path,
117 index,
118 identifier,
119 children,
120 child_count: 1,
121 edge_stash: Vec::new(),
122 input_messages: Vec::new(),
123 output_capabilities: Vec::new(),
124 logging,
125 summary_logging,
126 }
127 }
128
129 pub fn allocate_child_id(&mut self) -> usize {
131 self.child_count += 1;
132 self.child_count - 1
133 }
134
135 pub fn add_child(&mut self, child: Box<dyn Operate<TInner>>, index: usize, identifier: usize) {
137 if let Some(l) = &mut self.logging {
138 let mut child_path = Vec::with_capacity(self.path.len() + 1);
139 child_path.extend_from_slice(&self.path[..]);
140 child_path.push(index);
141
142 l.log(crate::logging::OperatesEvent {
143 id: identifier,
144 addr: child_path,
145 name: child.name().to_owned(),
146 });
147 }
148 self.children.push(PerOperatorState::new(child, index, identifier, self.logging.clone(), &mut self.summary_logging));
149 }
150
151 pub fn build<A: crate::worker::AsWorker>(mut self, worker: &mut A) -> Subgraph<TOuter, TInner> {
153 self.children.sort_by(|x,y| x.index.cmp(&y.index));
160 assert!(self.children.iter().enumerate().all(|(i,x)| i == x.index));
161
162 let inputs = self.input_messages.len();
163 let outputs = self.output_capabilities.len();
164
165 self.children[0] = PerOperatorState::empty(outputs, inputs);
167
168 let mut builder = reachability::Builder::new();
169
170 let summary = (0..outputs).map(|_| PortConnectivity::default()).collect();
172 builder.add_node(0, outputs, inputs, summary);
173 for (index, child) in self.children.iter().enumerate().skip(1) {
174 builder.add_node(index, child.inputs, child.outputs, child.internal_summary.clone());
175 }
176
177 for (source, target) in self.edge_stash {
178 self.children[source.node].edges[source.port].push(target);
179 builder.add_edge(source, target);
180 }
181
182 let type_name = std::any::type_name::<TInner>();
184 let reachability_logging =
185 worker.logger_for(&format!("timely/reachability/{type_name}"))
186 .map(|logger| reachability::logging::TrackerLogger::new(self.identifier, logger));
187 let progress_logging = worker.logger_for(&format!("timely/progress/{type_name}"));
188 let (tracker, scope_summary) = builder.build(reachability_logging);
189
190 let progcaster = Progcaster::new(worker, Rc::clone(&self.path), self.identifier, self.logging.clone(), progress_logging);
191
192 let mut incomplete = vec![true; self.children.len()];
193 incomplete[0] = false;
194 let incomplete_count = incomplete.len() - 1;
195
196 let activations = worker.activations();
197
198 activations.borrow_mut().activate(&self.path[..]);
199
200 Subgraph {
201 name: self.name,
202 path: self.path,
203 inputs,
204 outputs,
205 incomplete,
206 incomplete_count,
207 activations,
208 temp_active: BinaryHeap::new(),
209 maybe_shutdown: Vec::new(),
210 children: self.children,
211 input_messages: self.input_messages,
212 output_capabilities: self.output_capabilities,
213
214 local_pointstamp: ChangeBatch::new(),
215 final_pointstamp: ChangeBatch::new(),
216 progcaster,
217 pointstamp_tracker: tracker,
218
219 shared_progress: Rc::new(RefCell::new(SharedProgress::new(inputs, outputs))),
220 scope_summary,
221
222 progress_mode: worker.config().progress_mode,
223 }
224 }
225}
226
227
228pub struct Subgraph<TOuter, TInner>
233where
234 TOuter: Timestamp,
235 TInner: Timestamp+Refines<TOuter>,
236{
237 name: String, pub path: Rc<[usize]>,
240 inputs: usize, outputs: usize, children: Vec<PerOperatorState<TInner>>,
245
246 incomplete: Vec<bool>, incomplete_count: usize, activations: Rc<RefCell<Activations>>,
251 temp_active: BinaryHeap<Reverse<usize>>,
252 maybe_shutdown: Vec<usize>,
253
254 input_messages: Vec<Rc<RefCell<ChangeBatch<TInner>>>>,
256
257 output_capabilities: Vec<MutableAntichain<TOuter>>,
259
260 local_pointstamp: ChangeBatch<(Location, TInner)>,
262 final_pointstamp: ChangeBatch<(Location, TInner)>,
263
264 pointstamp_tracker: reachability::Tracker<TInner>,
267
268 progcaster: Progcaster<TInner>,
270
271 shared_progress: Rc<RefCell<SharedProgress<TOuter>>>,
272 scope_summary: Connectivity<TInner::Summary>,
273
274 progress_mode: ProgressMode,
275}
276
277impl<TOuter, TInner> Schedule for Subgraph<TOuter, TInner>
278where
279 TOuter: Timestamp,
280 TInner: Timestamp+Refines<TOuter>,
281{
282 fn name(&self) -> &str { &self.name }
283
284 fn path(&self) -> &[usize] { &self.path }
285
286 fn schedule(&mut self) -> bool {
287
288 self.accept_frontier(); self.harvest_inputs(); self.progcaster.recv(&mut self.final_pointstamp);
298
299 self.propagate_pointstamps();
301
302 { let temp_active = &mut self.temp_active;
304 self.activations
305 .borrow_mut()
306 .for_extensions(&self.path[..], |index| temp_active.push(Reverse(index)));
307 }
308
309 let mut previous = 0;
314 while let Some(Reverse(index)) = self.temp_active.pop() {
315 if index > previous {
317 self.activate_child(index);
319 previous = index;
320 }
321 }
322
323 self.send_progress();
325
326 if !self.final_pointstamp.is_empty() {
328 self.activations.borrow_mut().activate(&self.path[..]);
329 }
330
331 let incomplete = self.incomplete_count > 0;
333 let tracking = self.pointstamp_tracker.tracking_anything();
334
335 incomplete || tracking
336 }
337}
338
339
340impl<TOuter, TInner> Subgraph<TOuter, TInner>
341where
342 TOuter: Timestamp,
343 TInner: Timestamp+Refines<TOuter>,
344{
345 fn activate_child(&mut self, child_index: usize) -> bool {
349
350 let child = &mut self.children[child_index];
351
352 let incomplete = child.schedule();
353
354 if incomplete != self.incomplete[child_index] {
355 if incomplete { self.incomplete_count += 1; }
356 else { self.incomplete_count -= 1; }
357 self.incomplete[child_index] = incomplete;
358 }
359
360 if !incomplete {
361 let child_state = self.pointstamp_tracker.node_state(child_index);
363 let frontiers_empty = child_state.targets.iter().all(|x| x.implications.is_empty());
364 let no_capabilities = child_state.sources.iter().all(|x| x.pointstamps.is_empty());
365 if frontiers_empty && no_capabilities {
366 child.shut_down();
367 }
368 }
369 else {
370 #[cfg(debug_assertions)] {
372 child.validate_progress(self.pointstamp_tracker.node_state(child_index));
373 }
374 }
375
376 if child.local {
378 child.extract_progress(&mut self.local_pointstamp, &mut self.temp_active);
379 }
380 else {
381 child.extract_progress(&mut self.final_pointstamp, &mut self.temp_active);
382 }
383
384 incomplete
385 }
386
387 fn accept_frontier(&mut self) {
389 for (port, changes) in self.shared_progress.borrow_mut().frontiers.iter_mut().enumerate() {
390 let source = Source::new(0, port);
391 for (time, value) in changes.drain() {
392 self.pointstamp_tracker.update_source(
393 source,
394 TInner::to_inner(time),
395 value
396 );
397 }
398 }
399 }
400
401 fn harvest_inputs(&mut self) {
408 for input in 0 .. self.inputs {
409 let source = Location::new_source(0, input);
410 let mut borrowed = self.input_messages[input].borrow_mut();
411 for (time, delta) in borrowed.drain() {
412 for target in &self.children[0].edges[input] {
413 self.local_pointstamp.update((Location::from(*target), time.clone()), delta);
414 }
415 self.local_pointstamp.update((source, time), -delta);
416 }
417 }
418 }
419
420 fn propagate_pointstamps(&mut self) {
436
437 for ((location, timestamp), delta) in self.final_pointstamp.drain() {
439
440 if location.node == 0 {
442 match location.port {
443 Port::Source(scope_input) => {
446 self.shared_progress
447 .borrow_mut()
448 .consumeds[scope_input]
449 .update(timestamp.to_outer(), -delta);
450 },
451 Port::Target(scope_output) => {
455 self.shared_progress
456 .borrow_mut()
457 .produceds[scope_output]
458 .update(timestamp.to_outer(), delta);
459 },
460 }
461 }
462 else {
463 self.pointstamp_tracker.update(location, timestamp, delta);
464 }
465 }
466
467 self.pointstamp_tracker.propagate_all();
469
470 for ((location, time), diff) in self.pointstamp_tracker.pushed().drain() {
472 self.maybe_shutdown.push(location.node);
473 if let crate::progress::Port::Target(port) = location.port {
475 if self.children[location.node].notify {
476 self.temp_active.push(Reverse(location.node));
477 }
478 self.children[location.node]
482 .shared_progress
483 .borrow_mut()
484 .frontiers[port]
485 .update(time, diff);
486 }
487 }
488
489 self.maybe_shutdown.sort();
491 self.maybe_shutdown.dedup();
492 for child_index in self.maybe_shutdown.drain(..) {
493 let child_state = self.pointstamp_tracker.node_state(child_index);
494 let frontiers_empty = child_state.targets.iter().all(|x| x.implications.is_empty());
495 let no_capabilities = child_state.sources.iter().all(|x| x.pointstamps.is_empty());
496 if frontiers_empty && no_capabilities {
497 self.temp_active.push(Reverse(child_index));
498 }
499 }
500
501 for (output, internal) in self.shared_progress.borrow_mut().internals.iter_mut().enumerate() {
503 self.pointstamp_tracker
504 .pushed_output()[output]
505 .drain()
506 .map(|(time, diff)| (time.to_outer(), diff))
507 .filter_through(&mut self.output_capabilities[output])
508 .for_each(|(time, diff)| internal.update(time, diff));
509 }
510 }
511
512 fn send_progress(&mut self) {
517
518 let must_send = self.progress_mode == ProgressMode::Eager || {
521 let tracker = &mut self.pointstamp_tracker;
522 self.local_pointstamp
523 .iter()
524 .any(|((location, time), diff)|
525 tracker.is_global(*location, time) && *diff < 0
527 )
528 };
529
530 if must_send {
531 self.progcaster.send(&mut self.local_pointstamp);
532 }
533 }
534}
535
536
537impl<TOuter, TInner> Operate<TOuter> for Subgraph<TOuter, TInner>
538where
539 TOuter: Timestamp,
540 TInner: Timestamp+Refines<TOuter>,
541{
542 fn local(&self) -> bool { false }
543 fn inputs(&self) -> usize { self.inputs }
544 fn outputs(&self) -> usize { self.outputs }
545
546 fn get_internal_summary(&mut self) -> (Connectivity<TOuter::Summary>, Rc<RefCell<SharedProgress<TOuter>>>) {
549
550 assert_eq!(self.children[0].outputs, self.inputs());
552 assert_eq!(self.children[0].inputs, self.outputs());
553
554 let mut internal_summary = vec![PortConnectivity::default(); self.inputs()];
558 for (input_idx, input) in self.scope_summary.iter().enumerate() {
559 for (output_idx, output) in input.iter_ports() {
560 for outer in output.elements().iter().cloned().map(TInner::summarize) {
561 internal_summary[input_idx].insert(output_idx, outer);
562 }
563 }
564 }
565
566 debug_assert_eq!(
567 internal_summary.len(),
568 self.inputs(),
569 "the internal summary should have as many elements as there are inputs",
570 );
571 debug_assert!(
572 internal_summary.iter().all(|os| os.iter_ports().all(|(o,_)| o < self.outputs())),
573 "each element of the internal summary should only reference valid outputs",
574 );
575
576 for child in self.children.iter_mut() {
580 child.extract_progress(&mut self.final_pointstamp, &mut self.temp_active);
581 }
582
583 self.propagate_pointstamps(); (internal_summary, Rc::clone(&self.shared_progress))
587 }
588
589 fn set_external_summary(&mut self) {
590 self.accept_frontier();
591 self.propagate_pointstamps(); self.children
593 .iter_mut()
594 .flat_map(|child| child.operator.as_mut())
595 .for_each(|op| op.set_external_summary());
596 }
597}
598
599struct PerOperatorState<T: Timestamp> {
600
601 name: String, index: usize, id: usize, local: bool, notify: bool,
607 inputs: usize, outputs: usize, operator: Option<Box<dyn Operate<T>>>,
611
612 edges: Vec<Vec<Target>>, shared_progress: Rc<RefCell<SharedProgress<T>>>,
615
616 internal_summary: Connectivity<T::Summary>, logging: Option<Logger>,
619}
620
621impl<T: Timestamp> PerOperatorState<T> {
622
623 fn empty(inputs: usize, outputs: usize) -> PerOperatorState<T> {
624 PerOperatorState {
625 name: "External".to_owned(),
626 operator: None,
627 index: 0,
628 id: usize::MAX,
629 local: false,
630 notify: true,
631 inputs,
632 outputs,
633
634 edges: vec![Vec::new(); outputs],
635
636 logging: None,
637
638 shared_progress: Rc::new(RefCell::new(SharedProgress::new(inputs,outputs))),
639 internal_summary: Vec::new(),
640 }
641 }
642
643 pub fn new(
644 mut scope: Box<dyn Operate<T>>,
645 index: usize,
646 identifier: usize,
647 logging: Option<Logger>,
648 summary_logging: &mut Option<SummaryLogger<T::Summary>>,
649 ) -> PerOperatorState<T>
650 {
651 let local = scope.local();
652 let inputs = scope.inputs();
653 let outputs = scope.outputs();
654 let notify = scope.notify_me();
655
656 let (internal_summary, shared_progress) = scope.get_internal_summary();
657
658 if let Some(l) = summary_logging {
659 l.log(crate::logging::OperatesSummaryEvent {
660 id: identifier,
661 summary: internal_summary.clone(),
662 })
663 }
664
665 assert_eq!(
666 internal_summary.len(),
667 inputs,
668 "operator summary has {} inputs when {} were expected",
669 internal_summary.len(),
670 inputs,
671 );
672 assert!(
673 internal_summary.iter().all(|os| os.iter_ports().all(|(o,_)| o < outputs)),
674 "operator summary references invalid output port",
675 );
676
677 PerOperatorState {
678 name: scope.name().to_owned(),
679 operator: Some(scope),
680 index,
681 id: identifier,
682 local,
683 notify,
684 inputs,
685 outputs,
686 edges: vec![vec![]; outputs],
687
688 logging,
689
690 shared_progress,
691 internal_summary,
692 }
693 }
694
695 pub fn schedule(&mut self) -> bool {
696
697 if let Some(ref mut operator) = self.operator {
698
699 if let Some(l) = self.logging.as_mut() {
701 let frontiers = &mut self.shared_progress.borrow_mut().frontiers[..];
705 if frontiers.iter_mut().any(|buffer| !buffer.is_empty()) {
706 l.log(crate::logging::PushProgressEvent { op_id: self.id })
707 }
708
709 l.log(crate::logging::ScheduleEvent::start(self.id));
710 }
711
712 let incomplete = operator.schedule();
713
714 if let Some(l) = self.logging.as_mut() {
716 l.log(crate::logging::ScheduleEvent::stop(self.id));
717 }
718
719 incomplete
720 }
721 else {
722
723 if self.shared_progress.borrow_mut().frontiers.iter_mut().any(|x| !x.is_empty()) {
725 println!("Operator prematurely shut down: {}", self.name);
726 println!(" {:?}", self.notify);
727 println!(" {:?}", self.shared_progress.borrow_mut().frontiers);
728 panic!();
729 }
730
731 false
733 }
734 }
735
736 fn shut_down(&mut self) {
737 if self.operator.is_some() {
738 if let Some(l) = self.logging.as_mut() {
739 l.log(crate::logging::ShutdownEvent{ id: self.id });
740 }
741 self.operator = None;
742 }
743 }
744
745 fn extract_progress(&self, pointstamps: &mut ChangeBatch<(Location, T)>, temp_active: &mut BinaryHeap<Reverse<usize>>) {
747
748 let shared_progress = &mut *self.shared_progress.borrow_mut();
749
750 for (input, consumed) in shared_progress.consumeds.iter_mut().enumerate() {
752 let target = Location::new_target(self.index, input);
753 for (time, delta) in consumed.drain() {
754 pointstamps.update((target, time), -delta);
755 }
756 }
757 for (output, internal) in shared_progress.internals.iter_mut().enumerate() {
758 let source = Location::new_source(self.index, output);
759 for (time, delta) in internal.drain() {
760 pointstamps.update((source, time.clone()), delta);
761 }
762 }
763 for (output, produced) in shared_progress.produceds.iter_mut().enumerate() {
764 for (time, delta) in produced.drain() {
765 for target in &self.edges[output] {
766 pointstamps.update((Location::from(*target), time.clone()), delta);
767 temp_active.push(Reverse(target.node));
768 }
769 }
770 }
771 }
772
773 #[allow(dead_code)]
778 fn validate_progress(&self, child_state: &reachability::PerOperator<T>) {
779
780 let shared_progress = &mut *self.shared_progress.borrow_mut();
781
782 for (output, internal) in shared_progress.internals.iter_mut().enumerate() {
784 for (time, diff) in internal.iter() {
785 if *diff > 0 {
786 let consumed = shared_progress.consumeds.iter_mut().any(|x| x.iter().any(|(t,d)| *d > 0 && t.less_equal(time)));
787 let internal = child_state.sources[output].implications.less_equal(time);
788 if !consumed && !internal {
789 println!("Increment at {:?}, not supported by\n\tconsumed: {:?}\n\tinternal: {:?}", time, shared_progress.consumeds, child_state.sources[output].implications);
790 panic!("Progress error; internal {:?}", self.name);
791 }
792 }
793 }
794 }
795 for (output, produced) in shared_progress.produceds.iter_mut().enumerate() {
796 for (time, diff) in produced.iter() {
797 if *diff > 0 {
798 let consumed = shared_progress.consumeds.iter_mut().any(|x| x.iter().any(|(t,d)| *d > 0 && t.less_equal(time)));
799 let internal = child_state.sources[output].implications.less_equal(time);
800 if !consumed && !internal {
801 println!("Increment at {:?}, not supported by\n\tconsumed: {:?}\n\tinternal: {:?}", time, shared_progress.consumeds, child_state.sources[output].implications);
802 panic!("Progress error; produced {:?}", self.name);
803 }
804 }
805 }
806 }
807 }
808}
809
810impl<T: Timestamp> Drop for PerOperatorState<T> {
812 fn drop(&mut self) {
813 self.shut_down();
814 }
815}