File size: 7,595 Bytes
a8aea51
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from __future__ import annotations

import hashlib
import json
import time
from dataclasses import asdict, dataclass, field

from borderland import Campaign
from borderland.domain import canonical
from borderland.replay import source_hash
from borderland_eval.context import actor_view
from borderland_verify.causal_reference import CausalReference


def digest(value):
    return hashlib.sha256(canonical(value).encode()).hexdigest()


class BoundExceeded(RuntimeError):
    pass


@dataclass
class Counter:
    limit: int
    seconds: float
    started: float = field(default_factory=time.monotonic)
    used: int = 0
    current_commands: list = field(default_factory=list)

    def check(self):
        if self.used >= self.limit:
            raise BoundExceeded('action_cap')
        if time.monotonic() - self.started >= self.seconds:
            raise BoundExceeded('wall_cap')


@dataclass(frozen=True)
class PublicRecord:
    id: str
    subject: str
    supersedes: str | None
    applies_channel: str | None
    applies_bit: int | None
    packet: str


@dataclass(frozen=True)
class PublicEvidence:
    measurements: tuple[tuple[str, int, int], ...]
    records: tuple[PublicRecord, ...]
    history: tuple[str, ...]

    @property
    def services(self):
        return tuple(sorted({record.subject for record in self.records}))

    def candidates(self, service):
        return tuple(record for record in self.records if record.subject == service)

    def bit(self, channel):
        return next(bit for name, bit, _ in self.measurements if name == channel)


@dataclass
class Execution:
    campaign: Campaign
    counter: Counter
    commands: list = field(default_factory=list)
    trial_receipt: dict = field(default_factory=dict)

    def __post_init__(self):
        self.counter.current_commands = self.commands

    def command(self, kind, payload, role, local_limit=None):
        self.counter.check()
        if local_limit is not None and len(self.commands) >= local_limit:
            raise BoundExceeded('prefix_cap')
        transition = (self.campaign.step(payload) if kind == 'action'
                      else self.campaign.replace_notebook(payload))
        self.counter.used += 1
        self.commands.append(dict(kind=kind, input=payload, role=role,
                                  public_digest=digest(actor_view(transition)),
                                  transition_digest=digest(transition.to_dict())))
        if transition.error:
            raise ValueError('engine rejected command: ' + transition.error.code)
        return transition


@dataclass(frozen=True)
class ArchiveCase:
    root: int
    seed: int
    engine_hash: str
    prefix: tuple[str, ...]
    evidence: PublicEvidence
    public_digest: str

    @classmethod
    def acquire(cls, root, parity, counter):
        if type(root) is not int or root < 0 or parity not in (0, 1):
            raise ValueError('invalid root or parity')
        execution = Execution(Campaign.generated(2 * root + parity, generation_version=3,
                              memory_profile='commissioning', archive_workload='standard',
                              notebook_bytes=768), counter)
        transition = execution.campaign.observe()
        reference = CausalReference()
        measurements = {}
        transit = None
        records = {}
        history = []

        def ingest(t):
            nonlocal transit
            observation = actor_view(t)['observation']
            board = observation['board']
            if observation['phase'] == 1:
                values = measurements.setdefault(board['channel'], [None, None])
                if board['live_sensor'] is not None:
                    values[0] = board['live_sensor'] ^ (board['latch'] & 1)
                if board['phase_mark'] is not None:
                    values[1] = (board['phase_mark'] - board['latch']) % 4
            if observation['phase'] == 2 and board['transit_plate'] is not None:
                transit = board['transit_plate']
            if observation['phase'] == 3 and board['records']:
                history.append(canonical(actor_view(t)))
                for packet in board['records']:
                    records[packet['id']] = PublicRecord(
                        packet['id'], packet['subject'], packet['supersedes'],
                        packet['applies_channel'], packet['applies_bit'], canonical(packet))

        ingest(transition)
        while int(transition.observation.phase) < 3 and not transition.done:
            action = reference.choose(transition)
            transition = execution.command('action', action.to_dict(), 'public_reference_prefix', 240)
            ingest(transition)
        if int(transition.observation.phase) != 3:
            raise ValueError('prefix did not reach Archive')
        slots = actor_view(transition)['observation']['board']['slots']
        for slot in slots:
            for page in range(3):
                payload = dict(tag='open_scroll', arguments=dict(slot=slot)) if page == 0 else dict(tag='advance_page', arguments={})
                transition = execution.command('action', payload, 'public_archive_reading', 240)
                ingest(transition)
        if len(slots) != 8 or len(records) != 24 or transit is None or any(None in values for values in measurements.values()):
            raise ValueError('incomplete public acquisition')
        evidence = PublicEvidence(tuple((key, *values) for key, values in measurements.items()),
                                  tuple(records[key] for key in sorted(records)), tuple(history))
        note = canonical(dict(m=[(name, str(bit), phase) for name, bit, phase in evidence.measurements], t=transit))
        transition = execution.command('note', note, 'supplied_public_measurement_note', 240)
        case = cls(root, 2 * root + parity, source_hash(),
                   tuple(canonical(command) for command in execution.commands), evidence,
                   digest(actor_view(transition)))
        return case, execution

    def reconstruct(self, counter):
        if self.engine_hash != source_hash():
            raise ValueError('case source mismatch')
        execution = Execution(Campaign.generated(self.seed, generation_version=3,
                              memory_profile='commissioning', archive_workload='standard',
                              notebook_bytes=768), counter)
        for encoded in self.prefix:
            command = json.loads(encoded)
            transition = execution.command(command['kind'], command['input'], command['role'], 240)
            if execution.commands[-1] != command:
                raise ValueError('prefix replay mismatch')
        if digest(actor_view(transition)) != self.public_digest:
            raise ValueError('prefix final public mismatch')
        return execution

    def recipe(self):
        return asdict(self)


def actor_packet(execution, evidence):
    return dict(current=actor_view(execution.campaign.observe()),
                history=[json.loads(value) for value in evidence.history])


def surviving_projection(packet):
    value = json.loads(canonical(packet))
    value['current']['observation']['notebook'].pop('text')
    return value


def require_twins(left, right):
    if canonical(surviving_projection(left)) != canonical(surviving_projection(right)):
        raise ValueError('complete surviving actor projection mismatch')


def physical_projection(execution):
    value = asdict(execution.campaign._state)
    value.pop('notebook')
    value.pop('revision')
    return value