File size: 16,681 Bytes
0f0c909
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
"""NNAI scheduling v0.2: planted-feasible shift CSPs and diagnostic scoring.

Standard library only. Scores measure validity, not match to a reference schedule.
The frozen v0.1 multiple-choice suite is a separate benchmark.
"""
from __future__ import annotations
import argparse
from collections import Counter
import hashlib
from itertools import combinations
import json
from pathlib import Path
import random
from benchmark import ROOT, DATASET, ARTIFACTS, dump, read_rows, write_rows

VERSION = "nnai-scheduling-0.2"
FAMILIES = ("staffing", "availability", "skills", "no_overlap", "rest", "workload", "incompatibility")
SIZES = {"train": 120, "validation": 60, "test": 120}


def validate_predictions(predictions, questions):
    if not isinstance(predictions, list):
        raise ValueError("Scheduling predictions must be an array of {id, assignments} objects")
    expected = {q["id"]: q for q in questions}
    result = {}
    for p in predictions:
        if not isinstance(p, dict) or set(p) != {"id", "assignments"}:
            raise ValueError("Each schedule must contain exactly id and assignments")
        ident = p["id"]
        if not isinstance(ident, str) or ident not in expected or ident in result:
            raise ValueError("Unknown or duplicate scheduling ID")
        q = expected[ident]
        shifts = {s["id"] for s in q["shifts"]}
        workers = {w["id"] for w in q["workers"]}
        assignments = p["assignments"]
        if not isinstance(assignments, list) or len(assignments) != len(shifts):
            raise ValueError("Include every shift exactly once; use worker_ids: [] for an unfilled shift")
        mapping = {}
        for a in assignments:
            if not isinstance(a, dict) or set(a) != {"shift_id", "worker_ids"}:
                raise ValueError("Each assignment must contain exactly shift_id and worker_ids")
            sid, ids = a["shift_id"], a["worker_ids"]
            if not isinstance(sid, str) or sid not in shifts or sid in mapping:
                raise ValueError("Unknown or duplicate shift ID")
            if not isinstance(ids, list) or any(not isinstance(w, str) or w not in workers for w in ids):
                raise ValueError("Unknown worker ID or invalid worker_ids list")
            if len(set(ids)) != len(ids):
                raise ValueError("A worker cannot be listed twice in the same shift")
            mapping[sid] = ids
        result[ident] = mapping
    if set(result) != set(expected):
        raise ValueError(f"Expected {len(expected)} unique scheduling IDs, received {len(result)}")
    return result


def check_case(q, assignments):
    """Evaluate each instantiated constraint, with stable diagnostic identifiers."""
    checks = {f: [] for f in FAMILIES}
    shifts = {s["id"]: s for s in q["shifts"]}
    workers = {w["id"]: w for w in q["workers"]}
    by_worker = {wid: [] for wid in workers}
    def add(family, key, ok, expected, actual):
        checks[family].append({"constraint_id": key, "passed": bool(ok), "expected": expected, "actual": actual})
    for sid, s in shifts.items():
        ids = assignments[sid]
        add("staffing", f"staffing:{sid}", len(ids) == s["required_workers"], s["required_workers"], len(ids))
        for wid in ids:
            w = workers[wid]
            by_worker[wid].append(s)
            add("availability", f"availability:{sid}:{wid}", sid not in w["unavailable"], "available", "unavailable" if sid in w["unavailable"] else "available")
            add("skills", f"skills:{sid}:{wid}", s["required_skill"] in w["skills"], s["required_skill"], w["skills"])
        for a, b in q["incompatible_pairs"]:
            add("incompatibility", f"incompatibility:{sid}:{a}:{b}", not (a in ids and b in ids), "not on same shift", [w for w in (a, b) if w in ids])
    for wid, schedule in by_worker.items():
        w = workers[wid]
        ordered = sorted(schedule, key=lambda s: (s["start"], s["id"]))
        hours = sum(s["end"] - s["start"] for s in ordered)
        add("workload", f"min_shifts:{wid}", len(ordered) >= w["min_shifts"], w["min_shifts"], len(ordered))
        add("workload", f"max_shifts:{wid}", len(ordered) <= w["max_shifts"], w["max_shifts"], len(ordered))
        add("workload", f"max_hours:{wid}", hours <= w["max_hours"], w["max_hours"], hours)
        for first, second in combinations(ordered, 2):
            gap = second["start"] - first["end"]
            add("no_overlap", f"overlap:{wid}:{first['id']}:{second['id']}", gap >= 0, ">=0 hours gap", gap)
            add("rest", f"rest:{wid}:{first['id']}:{second['id']}", gap >= q["min_rest_hours"], q["min_rest_hours"], gap)
    family_report = {}
    violations = []
    for family, items in checks.items():
        passed = sum(c["passed"] for c in items)
        family_report[family] = {"passed": passed, "total": len(items), "satisfaction": 100 * passed / len(items) if items else 100.0}
        violations.extend({"family": family, **c} for c in items if not c["passed"])
    demand = sum(s["required_workers"] for s in shifts.values())
    filled = sum(min(len(assignments[sid]), s["required_workers"]) for sid, s in shifts.items())
    coverage = filled / demand
    raw = sum(c["satisfaction"] for c in family_report.values()) / len(FAMILIES)
    return {"id": q["id"], "difficulty": q["difficulty"], "feasible": not violations,
            "coverage": 100 * coverage, "raw_constraint_satisfaction": raw,
            "partial_score": raw * coverage, "families": family_report, "violations": violations}


