sh1k4ku commited on
Commit
8234d96
·
verified ·
1 Parent(s): 2ba5b44

Upload grader.worker.js with huggingface_hub

Browse files
Files changed (1) hide show
  1. grader.worker.js +191 -0
grader.worker.js ADDED
@@ -0,0 +1,191 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // ===========================================================================
2
+ // Grader Web Worker — runs its OWN Pyodide, holds the hidden answer key.
3
+ //
4
+ // The oracle / bug definitions / reasons live in THIS worker's Python
5
+ // interpreter, in a separate thread with separate memory. The student's code
6
+ // runs in the main-thread Pyodide and cannot reach into here: gc.get_objects(),
7
+ // closure reflection and print(globals()) only see the student's own interpreter.
8
+ //
9
+ // The worker receives {problem, source, tests(JSON)} and returns a JSON report.
10
+ // Student code never executes here — only their TESTS *data* crosses the boundary.
11
+ // ===========================================================================
12
+ const PYODIDE_INDEX = "https://cdn.jsdelivr.net/pyodide/v0.26.2/full/";
13
+ importScripts(PYODIDE_INDEX + "pyodide.js");
14
+
15
+ const PROBLEMS = {
16
+ Q1: { data: "q1.dat", public: "allocate" },
17
+ Q2: { data: "q2.dat", public: "approve" },
18
+ };
19
+
20
+ // ----- Decryption (must match build_blackbox.py / PASSPHRASE) -----
21
+ const PASSPHRASE = "t2-unsw-bbt-v1-rotate-me";
22
+ let __keyBytes = null;
23
+ async function _sha256(bytes) {
24
+ return new Uint8Array(await crypto.subtle.digest("SHA-256", bytes));
25
+ }
26
+ async function decryptDat(b64) {
27
+ if (!__keyBytes) __keyBytes = await _sha256(new TextEncoder().encode(PASSPHRASE));
28
+ const cipher = Uint8Array.from(atob(b64), (c) => c.charCodeAt(0));
29
+ const out = new Uint8Array(cipher.length);
30
+ const blk = new Uint8Array(__keyBytes.length + 8);
31
+ blk.set(__keyBytes, 0);
32
+ const dv = new DataView(blk.buffer);
33
+ let counter = -1, ks = null;
34
+ for (let off = 0; off < cipher.length; off++) {
35
+ const c = Math.floor(off / 32);
36
+ if (c !== counter) { counter = c; dv.setBigUint64(__keyBytes.length, BigInt(c), false); ks = await _sha256(blk); }
37
+ out[off] = cipher[off] ^ ks[off % 32];
38
+ }
39
+ return new TextDecoder("utf-8").decode(out);
40
+ }
41
+
42
+ // ----- The grading harness (closure-isolated; identical to the verified one) -----
43
+ const HARNESS_FACTORY = `
44
+ def __bb_make():
45
+ import sys, types, linecache, ast, json, inspect
46
+
47
+ _og = inspect.getsource
48
+ def _guard(obj, *a, **k):
49
+ if getattr(obj, "__module__", None) in (None, "blackbox", "blackbox_impl"):
50
+ raise OSError("source code is not available")
51
+ return _og(obj, *a, **k)
52
+ inspect.getsource = _guard
53
+ inspect.getsourcelines = lambda obj, *a, **k: (_ for _ in ()).throw(OSError("not available"))
54
+
55
+ state = {}
56
+
57
+ def install(public_name, source):
58
+ ns = {}
59
+ exec(compile(source, "blackbox_impl", "exec"), ns)
60
+ combined = ns["blackbox"]
61
+ ref = ns["reference"]
62
+ bugs = ns["BUGS"]
63
+ reasons = ns.get("REASONS", {})
64
+ for k in ("reference", "BUGS", "REASONS", "_b1", "_b2", "_b3", "_b4", "_b5"):
65
+ ns.pop(k, None)
66
+ linecache.cache.clear()
67
+ def _public(*a, **k):
68
+ return combined(*a, **k)
69
+ _public.__name__ = public_name
70
+ sys.modules.pop("blackbox", None)
71
+ pub = types.ModuleType("blackbox")
72
+ setattr(pub, public_name, _public)
73
+ sys.modules["blackbox"] = pub
74
+ state.clear()
75
+ state.update(fn=combined, ref=ref, bugs=bugs, reasons=reasons)
76
+
77
+ def _s(v):
78
+ return v if isinstance(v, str) else repr(v)
79
+
80
+ def run(source, tests):
81
+ fn = state["fn"]; ref = state["ref"]; BUGS = state["bugs"]; REASONS = state["reasons"]
82
+ order = list(BUGS)
83
+ linenos = {}
84
+ try:
85
+ tree = ast.parse(source)
86
+ for node in ast.walk(tree):
87
+ if isinstance(node, ast.Assign) and any(isinstance(t, ast.Name) and t.id == "TESTS" for t in node.targets):
88
+ if isinstance(node.value, (ast.List, ast.Tuple)):
89
+ for i, el in enumerate(node.value.elts):
90
+ linenos[i] = el.lineno
91
+ except Exception:
92
+ pass
93
+ if not isinstance(tests, (list, tuple)):
94
+ return json.dumps({"ok": False, "error": "Define a list named TESTS = [ ((args), expected), ... ] -- one case per line."})
95
+ caught = {}
96
+ rows = []
97
+ for i, case in enumerate(tests):
98
+ line = linenos.get(i)
99
+ try:
100
+ args, expected = case
101
+ args = tuple(args)
102
+ except Exception:
103
+ rows.append({"line": line, "status": "malformed", "raw": repr(case)})
104
+ continue
105
+ try:
106
+ actual = fn(*args)
107
+ except Exception as e:
108
+ rows.append({"line": line, "status": "error", "argstr": repr(args), "msg": str(e)})
109
+ continue
110
+ spec = ref(*args)
111
+ bug = None
112
+ for name in BUGS:
113
+ try:
114
+ if BUGS[name][0](*args) != spec:
115
+ bug = name; break
116
+ except Exception:
117
+ pass
118
+ argstr = repr(args)
119
+ valid_expected = (expected == spec)
120
+ if actual != expected:
121
+ if not valid_expected:
122
+ rows.append({"line": line, "status": "invalid", "argstr": argstr,
123
+ "expected": _s(expected), "actual": _s(actual)})
124
+ else:
125
+ if bug is None:
126
+ bug = "(unknown)"
127
+ num = order.index(bug) + 1 if bug in order else "?"
128
+ first = bug not in caught
129
+ if first:
130
+ caught[bug] = line
131
+ rows.append({"line": line, "status": "bug" if first else "dup",
132
+ "bug": bug, "num": num, "total": len(BUGS),
133
+ "reason": REASONS.get(bug, "output differs from the spec"),
134
+ "argstr": argstr, "actual": _s(actual), "expected": _s(expected)})
135
+ else:
136
+ if not valid_expected:
137
+ rows.append({"line": line, "status": "invalid", "argstr": argstr,
138
+ "expected": _s(expected), "actual": _s(actual)})
139
+ else:
140
+ rows.append({"line": line, "status": "ok", "argstr": argstr, "actual": _s(actual)})
141
+ return json.dumps({"ok": True, "rows": rows, "caught": list(caught.keys()),
142
+ "caughtCount": len(caught), "totalBugs": len(BUGS), "numTests": len(tests)})
143
+
144
+ class _H:
145
+ pass
146
+ h = _H()
147
+ h.install = install
148
+ h.run = run
149
+ return h
150
+
151
+ __bb_make()
152
+ `;
153
+
154
+ let pyodide, harness, bbInstall, bbRun, installed = null;
155
+
156
+ async function init() {
157
+ pyodide = await loadPyodide({ indexURL: PYODIDE_INDEX });
158
+ harness = pyodide.runPython(HARNESS_FACTORY);
159
+ pyodide.runPython("del __bb_make");
160
+ bbInstall = harness.install;
161
+ bbRun = harness.run;
162
+ postMessage({ type: "ready" });
163
+ }
164
+ const ready = init().catch((e) => postMessage({ type: "fatal", error: String(e) }));
165
+
166
+ async function ensureProblem(key) {
167
+ if (installed === key) return;
168
+ const b64 = (await (await fetch(PROBLEMS[key].data, { cache: "no-store" })).text()).trim();
169
+ const src = await decryptDat(b64);
170
+ if (!src.includes("def blackbox") || !src.includes("def reference")) {
171
+ throw new Error("Could not decrypt " + PROBLEMS[key].data);
172
+ }
173
+ bbInstall(PROBLEMS[key].public, src);
174
+ installed = key;
175
+ }
176
+
177
+ onmessage = async (e) => {
178
+ const { id, problem, source, tests } = e.data;
179
+ try {
180
+ await ready;
181
+ await ensureProblem(problem);
182
+ pyodide.globals.set("__tests_json", tests);
183
+ const testsPy = pyodide.runPython("import json\njson.loads(__tests_json)");
184
+ const report = bbRun(source, testsPy);
185
+ if (testsPy && typeof testsPy.destroy === "function") testsPy.destroy();
186
+ pyodide.runPython("del __tests_json");
187
+ postMessage({ id, ok: true, report });
188
+ } catch (err) {
189
+ postMessage({ id, ok: false, error: String((err && err.message) || err) });
190
+ }
191
+ };