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

Upload index.html with huggingface_hub

Browse files
Files changed (1) hide show
  1. index.html +54 -169
index.html CHANGED
@@ -259,185 +259,64 @@ problemSel.onchange = async () => {
259
 
260
  applyMode();
261
 
262
- // ===== Grading harness (closure-isolated) =====
263
- // The whole harness is built inside a factory function. Its state (oracle, bug
264
- // definitions, reasons) lives ONLY in closures held by the returned object, which
265
- // we keep solely as a JS-side proxy. Nothing is stored in Python globals(), so
266
- // student code (e.g. print(globals())) can never see the answer key.
267
- const HARNESS_FACTORY = `
268
- def __bb_make():
269
- import sys, types, linecache, ast, json, inspect
270
-
271
- # Block reading hidden source via inspect (defence in depth).
272
- _og = inspect.getsource
273
- def _guard(obj, *a, **k):
274
- if getattr(obj, "__module__", None) in (None, "blackbox", "blackbox_impl"):
275
- raise OSError("source code is not available")
276
- return _og(obj, *a, **k)
277
- inspect.getsource = _guard
278
- inspect.getsourcelines = lambda obj, *a, **k: (_ for _ in ()).throw(OSError("not available"))
279
-
280
- state = {} # captured in closures only; never placed in any global
281
-
282
- def install(public_name, source):
283
- ns = {}
284
- exec(compile(source, "blackbox_impl", "exec"), ns)
285
- combined = ns["blackbox"] # the 5-bug program students test
286
- ref = ns["reference"] # the correct spec oracle (kept hidden)
287
- bugs = ns["BUGS"] # name -> (single_bug_fn, marks) (hidden)
288
- reasons = ns.get("REASONS", {})
289
- for k in ("reference", "BUGS", "REASONS", "_b1", "_b2", "_b3", "_b4", "_b5"):
290
- ns.pop(k, None)
291
- linecache.cache.clear()
292
- # public wrapper: its __globals__ is this clean module, not the impl ns
293
- def _public(*a, **k):
294
- return combined(*a, **k)
295
- _public.__name__ = public_name
296
- sys.modules.pop("blackbox", None)
297
- pub = types.ModuleType("blackbox")
298
- setattr(pub, public_name, _public)
299
- sys.modules["blackbox"] = pub
300
- state.clear()
301
- state.update(fn=combined, ref=ref, bugs=bugs, reasons=reasons)
302
-
303
- def _s(v):
304
- return v if isinstance(v, str) else repr(v)
305
-
306
- def run(source, tests):
307
- fn = state["fn"]; ref = state["ref"]; BUGS = state["bugs"]; REASONS = state["reasons"]
308
- order = list(BUGS) # fixed bug numbering: order.index(name)+1
309
- linenos = {}
310
- try:
311
- tree = ast.parse(source)
312
- for node in ast.walk(tree):
313
- if isinstance(node, ast.Assign) and any(isinstance(t, ast.Name) and t.id == "TESTS" for t in node.targets):
314
- if isinstance(node.value, (ast.List, ast.Tuple)):
315
- for i, el in enumerate(node.value.elts):
316
- linenos[i] = el.lineno
317
- except Exception:
318
- pass
319
- if not isinstance(tests, (list, tuple)):
320
- return json.dumps({"ok": False, "error": "Define a list named TESTS = [ ((args), expected), ... ] -- one case per line."})
321
- caught = {}
322
- rows = []
323
- for i, case in enumerate(tests):
324
- line = linenos.get(i)
325
- try:
326
- args, expected = case
327
- args = tuple(args)
328
- except Exception:
329
- rows.append({"line": line, "status": "malformed", "raw": repr(case)})
330
- continue
331
- try:
332
- actual = fn(*args)
333
- except Exception as e:
334
- rows.append({"line": line, "status": "error", "argstr": repr(args), "msg": str(e)})
335
- continue
336
- spec = ref(*args)
337
- bug = None
338
- for name in BUGS:
339
- try:
340
- if BUGS[name][0](*args) != spec:
341
- bug = name; break
342
- except Exception:
343
- pass
344
- argstr = repr(args)
345
- valid_expected = (expected == spec)
346
- if actual != expected:
347
- if not valid_expected:
348
- rows.append({"line": line, "status": "invalid", "argstr": argstr,
349
- "expected": _s(expected), "spec": _s(spec)})
350
- else:
351
- if bug is None:
352
- bug = "(unknown)"
353
- num = order.index(bug) + 1 if bug in order else "?"
354
- first = bug not in caught
355
- if first:
356
- caught[bug] = line
357
- rows.append({"line": line, "status": "bug" if first else "dup",
358
- "bug": bug, "num": num, "total": len(BUGS),
359
- "reason": REASONS.get(bug, "output differs from the spec"),
360
- "argstr": argstr, "actual": _s(actual), "expected": _s(expected)})
361
- else:
362
- if not valid_expected:
363
- rows.append({"line": line, "status": "invalid", "argstr": argstr,
364
- "expected": _s(expected), "spec": _s(spec)})
365
- else:
366
- rows.append({"line": line, "status": "ok", "argstr": argstr, "actual": _s(actual)})
367
- return json.dumps({"ok": True, "rows": rows, "caught": list(caught.keys()),
368
- "caughtCount": len(caught), "totalBugs": len(BUGS), "numTests": len(tests)})
369
-
370
- class _H:
371
- pass
372
- h = _H()
373
- h.install = install
374
- h.run = run
375
- return h
376
-
377
- __bb_make()
378
- `;
379
 
380
- // ===== Decryption of the hidden .dat files =====
381
- // Must match PASSPHRASE in build_blackbox.py. NOTE: this only raises the bar --
382
- // the passphrase ships here, so a determined reader can still recover the source.
383
- const PASSPHRASE = "t2-unsw-bbt-v1-rotate-me";
384
- let __keyBytes = null;
385
- async function _sha256(bytes) {
386
- return new Uint8Array(await crypto.subtle.digest("SHA-256", bytes));
387
  }
388
- async function decryptDat(b64) {
389
- if (!__keyBytes) __keyBytes = await _sha256(new TextEncoder().encode(PASSPHRASE));
390
- const cipher = Uint8Array.from(atob(b64), (c) => c.charCodeAt(0));
391
- const out = new Uint8Array(cipher.length);
392
- const blk = new Uint8Array(__keyBytes.length + 8);
393
- blk.set(__keyBytes, 0);
394
- const dv = new DataView(blk.buffer);
395
- let counter = -1, ks = null;
396
- for (let off = 0; off < cipher.length; off++) {
397
- const c = Math.floor(off / 32);
398
- if (c !== counter) { counter = c; dv.setBigUint64(__keyBytes.length, BigInt(c), false); ks = await _sha256(blk); }
399
- out[off] = cipher[off] ^ ks[off % 32];
400
  }
401
- return new TextDecoder("utf-8").decode(out);
402
  }
403
 
404
- // ===== Load Pyodide + the hidden implementation =====
405
  let pyodide;
406
- let harness, bbInstall, bbRun; // JS-side proxies; harness state stays in closures
407
 
408
- // Fetch problem <key>'s encrypted source, decrypt it, and install it. Only the
409
- // public function is exposed as "blackbox"; the oracle/bugs/reasons stay in the closure.
410
  async function loadProblem(key) {
411
- if (!pyodide) return; // not ready yet; startup will load the current prob
412
- // no-store: never reuse a stale (e.g. pre-encryption) .dat from the browser cache
413
- const b64 = (await (await fetch(PROBLEMS[key].data, { cache: "no-store" })).text()).trim();
414
- const src = await decryptDat(b64);
415
- if (!src.includes("def blackbox") || /[\u0000-\u0008]/.test(src)) {
416
- throw new Error("Could not decrypt " + PROBLEMS[key].data + " — try a hard refresh (Cmd/Ctrl+Shift+R).");
417
- }
418
- bbInstall(PROBLEMS[key].public, src);
419
- modinfo.textContent = key + " · " + PROBLEMS[key].sig;
420
  }
421
 
 
422
  (async () => {
423
  try {
424
  pyodide = await loadPyodide({
425
  stdout: (s) => append(s + "\n"),
426
  stderr: (s) => append(s + "\n", "err"),
427
  });
428
-
429
- // Build the harness; keep its entry points only as JS proxies, then delete the
430
- // single global name so nothing about the harness remains in Python globals().
431
- harness = pyodide.runPython(HARNESS_FACTORY);
432
- pyodide.runPython("del __bb_make");
433
- bbInstall = harness.install;
434
- bbRun = harness.run;
435
-
436
- await loadProblem(prob); // load the currently selected problem
437
-
438
- statusEl.textContent = "✓ Ready";
439
- statusEl.className = "status ready";
440
- runBtn.disabled = false;
441
  } catch (e) {
442
  statusEl.textContent = "Failed to load";
443
  statusEl.className = "status error";
@@ -455,13 +334,19 @@ async function run() {
455
  const code = editor.getValue();
456
  try {
457
  if (mode === "test") {
458
- // Run the student's code in the (clean) main globals to define TESTS, then
459
- // grade via the closure proxy -- TESTS is passed in, nothing sensitive is shared.
 
460
  pyodide.runPython("globals().pop('TESTS', None)");
461
  await pyodide.runPythonAsync(code); // defines TESTS (and any prints)
462
- const tests = pyodide.globals.get("TESTS");
463
- const rep = JSON.parse(bbRun(code, tests === undefined ? null : tests));
464
- if (tests && typeof tests.destroy === "function") tests.destroy();
 
 
 
 
 
465
  renderReport(rep);
466
  } else {
467
  // Plain run: just execute and show output, no grading
@@ -493,7 +378,7 @@ function renderReport(rep) {
493
  } else if (r.status === "dup") {
494
  append(`· ${at}: catches bug #${r.num} again\n`, "meta");
495
  } else if (r.status === "invalid") {
496
- append(`⚠ ${at}: expected ${r.expected} does NOT match the spec (spec says ${r.spec}) — this test does not count\n`, "warn");
497
  } else if (r.status === "ok") {
498
  append(`· ${at}: program matches the spec (${r.actual}) — no bug here\n`, "meta");
499
  } else if (r.status === "malformed") {
 
259
 
260
  applyMode();
261
 
262
+ // ===== Grader Web Worker =====
263
+ // The answer key (oracle / bug definitions / reasons) lives in a SEPARATE Pyodide
264
+ // running inside grader.worker.js, on its own thread with its own memory. Student
265
+ // code runs in the main-thread Pyodide below and cannot reach into the worker:
266
+ // gc.get_objects(), closure reflection and print(globals()) only see this interpreter.
267
+ let grader = null, graderReady = false, mainReady = false;
268
+ let __msgId = 0;
269
+ const __pending = new Map();
270
+
271
+ function startGrader() {
272
+ grader = new Worker("grader.worker.js");
273
+ grader.onmessage = (e) => {
274
+ const d = e.data || {};
275
+ if (d.type === "ready") { graderReady = true; maybeReady(); return; }
276
+ if (d.type === "fatal") { append("Grader failed to load: " + d.error + "\n", "err"); return; }
277
+ const p = __pending.get(d.id);
278
+ if (!p) return;
279
+ __pending.delete(d.id);
280
+ if (d.ok) p.resolve(JSON.parse(d.report)); else p.reject(new Error(d.error));
281
+ };
282
+ grader.onerror = (e) => append("Grader worker error: " + (e.message || e) + "\n", "err");
283
+ }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
284
 
285
+ // Send a grading request to the worker and await its report.
286
+ function gradeViaWorker(problem, source, testsJson) {
287
+ return new Promise((resolve, reject) => {
288
+ const id = ++__msgId;
289
+ __pending.set(id, { resolve, reject });
290
+ grader.postMessage({ id, problem, source, tests: testsJson });
291
+ });
292
  }
293
+
294
+ function maybeReady() {
295
+ if (mainReady && graderReady) {
296
+ statusEl.textContent = "\u2713 Ready";
297
+ statusEl.className = "status ready";
298
+ runBtn.disabled = false;
 
 
 
 
 
 
299
  }
 
300
  }
301
 
302
+ // ===== Load Pyodide (main thread runs student code only -- no answer key here) =====
303
  let pyodide;
 
304
 
305
+ // Problem switch: just update the label. The worker loads the .dat lazily on first grade.
 
306
  async function loadProblem(key) {
307
+ modinfo.textContent = key + " \u00b7 " + PROBLEMS[key].sig;
 
 
 
 
 
 
 
 
308
  }
309
 
310
+ startGrader();
311
  (async () => {
312
  try {
313
  pyodide = await loadPyodide({
314
  stdout: (s) => append(s + "\n"),
315
  stderr: (s) => append(s + "\n", "err"),
316
  });
317
+ await loadProblem(prob);
318
+ mainReady = true;
319
+ maybeReady();
 
 
 
 
 
 
 
 
 
 
320
  } catch (e) {
321
  statusEl.textContent = "Failed to load";
322
  statusEl.className = "status error";
 
334
  const code = editor.getValue();
335
  try {
336
  if (mode === "test") {
337
+ // Run the student's code in the (clean) main interpreter to define TESTS,
338
+ // then send ONLY the TESTS data to the worker. The worker holds the answer
339
+ // key in its own interpreter; nothing sensitive lives in this one.
340
  pyodide.runPython("globals().pop('TESTS', None)");
341
  await pyodide.runPythonAsync(code); // defines TESTS (and any prints)
342
+ let testsJson;
343
+ try {
344
+ testsJson = pyodide.runPython("import json\njson.dumps(globals().get('TESTS'))");
345
+ } catch (se) {
346
+ append("\nYour TESTS contains values that can't be graded: " + cleanError(se.message || String(se)) + "\n", "err");
347
+ return;
348
+ }
349
+ const rep = await gradeViaWorker(prob, code, testsJson);
350
  renderReport(rep);
351
  } else {
352
  // Plain run: just execute and show output, no grading
 
378
  } else if (r.status === "dup") {
379
  append(`· ${at}: catches bug #${r.num} again\n`, "meta");
380
  } else if (r.status === "invalid") {
381
+ append(`⚠ ${at}: your expected ${r.expected} does NOT match the spec — this test does not count (program returned ${r.actual})\n`, "warn");
382
  } else if (r.status === "ok") {
383
  append(`· ${at}: program matches the spec (${r.actual}) — no bug here\n`, "meta");
384
  } else if (r.status === "malformed") {