Files @ a226385adc2d
Branch filter:

Location: CSY/reowolf/src/runtime/mod.rs

a226385adc2d 16.1 KiB application/rls-services+xml Show Annotation Show as Raw Download as Raw
Christopher Esterhuyse
natives working
  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
#[cfg(feature = "ffi")]
pub mod ffi;

mod actors;
pub(crate) mod communication;
pub(crate) mod connector;
pub(crate) mod endpoint;
pub mod errors;
mod predicate; // TODO later
mod serde;
pub(crate) mod setup;

pub(crate) type ProtocolD = crate::protocol::ProtocolDescriptionImpl;
pub(crate) type ProtocolS = crate::protocol::ComponentStateImpl;

use crate::common::*;
use actors::*;
use endpoint::*;
use errors::*;

#[derive(Debug, PartialEq)]
pub(crate) enum CommonSatResult {
    FormerNotLatter,
    LatterNotFormer,
    Equivalent,
    New(Predicate),
    Nonexistant,
}

#[derive(Clone, Eq, PartialEq, Hash)]
pub(crate) struct Predicate {
    pub assigned: BTreeMap<ChannelId, bool>,
}

#[derive(Debug, Default)]
struct SyncBatch {
    puts: HashMap<Key, Payload>,
    gets: HashSet<Key>,
}

#[derive(Debug)]
pub enum Connector {
    Unconfigured(Unconfigured),
    Configured(Configured),
    Connected(Connected), // TODO consider boxing. currently takes up a lot of stack real estate
}
#[derive(Debug)]
pub struct Unconfigured {
    pub controller_id: ControllerId,
}
#[derive(Debug)]
pub struct Connected {
    native_interface: Vec<(Key, Polarity)>,
    sync_batches: Vec<SyncBatch>,
    controller: Controller,
}
#[derive(Debug)]
pub struct Configured {
    // invariant: proto_maybe_bindings.len() is the size of the protocol's interface
    controller_id: ControllerId,
    proto_maybe_bindings: Vec<(Polarity, Option<PortBinding>)>,
    protocol_description: Arc<ProtocolD>,
}

#[derive(Debug, Copy, Clone)]
pub enum PortBinding {
    Native,
    Active(SocketAddr),
    Passive(SocketAddr),
}

#[derive(Debug)]
struct Arena<T> {
    storage: Vec<T>,
}

#[derive(Debug)]
struct ReceivedMsg {
    recipient: Key,
    msg: Msg,
}

#[derive(Debug)]
struct MessengerState {
    poll: Poll,
    events: Events,
    delayed: Vec<ReceivedMsg>,
    undelayed: Vec<ReceivedMsg>,
    polled_undrained: IndexSet<Key>,
}
#[derive(Debug)]
struct ChannelIdStream {
    controller_id: ControllerId,
    next_channel_index: ChannelIndex,
}

#[derive(Debug)]
struct Controller {
    protocol_description: Arc<ProtocolD>,
    inner: ControllerInner,
    ephemeral: ControllerEphemeral,
}
#[derive(Debug)]
struct ControllerInner {
    round_index: usize,
    channel_id_stream: ChannelIdStream,
    endpoint_exts: Arena<EndpointExt>,
    messenger_state: MessengerState,
    mono_n: Option<MonoN>,
    mono_ps: Vec<MonoP>,
    family: ControllerFamily,
    logger: String,
}

/// This structure has its state entirely reset between synchronous rounds
#[derive(Debug, Default)]
struct ControllerEphemeral {
    solution_storage: SolutionStorage,
    poly_n: Option<PolyN>,
    poly_ps: Vec<PolyP>,
    ekey_to_holder: HashMap<Key, PolyId>,
}

#[derive(Debug)]
struct ControllerFamily {
    parent_ekey: Option<Key>,
    children_ekeys: Vec<Key>,
}

#[derive(Debug)]
pub(crate) enum SyncRunResult {
    BlockingForRecv,
    AllBranchesComplete,
    NoBranches,
}

// Used to identify poly actors
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
enum PolyId {
    N,
    P { index: usize },
}

#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub(crate) enum SubtreeId {
    PolyN,
    PolyP { index: usize },
    ChildController { ekey: Key },
}

