"""Synthetic Chinese demand-paging exercises with deterministic physical frame traces. make_group generates sibling rows for a workload. verify independently replays each row. All page identifiers are integers and all steps count from one. """ from collections import deque from random import Random POLICIES = ("FIFO", "LRU", "OPT") TASKS = ("full_trace", "summary", "checkpoint", "window") FAMILIES = ("cyclic_scan", "hot_set", "phase_shift", "bursts", "scan_with_reuse", "uniform", "interleaved_streams") RULES = { "FIFO": "FIFO 每次淘汰当前连续驻留时间最长的页,命中不更新入驻时间。", "LRU": "LRU 每次淘汰上一次访问时间最早的驻留页,命中也更新访问时间。", "OPT": "OPT 每次淘汰下次访问最晚的驻留页;以后不再访问视为无穷远。并列时选页框编号最小者。", } def _workload(rng, family, size, length): pages = rng.sample(range(1, 100), size) if family == "uniform": return rng.choices(pages, k=length) if family == "cyclic_scan": index = 0 seq = [] for _ in range(length): seq.append(pages[index]) index = (index + rng.choices((0, 1, 2), weights=(1, 8, 1))[0]) % size return seq if family == "hot_set": hot = pages[:rng.randint(1, max(1, size // 2))] return [rng.choice(hot if rng.random() < 0.78 else pages[len(hot):]) for _ in range(length)] if family == "phase_shift": pivot = rng.randint(length // 3, 2 * length // 3) left = pages[:(size + 1) // 2] right = pages[size // 2:] return rng.choices(left, k=pivot) + rng.choices(right, k=length - pivot) if family == "bursts": seq = [] while len(seq) < length: seq.extend([rng.choice(pages)] * rng.randint(1, 4)) return seq[:length] if family == "scan_with_reuse": seq = [] cursor = 1 while len(seq) < length: seq.append(pages[0]) for _ in range(rng.randint(1, 4)): seq.append(pages[cursor]) cursor = 1 + cursor % (size - 1) return seq[:length] streams = (pages[::2], pages[1::2]) indices = [0, 0] seq = [] for _ in range(length): channel = rng.randrange(2) stream = streams[channel] seq.append(stream[indices[channel] % len(stream)]) indices[channel] += 1 return seq def _trace(pages, capacity, policy): """Generate labels with a queue for FIFO and a recency queue for LRU.""" frames = [None] * capacity order = deque() trace = [] for pos, page in enumerate(pages): hit = page in frames evicted = None if hit: if policy == "LRU": order.remove(page) order.append(page) else: if None in frames: index = frames.index(None) elif policy == "OPT": future = pages[pos + 1:] index = max(range(capacity), key=lambda i: future.index(frames[i]) if frames[i] in future else len(future)) else: index = frames.index(order.popleft()) evicted = frames[index] frames[index] = page if policy != "OPT": order.append(page) trace.append(dict(step=pos + 1, page=page, hit=hit, evicted=evicted, frames_after=frames.copy())) return trace def _answer(task, instance, trace): if task == "full_trace": return {"steps": trace} if task == "checkpoint": return trace[instance["at_step"] - 1] if task == "window": start, end = instance["interval"] window = trace[start - 1:end] return {"hit_steps": [s["step"] for s in window if s["hit"]], "eviction_steps": [s["step"] for s in window if s["evicted"] is not None], "faults": sum(not s["hit"] for s in window)} hits = sum(s["hit"] for s in trace) return {"hits": hits, "faults": len(trace) - hits, "evictions": sum(s["evicted"] is not None for s in trace), "final_frames": trace[-1]["frames_after"]} _OPENINGS = ( "一个进程按顺序访问如下虚拟页:{pages}。分给它的页框数为 {capacity}。", "请复核一次按需分页模拟。可用页框有 {capacity} 个,依次引用的页号为 {pages}。", "给定访存记录 {pages},系统给进程固定分配 {capacity} 个物理页框。", "在 {capacity} 个页框上重放这段页号日志(从左到右):{pages}。", ) _EVENT_FIELDS = ( "每步记录 step(从 1 起的步号)、page(访问页号)、hit(命中为 true,否则为 false)、" "evicted(被淘汰页,未淘汰为 null)和 frames_after(访问后按页框编号升序列出的页号,空位写 null)。" ) def _question(task, instance, rng): pages = "、".join(map(str, instance["pages"])) opening = rng.choice(_OPENINGS).format(pages=pages, capacity=instance["capacity"]) rules = ("初始页框全空,从 0 编号。访问驻留页算命中,其他访问均算缺页," "缺页先占用编号最小的空框,只有满框才淘汰。") if task == "full_trace": request = rng.choice(("请复原整个访问过程,", "请做一份可逐步核对的记录,")) request += "用 JSON 对象的 steps 字段给出全部步骤。" + _EVENT_FIELDS elif task == "checkpoint": t = instance["at_step"] request = rng.choice((f"只需给出第 {t} 次访问的记录。", f"请还原第 {t} 步刚结束时的这一步记录。")) request += "以一个 JSON 对象作答。" + _EVENT_FIELDS elif task == "window": a, b = instance["interval"] request = (f"从第 1 步开始模拟,只统计第 {a} 到第 {b} 步(两端均含)。" "用 JSON 给出命中步号列表 hit_steps、发生淘汰的步号列表 eviction_steps 以及缺页次数 faults。" "步号按整段日志从 1 计,列表按时间排序。") else: request = rng.choice(("请汇总这段记录。", "运行完这段访问后,给出汇总结果。")) request += ("用 JSON 给出命中次数 hits、缺页次数 faults、实际淘汰次数 evictions 和最终页框 final_frames" "(按页框编号升序,空位写 null)。") return opening + rules + RULES[instance["policy"]] + request def make_group(seed: int, split: str) -> tuple[str, list[dict]]: """Generate three siblings. The key ignores policy, capacity and page names. The seed fixes question style and content independently of split assignment. """ rng = Random(seed) family = rng.choice(FAMILIES) size = rng.randint(3, 10) capacity = rng.randint(1, min(6, size + 1)) pages = _workload(rng, family, size, rng.randint(8, 26)) normalized = {} key = ",".join(str(normalized.setdefault(page, len(normalized))) for page in pages) rows = [] for policy, task in zip(POLICIES, rng.sample(TASKS, k=len(POLICIES))): instance = dict(pages=pages.copy(), capacity=capacity, policy=policy) if task == "checkpoint": instance["at_step"] = rng.randint(1, len(pages)) elif task == "window": start = rng.randint(1, len(pages) - 1) instance["interval"] = [start, rng.randint(start + 1, len(pages))] trace = _trace(pages, capacity, policy) rows.append(dict(task=task, family=family, variant=policy, question=_question(task, instance, rng), instance=instance, answer=_answer(task, instance, trace), trace=trace)) return key, rows def verify(row: dict) -> None: """Replay via frame timestamps and backwards-computed next-use indices.""" instance = row["instance"] pages, cap, policy = instance["pages"], instance["capacity"], instance["policy"] if (not pages or type(cap) is not int or cap < 1 or policy not in POLICIES or any(type(p) is not int for p in pages) or row["variant"] != policy or len(row["trace"]) != len(pages)): raise ValueError("Invalid demand-paging instance or label count") future, next_use = {}, [len(pages)] * len(pages) for i in reversed(range(len(pages))): p = pages[i] next_use[i] = future.get(p, len(pages)) future[p] = i residents = {} # page -> (frame, inserted_at, last_access, next_access) hit_steps, eviction_steps, expected_steps = [], [], [] for i, page in enumerate(pages): step = i + 1 hit = page in residents victim = None if hit: frame, entered, _, _ = residents[page] hit_steps.append(step) else: entered = i if len(residents) == cap: if policy == "FIFO": victim = min(residents, key=lambda p: residents[p][1]) elif policy == "LRU": victim = min(residents, key=lambda p: residents[p][2]) else: victim = min(residents, key=lambda p: (-residents[p][3], residents[p][0])) frame = residents.pop(victim)[0] eviction_steps.append(step) else: frame = min(set(range(cap)) - {entry[0] for entry in residents.values()}) residents[page] = (frame, entered, i, next_use[i]) frames = [None] * cap for resident, entry in residents.items(): frames[entry[0]] = resident expected = dict(step=step, page=page, hit=hit, evicted=victim, frames_after=frames) actual = row["trace"][i] if expected != actual or type(actual.get("hit")) is not bool: raise ValueError(f"{policy} trace mismatch at step {step}") expected_steps.append(expected) task = row["task"] if task == "summary": target = dict(hits=len(hit_steps), faults=len(pages) - len(hit_steps), evictions=len(eviction_steps), final_frames=frames) elif task == "checkpoint": t = instance["at_step"] if type(t) is not int or not 1 <= t <= len(pages): raise ValueError("Invalid checkpoint") target = expected_steps[t - 1] elif task == "full_trace": target = {"steps": expected_steps} elif task == "window": a, b = instance["interval"] if type(a) is not int or type(b) is not int or not 1 <= a <= b <= len(pages): raise ValueError("Invalid window") hits = [s for s in hit_steps if a <= s <= b] target = dict(hit_steps=hits, eviction_steps=[s for s in eviction_steps if a <= s <= b], faults=b - a + 1 - len(hits)) else: raise ValueError(f"Unknown task {task}") if row["answer"] != target: raise ValueError(f"{policy} answer mismatch for {task}") def self_test() -> None: """Hand-checked policy ties, warm-up misses, partial residency and anomaly.""" pages = [1, 2, 1, 3, 2, 4] fixtures = { "FIFO": ([None, None, None, 1, None, 2], [3, 4]), "LRU": ([None, None, None, 2, 1, 3], [2, 4]), "OPT": ([None, None, None, 1, None, 3], [4, 2]), } for policy, (victims, final) in fixtures.items(): trace = _trace(pages, 2, policy) if [s["evicted"] for s in trace] != victims or trace[-1]["frames_after"] != final: raise AssertionError(f"Hand-worked {policy} trace failed") for task in TASKS: instance = dict(policy=policy, pages=pages, capacity=2, interval=[3, 5], at_step=4) verify(dict(instance=instance, trace=trace, answer=_answer(task, instance, trace), variant=policy, task=task)) anomaly = [1, 2, 3, 4, 1, 2, 5, 1, 2, 3, 4, 5] if [sum(not s["hit"] for s in _trace(anomaly, cap, "FIFO")) for cap in (3, 4)] != [9, 10]: raise AssertionError("Belady anomaly fixture failed") small = _trace([8, 8, 9], 4, "LRU") if _answer("summary", {}, small) != dict(hits=1, faults=2, evictions=0, final_frames=[8, 9, None, None]): raise AssertionError("Warm-up fixture failed")