def score_schedules(predictions, questions):
    mappings = validate_predictions(predictions, questions)
    cases = [check_case(q, mappings[q["id"]]) for q in questions]
    if not cases:
        raise ValueError("Cannot score an empty benchmark")
    def mean(key, subset=cases):
        return sum(c[key] for c in subset) / len(subset)
    families = {}
    for f in FAMILIES:
        families[f] = {"mean_satisfaction": sum(c["families"][f]["satisfaction"] for c in cases) / len(cases),
                       "passed": sum(c["families"][f]["passed"] for c in cases),
                       "total": sum(c["families"][f]["total"] for c in cases),
                       "violations": sum(c["families"][f]["total"] - c["families"][f]["passed"] for c in cases)}
    tiers = {}
    for tier in sorted({c["difficulty"] for c in cases}):
        subset = [c for c in cases if c["difficulty"] == tier]
        tiers[str(tier)] = {"total": len(subset), "feasible_rate": 100 * mean("feasible", subset), "partial_score": mean("partial_score", subset)}
    return {"benchmark_version": VERSION, "total": len(cases), "feasible_count": sum(c["feasible"] for c in cases),
            "feasible_rate": 100 * mean("feasible"), "partial_score": mean("partial_score"),
            "raw_constraint_satisfaction": mean("raw_constraint_satisfaction"), "coverage": mean("coverage"),
            "families": families, "tiers": tiers, "cases": cases}


def compatible(q, s, wid, allocated):
    w = next(w for w in q["workers"] if w["id"] == wid)
    if s["id"] in w["unavailable"] or s["required_skill"] not in w["skills"]:
        return False
    old = allocated[wid]
    if len(old) >= w["max_shifts"] or sum(x["end"] - x["start"] for x in old) + s["end"] - s["start"] > w["max_hours"]:
        return False
    return all(s["start"] - x["end"] >= q["min_rest_hours"] or x["start"] - s["end"] >= q["min_rest_hours"] for x in old)