pub(crate) struct MonoPContext<'a> {
    inner: &'a mut ControllerInner,
    ekeys: &'a mut HashSet<Key>,
}
pub(crate) struct PolyPContext<'a> {
    my_subtree_id: SubtreeId,
    inner: &'a mut ControllerInner,
    solution_storage: &'a mut SolutionStorage,
}
impl PolyPContext<'_> {
    #[inline(always)]
    fn reborrow<'a>(&'a mut self) -> PolyPContext<'a> {
        let Self { solution_storage, my_subtree_id, inner } = self;
        PolyPContext { solution_storage, my_subtree_id: *my_subtree_id, inner }
    }
}
struct BranchPContext<'m, 'r> {
    m_ctx: PolyPContext<'m>,
    ekeys: &'r HashSet<Key>,
    predicate: &'r Predicate,
    inbox: &'r HashMap<Key, Payload>,
}

#[derive(Debug, Default)]
pub(crate) struct SolutionStorage {
    old_local: HashSet<Predicate>,
    new_local: HashSet<Predicate>,
    // this pair acts as SubtreeId -> HashSet<Predicate> which is friendlier to iteration
    subtree_solutions: Vec<HashSet<Predicate>>,
    subtree_id_to_index: HashMap<SubtreeId, usize>,
}

trait Messengerlike {
    fn get_state_mut(&mut self) -> &mut MessengerState;
    fn get_endpoint_mut(&mut self, eekey: Key) -> &mut Endpoint;

    fn delay(&mut self, received: ReceivedMsg) {
        self.get_state_mut().delayed.push(received);
    }
    fn undelay_all(&mut self) {
        let MessengerState { delayed, undelayed, .. } = self.get_state_mut();
        undelayed.extend(delayed.drain(..))
    }

    fn send(&mut self, to: Key, msg: Msg) -> Result<(), EndpointErr> {
        self.get_endpoint_mut(to).send(msg)
    }

    // attempt to receive a message from one of the endpoints before the deadline
    fn recv(&mut self, deadline: Instant) -> Result<Option<ReceivedMsg>, MessengerRecvErr> {
        // try get something buffered
        if let Some(x) = self.get_state_mut().undelayed.pop() {
            return Ok(Some(x));
        }

        loop {
            // polled_undrained may not be empty
            while let Some(eekey) = self.get_state_mut().polled_undrained.pop() {
                if let Some(msg) = self.get_endpoint_mut(eekey).recv()? {
                    // this endpoint MAY still have messages! check again in future
                    self.get_state_mut().polled_undrained.insert(eekey);
                    return Ok(Some(ReceivedMsg { recipient: eekey, msg }));
                }
            }

            let state = self.get_state_mut();
            match state.poll_events(deadline) {
                Ok(()) => {
                    for e in state.events.iter() {
                        state.polled_undrained.insert(Key::from_token(e.token()));
                    }
                }
                Err(PollDeadlineErr::PollingFailed) => return Err(MessengerRecvErr::PollingFailed),
                Err(PollDeadlineErr::Timeout) => return Ok(None),
            }
        }
    }
}

/////////////////////////////////

impl From<EvalErr> for SyncErr {
    fn from(e: EvalErr) -> SyncErr {
        SyncErr::EvalErr(e)
    }
}
impl From<MessengerRecvErr> for SyncErr {
    fn from(e: MessengerRecvErr) -> SyncErr {
        SyncErr::MessengerRecvErr(e)
    }
}
impl From<MessengerRecvErr> for ConnectErr {
    fn from(e: MessengerRecvErr) -> ConnectErr {
        ConnectErr::MessengerRecvErr(e)
    }
}
impl From<EndpointErr> for MessengerRecvErr {
    fn from(e: EndpointErr) -> MessengerRecvErr {
        MessengerRecvErr::EndpointErr(e)
    }
}
impl<T> Default for Arena<T> {
    fn default() -> Self {
        Self { storage: vec![] }
    }
}
impl<T> Arena<T> {
    pub fn alloc(&mut self, t: T) -> Key {
        self.storage.push(t);
        Key::from_raw(self.storage.len() as u64 - 1)
    }
    pub fn get(&self, key: Key) -> Option<&T> {
        self.storage.get(key.to_raw() as usize)
    }
    pub fn get_mut(&mut self, key: Key) -> Option<&mut T> {
        self.storage.get_mut(key.to_raw() as usize)
    }
    pub fn type_convert<X>(self, f: impl FnMut((Key, T)) -> X) -> Arena<X> {
        Arena { storage: self.keyspace().zip(self.storage.into_iter()).map(f).collect() }
    }
    pub fn iter(&self) -> impl Iterator<Item = (Key, &T)> {
        self.keyspace().zip(self.storage.iter())
    }
    pub fn len(&self) -> usize {
        self.storage.len()
    }
    pub fn keyspace(&self) -> impl Iterator<Item = Key> {
        (0..(self.storage.len() as u64)).map(Key::from_raw)
    }
}

