Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions app/.gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,4 @@ dist
.dev.vars
.wrangler
worker-configuration.d.ts
.artifacts
5 changes: 4 additions & 1 deletion app/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
76 changes: 76 additions & 0 deletions app/scripts/bench-solver.ts
Original file line number Diff line number Diff line change
@@ -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));
76 changes: 76 additions & 0 deletions app/scripts/build-solver.mjs
Original file line number Diff line number Diff line change
@@ -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 });
}
31 changes: 31 additions & 0 deletions app/scripts/test-solver-native.mjs
Original file line number Diff line number Diff line change
@@ -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 });
}
80 changes: 80 additions & 0 deletions app/solver/README.md
Original file line number Diff line number Diff line change
@@ -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.
39 changes: 39 additions & 0 deletions app/solver/native-test.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
#include <cassert>
#include <cstdint>
#include <cstdio>
#include <vector>
#define PI_NATIVE_TEST
#include "schedule.cpp"

std::vector<int> fixture(int count) {
std::vector<int> v{0x50495331,1,count,count*2,count*2,0,0,1440,0,0,10000,3,0,0,0,0};
for (int g=0;g<count;++g) v.insert(v.end(),{g*2,2,-1});
for (int g=0;g<count;++g) for(int o=0;o<2;++o) v.insert(v.end(),{g,g*2+o,1,0,1});
for (int g=0;g<count;++g) for(int o=0;o<2;++o) v.insert(v.end(),{1,540+o*60,590+o*60});
return v;
}
int run(const std::vector<int>& v) {
for (unsigned i=0;i<v.size();++i) solver_input()[i]=v[i];
return solver_run(static_cast<int>(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<unsigned>(mutated.size());
seed=seed*1664525u+1013904223u;
mutated[index]=static_cast<int>(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.");
}
Loading
Loading