From 9ea1ef2632de8a5c3e3efc8671bb991c22bb629b Mon Sep 17 00:00:00 2001 From: Aikhan Jumashukurov <117706338+aikhanj@users.noreply.github.com> Date: Thu, 5 Nov 2026 20:36:18 -0500 Subject: [PATCH] Add a bounded C++ and WebAssembly schedule solver --- .github/workflows/ci.yml | 4 + app/.gitignore | 1 + app/package.json | 5 +- app/scripts/bench-solver.ts | 76 +++++++ app/scripts/build-solver.mjs | 76 +++++++ app/scripts/test-solver-native.mjs | 31 +++ app/solver/README.md | 80 +++++++ app/solver/native-test.cpp | 39 ++++ app/solver/schedule.cpp | 214 +++++++++++++++++++ app/src/client/scheduling/engine.ts | 281 +++++++++++++++++++++++++ app/src/client/scheduling/junction.ts | 170 +++++++++++++++ app/src/client/scheduling/model.ts | 73 +++++++ app/src/client/scheduling/solver.wasm | Bin 0 -> 6077 bytes app/tests/fixtures/semester.ts | 126 ++++++++++++ app/tests/scheduling.test.ts | 286 ++++++++++++++++++++++++++ 15 files changed, 1461 insertions(+), 1 deletion(-) create mode 100644 app/scripts/bench-solver.ts create mode 100644 app/scripts/build-solver.mjs create mode 100644 app/scripts/test-solver-native.mjs create mode 100644 app/solver/README.md create mode 100644 app/solver/native-test.cpp create mode 100644 app/solver/schedule.cpp create mode 100644 app/src/client/scheduling/engine.ts create mode 100644 app/src/client/scheduling/junction.ts create mode 100644 app/src/client/scheduling/model.ts create mode 100755 app/src/client/scheduling/solver.wasm create mode 100644 app/tests/fixtures/semester.ts create mode 100644 app/tests/scheduling.test.ts diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 933bb19..1586733 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -22,6 +22,10 @@ jobs: - run: npm ci - run: cp .dev.vars.example .dev.vars - run: npx wrangler types + - run: sudo apt-get update && sudo apt-get install -y clang lld + working-directory: . + - run: npm run build:solver + - run: npm run test:solver-native - run: npm run typecheck - run: npm test - run: npm run build diff --git a/app/.gitignore b/app/.gitignore index 8694df6..ebb74cf 100644 --- a/app/.gitignore +++ b/app/.gitignore @@ -3,3 +3,4 @@ dist .dev.vars .wrangler worker-configuration.d.ts +.artifacts diff --git a/app/package.json b/app/package.json index 6c592d2..485bb09 100644 --- a/app/package.json +++ b/app/package.json @@ -9,7 +9,10 @@ "build": "vite build", "deploy": "vite build && wrangler deploy -c dist/pi/wrangler.json", "typecheck": "tsc --noEmit", - "test": "tsx --test tests/*.test.ts" + "test": "tsx --test tests/*.test.ts", + "build:solver": "node scripts/build-solver.mjs", + "test:solver-native": "node scripts/test-solver-native.mjs", + "bench:solver": "tsx scripts/bench-solver.ts" }, "dependencies": { "@ai-sdk/anthropic": "^4.0.0", diff --git a/app/scripts/bench-solver.ts b/app/scripts/bench-solver.ts new file mode 100644 index 0000000..2b83795 --- /dev/null +++ b/app/scripts/bench-solver.ts @@ -0,0 +1,76 @@ +import assert from "node:assert/strict"; +import { createHash } from "node:crypto"; +import { readFile } from "node:fs/promises"; +import { cpus } from "node:os"; +import { createSolver } from "../src/client/scheduling/engine.ts"; +import { DEFAULT_CONSTRAINTS } from "../src/client/scheduling/model.ts"; +import { impossible, semester } from "../tests/fixtures/semester.ts"; + +const bytes = await readFile( + new URL("../src/client/scheduling/solver.wasm", import.meta.url), +); +const source = await readFile(new URL("../solver/schedule.cpp", import.meta.url)); +const engine = await createSolver(bytes); +const warmup = 100; +const samples = 1000; +const constraints = { ...DEFAULT_CONSTRAINTS, earliest: 600, latest: 1440 }; +const workloads = [ + { name: "compact semester", problem: semester, constraints }, + { + name: "compact semester with Friday free", + problem: semester, + constraints: { ...constraints, offDays: 16 }, + }, + { + name: "three groups in two slots", + problem: impossible, + constraints: { ...DEFAULT_CONSTRAINTS, earliest: 0, latest: 1440 }, + }, +]; + +const results = workloads.map(({ name, problem, constraints }) => { + const expected = engine.solve(problem, constraints); + assert.equal(expected.status, problem === impossible ? "infeasible" : "optimal"); + for (let i = 0; i < warmup; i++) engine.solve(problem, constraints); + const durations: number[] = []; + let checksum = 0; + for (let i = 0; i < samples; i++) { + const start = performance.now(); + const result = engine.solve(problem, constraints); + durations.push(performance.now() - start); + // Consume and validate outside the timed interval. + assert.equal(result.status, expected.status); + assert.deepEqual(result.plans, expected.plans); + checksum += result.nodes + result.plans.reduce((sum, plan) => sum + plan.score, 0); + } + durations.sort((a, b) => a - b); + const percentile = (p: number) => durations[Math.ceil(p * samples) - 1]; + return { + name, + groups: problem.groups.length, + options: problem.groups.reduce((sum, group) => sum + group.options.length, 0), + status: expected.status, + plans: expected.plans.length, + nodes: expected.nodes, + medianMs: (durations[samples / 2 - 1] + durations[samples / 2]) / 2, + p95Ms: percentile(0.95), + minMs: durations[0], + maxMs: durations[samples - 1], + checksum, + }; +}); + +console.log(JSON.stringify({ + node: process.versions.node, + platform: process.platform, + architecture: process.arch, + cpu: cpus()[0]?.model, + wasmSha256: createHash("sha256").update(bytes).digest("hex"), + sourceSha256: createHash("sha256").update(source).digest("hex"), + warmup, + samples, + boundary: "Warm engine.solve including JS validation, encoding, Wasm, and decoding", + excludes: "Compilation, instantiation, workers, conflict diagnosis, rendering", + limitations: "Repeated synthetic fixtures. No production tail-latency or speedup claim.", + results, +}, null, 2)); diff --git a/app/scripts/build-solver.mjs b/app/scripts/build-solver.mjs new file mode 100644 index 0000000..979fe45 --- /dev/null +++ b/app/scripts/build-solver.mjs @@ -0,0 +1,76 @@ +import { execFileSync } from "node:child_process"; +import { existsSync, mkdirSync, mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { dirname, join, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; + +const root = resolve(dirname(fileURLToPath(import.meta.url)), ".."); +const compiler = + process.env.WASM_CXX || + (existsSync("/opt/homebrew/opt/llvm/bin/clang++") + ? "/opt/homebrew/opt/llvm/bin/clang++" + : "clang++"); +let linker = process.env.WASM_LD || "wasm-ld"; +if (!process.env.WASM_LD && process.platform === "darwin") { + try { + const sysroot = execFileSync("rustc", ["--print", "sysroot"], { + encoding: "utf8", + }).trim(); + const candidate = join( + sysroot, + "lib/rustlib/aarch64-apple-darwin/bin/gcc-ld/wasm-ld", + ); + if (existsSync(candidate)) linker = candidate; + } catch { + /* Use PATH when no Rust toolchain is installed. */ + } +} +const temporary = mkdtempSync(join(tmpdir(), "pi-solver-")); +try { + const object = join(temporary, "schedule.o"); + execFileSync( + compiler, + [ + "--target=wasm32", + "-std=c++17", + "-O3", + "-Wall", + "-Wextra", + "-Werror", + "-ffreestanding", + "-fno-exceptions", + "-fno-rtti", + "-fno-builtin", + "-c", + join(root, "solver/schedule.cpp"), + "-o", + object, + ], + { stdio: "inherit" }, + ); + const target = join(root, "src/client/scheduling/solver.wasm"); + mkdirSync(dirname(target), { recursive: true }); + execFileSync( + linker, + [ + "--no-entry", + "--export=solver_input", + "--export=solver_output", + "--export=solver_capacity", + "--export=solver_run", + "--export-memory", + "--initial-memory=524288", + "--max-memory=524288", + "-z", + "stack-size=65536", + "--strip-all", + object, + "-o", + target, + ], + { stdio: "inherit" }, + ); + console.log("Built solver.wasm from solver/schedule.cpp"); +} finally { + rmSync(temporary, { recursive: true, force: true }); +} diff --git a/app/scripts/test-solver-native.mjs b/app/scripts/test-solver-native.mjs new file mode 100644 index 0000000..03e9fd6 --- /dev/null +++ b/app/scripts/test-solver-native.mjs @@ -0,0 +1,31 @@ +import { execFileSync } from "node:child_process"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { dirname, join, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; +const root = resolve(dirname(fileURLToPath(import.meta.url)), ".."); +const folder = mkdtempSync(join(tmpdir(), "pi-native-test-")); +try { + const binary = join(folder, "test"); + execFileSync( + process.env.CXX || "clang++", + [ + "-std=c++17", + "-O1", + "-g", + "-Wall", + "-Wextra", + "-Werror", + "-pedantic", + "-fsanitize=address,undefined", + "-fno-omit-frame-pointer", + join(root, "solver/native-test.cpp"), + "-o", + binary, + ], + { stdio: "inherit" }, + ); + execFileSync(binary, [], { stdio: "inherit" }); +} finally { + rmSync(folder, { recursive: true, force: true }); +} diff --git a/app/solver/README.md b/app/solver/README.md new file mode 100644 index 0000000..2ad3661 --- /dev/null +++ b/app/solver/README.md @@ -0,0 +1,80 @@ +# Semester Lab engine + +`schedule.cpp` is a freestanding C++17 finite-domain solver compiled to +WebAssembly. It has no allocator, WASI dependency, network calls, or JavaScript +imports. A TypeScript adapter validates inputs and decodes ranked answers. + +Each section group requires one option. An option can have several meetings. +Hard constraints are nonoverlapping meetings, earliest start, latest finish, +free days, protected intervals, section locks, and listed section availability. +Canceled sections are always excluded. Closed sections require an explicit toggle. + +The engine precomputes option-conflict bitsets, searches the most constrained +remaining group, and keeps the best three assignments. Branch-and-bound uses only +monotonic lower bounds. In particular, partial gap minutes are not a valid lower +bound because inserting another class can shrink a gap. + +Ranking is deterministic. Compact minimizes gap minutes plus 30 per active day. +Fewest changes first minimizes deviations from explicitly selected sections, +then gaps. Latest start first maximizes the earliest meeting across the week, +then minimizes gaps. Exact score ties use input option order. With at most seven +days, the 20,000 weight makes the latter objectives lexicographic. + +Results distinguish an exhaustive top-three ranking, proved infeasibility, and +an unfinished search. A finite node budget never becomes a claim of infeasibility. +Conflict explanations remove section groups and test the reduced problems. Unknown +subproblems are retained. Suggested relaxations are returned only after a full +assignment was actually found under that relaxation. + +## Build and verify + +Install LLVM clang with the wasm32 backend and `wasm-ld`. Apple clang does not +include that backend. On macOS the build script also recognizes Homebrew LLVM +and the wasm linker shipped with a Rust toolchain. `WASM_CXX` and `WASM_LD` can +select explicit paths. The native sanitizer test uses `CXX` or `clang++`. + +``` +npm run build:solver +npm run test:solver-native +npm test +npx wrangler types +npm run typecheck +npm run build +``` + +The small generated `src/client/scheduling/solver.wasm` is included so ordinary +builds need no extra compiler. CI rebuilds it from source before +testing. The native suite exercises malformed inputs under ASan/UBSan. The Wasm +suite compares actual ranked answers against a separate exhaustive oracle on 300 +seeded problems and a larger presentation fixture. + +## Data boundaries + +The Junction adapter accepts the `get_schedule_details` payload. It uses +original section rows instead of the calendar's merged display data. +Sections sharing a title retain all their meetings, and distinct section titles +are kept even when they meet at the same time. Missing times, unknown availability, +missing courses, or inconsistent records fail explicitly. + +Completeness is relative to the supplied groups. The current Junction payload +does not expose linked-section restrictions, prerequisites, travel time, or +registration eligibility. These are not checked. Availability is a snapshot, +not a seat reservation. The engine and adapter do not write to Junction or +register courses. +Real account integration and deployment require separate live validation. + +Limits are 32 groups, 512 options, 2,048 meetings, 64 protected intervals, and +200,000 search nodes per interactive solve. Native input validation rejects +out-of-range indices and lengths before reading records. The Wasm +memory is fixed at 512 KiB. + +## Reproduce the warm solve measurement + +Run `npm run bench:solver` after building the solver. It prints the Node version, +CPU, Wasm and C++ source hashes, input sizes, warmup and sample counts, and median +and p95 duration of individual `engine.solve` calls. The timed boundary includes +JavaScript validation, encoding, the Wasm solver, and result decoding. It excludes +module compilation and instantiation, workers, conflict diagnosis, and rendering. +The fixtures are synthetic and repeated in a warm process. These measurements +do not establish browser interaction latency, production tail latency, a speedup +over another solver, or worst-case performance. There is no CI timing threshold. diff --git a/app/solver/native-test.cpp b/app/solver/native-test.cpp new file mode 100644 index 0000000..ac26bed --- /dev/null +++ b/app/solver/native-test.cpp @@ -0,0 +1,39 @@ +#include +#include +#include +#include +#define PI_NATIVE_TEST +#include "schedule.cpp" + +std::vector fixture(int count) { + std::vector v{0x50495331,1,count,count*2,count*2,0,0,1440,0,0,10000,3,0,0,0,0}; + for (int g=0;g& v) { + for (unsigned i=0;i(v.size())); +} +int main() { + assert(run(fixture(2))==0); + assert(run(fixture(3))==1); + auto limited=fixture(3); limited[10]=1; + assert(run(limited)==2); + assert(solver_run(-1)==3); + assert(solver_run(10001)==3); + const auto valid=fixture(3); + std::uint32_t seed=20261105; + for (int i=0;i<20000;++i) { + auto mutated=valid; + seed=seed*1664525u+1013904223u; + const unsigned index=seed%static_cast(mutated.size()); + seed=seed*1664525u+1013904223u; + mutated[index]=static_cast(seed); + const int result=run(mutated); + assert(result>=0 && result<=3); + } + assert(run(fixture(2))==0); // Bad calls must not poison later valid requests. + std::puts("Native solver passed. ASan/UBSan, 20,000 ABI mutations, valid and bounded searches."); +} diff --git a/app/solver/schedule.cpp b/app/solver/schedule.cpp new file mode 100644 index 0000000..2a3d642 --- /dev/null +++ b/app/solver/schedule.cpp @@ -0,0 +1,214 @@ +// Bounded finite-domain scheduling. No allocator, libc, or JavaScript imports. +// The same implementation runs natively under sanitizers and in WebAssembly. +// Wire format and validation live beside the adapter in scheduling/engine.ts. +using u32 = unsigned int; +static_assert(sizeof(int) == 4 && sizeof(u32) == 4, "The ABI uses 32-bit words"); + +namespace { +constexpr int MAGIC = 0x50495331; +constexpr int GROUPS = 32, OPTIONS = 512, MEETINGS = 2048, BUSY = 64; +constexpr int WORDS = OPTIONS / 32, INPUT = 10000, OUTPUT = 256, TOP = 3; +struct Slot { int days, start, end; }; +struct Group { int first, count, lock; bool has_selection; }; +struct Option { int group, first, count, selected, enabled; }; +struct Answer { int score, gaps, days, earliest, changes, latest; int picks[GROUPS]; }; +int input[INPUT], output[OUTPUT]; +Group groups[GROUPS]; +Option options[OPTIONS]; +Slot meetings[MEETINGS], busy[BUSY]; +u32 conflicts[OPTIONS][WORDS], excluded[WORDS]; +Answer answers[TOP]; +int ng, no, nm, nb, early, late, off, objective, budget, top, first_only; +int nodes, found, chosen[GROUPS]; +bool stopped; + +bool overlap(const Slot& a, const Slot& b) { + return (a.days & b.days) && a.start < b.end && b.start < a.end; +} +bool valid_slot(const Slot& s) { + return s.days > 0 && s.days < 128 && s.start >= 0 && s.end <= 1440 && s.start < s.end; +} +bool blocked(const u32* mask, int index) { return (mask[index / 32] & (1u << (index % 32))) != 0; } +void block(u32* mask, int index) { mask[index / 32] |= 1u << (index % 32); } + +bool parse(int size) { + if (size < 16 || size > INPUT || input[0] != MAGIC || input[1] != 1) return false; + ng = input[2]; no = input[3]; nm = input[4]; nb = input[5]; + early = input[6]; late = input[7]; off = input[8]; objective = input[9]; + budget = input[10]; top = input[11]; first_only = input[12]; + if (ng < 1 || ng > GROUPS || no < 1 || no > OPTIONS || nm < 1 || nm > MEETINGS || nb < 0 || nb > BUSY) return false; + if (early < 0 || late > 1440 || early > late || off < 0 || off > 127 || objective < 0 || objective > 2) return false; + if (budget < 1 || budget > 1000000 || top < 1 || top > TOP || (first_only != 0 && first_only != 1)) return false; + if (16 + ng * 3 + no * 5 + (nm + nb) * 3 != size) return false; + int at = 16, next = 0; + for (int g = 0; g < ng; ++g) { + groups[g] = {input[at], input[at + 1], input[at + 2], false}; at += 3; + const Group& group = groups[g]; + if (group.first != next || group.count < 1 || group.count > no - next) return false; + if (group.lock != -1 && (group.lock < next || group.lock >= next + group.count)) return false; + next += group.count; + } + if (next != no) return false; + next = 0; + for (int o = 0; o < no; ++o) { + options[o] = {input[at], input[at + 1], input[at + 2], input[at + 3], input[at + 4]}; at += 5; + const Option& option = options[o]; + if (option.group < 0 || option.group >= ng || option.first != next || option.count < 1 || option.count > nm - next) return false; + const Group& group = groups[option.group]; + if (o < group.first || o >= group.first + group.count || (option.selected != 0 && option.selected != 1) || (option.enabled != 0 && option.enabled != 1)) return false; + if (option.selected) groups[option.group].has_selection = true; + next += option.count; + } + if (next != nm) return false; + for (int m = 0; m < nm; ++m) { + meetings[m] = {input[at], input[at + 1], input[at + 2]}; at += 3; + if (!valid_slot(meetings[m])) return false; + } + for (int b = 0; b < nb; ++b) { + busy[b] = {input[at], input[at + 1], input[at + 2]}; at += 3; + if (!valid_slot(busy[b])) return false; + } + return true; +} + +void prepare() { + for (int w = 0; w < WORDS; ++w) excluded[w] = 0; + for (int a = 0; a < no; ++a) { + for (int w = 0; w < WORDS; ++w) conflicts[a][w] = 0; + const Option& option = options[a]; + const Group& group = groups[option.group]; + if (!option.enabled || (group.lock != -1 && group.lock != a)) block(excluded, a); + for (int i = option.first; i < option.first + option.count; ++i) { + const Slot& slot = meetings[i]; + if (slot.start < early || slot.end > late || (slot.days & off)) block(excluded, a); + for (int b = 0; b < nb; ++b) if (overlap(slot, busy[b])) block(excluded, a); + // A selected section may meet several times. Every meeting must fit. + for (int j = option.first; j < i; ++j) if (overlap(slot, meetings[j])) block(excluded, a); + } + } + for (int a = 0; a < no; ++a) for (int b = a + 1; b < no; ++b) { + if (options[a].group == options[b].group) continue; + bool clash = false; + for (int i = options[a].first; i < options[a].first + options[a].count && !clash; ++i) + for (int j = options[b].first; j < options[b].first + options[b].count; ++j) + if (overlap(meetings[i], meetings[j])) { clash = true; break; } + if (clash) { block(conflicts[a], b); block(conflicts[b], a); } + } +} + +// Metrics use exact minute intervals. All chosen intervals are nonoverlapping. +Answer measure() { + Answer a{}; a.earliest = 1440; + int starts[7], ends[7]{}, duration[7]{}; + for (int d = 0; d < 7; ++d) starts[d] = 1440; + for (int g = 0; g < ng; ++g) { + a.picks[g] = chosen[g]; + if (chosen[g] < 0) continue; + const Option& option = options[chosen[g]]; + if (groups[g].has_selection && !option.selected) ++a.changes; + for (int m = option.first; m < option.first + option.count; ++m) { + const Slot& s = meetings[m]; + for (int d = 0; d < 7; ++d) if (s.days & (1 << d)) { + if (s.start < starts[d]) starts[d] = s.start; + if (s.end > ends[d]) ends[d] = s.end; + duration[d] += s.end - s.start; + } + } + } + for (int d = 0; d < 7; ++d) if (ends[d]) { + ++a.days; + a.gaps += ends[d] - starts[d] - duration[d]; + if (starts[d] < a.earliest) a.earliest = starts[d]; + if (ends[d] > a.latest) a.latest = ends[d]; + } + a.score = objective == 0 ? a.gaps + a.days * 30 + : objective == 1 ? a.changes * 20000 + a.gaps + : (1440 - a.earliest) * 20000 + a.gaps; + return a; +} + +bool before(const Answer& a, const Answer& b) { + if (a.score != b.score) return a.score < b.score; + for (int g = 0; g < ng; ++g) if (a.picks[g] != b.picks[g]) return a.picks[g] < b.picks[g]; + return false; +} +void record() { + Answer answer = measure(); + int pos = 0; + while (pos < found && !before(answer, answers[pos])) ++pos; + if (pos >= top) return; + if (found < top) ++found; + for (int i = found - 1; i > pos; --i) answers[i] = answers[i - 1]; + answers[pos] = answer; +} + +void search(int depth, const u32* banned) { + if (stopped || (first_only && found)) return; + if (nodes >= budget) { stopped = true; return; } + ++nodes; + if (depth == ng) { record(); return; } + // Only monotonic metrics are used as bounds. Inserting a class can REDUCE gaps. + if (found == top) { + const Answer partial = measure(); + const int bound = objective == 0 ? partial.days * 30 + : objective == 1 ? partial.changes * 20000 + : (1440 - partial.earliest) * 20000; + if (bound > answers[found - 1].score) return; + } + int next = -1, smallest = OPTIONS + 1; + for (int g = 0; g < ng; ++g) if (chosen[g] < 0) { + int remaining = 0; + for (int o = groups[g].first; o < groups[g].first + groups[g].count; ++o) + if (!blocked(banned, o)) ++remaining; + if (!remaining) return; + if (remaining < smallest) { smallest = remaining; next = g; } + } + for (int o = groups[next].first; o < groups[next].first + groups[next].count; ++o) { + if (blocked(banned, o)) continue; + chosen[next] = o; + u32 child[WORDS]; + for (int w = 0; w < WORDS; ++w) child[w] = banned[w] | conflicts[o][w]; + search(depth + 1, child); + chosen[next] = -1; + if (stopped || (first_only && found)) break; + } +} +} + +extern "C" int* solver_input() { return input; } +extern "C" int solver_capacity() { return INPUT; } +extern "C" int* solver_output() { return output; } +extern "C" int solver_run(int size) { + for (int i = 0; i < OUTPUT; ++i) output[i] = 0; + output[0] = MAGIC; output[1] = 1; output[2] = 3; + if (!parse(size)) return 3; + nodes = 0; found = 0; stopped = false; + for (int g = 0; g < ng; ++g) chosen[g] = -1; + prepare(); search(0, excluded); + // 0 is an exhaustive answer, 1 a proof of infeasibility, 2 an unfinished search. + const int status = stopped || (first_only && found) ? 2 : found ? 0 : 1; + output[2] = status; output[3] = found; output[4] = nodes; output[5] = ng; + int at = 8; + for (int i = 0; i < found; ++i) { + const Answer& a = answers[i]; + output[at++] = a.score; output[at++] = a.gaps; output[at++] = a.days; + output[at++] = a.earliest; output[at++] = a.changes; output[at++] = a.latest; + for (int g = 0; g < ng; ++g) output[at++] = a.picks[g]; + } + return status; +} + +// Clang may emit these even for a freestanding optimized build. +#ifndef PI_NATIVE_TEST +extern "C" void* memset(void* dest, int value, __SIZE_TYPE__ length) { + auto* bytes = static_cast(dest); + for (__SIZE_TYPE__ i = 0; i < length; ++i) bytes[i] = static_cast(value); + return dest; +} +extern "C" void* memcpy(void* dest, const void* src, __SIZE_TYPE__ length) { + auto* out = static_cast(dest); + const auto* in = static_cast(src); + for (__SIZE_TYPE__ i = 0; i < length; ++i) out[i] = in[i]; + return dest; +} +#endif diff --git a/app/src/client/scheduling/engine.ts b/app/src/client/scheduling/engine.ts new file mode 100644 index 0000000..2c9c4c8 --- /dev/null +++ b/app/src/client/scheduling/engine.ts @@ -0,0 +1,281 @@ +import { + type Constraints, + type Diagnosis, + type Plan, + type ScheduleProblem, + type SolveResult, + type TimeSlot, + DAYS, + overlaps, + timeLabel, +} from "./model"; + +const MAGIC = 0x50495331; +type Exports = { + memory: WebAssembly.Memory; + solver_input(): number; + solver_output(): number; + solver_capacity(): number; + solver_run(length: number): number; +}; +type Limits = { nodes?: number; first?: boolean; top?: number }; +function checkSlot(s: TimeSlot) { + if ( + ![s.days, s.start, s.end].every(Number.isInteger) || + s.days < 1 || + s.days > 127 || + s.start < 0 || + s.end > 1440 || + s.start >= s.end + ) + throw new Error( + "Every section needs valid days and complete meeting times.", + ); +} + +export async function createSolver(bytes: BufferSource) { + const module = await WebAssembly.compile(bytes); + const instance = await WebAssembly.instantiate(module, {}); + const wasm = instance.exports as unknown as Exports; + + function solve( + problem: ScheduleProblem, + constraints: Constraints, + limits: Limits = {}, + ): SolveResult { + const start = performance.now(); + const groups = problem.groups; + if (!groups.length || groups.length > 32) + throw new Error("Choose a schedule with 1 to 32 section groups."); + if (new Set(groups.map((g) => g.id)).size !== groups.length) + throw new Error("Section group identifiers must be unique."); + const options = groups.flatMap((g) => g.options); + const meetings = options.flatMap((o) => o.meetings); + if ( + !options.length || + options.length > 512 || + meetings.length > 2048 || + constraints.busy.length > 64 + ) + throw new Error("This schedule exceeds the planner's supported size."); + if ( + ![constraints.earliest, constraints.latest, constraints.offDays].every( + Number.isInteger, + ) || + constraints.earliest < 0 || + constraints.latest > 1440 || + constraints.earliest > constraints.latest || + constraints.offDays < 0 || + constraints.offDays > 127 + ) + throw new Error("Check the time range and days off."); + const objective = ["compact", "changes", "late"].indexOf( + constraints.objective, + ); + const nodes = limits.nodes ?? 200000, + top = limits.top ?? 3; + if ( + objective < 0 || + !Number.isInteger(nodes) || + nodes < 1 || + nodes > 1000000 || + !Number.isInteger(top) || + top < 1 || + top > 3 + ) + throw new Error("Invalid search settings."); + if ( + Object.keys(constraints.locks).some( + (id) => !groups.some((g) => g.id === id), + ) + ) + throw new Error("A locked section is no longer in this schedule."); + const input = [ + MAGIC, + 1, + groups.length, + options.length, + meetings.length, + constraints.busy.length, + constraints.earliest, + constraints.latest, + constraints.offDays, + objective, + nodes, + top, + limits.first ? 1 : 0, + 0, + 0, + 0, + ]; + let first = 0; + for (const group of groups) { + if ( + !group.options.length || + new Set(group.options.map((o) => o.id)).size !== group.options.length + ) + throw new Error(`${group.course} needs distinct section choices.`); + if (group.options.filter((o) => o.selected).length > 1) + throw new Error( + `${group.course} has ambiguous current section selections.`, + ); + const lock = constraints.locks[group.id]; + const local = + lock == null ? -1 : group.options.findIndex((o) => o.id === lock); + if (lock != null && local < 0) + throw new Error( + `The locked section for ${group.course} is no longer available.`, + ); + input.push(first, group.options.length, local < 0 ? -1 : first + local); + first += group.options.length; + } + let meeting = 0; + for (let gi = 0; gi < groups.length; gi++) + for (const option of groups[gi].options) { + if (!option.meetings.length) + throw new Error( + `${groups[gi].course} ${option.title} has no complete meeting times.`, + ); + if (!["open", "closed", "canceled"].includes(option.status)) + throw new Error("Section availability was not provided."); + for (let i = 0; i < option.meetings.length; i++) { + checkSlot(option.meetings[i]); + if ( + option.meetings + .slice(i + 1) + .some((s) => overlaps(s, option.meetings[i])) + ) + throw new Error( + `${groups[gi].course} ${option.title} contains overlapping meeting records.`, + ); + } + const enabled = + option.status === "open" || + (constraints.allowClosed && option.status === "closed"); + input.push( + gi, + meeting, + option.meetings.length, + option.selected ? 1 : 0, + enabled ? 1 : 0, + ); + meeting += option.meetings.length; + } + for (const slot of [...meetings, ...constraints.busy]) { + checkSlot(slot); + input.push(slot.days, slot.start, slot.end); + } + if (input.length > wasm.solver_capacity()) + throw new Error("This schedule exceeds the solver's input capacity."); + new Int32Array(wasm.memory.buffer, wasm.solver_input(), input.length).set( + input, + ); + const status = wasm.solver_run(input.length); + if (status === 3) + throw new Error("The solver rejected incomplete schedule data."); + const output = new Int32Array( + wasm.memory.buffer, + wasm.solver_output(), + 256, + ); + if (output[0] !== MAGIC || output[1] !== 1 || output[5] !== groups.length) + throw new Error("The planner engine version does not match this page."); + const plans: Plan[] = []; + let at = 8; + for (let i = 0; i < output[3]; i++) { + const [score, gaps, days, earliest, changes, latest] = output.slice( + at, + at + 6, + ); + at += 6; + const picks: Record = {}; + for (const group of groups) picks[group.id] = options[output[at++]].id; + plans.push({ score, gaps, days, earliest, changes, latest, picks }); + } + return { + status: + status === 0 ? "optimal" : status === 1 ? "infeasible" : "limited", + plans, + nodes: output[4], + solveMs: performance.now() - start, + }; + } + + // Deletion-based irreducible conflict, with its own finite work budget. + // Unknown subproblems are kept. We never call a bounded-out search a proof. + function diagnose( + problem: ScheduleProblem, + constraints: Constraints, + ): Diagnosis { + let core = [...problem.groups], + minimal = true; + for (const group of problem.groups) { + if (core.length === 1) break; + const trial = core.filter((g) => g.id !== group.id); + const locks = Object.fromEntries( + Object.entries(constraints.locks).filter(([id]) => + trial.some((g) => g.id === id), + ), + ); + const result = solve( + { ...problem, groups: trial }, + { ...constraints, locks }, + { nodes: 20000, first: true }, + ); + if (result.status === "infeasible") core = trial; + else if (!result.plans.length) minimal = false; + } + const candidates: Diagnosis["relaxations"] = []; + if (constraints.earliest > 0) + candidates.push({ + label: `Allow classes before ${timeLabel(constraints.earliest)}`, + constraints: { ...constraints, earliest: 0 }, + }); + if (constraints.latest < 1440) + candidates.push({ + label: `Allow classes after ${timeLabel(constraints.latest)}`, + constraints: { ...constraints, latest: 1440 }, + }); + for (let d = 0; d < 7; d++) + if (constraints.offDays & (1 << d)) + candidates.push({ + label: `Allow classes on ${DAYS[d]}`, + constraints: { + ...constraints, + offDays: constraints.offDays & ~(1 << d), + }, + }); + for (const [id, option] of Object.entries(constraints.locks)) { + const group = problem.groups.find((g) => g.id === id)!; + const locks = { ...constraints.locks }; + delete locks[id]; + candidates.push({ + label: `Unlock ${group.course} ${group.options.find((o) => o.id === option)?.title ?? group.category}`, + constraints: { ...constraints, locks }, + }); + } + for (const block of constraints.busy) + candidates.push({ + label: `Remove ${block.label}`, + constraints: { + ...constraints, + busy: constraints.busy.filter((b) => b.id !== block.id), + }, + }); + if (!constraints.allowClosed) + candidates.push({ + label: "Include full sections", + constraints: { ...constraints, allowClosed: true }, + }); + const relaxations = candidates + .slice(0, 24) + .filter( + (c) => + solve(problem, c.constraints, { nodes: 20000, first: true }).plans + .length > 0, + ) + .slice(0, 3); + return { groups: core.map((g) => g.id), minimal, relaxations }; + } + return { solve, diagnose }; +} diff --git a/app/src/client/scheduling/junction.ts b/app/src/client/scheduling/junction.ts new file mode 100644 index 0000000..1854fd1 --- /dev/null +++ b/app/src/client/scheduling/junction.ts @@ -0,0 +1,170 @@ +import type { ScheduleProblem, SectionGroup, TimeSlot } from "./model"; + +const clock = (value: unknown) => { + if (typeof value !== "string") return null; + const match = value.trim().match(/^(\d{1,2}):(\d{2})\s*(AM|PM)$/i); + if (!match) return null; + const h = Number(match[1]), + m = Number(match[2]); + if (h < 1 || h > 12 || m > 59) return null; + return ((h % 12) + (match[3].toUpperCase() === "PM" ? 12 : 0)) * 60 + m; +}; +const aliases: Record = { + m: 1, + mon: 1, + monday: 1, + t: 2, + tue: 2, + tuesday: 2, + w: 4, + wed: 4, + wednesday: 4, + th: 8, + thu: 8, + thursday: 8, + f: 16, + fri: 16, + friday: 16, + s: 32, + sat: 32, + saturday: 32, + su: 64, + sun: 64, + sunday: 64, +}; +const record = (value: unknown): Record => { + if (!value || typeof value !== "object" || Array.isArray(value)) + throw new Error("Junction did not return a complete schedule."); + return value as Record; +}; +const codeKey = (value: string) => value.replace(/\s+/g, "").toUpperCase(); + +/** Decode the raw tool payload. Never use the calendar's merged display rows. */ +export function fromJunction(value: unknown): ScheduleProblem { + const data = record(value), + schedule = record(data.schedule); + if ( + !Array.isArray(data.sections) || + !data.sections.length || + !Array.isArray(data.courses) || + !data.courses.length + ) + throw new Error( + "Add courses with section times in Junction to open the planning lab.", + ); + const courses = new Map( + data.courses.map((c) => { + const row = record(c); + if (typeof row.code !== "string" || !row.code.trim()) + throw new Error("A course identifier is missing."); + return [ + codeKey(row.code), + { + code: row.code, + title: typeof row.title === "string" ? row.title : undefined, + }, + ]; + }), + ); + const groups = new Map(); + for (const raw of data.sections) { + const row = record(raw); + if ( + typeof row.courseCode !== "string" || + typeof row.sectionTitle !== "string" + ) + throw new Error("Junction did not provide section identifiers."); + const course = courses.get(codeKey(row.courseCode)); + if (!course) + throw new Error("Junction returned a section without its course."); + const category = + typeof row.category === "string" && /^[A-Z]+$/i.test(row.category) + ? row.category.toUpperCase() + : row.sectionTitle.match(/^([A-Za-z]+)\d/)?.[1].toUpperCase(); + if (!category) + throw new Error( + `${course.code} ${row.sectionTitle} has an unknown section type.`, + ); + const rawDays = Array.isArray(row.days) + ? row.days + : typeof row.days === "string" + ? row.days.split(/[,\s]+/).filter(Boolean) + : []; + let days = 0; + for (const day of rawDays) { + const bit = + typeof day === "string" ? aliases[day.toLowerCase()] : undefined; + if (!bit) + throw new Error( + `${course.code} ${row.sectionTitle} has an unknown meeting day.`, + ); + days |= bit; + } + const start = clock(row.startTime), + end = clock(row.endTime); + if (!days || start == null || end == null || start >= end) + throw new Error( + `${course.code} ${row.sectionTitle} needs complete meeting times before PI can check it.`, + ); + if (!["open", "closed", "canceled"].includes(String(row.status))) + throw new Error( + `${course.code} ${row.sectionTitle} is missing availability information.`, + ); + const id = `${codeKey(course.code)}|${category}`, + optionId = `${id}|${row.sectionTitle}`; + let group = groups.get(id); + if (!group) { + group = { + id, + course: course.code, + courseTitle: course.title, + category, + options: [], + }; + groups.set(id, group); + } + const slot: TimeSlot = { days, start, end }; + const existing = group.options.find((o) => o.id === optionId); + if (existing) { + if ( + existing.status !== row.status || + existing.selected !== (row.selected === true) + ) + throw new Error( + `${course.code} ${row.sectionTitle} has inconsistent meeting records.`, + ); + if ( + !existing.meetings.some( + (m) => m.days === days && m.start === start && m.end === end, + ) + ) + existing.meetings.push(slot); + } else + group.options.push({ + id: optionId, + title: row.sectionTitle, + meetings: [slot], + selected: row.selected === true, + status: row.status as "open" | "closed" | "canceled", + room: typeof row.room === "string" ? row.room : undefined, + }); + } + for (const course of courses.values()) + if ( + ![...groups.values()].some( + (g) => codeKey(g.course) === codeKey(course.code), + ) + ) + throw new Error( + `${course.code} has no section data. PI cannot check the complete schedule yet.`, + ); + return { + title: typeof schedule.title === "string" ? schedule.title : "My schedule", + term: + typeof schedule.termName === "string" + ? schedule.termName + : String(schedule.term ?? ""), + source: "junction", + groups: [...groups.values()], + }; +} diff --git a/app/src/client/scheduling/model.ts b/app/src/client/scheduling/model.ts new file mode 100644 index 0000000..fa42267 --- /dev/null +++ b/app/src/client/scheduling/model.ts @@ -0,0 +1,73 @@ +export const DAYS = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"] as const; +export type TimeSlot = { days: number; start: number; end: number }; +export type Section = { + id: string; + title: string; + meetings: TimeSlot[]; + selected: boolean; + status: "open" | "closed" | "canceled"; + room?: string; +}; +export type SectionGroup = { + id: string; + course: string; + courseTitle?: string; + category: string; + options: Section[]; +}; +export type ScheduleProblem = { + title: string; + term: string; + source: "sample" | "junction"; + groups: SectionGroup[]; +}; +export type Constraints = { + earliest: number; + latest: number; + offDays: number; + locks: Record; + busy: Array; + objective: "compact" | "changes" | "late"; + allowClosed: boolean; +}; +export const DEFAULT_CONSTRAINTS: Constraints = { + earliest: 8 * 60, + latest: 20 * 60, + offDays: 0, + locks: {}, + busy: [], + objective: "compact", + allowClosed: false, +}; +export type Plan = { + score: number; + gaps: number; + days: number; + earliest: number; + changes: number; + latest: number; + picks: Record; +}; +export type SolveResult = { + status: "optimal" | "infeasible" | "limited"; + plans: Plan[]; + nodes: number; + solveMs: number; +}; +export type Relaxation = { label: string; constraints: Constraints }; +export type Diagnosis = { + groups: string[]; + minimal: boolean; + relaxations: Relaxation[]; +}; +export function timeLabel(minutes: number) { + const h = Math.floor(minutes / 60), + m = minutes % 60; + return `${h % 12 || 12}${m ? `.${String(m).padStart(2, "0")}` : ""}${h >= 12 && h < 24 ? "pm" : "am"}`; +} +export function dayLabel(mask: number) { + return DAYS.filter((_, i) => mask & (1 << i)).join(" / "); +} +export function overlaps(a: TimeSlot, b: TimeSlot) { + return !!(a.days & b.days) && a.start < b.end && b.start < a.end; +} diff --git a/app/src/client/scheduling/solver.wasm b/app/src/client/scheduling/solver.wasm new file mode 100755 index 0000000000000000000000000000000000000000..73e1ecece4cb45059ab9c20079e5e59ec155b85f GIT binary patch literal 6077 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 { + const id = `${g.course}|${g.category}`; + return { + id, + course: g.course, + courseTitle: g.courseTitle, + category: g.category, + options: g.slots.map(([days, start, end], i) => ({ + id: `${id}|${i}`, + title: `${g.category}0${i + 1}`, + meetings: [{ days, start, end }], + selected: i === 0, + status: "open" as const, + room: ["Friend Center", "McCosh", "Fine Hall", "Robertson"][ + Math.floor(i / 2) % 4 + ], + })), + }; + }), +}; + +export const impossible: ScheduleProblem = { + title: "Three courses. Two time slots.", + term: "Correctness example", + source: "sample", + groups: ["Course A", "Course B", "Course C"].map((course) => ({ + id: course, + course, + category: "L", + options: [540, 600].map((start, i) => ({ + id: `${course}|${i}`, + title: `L0${i + 1}`, + selected: false, + status: "open" as const, + meetings: [{ days: 1, start, end: start + 50 }], + })), + })), +}; diff --git a/app/tests/scheduling.test.ts b/app/tests/scheduling.test.ts new file mode 100644 index 0000000..678f607 --- /dev/null +++ b/app/tests/scheduling.test.ts @@ -0,0 +1,286 @@ +import assert from "node:assert/strict"; +import { readFile } from "node:fs/promises"; +import { test } from "node:test"; +import { createSolver } from "../src/client/scheduling/engine.ts"; +import { + DEFAULT_CONSTRAINTS, + overlaps, + type Constraints, + type Plan, + type ScheduleProblem, + type Section, +} from "../src/client/scheduling/model.ts"; +import { fromJunction } from "../src/client/scheduling/junction.ts"; +import { impossible, semester } from "./fixtures/semester.ts"; + +const engine = await createSolver( + await readFile( + new URL("../src/client/scheduling/solver.wasm", import.meta.url), + ), +); +const open: Constraints = { ...DEFAULT_CONSTRAINTS, earliest: 0, latest: 1440 }; + +// Independent exhaustive oracle. It builds Cartesian products without the +// engine's bitsets, MRV ordering, or lower-bound pruning. +function brute(problem: ScheduleProblem, c: Constraints): Plan[] { + let products: Section[][] = [[]]; + for (const g of problem.groups) + products = products.flatMap((p) => g.options.map((o) => [...p, o])); + const plans: Array = []; + for (const picks of products) { + if ( + picks.some( + (p, i) => + (c.locks[problem.groups[i].id] && + c.locks[problem.groups[i].id] !== p.id) || + p.status === "canceled" || + (!c.allowClosed && p.status === "closed"), + ) + ) + continue; + const meetings = picks.flatMap((p) => p.meetings); + if ( + meetings.some( + (m) => + m.start < c.earliest || + m.end > c.latest || + m.days & c.offDays || + c.busy.some((b) => overlaps(m, b)), + ) + ) + continue; + if ( + meetings.some((a, i) => meetings.slice(i + 1).some((b) => overlaps(a, b))) + ) + continue; + let gaps = 0, + days = 0, + earliest = 1440, + latest = 0; + for (let d = 0; d < 7; d++) { + const today = meetings + .filter((m) => m.days & (1 << d)) + .sort((a, b) => a.start - b.start); + if (!today.length) continue; + days++; + for (let i = 1; i < today.length; i++) + gaps += today[i].start - today[i - 1].end; + earliest = Math.min(earliest, today[0].start); + latest = Math.max(latest, today.at(-1)!.end); + } + const changes = picks.filter( + (p, i) => + problem.groups[i].options.some((o) => o.selected) && !p.selected, + ).length; + const score = + c.objective === "compact" + ? gaps + days * 30 + : c.objective === "changes" + ? changes * 20000 + gaps + : (1440 - earliest) * 20000 + gaps; + plans.push({ + score, + gaps, + days, + earliest, + latest, + changes, + picks: Object.fromEntries( + picks.map((p, i) => [problem.groups[i].id, p.id]), + ), + order: picks.map((p, i) => problem.groups[i].options.indexOf(p)), + }); + } + return plans + .sort( + (a, b) => + a.score - b.score || + a.order.reduce((diff, x, i) => diff || x - b.order[i], 0), + ) + .slice(0, 3) + .map(({ order, ...p }) => p); +} + +test("three courses sharing two slots are globally infeasible despite pairwise compatibility", () => { + for (let i = 0; i < 3; i++) + assert.ok( + engine.solve( + { ...impossible, groups: impossible.groups.filter((_, j) => j !== i) }, + open, + ).plans.length, + ); + assert.equal(engine.solve(impossible, open).status, "infeasible"); + const diagnosis = engine.diagnose(impossible, open); + assert.deepEqual( + diagnosis.groups, + impossible.groups.map((g) => g.id), + ); + assert.equal(diagnosis.minimal, true); +}); +test("C++/Wasm top three exactly match independent exhaustive search on 300 seeded cases", () => { + let seed = 20261105; + const random = (n: number) => { + seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0; + return seed % n; + }; + for (let trial = 0; trial < 300; trial++) { + const problem: ScheduleProblem = { + title: "generated", + term: "test", + source: "sample", + groups: Array.from({ length: 2 + random(4) }, (_, g) => ({ + id: `g${g}`, + course: `C${g}`, + category: "L", + options: Array.from({ length: 1 + random(4) }, (_, o) => { + const start = 480 + random(8) * 60; + return { + id: `${g}:${o}`, + title: `L${o}`, + selected: o === 0, + status: random(8) === 0 ? ("closed" as const) : ("open" as const), + meetings: [ + { days: 1 << random(5), start, end: start + 30 + random(2) * 30 }, + ], + }; + }), + })), + }; + const constraints: Constraints = { + ...open, + objective: (["compact", "changes", "late"] as const)[trial % 3], + earliest: trial % 5 === 0 ? 600 : 0, + offDays: trial % 7 === 0 ? 16 : 0, + busy: + trial % 3 === 0 + ? [{ id: "b", label: "practice", days: 1, start: 600, end: 700 }] + : [], + }; + if (trial % 4 === 0) + constraints.locks = { + [problem.groups[0].id]: problem.groups[0].options[0].id, + }; + assert.deepEqual( + engine.solve(problem, constraints).plans, + brute(problem, constraints), + `seeded case ${trial}`, + ); + } +}); +test("presentation fixture has exact ranked solutions and changes when Friday is protected", () => { + for (const offDays of [0, 16]) { + const constraints = { ...open, earliest: 600, offDays }; + const result = engine.solve(semester, constraints); + assert.equal(result.status, "optimal"); + assert.equal(result.plans.length, 3); + assert.deepEqual(result.plans, brute(semester, constraints)); + } +}); +test("search exhaustion is reported as unfinished, never infeasible or optimal", () => { + const result = engine.solve(semester, open, { nodes: 1 }); + assert.equal(result.status, "limited"); + assert.deepEqual(result.plans, []); +}); +test("touching endpoints fit and every meeting of a multi-meeting section is checked", () => { + const problem = structuredClone(impossible); + problem.groups = problem.groups.slice(0, 2); + problem.groups[0].options = [ + { + ...problem.groups[0].options[0], + meetings: [ + { days: 1, start: 540, end: 600 }, + { days: 2, start: 600, end: 650 }, + ], + }, + ]; + problem.groups[1].options = [ + { + ...problem.groups[1].options[0], + meetings: [{ days: 1, start: 600, end: 650 }], + }, + ]; + assert.equal(engine.solve(problem, open).status, "optimal"); + problem.groups[1].options[0].meetings[0].days = 2; + assert.equal(engine.solve(problem, open).status, "infeasible"); +}); +test("a suggested relaxation has a verified full schedule", () => { + const constraints = { ...open, earliest: 1100 }; + assert.equal(engine.solve(semester, constraints).status, "infeasible"); + const diagnosis = engine.diagnose(semester, constraints); + assert.ok(diagnosis.relaxations.length); + for (const fix of diagnosis.relaxations) + assert.ok(engine.solve(semester, fix.constraints).plans.length); +}); +test("canceled sections never become available and unknown lock IDs fail explicitly", () => { + const problem = structuredClone(impossible); + problem.groups = problem.groups.slice(0, 1); + for (const o of problem.groups[0].options) o.status = "canceled"; + assert.equal( + engine.solve(problem, { ...open, allowClosed: true }).status, + "infeasible", + ); + assert.throws( + () => engine.solve(semester, { ...open, locks: { missing: "bad" } }), + /no longer/, + ); +}); +test("Junction adapter preserves distinct sections and multiple meetings, rejects incomplete courses", () => { + const row = { + courseCode: "COS 217", + sectionTitle: "P01", + days: ["M"], + startTime: "9:00 AM", + endTime: "9:50 AM", + selected: true, + status: "open", + }; + const payload = { + schedule: { title: "Fall", termName: "Fall 2026" }, + courses: [{ code: "COS217", title: "Systems" }], + sections: [ + row, + { ...row, days: ["W"] }, + { ...row, sectionTitle: "P02", selected: false }, + ], + }; + const result = fromJunction(payload); + assert.equal(result.groups[0].options.length, 2); + assert.equal(result.groups[0].options[0].meetings.length, 2); + assert.throws( + () => + fromJunction({ + ...payload, + courses: [ + ...payload.courses, + { code: "MAT202", title: "Linear Algebra" }, + ], + }), + /no section data/, + ); + assert.throws( + () => + fromJunction({ + ...payload, + sections: [{ ...row, startTime: "8:12.5 AM" }], + }), + /complete meeting/, + ); + assert.throws( + () => fromJunction({ ...payload, sections: [{ ...row, days: [] }] }), + /complete meeting/, + ); +}); +test("malformed and oversized inputs are rejected before crossing the Wasm boundary", () => { + assert.throws( + () => engine.solve({ ...semester, groups: [] }, open), + /1 to 32/, + ); + assert.throws( + () => engine.solve(semester, { ...open, earliest: NaN }), + /time range/, + ); + assert.throws( + () => engine.solve(semester, open, { nodes: 2147483648 }), + /search settings/, + ); +});