impl ChannelIdStream {
    fn new(controller_id: ControllerId) -> Self {
        Self { controller_id, next_channel_index: 0 }
    }
    fn next(&mut self) -> ChannelId {
        self.next_channel_index += 1;
        ChannelId { controller_id: self.controller_id, channel_index: self.next_channel_index - 1 }
    }
}

impl MessengerState {
    // does NOT guarantee that events is non-empty
    fn poll_events(&mut self, deadline: Instant) -> Result<(), PollDeadlineErr> {
        use PollDeadlineErr::*;
        self.events.clear();
        let poll_timeout = deadline.checked_duration_since(Instant::now()).ok_or(Timeout)?;
        self.poll.poll(&mut self.events, Some(poll_timeout)).map_err(|_| PollingFailed)?;
        Ok(())
    }
}
impl From<PollDeadlineErr> for ConnectErr {
    fn from(e: PollDeadlineErr) -> ConnectErr {
        match e {
            PollDeadlineErr::Timeout => ConnectErr::Timeout,
            PollDeadlineErr::PollingFailed => ConnectErr::PollingFailed,
        }
    }
}

impl std::ops::Not for Polarity {
    type Output = Self;
    fn not(self) -> Self::Output {
        use Polarity::*;
        match self {
            Putter => Getter,
            Getter => Putter,
        }
    }
}

impl Predicate {
    // returns true IFF self.unify would return Equivalent OR FormerNotLatter
    pub fn satisfies(&self, other: &Self) -> bool {
        let mut s_it = self.assigned.iter();
        let mut s = if let Some(s) = s_it.next() {
            s
        } else {
            return other.assigned.is_empty();
        };
        for (oid, ob) in other.assigned.iter() {
            while s.0 < oid {
                s = if let Some(s) = s_it.next() {
                    s
                } else {
                    return false;
                };
            }
            if s.0 > oid || s.1 != ob {
                return false;
            }
        }
        true
    }

    /// Given self and other, two predicates, return the most general Predicate possible, N
    /// such that n.satisfies(self) && n.satisfies(other).
    /// If none exists Nonexistant is returned.
    /// If the resulting predicate is equivlanet to self, other, or both,
    /// FormerNotLatter, LatterNotFormer and Equivalent are returned respectively.
    /// otherwise New(N) is returned.
    pub fn common_satisfier(&self, other: &Self) -> CommonSatResult {
        use CommonSatResult::*;
        // iterators over assignments of both predicates. Rely on SORTED ordering of BTreeMap's keys.
        let [mut s_it, mut o_it] = [self.assigned.iter(), other.assigned.iter()];
        let [mut s, mut o] = [s_it.next(), o_it.next()];
        // lists of assignments in self but not other and vice versa.
        let [mut s_not_o, mut o_not_s] = [vec![], vec![]];
        loop {
            match [s, o] {
                [None, None] => break,
                [None, Some(x)] => {
                    o_not_s.push(x);
                    o_not_s.extend(o_it);
                    break;
                }
                [Some(x), None] => {
                    s_not_o.push(x);
                    s_not_o.extend(s_it);
                    break;
                }
                [Some((sid, sb)), Some((oid, ob))] => {
                    if sid < oid {
                        // o is missing this element
                        s_not_o.push((sid, sb));
                        s = s_it.next();
                    } else if sid > oid {
                        // s is missing this element
                        o_not_s.push((sid, sb));
                        o = o_it.next();
                    } else if sb != ob {
                        assert_eq!(sid, oid);
                        // both predicates assign the variable but differ on the value
                        return Nonexistant;
                    } else {
                        // both predicates assign the variable to the same value
                        s = s_it.next();
                        o = o_it.next();
                    }
                }
            }
        }
        // Observed zero inconsistencies. A unified predicate exists...
        match [s_not_o.is_empty(), o_not_s.is_empty()] {
            [true, true] => Equivalent,       // ... equivalent to both.
            [false, true] => FormerNotLatter, // ... equivalent to self.
            [true, false] => LatterNotFormer, // ... equivalent to other.
            [false, false] => {
                // ... which is the union of the predicates' assignments but
                //     is equivalent to neither self nor other.
                let mut predicate = self.clone();
                for (&id, &b) in o_not_s {
                    predicate.assigned.insert(id, b);
                }
                New(predicate)
            }
        }
    }