def solve(q, max_nodes=20000):
    """Bounded backtracking with MRV and minimum-workload forward checking.

    Receives only question fields. Exhausting the node budget returns an empty
    schedule, never a claim of unsatisfiability. No reference witness is read.
    """
    workers = {w["id"]: w for w in q["workers"]}
    allocated = {wid: [] for wid in workers}
    result, nodes = {}, 0
    forbidden = {frozenset(p) for p in q["incompatible_pairs"]}
    def domain(s):
        candidates = [wid for wid in workers if compatible(q, s, wid, allocated)]
        combos = [c for c in combinations(candidates, s["required_workers"]) if all(frozenset(p) not in forbidden for p in combinations(c, 2))]
        return sorted(combos, key=lambda c: (-sum(max(0, workers[w]["min_shifts"] - len(allocated[w])) for w in c), sum(len(allocated[w]) for w in c), c))
    def search(remaining):
        nonlocal nodes
        nodes += 1
        if nodes > max_nodes:
            return False
        if not remaining:
            return all(len(allocated[wid]) >= w["min_shifts"] for wid, w in workers.items())
        for wid, w in workers.items():
            if len(allocated[wid]) + sum(compatible(q, s, wid, allocated) for s in remaining) < w["min_shifts"]:
                return False
        domains = [(s, domain(s)) for s in remaining]
        s, options = min(domains, key=lambda pair: (len(pair[1]), pair[0]["start"], pair[0]["id"]))
        rest = [x for x in remaining if x["id"] != s["id"]]
        for ids in options:
            result[s["id"]] = list(ids)
            for wid in ids: allocated[wid].append(s)
            if search(rest): return True
            for wid in ids: allocated[wid].pop()
            result.pop(s["id"], None)
            if nodes > max_nodes: break
        return False
    found = search(q["shifts"])
    return {"id": q["id"], "assignments": [{"shift_id": s["id"], "worker_ids": result[s["id"]] if found else []} for s in q["shifts"]]}, {"nodes": nodes, "found": found, "budget_exhausted": nodes > max_nodes}


def greedy(q):
    """Chronological, low-load greedy baseline with no backtracking."""
    allocated = {w["id"]: [] for w in q["workers"]}
    result = []
    forbidden = {frozenset(p) for p in q["incompatible_pairs"]}
    for s in sorted(q["shifts"], key=lambda s: (s["start"], s["id"])):
        chosen = []
        for wid in sorted(allocated, key=lambda w: (len(allocated[w]), w)):
            if compatible(q, s, wid, allocated) and all(frozenset((wid, x)) not in forbidden for x in chosen):
                chosen.append(wid)
                allocated[wid].append(s)
                if len(chosen) == s["required_workers"]: break
        result.append({"shift_id": s["id"], "worker_ids": chosen})
    return {"id": q["id"], "assignments": result}


def make_case(split, i, rng):
    tier = i % 3 + 1
    count, days, per_day = ((5, 3, 2), (7, 5, 2), (10, 7, 3))[tier - 1]
    tag = f"{split[0]}{rng.getrandbits(32):08x}"
    skills = ["general"] if tier == 1 else ["care", "technical", "logistics"]
    while True:
        workers = [{"id": f"w_{tag}_{j}", "skills": skills[:] if tier == 1 else rng.sample(skills, rng.randint(1, 3)),
                    "unavailable": [], "min_shifts": 0, "max_shifts": 100, "max_hours": 800} for j in range(count)]
        shifts = [{"id": f"d{d}_s{s}", "start": d * 24 + (8 if per_day == 2 else 0) + s * 8,
                   "end": d * 24 + (8 if per_day == 2 else 0) + s * 8 + 8,
                   "required_skill": rng.choice(skills), "required_workers": 1 if tier == 1 else rng.choice((1, 2, 2))}
                  for d in range(days) for s in range(per_day)]
        pairs = [list(p) for p in rng.sample(list(combinations([w["id"] for w in workers], 2)), tier - 1)]
        q = {"id": f"scheduling-v02-{split}-{i:04d}", "benchmark_version": VERSION, "split": split, "difficulty": tier,
             "prompt": "Assign workers to every shift. Respect exact staffing, required skills, availability, non-overlap, minimum rest, each worker's min/max shifts and max hours, and incompatible pairs. Times are integer hours from day 0; intervals are half-open. Return shift_id and worker_ids for every shift.",
             "workers": workers, "shifts": shifts, "min_rest_hours": 8 if tier == 1 else 12, "incompatible_pairs": pairs}
        # Plant a feasible assignment first, then tighten limits/unavailability.
        allocated = {w["id"]: [] for w in workers}
        planted = []
        forbidden = {frozenset(p) for p in pairs}
        for s in shifts:
            choices = [w["id"] for w in workers if compatible(q, s, w["id"], allocated)]
            rng.shuffle(choices)
            choices.sort(key=lambda wid: len(allocated[wid]))
            ids = []
            for wid in choices:
                if all(frozenset((wid, other)) not in forbidden for other in ids): ids.append(wid)
                if len(ids) == s["required_workers"]: break
            if len(ids) < s["required_workers"]: break
            for wid in ids: allocated[wid].append(s)
            planted.append({"shift_id": s["id"], "worker_ids": ids})
        if len(planted) == len(shifts): break
    for w in workers:
        used = {s["id"] for s in allocated[w["id"]]}
        w["min_shifts"] = max(0, len(used) - rng.randint(0, 1))
        w["max_shifts"] = len(used) + rng.randint(0, 1)
        w["max_hours"] = 8 * (len(used) + rng.randint(0, 1))
        w["unavailable"] = [s["id"] for s in shifts if s["id"] not in used and rng.random() < (.15, .25, .35)[tier - 1]]
    rng.shuffle(q["workers"])
    rng.shuffle(q["shifts"])
    return q, {"id": q["id"], "assignments": planted}


