-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkernelElectionProbe.html
More file actions
252 lines (235 loc) · 12.5 KB
/
Copy pathkernelElectionProbe.html
File metadata and controls
252 lines (235 loc) · 12.5 KB
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
<!DOCTYPE html>
<!--
Immortal Python Machine 실측. iframe 3개가 실제 독립 browsing context로 Web Locks 선출에
참여한다. leader context를 정상 leave 없이 제거하고, 마지막에는 모든 participant context를
제거한 뒤 새 context를 열어 OPFS의 힙 + /home 세대와 영속 epoch를 복구한다.
-->
<html lang="ko">
<head><meta charset="utf-8"><title>probe: immortal Python machine</title>
<style>body{font:14px/1.5 system-ui;margin:2rem;max-width:58rem} pre{background:#f4f4f5;padding:1rem;border-radius:6px;white-space:pre-wrap}</style></head>
<body>
<h1>probe: Immortal Python Machine</h1>
<pre id="out">실행 중...</pre>
<div id="tabs"></div>
<script type="module">
const out = document.getElementById("out");
const checks = [];
const timings = {};
const check = (name, pass, info = "") => {
checks.push({ name, pass: !!pass, info: String(info) });
out.textContent += `\n${pass ? "PASS" : "FAIL"} ${name}${info ? " (" + info + ")" : ""}`;
};
const report = async () => {
const ok = checks.length > 0 && checks.every((entry) => entry.pass);
try {
await fetch("/gateReport", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ ok, checks, timings }),
});
} catch (error) {}
};
const indexParam = new URLSearchParams(location.search).get("indexURL");
const query = indexParam ? "?indexURL=" + encodeURIComponent(indexParam) : "";
const machineName = "immortalProbe";
const journalName = "pyprocImmortalProbe";
const tabs = new Map();
const statuses = new Map();
const statusEvents = [];
let sequence = 0;
window.addEventListener("message", (event) => {
const message = event.data;
if (!message || message.from !== "kernelTab") return;
if (message.event === "status") {
statuses.set(message.id, message.status);
statusEvents.push({ id: message.id, status: message.status, time: performance.now() });
return;
}
if (message.reqId != null) {
for (const tab of tabs.values()) {
const pending = tab.pending.get(message.reqId);
if (!pending) continue;
tab.pending.delete(message.reqId);
if (message.ok) pending.resolve(message);
else {
const error = new Error(message.error);
error.code = message.code;
error.retryable = message.retryable;
error.status = message.status;
pending.reject(error);
}
break;
}
}
});
function makeTab(tabId) {
return new Promise((resolve) => {
const frame = document.createElement("iframe");
frame.style.width = frame.style.height = "1px";
const pending = new Map();
tabs.set(tabId, { frame, pending });
const onReady = (event) => {
if (event.data?.from !== "kernelTab" || event.data.event !== "ready" || event.source !== frame.contentWindow) return;
window.removeEventListener("message", onReady);
resolve();
};
window.addEventListener("message", onReady);
frame.src = "kernelTab.html" + query;
document.getElementById("tabs").appendChild(frame);
});
}
function command(tabId, payload) {
const tab = tabs.get(tabId);
if (!tab) return Promise.reject(new Error("no tab " + tabId));
const reqId = "r" + (++sequence);
return new Promise((resolve, reject) => {
tab.pending.set(reqId, { resolve, reject });
tab.frame.contentWindow.postMessage({ to: "kernelTab", tabId, reqId, ...payload }, "*");
});
}
const waitFor = async (predicate, timeoutMs, stepMs = 50) => {
const deadline = performance.now() + timeoutMs;
while (performance.now() < deadline) {
const value = predicate();
if (value) return value;
await new Promise((resolve) => setTimeout(resolve, stepMs));
}
return null;
};
const percentile = (values, ratio) => {
const sorted = values.slice().sort((a, b) => a - b);
return +sorted[Math.min(sorted.length - 1, Math.floor(sorted.length * ratio))].toFixed(2);
};
const removeTab = (tabId) => {
const tab = tabs.get(tabId);
if (!tab) return;
tab.frame.remove();
tabs.delete(tabId);
statuses.delete(tabId);
};
try {
const root = await navigator.storage.getDirectory();
try { await root.removeEntry(journalName, { recursive: true }); } catch (error) {}
const initialStarted = performance.now();
await Promise.all([makeTab("A"), makeTab("B"), makeTab("C")]);
const joined = await Promise.all(["A", "B", "C"].map((id) => command(id, {
cmd: "join", name: machineName, journalName, tabId: id,
})));
timings.initialReadyMs = Math.round(performance.now() - initialStarted);
const initialStatuses = joined.map((entry) => entry.status);
const initialLeader = initialStatuses.find((status) => status.role === "leader");
const leaderId = initialLeader?.leaderId;
const initialEpoch = initialLeader?.epoch;
const followers = ["A", "B", "C"].filter((id) => id !== leaderId);
timings.leaderBootMs = initialLeader?.bootMs ?? -1;
const sameIdentity = initialStatuses.every((status) =>
status.name === machineName && status.leaderId === leaderId && status.epoch === initialEpoch && status.phase === "ready"
);
check("3 browsing contexts, exactly one leader, shared identity", initialStatuses.filter((status) => status.role === "leader").length === 1 && sameIdentity,
`leader=${leaderId}, epoch=${initialEpoch}, ready=${timings.initialReadyMs}ms`);
check("canonical kernel keeps COI, SAB lane and JSPI", initialStatuses.every((status) => status.crossOriginIsolated && status.jspi),
`coi=${initialLeader?.crossOriginIsolated}, jspi=${initialLeader?.jspi}`);
await command(followers[0], { cmd: "run", code: [
"import os",
"os.makedirs('/home/web/immortal', exist_ok=True)",
"sharedValue = 41",
"open('/home/web/immortal/state.txt', 'w').write('survives')",
].join("\n") });
const shared = await command(followers[1], {
cmd: "run",
code: "f'{sharedValue + 1}|{open(\"/home/web/immortal/state.txt\").read()}|{preparedValue}|' + json.dumps({'lane': 'prepared'}, sort_keys=True)",
});
const collisionPair = await Promise.all([
command(followers[0], { cmd: "run", code: "'participant-left'" }),
command(followers[1], { cmd: "run", code: "'participant-right'" }),
]);
check("followers share variables, /home, prepared environment and collision-free request IDs",
shared.result === '42|survives|7|{"lane": "prepared"}' &&
collisionPair[0].result === "participant-left" && collisionPair[1].result === "participant-right",
`${shared.result} | ${collisionPair.map((entry) => entry.result).join("/")}`);
const rpcSamples = [];
for (let i = 0; i < 30; i++) {
const started = performance.now();
await command(followers[0], { cmd: "run", code: "1 + 1" });
rpcSamples.push(performance.now() - started);
}
timings.rpcP50Ms = percentile(rpcSamples, 0.5);
timings.rpcP90Ms = percentile(rpcSamples, 0.9);
const lateOutcome = await command(followers[0], {
cmd: "run", code: "import asyncio\nawait asyncio.sleep(0.2)\n'late-response'", async: true, timeoutMs: 50,
}).then((result) => ({ ok: true, result }), (error) => ({ ok: false, error }));
await new Promise((resolve) => setTimeout(resolve, 300));
const afterLate = await command(followers[1], { cmd: "run", code: "40 + 3" });
check("participant RPC stays below 3ms p50 and ignores a late response after timeout",
timings.rpcP50Ms < 3 && lateOutcome.ok === false && lateOutcome.error.code === "PYPROC_RPC_OUTCOME_UNKNOWN" && afterLate.result === 43,
`p50=${timings.rpcP50Ms}ms, p90=${timings.rpcP90Ms}ms, late=${lateOutcome.ok ? "unexpected" : lateOutcome.error.code}`);
const commit = await command(followers[0], { cmd: "commit", timeoutMs: 12000 });
check("follower commit durably seals heap and /home", !!commit.commit?.committedAt && commit.commit?.home?.files === 1,
`pages=${commit.commit?.pages}, homeFiles=${commit.commit?.home?.files}`);
const uncertainRequest = command(followers[0], {
cmd: "run",
code: "import asyncio\nawait asyncio.sleep(10)\nuncertainCount = globals().get('uncertainCount', 0) + 1\nuncertainCount",
async: true,
timeoutMs: 7000,
}).then((result) => ({ ok: true, result }), (error) => ({ ok: false, error }));
await waitFor(() => statuses.get(followers[0])?.pendingRequests === 1, 2000);
const killAt = performance.now();
removeTab(leaderId);
const promoted = await waitFor(() => statusEvents.find((entry) =>
entry.time >= killAt && entry.status.phase === "ready" && entry.status.epoch > initialEpoch && entry.status.leaderId !== leaderId
), 7000);
timings.failoverMs = promoted ? Math.round(promoted.time - killAt) : -1;
const promotedStatus = promoted?.status;
const newLeaderId = promotedStatus?.leaderId;
const survivorIds = followers.filter((id) => tabs.has(id));
const survivorStatuses = await Promise.all(survivorIds.map((id) => command(id, { cmd: "status" })));
check("forced leader context removal elects one fenced successor", !!promotedStatus && timings.failoverMs < 5000 &&
survivorStatuses.filter((entry) => entry.status.role === "leader").length === 1 && promotedStatus.epoch === initialEpoch + 1,
`leader=${newLeaderId}, epoch=${promotedStatus?.epoch}, failover=${timings.failoverMs}ms`);
timings.recoveryMs = promotedStatus?.recoveryMs ?? -1;
check("successor reports journal recovery", promotedStatus?.recovered === true, `recovery=${timings.recoveryMs}ms`);
const afterFailover = await command(survivorIds[0], {
cmd: "run",
code: "f'{sharedValue}|{open(\"/home/web/immortal/state.txt\").read()}|{preparedValue}|' + json.dumps({'lane': 'prepared'}, sort_keys=True)",
timeoutMs: 9000,
});
check("failover restores variable, /home and prepared environment, then keeps running",
afterFailover.result === '41|survives|7|{"lane": "prepared"}', afterFailover.result);
const uncertain = await uncertainRequest;
const uncertainStatus = await command(followers[0], { cmd: "status" });
check("in-flight failover RPC has explicit non-retryable unknown outcome and no leak",
uncertain.ok === false && uncertain.error.code === "PYPROC_RPC_OUTCOME_UNKNOWN" && uncertain.error.retryable === false && uncertainStatus.status.pendingRequests === 0,
uncertain.ok ? "unexpected success" : `${uncertain.error.code}, pending=${uncertainStatus.status.pendingRequests}`);
const uncertainValue = await command(survivorIds[1], { cmd: "run", code: "globals().get('uncertainCount', 0)" });
check("unknown-outcome request is not auto-replayed on successor", uncertainValue.result === 0, `uncertainCount=${uncertainValue.result}`);
await command(survivorIds[0], { cmd: "run", code: [
"coldValue = 99",
"open('/home/web/immortal/state.txt', 'w').write('cold-survives')",
].join("\n") });
const coldCommit = await command(survivorIds[1], { cmd: "commit", timeoutMs: 12000 });
const coldEpoch = coldCommit.status.epoch;
for (const id of survivorIds) removeTab(id);
const reopenStarted = performance.now();
await makeTab("D");
const reopened = await command("D", { cmd: "join", name: machineName, journalName, tabId: "D" });
timings.coldReopenMs = Math.round(performance.now() - reopenStarted);
const reopenedValue = await command("D", {
cmd: "run",
code: "f'{sharedValue}|{coldValue}|{open(\"/home/web/immortal/state.txt\").read()}|{preparedValue}|' + json.dumps({'lane': 'prepared'}, sort_keys=True)",
});
check("all participants gone, new context cold-reopens last commit", reopened.status.role === "leader" && reopened.status.recovered === true &&
reopened.status.epoch === coldEpoch + 1 && reopenedValue.result === '41|99|cold-survives|7|{"lane": "prepared"}',
`epoch=${reopened.status.epoch}, value=${reopenedValue.result}, ${timings.coldReopenMs}ms`);
check("durable epoch, leader identity and commit time are observable", reopened.status.leaderId === "D" &&
reopened.status.participantId === "D" && reopened.status.lastCommitAt === coldCommit.commit.committedAt,
`leader=${reopened.status.leaderId}, committedAt=${reopened.status.lastCommitAt}`);
await command("D", { cmd: "leave" });
removeTab("D");
await root.removeEntry(journalName, { recursive: true });
} catch (error) {
check("uncaught", false, String(error.stack || error).slice(-500));
for (const id of [...tabs.keys()]) removeTab(id);
}
await report();
</script>
</body></html>