    pub fn iter_matching(&self, value: bool) -> impl Iterator<Item = ChannelId> + '_ {
        self.assigned
            .iter()
            .filter_map(move |(&channel_id, &b)| if b == value { Some(channel_id) } else { None })
    }

    pub fn batch_assign_nones(
        &mut self,
        channel_ids: impl Iterator<Item = ChannelId>,
        value: bool,
    ) {
        for channel_id in channel_ids {
            self.assigned.entry(channel_id).or_insert(value);
        }
    }
    pub fn replace_assignment(&mut self, channel_id: ChannelId, value: bool) -> Option<bool> {
        self.assigned.insert(channel_id, value)
    }
    pub fn union_with(&self, other: &Self) -> Option<Self> {
        let mut res = self.clone();
        for (&channel_id, &assignment_1) in other.assigned.iter() {
            match res.assigned.insert(channel_id, assignment_1) {
                Some(assignment_2) if assignment_1 != assignment_2 => return None,
                _ => {}
            }
        }
        Some(res)
    }
    pub fn query(&self, x: ChannelId) -> Option<bool> {
        self.assigned.get(&x).copied()
    }
    pub fn new_trivial() -> Self {
        Self { assigned: Default::default() }
    }
}
impl Debug for Predicate {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        f.pad("{")?;
        for (ChannelId { controller_id, channel_index }, &v) in self.assigned.iter() {
            f.write_fmt(format_args!(
                "({:?},{:?})=>{}, ",
                controller_id,
                channel_index,
                if v { 'T' } else { 'F' }
            ))?
        }
        f.pad("}")
    }
}

#[test]
fn pred_sat() {
    use maplit::btreemap;
    let mut c = ChannelIdStream::new(0);
    let ch = std::iter::repeat_with(move || c.next()).take(5).collect::<Vec<_>>();
    let p = Predicate::new_trivial();
    let p_0t = Predicate { assigned: btreemap! { ch[0] => true } };
    let p_0f = Predicate { assigned: btreemap! { ch[0] => false } };
    let p_0f_3f = Predicate { assigned: btreemap! { ch[0] => false, ch[3] => false } };
    let p_0f_3t = Predicate { assigned: btreemap! { ch[0] => false, ch[3] => true } };

    assert!(p.satisfies(&p));
    assert!(p_0t.satisfies(&p_0t));
    assert!(p_0f.satisfies(&p_0f));
    assert!(p_0f_3f.satisfies(&p_0f_3f));
    assert!(p_0f_3t.satisfies(&p_0f_3t));

    assert!(p_0t.satisfies(&p));
    assert!(p_0f.satisfies(&p));
    assert!(p_0f_3f.satisfies(&p_0f));
    assert!(p_0f_3t.satisfies(&p_0f));

    assert!(!p.satisfies(&p_0t));
    assert!(!p.satisfies(&p_0f));
    assert!(!p_0f.satisfies(&p_0t));
    assert!(!p_0t.satisfies(&p_0f));
    assert!(!p_0f_3f.satisfies(&p_0f_3t));
    assert!(!p_0f_3t.satisfies(&p_0f_3f));
    assert!(!p_0t.satisfies(&p_0f_3f));
    assert!(!p_0f.satisfies(&p_0f_3f));
    assert!(!p_0t.satisfies(&p_0f_3t));
    assert!(!p_0f.satisfies(&p_0f_3t));
}

#[test]
fn pred_common_sat() {
    use maplit::btreemap;
    use CommonSatResult::*;

    let mut c = ChannelIdStream::new(0);
    let ch = std::iter::repeat_with(move || c.next()).take(5).collect::<Vec<_>>();
    let p = Predicate::new_trivial();
    let p_0t = Predicate { assigned: btreemap! { ch[0] => true } };
    let p_0f = Predicate { assigned: btreemap! { ch[0] => false } };
    let p_3f = Predicate { assigned: btreemap! { ch[3] => false } };
    let p_0f_3f = Predicate { assigned: btreemap! { ch[0] => false, ch[3] => false } };
    let p_0f_3t = Predicate { assigned: btreemap! { ch[0] => false, ch[3] => true } };

    assert_eq![p.common_satisfier(&p), Equivalent];
    assert_eq![p_0t.common_satisfier(&p_0t), Equivalent];

    assert_eq![p.common_satisfier(&p_0t), LatterNotFormer];
    assert_eq![p_0t.common_satisfier(&p), FormerNotLatter];

    assert_eq![p_0t.common_satisfier(&p_0f), Nonexistant];
    assert_eq![p_0f_3t.common_satisfier(&p_0f_3f), Nonexistant];
    assert_eq![p_0f_3t.common_satisfier(&p_3f), Nonexistant];
    assert_eq![p_3f.common_satisfier(&p_0f_3t), Nonexistant];

    assert_eq![p_0f.common_satisfier(&p_3f), New(p_0f_3f)];
}