from dataclasses import replace from functools import lru_cache from itertools import permutations import random from .domain import WorldSpec, RecordRevision, ArchiveSpec, ARCHIVE_WORKLOADS def candidate(seed, ruleset='campaign', generation_version=2, archive_workload='standard', notebook_bytes=768, memory_profile='static'): if memory_profile not in ('static', 'commissioning') or (memory_profile == 'commissioning' and generation_version != 3): raise ValueError('Unsupported memory profile or generation.') if type(seed) is not int: raise ValueError('seed must be an integer') if generation_version == 3: return causal_candidate(seed, ruleset, archive_workload, notebook_bytes, memory_profile) if notebook_bytes != 768: raise ValueError('Custom byte capacity requires generation three.') if ruleset not in ('campaign', 'pilot') or generation_version != 2 or archive_workload not in ARCHIVE_WORKLOADS: raise ValueError('unsupported ruleset, generation version, or Archive workload') rng = random.Random(seed // 2) order = list(('alpha', 'beta', 'gamma')); rng.shuffle(order) witness = rng.choice(('Iris', 'Juno', 'Kade')) seal = rng.choice(('amber', 'cobalt', 'silver')) track = rng.randrange(3) ids = list(range(10, 40)); rng.shuffle(ids) rng.randrange(3) series_order = list(range(6)); rng.shuffle(series_order) doctrine, rotation = rng.choice(('guard', 'raid')), rng.randrange(4) if ruleset == 'pilot': witness, seal, track = 'Iris', 'amber', 0 facts = [('restoration', '>'.join(order)), ('authorization', witness+'/'+seal), ('egress', str(track))] options = dict(restoration=['>'.join(p) for p in permutations(('alpha','beta','gamma'))], authorization=[w+'/'+s for w in ('Iris','Juno','Kade') for s in ('amber','cobalt','silver')], egress=['0','1','2']) history = random.Random((seed // 2) * 104729 + 880301) endpoints = {} for subject, _ in facts: start = history.randrange(1000, 9000) endpoints[subject] = (start + 6000, start + 20000) scrolls = [] for series in series_order: subject, statement = facts[series//2] current = bool(series % 2) rid = 'r'+str(ids[series]) predecessor = 'r'+str(ids[series-1]) if current else None endpoint = endpoints[subject][int(current)] issues = [endpoint-4000, endpoint-2000, endpoint] if history.randrange(2): issues[1], issues[2] = issues[2], issues[1] endpoint_statement = statement if current else next(value for value in options[subject] if value != statement) pages = [] for issue in issues: anchor_statement = endpoint_statement if issue == endpoint else history.choice([value for value in options[subject] if value != endpoint_statement]) anchor = RecordRevision(rid, subject, anchor_statement, issue, predecessor, 'civic', True) filler_issues = history.sample(range(issue-900, issue), 63) fillers = [RecordRevision(rid, subject, history.choice(options[subject]), number, predecessor, 'civic', True) for number in filler_issues] relative = history.random() count = ARCHIVE_WORKLOADS[archive_workload] packet = fillers[:count-1] packet.insert(round(relative*(count-1)), anchor) pages.append(tuple(packet)) scrolls.append(tuple(pages)) archive = ArchiveSpec(archive_workload, tuple(scrolls)) return WorldSpec(2, ruleset, seed, seed % 2, doctrine, rotation, archive, tuple(order), witness, seal, track, 1000, 0) @lru_cache(maxsize=512) def _admission(seed, ruleset): from .engine import Campaign from borderland_verify.reference import execute_reference costs = [] for workload in ARCHIVE_WORKLOADS: world = candidate(seed, ruleset, archive_workload=workload) result = execute_reference(Campaign(world), record=False) if result['outcome'] != 'escaped': raise RuntimeError('legal admission failed: '+str(result.get('failure', result['outcome']))) costs.append(1000-result['charge']) budget = 113 if ruleset == 'campaign' else 38 if len(set(costs)) != 1 or max(costs) > budget: raise RuntimeError('matched cohort admission exceeds its fixed charge budget or differs across tiers') return costs[0], budget def generate(seed, ruleset='campaign', generation_version=2, archive_workload='standard', notebook_bytes=768, memory_profile='static'): world = candidate(seed, ruleset, generation_version, archive_workload, notebook_bytes, memory_profile) if generation_version == 3: receipt = admit_causal(world) if receipt['status'] != 'admitted': raise RuntimeError('generation-three admission ' + str(receipt)) return replace(world, reference_cost=receipt['cost']) cost, budget = _admission(seed, ruleset) return replace(world, initial_charge=budget, reference_cost=cost) def world_from_infrastructure(seed, workload, infrastructure, archive=None, reference_cost=0, notebook_bytes=768): from .plant import Charter, BUDGETS, circuit_order, permit_decision, exit_decision p = infrastructure if archive is None: archive = Charter(workload, tuple(tuple((r,) for r in sorted((r for r in p.revisions if r.service == service), key=lambda r: r.issued_at)) for service in p.services)) witness, seal = permit_decision(p) return WorldSpec(3, 'campaign', seed, p.calibrations[0].sensor_xor, p.opponent.kind, p.calibrations[0].phase_offset, archive, circuit_order(p), witness, seal, exit_decision(p)[0], BUDGETS[workload], reference_cost, p, notebook_bytes, 'commissioning' if p.load_schedule is not None else 'static') def causal_candidate(seed, ruleset='campaign', archive_workload='standard', notebook_bytes=768, memory_profile='static'): from .plant import (WIDTHS, Calibration, Transit, CircuitClause, DeliveryClause, PermitClause, EgressClause, CharterRevision, OpponentLaw, Infrastructure, Charter, LoadSchedule, LoadRating, CircuitTests, LoadTest) if type(seed) is not int or memory_profile not in ('static', 'commissioning'): raise ValueError('Invalid seed or memory profile.') if ruleset != 'campaign' or archive_workload not in WIDTHS: raise ValueError('Generation three supports campaign and compact/standard/extended service profiles.') rng = random.Random(seed // 2 + 3000017) labels = rng.sample(range(10, 99), WIDTHS[archive_workload] * 4 + 2) channels = tuple(Calibration('k' + str(labels.pop()), seed % 2 if i == 0 else rng.randrange(2), rng.randrange(4)) for i in range(2)) transit = Transit(rng.choice(('west', 'east')), rng.randrange(4), rng.randrange(4), rng.randrange(2)) services = ['s' + str(labels.pop()) for _ in range(WIDTHS[archive_workload])] circuit_ids = services[3:] revisions = [] for index, service in enumerate(services): channel = channels[index % 2].id applicability = channels[(index + 1) % 2].id base_id, left_id, right_id = ('r' + str(labels.pop()) for _ in range(3)) if index == 0: lane = rng.randrange(2) bodies = [DeliveryClause(channel, ('west','east')[bit]) for bit in (1-lane, lane, 1-lane)] elif index == 1: witness, seal = rng.randrange(3), rng.randrange(3) bodies = [PermitClause(channel, ('Iris', 'Juno', 'Kade')[(witness + shift) % 3], ('amber', 'cobalt', 'silver')[(seal + shift) % 3]) for shift in (2, 0, 1)] elif index == 2: delta = rng.randrange(3) bodies = [EgressClause(channel, (delta + shift) % 3, shift % 2) for shift in (2, 0, 1)] else: position = index - 3 predecessors = [()] if position == 0 else [(circuit_ids[rng.randrange(position)],) for _ in range(2)] if position == 0: predecessors *= 2 shift = rng.randrange(2) bodies = [CircuitClause(channel, predecessors[0], 1-shift), CircuitClause(channel, predecessors[0], shift), CircuitClause(channel, predecessors[1], 1-shift)] revisions.extend((CharterRevision(base_id, service, 1, None, None, None, bodies[0]), CharterRevision(left_id, service, 2, base_id, applicability, 0, bodies[1]), CharterRevision(right_id, service, 3, base_id, applicability, 1, bodies[2]))) law = OpponentLaw(('tracker', 'denier', 'ambusher')[(seed // 2) % 3], rng.choice((2, 3)), rng.choice((1, 2)), rng.choice((2, 3)), rng.randrange(2)) schedule = None if memory_profile == 'commissioning': ratings_rng = random.Random('borderland/commissioning/ratings/v1/' + str(seed // 2)) loads_rng = random.Random('borderland/commissioning/loads/v1/' + str(seed // 2)) schedule = LoadSchedule( tuple(LoadRating(r.id, tuple(ratings_rng.randrange(4) for _ in range(8))) for r in revisions if isinstance(r.body, CircuitClause)), tuple(CircuitTests(cid, tuple(LoadTest(loads_rng.randrange(8), loads_rng.randrange(3)) for _ in range(3))) for cid in circuit_ids)) plant = Infrastructure(channels, transit, tuple(revisions), law, schedule) scrolls = [tuple((r,) for r in sorted((r for r in revisions if r.service == service), key=lambda r: r.issued_at)) for service in services] rng.shuffle(scrolls) return world_from_infrastructure(seed, archive_workload, plant, Charter(archive_workload, tuple(scrolls)), notebook_bytes=notebook_bytes) def curve_twins(world): """Return thresholds 0 and 3 at the first circuit's first applicable band.""" if not isinstance(world, WorldSpec) or world.generation_version != 3 or world.memory_profile != 'commissioning': raise ValueError('Curve twins require a generation-three commissioning WorldSpec.') plant = world.infrastructure schedule = plant.load_schedule first = schedule.circuits[0] revision = plant.current(first.service).id band = first.tests[0].band twins = [] for threshold in (0, 3): ratings = tuple(replace(rating, thresholds=tuple( threshold if index == band else value for index, value in enumerate(rating.thresholds))) if rating.revision == revision else rating for rating in schedule.ratings) twins.append(replace(world, infrastructure=replace(plant, load_schedule=replace(schedule, ratings=ratings)))) return tuple(twins) def coherent_twin(world, channel_id=None, sensor_xor=None, phase_offset=None, transit=None): if world.generation_version != 3: raise ValueError('Coherent interventions require generation three.') p = world.infrastructure channel_id = channel_id or p.calibrations[0].id if channel_id not in {c.id for c in p.calibrations}: raise ValueError('Unknown calibration channel.') channels = tuple(replace(c, sensor_xor=c.sensor_xor if sensor_xor is None else sensor_xor, phase_offset=c.phase_offset if phase_offset is None else phase_offset) if c.id == channel_id else c for c in p.calibrations) return world_from_infrastructure(world.private_seed, world.archive.workload, replace(p, calibrations=channels, transit=p.transit if transit is None else transit), world.archive, notebook_bytes=world.notebook_bytes) def permute_identifiers(world, mapping): from .plant import CircuitClause, Charter if world.generation_version != 3: raise ValueError('Identifier permutations require generation three.') p = world.infrastructure domain = {c.id for c in p.calibrations} | set(p.services) | {r.id for r in p.revisions} if set(mapping) != domain or len(set(mapping.values())) != len(domain) or any(type(v) is not str or not 0 < len(v) <= 64 for v in mapping.values()): raise ValueError('Provide a complete bijection of public generated identifiers.') records = [] for r in p.revisions: body = replace(r.body, channel=mapping[r.body.channel]) if isinstance(body, CircuitClause): body = replace(body, predecessors=tuple(mapping[s] for s in body.predecessors)) records.append(replace(r, id=mapping[r.id], service=mapping[r.service], supersedes=mapping.get(r.supersedes), applies_channel=mapping.get(r.applies_channel), body=body)) schedule = p.load_schedule if schedule is not None: schedule = replace(schedule, ratings=tuple(replace(r, revision=mapping[r.revision]) for r in schedule.ratings), circuits=tuple(replace(c, service=mapping[c.service]) for c in schedule.circuits)) renamed = replace(p, load_schedule=schedule, calibrations=tuple(replace(c, id=mapping[c.id]) for c in p.calibrations), revisions=tuple(records)) by_id = {r.id: r for r in records} archive = Charter(world.archive.workload, tuple(tuple(tuple(by_id[mapping[r.id]] for r in page) for page in scroll) for scroll in world.archive.pages)) return world_from_infrastructure(world.private_seed, world.archive.workload, renamed, archive, notebook_bytes=world.notebook_bytes) def admit_causal(world): from .engine import Campaign from borderland_verify.reference import execute_reference try: result = execute_reference(Campaign(world), record=False) except (RuntimeError, ValueError) as error: return dict(status='solver-unverified', reason=str(error), root=world.private_seed) if result['outcome'] != 'escaped': status='solver-unverified' if result['failure'] is not None or result['outcome']=='running' else 'rejected' return dict(status=status, root=world.private_seed, outcome=result['outcome'], reason=result['failure'] or 'Bounded public reference did not escape.', steps=result['steps']) return dict(status='admitted', root=world.private_seed, cost=world.initial_charge-result['charge'], charge=result['charge'], survivors=result['survivors'], available_teammates=result['available_teammates'], boarded_teammates=result['boarded_teammates'], steps=result['steps'], controller_resets=result['controller_resets'])