def generate():
    destination = DATASET / "scheduling_v02"
    witnesses = []
    for k, (split, n) in enumerate(SIZES.items()):
        rng = random.Random(20261019 + k)
        rows = []
        for i in range(n):
            q, witness = make_case(split, i, rng)
            assert score_schedules([witness], [q])["feasible_rate"] == 100
            rows.append(q)
            witnesses.append(witness)
        write_rows(destination / f"{split}.jsonl", rows)
        if split == "test":
            dump(ARTIFACTS / "scheduling-test.json", rows)
            dump(destination / "example_predictions.json", [{"id": q["id"], "assignments": [{"shift_id": s["id"], "worker_ids": []} for s in q["shifts"]]} for q in rows])
    dump(destination / "reference_witnesses.json", witnesses)
    manifest = {"benchmark_version": VERSION, "seed": 20261019, "split_sizes": SIZES, "families": FAMILIES,
                "sha256": {p.name: hashlib.sha256(p.read_bytes()).hexdigest() for p in sorted(destination.glob("*.json*")) if p.name != "manifest.json"}}
    dump(destination / "manifest.json", manifest)
    dump(ARTIFACTS / "scheduling-manifest.json", manifest)
    print("Generated", sum(SIZES.values()), "scheduling cases")


def baselines():
    questions = read_rows(DATASET / "scheduling_v02/test.jsonl")
    entries = []
    for name, solver in (("greedy", greedy), ("bounded-backtracking", lambda q: solve(q)[0])):
        predictions = [solver(q) for q in questions]
        report = score_schedules(predictions, questions)
        dump(ARTIFACTS / f"scheduling-baselines/{name}.predictions.json", predictions)
        dump(ARTIFACTS / f"scheduling-baselines/{name}.report.json", report)
        summary = {k: v for k, v in report.items() if k != "cases"}
        entries.append({"id": name, "name": name.replace("-", " ").title(), "architecture": "symbolic search", "kind": "baseline", "status": "reproduced", "track": "closed-book", "training_provenance": "no neural training/data", "test_exposure": "template-informed baseline", "source_url": "https://huggingface.co/datasets/vynly/nnai-bench/blob/main/scheduling.py", "score": summary})
        print(name, "feasible", round(report["feasible_rate"], 2), "partial", round(report["partial_score"], 2))
    dump(ARTIFACTS / "scheduling-leaderboard.json", {"benchmark_version": VERSION, "entries": entries})


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    sub = parser.add_subparsers(dest="command", required=True)
    sub.add_parser("generate")
    sub.add_parser("baselines")
    run = sub.add_parser("solve")
    run.add_argument("--questions", default=str(DATASET / "scheduling_v02/test.jsonl"))
    run.add_argument("--output", default="scheduling_predictions.json")
    run.add_argument("--max-nodes", type=int, default=20000)
    ev = sub.add_parser("score")
    ev.add_argument("predictions")
    ev.add_argument("--questions", default=str(DATASET / "scheduling_v02/test.jsonl"))
    ev.add_argument("--output")
    args = parser.parse_args()
    if args.command == "generate": generate()
    elif args.command == "baselines": baselines()
    elif args.command == "solve":
        dump(args.output, [solve(q, args.max_nodes)[0] for q in read_rows(args.questions)])
    else:
        report = score_schedules(json.loads(Path(args.predictions).read_text(encoding="utf-8")), read_rows(args.questions))
        if args.output: dump(args.output, report)
        print(json.dumps({k: v for k, v in report.items() if k != "cases"}, indent=2))


if __name__ == "__main__": main()