From 5ce0933518c1c8167f5b261edf3f66c39d4aa423 Mon Sep 17 00:00:00 2001 From: Stavan Somaiya Date: Mon, 23 Nov 2026 10:16:46 +0530 Subject: [PATCH] docs(KruskalMST): add an executable DisjointSetTreeNode example and tests (R50-T007) Fixes: #7 --- Graphs/KruskalMST.js | 41 ++++- Graphs/test/KruskalMST.test.js | 118 +++++++++++++ work/R50-T007/README.md | 79 +++++++++ work/R50-T007/check.py | 267 ++++++++++++++++++++++++++++++ work/R50-T007/commands.log | 16 ++ work/R50-T007/evidence.mjs | 155 +++++++++++++++++ work/R50-T007/results.json | 163 ++++++++++++++++++ work/R50-T007/task.json | 14 ++ work/R50-T007/trace.txt | 4 + work/R50-T007/versions.txt | 5 + work/R50-T007/vitest-focused.json | 28 ++++ 11 files changed, 888 insertions(+), 2 deletions(-) create mode 100644 Graphs/test/KruskalMST.test.js create mode 100644 work/R50-T007/README.md create mode 100644 work/R50-T007/check.py create mode 100644 work/R50-T007/commands.log create mode 100644 work/R50-T007/evidence.mjs create mode 100644 work/R50-T007/results.json create mode 100644 work/R50-T007/task.json create mode 100644 work/R50-T007/trace.txt create mode 100644 work/R50-T007/versions.txt create mode 100644 work/R50-T007/vitest-focused.json diff --git a/Graphs/KruskalMST.js b/Graphs/KruskalMST.js index c2f749c68d..10f2a009c5 100644 --- a/Graphs/KruskalMST.js +++ b/Graphs/KruskalMST.js @@ -1,5 +1,38 @@ +/** + * Disjoint Set Node to store the parent and rank. + * + * A new node is the root of its own one-element set: its `parent` is itself + * and its `rank` (an upper bound on the height of its tree) is 0. + * + * The decisive state transition happens in `DisjointSetTree.link`: when two + * roots of equal rank are joined, the first root's `parent` is set to the + * second root and the second root's `rank` goes up by 1. When the ranks + * differ, the lower-rank root is attached below the higher one and no rank + * changes. `findSet` then answers "which set?" by following `parent` links + * up to the root. + * + * The example below is executed by Graphs/test/KruskalMST.test.js, which + * checks each printed value against the comment on the same line. + * + * @example + * import { DisjointSetTreeNode, DisjointSetTree } from './KruskalMST.js' + * + * const node = new DisjointSetTreeNode('a') + * console.log(node.key, node.parent === node, node.rank) // a true 0 + * + * const sets = new DisjointSetTree() + * sets.makeSet('a') + * sets.makeSet('b') + * sets.makeSet('c') + * // equal ranks (0, 0): a.parent = b and b.rank becomes 1 + * sets.union('a', 'b') + * console.log(sets.findSet('a').key, sets.map.b.rank) // b 1 + * // ranks differ (c: 0, root b: 1): c goes below b, b.rank stays 1 + * sets.union('c', 'a') + * console.log(sets.findSet('c').key, sets.map.b.rank) // b 1 + * console.log(sets.map.a.rank, sets.map.c.rank) // 0 0 + */ class DisjointSetTreeNode { - // Disjoint Set Node to store the parent and rank constructor(key) { this.key = key this.parent = this @@ -105,7 +138,11 @@ class GraphWeightedUndirectedAdjacencyList { } } -export { GraphWeightedUndirectedAdjacencyList } +export { + GraphWeightedUndirectedAdjacencyList, + DisjointSetTreeNode, + DisjointSetTree +} // const graph = new GraphWeightedUndirectedAdjacencyList() // graph.addEdge(1, 2, 1) diff --git a/Graphs/test/KruskalMST.test.js b/Graphs/test/KruskalMST.test.js new file mode 100644 index 0000000000..d8fcca697e --- /dev/null +++ b/Graphs/test/KruskalMST.test.js @@ -0,0 +1,118 @@ +import { readFileSync } from 'fs' +import * as KruskalModule from '../KruskalMST' +import { + DisjointSetTreeNode, + DisjointSetTree, + GraphWeightedUndirectedAdjacencyList +} from '../KruskalMST' + +// Pull the @example block out of the DisjointSetTreeNode JSDoc +// (KruskalMST.js, above the class) so the documentation itself is executed. +const readDocExample = () => { + const source = readFileSync( + new URL('../KruskalMST.js', import.meta.url), + 'utf8' + ) + const start = source.indexOf('@example') + const end = source.indexOf('*/', start) + const lines = source + .slice(start + '@example'.length, end) + .split('\n') + .map((line) => line.replace(/^\s*\* ?/, '')) + const importLine = lines.find((line) => line.startsWith('import ')) + const [, names, from] = importLine.match(/^import \{ (.+) \} from '(.+)'$/) + return { + importedNames: names.split(',').map((name) => name.trim()), + importedFrom: from, + body: lines.filter((line) => !line.startsWith('import ')).join('\n'), + documented: lines + .filter((line) => line.includes('console.log(')) + .map((line) => line.split('// ')[1].trim()) + } +} + +describe('DisjointSetTreeNode documentation example', () => { + const example = readDocExample() + + it('imports real public names from this file', () => { + expect(example.importedFrom).toBe('./KruskalMST.js') + expect(example.importedNames).toEqual([ + 'DisjointSetTreeNode', + 'DisjointSetTree' + ]) + for (const name of example.importedNames) { + expect(typeof KruskalModule[name]).toBe('function') + } + }) + + it('prints exactly what the comments next to each console.log say', () => { + const printed = [] + const fakeConsole = { + log: (...args) => printed.push(args.map(String).join(' ')) + } + // Run the example body with exactly the names its import line binds. + new Function(...example.importedNames, 'console', example.body)( + ...example.importedNames.map((name) => KruskalModule[name]), + fakeConsole + ) + + // The documented output, pinned so the doc cannot drift silently. + expect(example.documented).toEqual(['a true 0', 'b 1', 'b 1', '0 0']) + expect(printed).toEqual(['a true 0', 'b 1', 'b 1', '0 0']) + }) +}) + +describe('DisjointSetTreeNode states (calculated by hand)', () => { + // Precondition: constructor sets parent = this and rank = 0 + // (KruskalMST.js lines 38-39). + it('smallest valid input: a new node is the root of its own set', () => { + const node = new DisjointSetTreeNode('a') + expect(node.key).toBe('a') + expect(node.parent).toBe(node) + expect(node.rank).toBe(0) + }) + + // Precondition: link joins x below y and bumps y.rank only on equal ranks + // (KruskalMST.js lines 68-78). + it('ordinary input: union of equal ranks, then unequal ranks', () => { + const sets = new DisjointSetTree() + sets.makeSet('a') + sets.makeSet('b') + sets.makeSet('c') + + sets.union('a', 'b') // ranks 0 and 0 + expect(sets.map.a.parent).toBe(sets.map.b) + expect(sets.map.b.parent).toBe(sets.map.b) + expect([sets.map.a.rank, sets.map.b.rank, sets.map.c.rank]).toEqual([ + 0, 1, 0 + ]) + + sets.union('c', 'a') // root c has rank 0, root b has rank 1 + expect(sets.map.c.parent).toBe(sets.map.b) + expect(sets.findSet('c')).toBe(sets.map.b) + expect([sets.map.a.rank, sets.map.b.rank, sets.map.c.rank]).toEqual([ + 0, 1, 0 + ]) + }) +}) + +describe('KruskalMST example from the bottom of KruskalMST.js', () => { + it('keeps the 4 cheapest edges that do not form a cycle', () => { + const graph = new GraphWeightedUndirectedAdjacencyList() + graph.addEdge(1, 2, 1) + graph.addEdge(2, 3, 2) + graph.addEdge(3, 4, 1) + graph.addEdge(3, 5, 100) // Removed in MST + graph.addEdge(4, 5, 5) + + // Sorted edges: 1-2 (1), 3-4 (1), 2-3 (2), 4-5 (5), 3-5 (100). + // The first four join new sets; 3-5 would close a cycle. + expect(graph.KruskalMST().connections).toEqual({ + 1: { 2: 1 }, + 2: { 1: 1, 3: 2 }, + 3: { 2: 2, 4: 1 }, + 4: { 3: 1, 5: 5 }, + 5: { 4: 5 } + }) + }) +}) diff --git a/work/R50-T007/README.md b/work/R50-T007/README.md new file mode 100644 index 0000000000..954b8e53e6 --- /dev/null +++ b/work/R50-T007/README.md @@ -0,0 +1,79 @@ +# R50-T007 — Runnable example for `DisjointSetTreeNode` + +Source: `Graphs/KruskalMST.js`, `DisjointSetTreeNode` (line 35 after this change; line 1 at pinned commit `5c39e87`). + +## Recorded contract (before any change) + +| Aspect | Observation | +| --------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Input | `key` (any value used as a set member name). | +| Result | node with `key`, `parent === this` and `rank === 0` (lines 38-39): the root of a one-element set. | +| Mutation | none by itself; `DisjointSetTree.link` (lines 68-78) later rewrites `parent` and `rank`. | +| External dependencies | none. | +| Public interface | `GraphWeightedUndirectedAdjacencyList` unchanged; `DisjointSetTreeNode` and `DisjointSetTree` are now also exported so the example can import them by their real names. | + +There was no test file for `KruskalMST.js` before this change. + +## Hand-calculated states (written before running), then compared with a traced run + +| Step | parents of a, b, c | ranks of a, b, c | Why | +| ------------------------------ | ------------------ | ---------------- | --------------------------------------------------- | +| `new DisjointSetTreeNode('a')` | a → itself | 0 | constructor, lines 38-39 | +| `makeSet` a, b, c | a, b, c | 0, 0, 0 | three roots | +| `union('a', 'b')` | **b**, b, c | 0, **1**, 0 | equal ranks: `x.parent = y`, `y.rank += 1` (73-75) | +| `union('c', 'a')` | b, b, **b** | 0, 1, 0 | find(a) = b; rank 0 < 1, so c goes below b, no bump | + +`trace.txt` holds the traced execution; it matched every row. + +**Decisive transition:** joining two roots of _equal_ rank is the only step that raises a rank. +Everything else is either following `parent` links (`findSet`) or hanging a shorter tree under a +taller one with no rank change. + +## Executable documentation + +The JSDoc above `DisjointSetTreeNode` (lines 1-34) contains an `@example` with `console.log` lines, +each followed by a comment showing what it prints. It is executed in two independent ways: + +1. **In the normal test suite** (`Graphs/test/KruskalMST.test.js`). The test reads the block + straight from the source file and checks that its `import` line names real exports of + `./KruskalMST.js` (`DisjointSetTreeNode`, `DisjointSetTree`). It then runs the example body + with exactly those bindings and a captured `console`, and asserts the printed lines equal the + documented ones: `a true 0`, `b 1`, `b 1`, `0 0`. +2. **Verbatim with Node** (`evidence.mjs`, run by `check.py`). The example is written unchanged, + import line included, into a temporary ES module next to a copy of `KruskalMST.js`, run with + `node`, and its real stdout is compared with the documented comments. + +If either the documentation or the code drifts, both checks fail. + +The test file also asserts the hand-calculated states above, and turns the commented-out example +at the bottom of `KruskalMST.js` into an asserted MST: edges 1-2, 3-4, 2-3 and 4-5 are kept, and +3-5 is skipped because it would close a cycle. + +## Sensitivity check (temporary copy only) + +`check.py` changes `y.rank += 1` to `y.rank += 2` in a temp copy; the doc-example test fails (prints +`b 2`, documented `b 1`). The real source is untouched. + +## How to run + +From the repository root: + +```sh +python3 work/R50-T007/check.py +``` + +`check.py` installs dependencies from `package-lock.json`, runs the focused test file, evaluates the fixture with `evidence.mjs` (input, expected, actual and source line for every case), runs each deliberate mutant in a temporary copy, and finally runs the repository test script in non-watch mode (`npm test`, which is `vitest run`). It exits non-zero if any assertion or step fails, and records every command it ran in `commands.log`. + +### Recorded run (files in this folder) + +| Step | Command | Result | +| ------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------- | +| Install from lockfile | `npm ci --ignore-scripts --no-audit --no-fund` (exit 0) | ok | +| Focused tests | `node_modules/.bin/vitest run Graphs/test/KruskalMST.test.js --reporter=json --outputFile=work/R50-T007/vitest-focused.raw.json` | 5/5 passed | +| Fixture evidence | `node work/R50-T007/evidence.mjs` | 7/7 rows match | +| Mutant: rank grows by 2 on equal-rank link | temporary copy | killed by `prints exactly what the comments next to each console.log say` | +| Repository test script | `npm test -- --reporter=json --outputFile=work/R50-T007/vitest-full.raw.json` | 11975/11975 passed | + +Tool versions (`versions.txt`): python 3.12.10; node v26.13.1; npm 11.20.0; platform macOS-27.2.1-arm64-arm-64bit; vitest vitest/1.2.1 darwin-arm64 node-v26.13.1. + +Files: `results.json` (all of the above, machine-readable), `vitest-focused.json` (each focused test and its status), `commands.log`, `versions.txt`. diff --git a/work/R50-T007/check.py b/work/R50-T007/check.py new file mode 100644 index 0000000000..401798fcb2 --- /dev/null +++ b/work/R50-T007/check.py @@ -0,0 +1,267 @@ +#!/usr/bin/env python3 +"""Focused check runner for R50-T007. + +Run from the repository root: + + python3 work/R50-T007/check.py + +Steps (everything is recorded under work/R50-T007/): + 1. Record tool versions -> versions.txt + 2. Install dependencies from the lockfile -> `npm ci --ignore-scripts` + (set SKIP_INSTALL=1 to reuse an existing node_modules) + 3. Run the focused Vitest file(s) for this task; require a non-zero test + count and zero failures -> vitest-focused.json + 4. Run evidence.mjs: literal fixture inputs against the real source, with + input / expected / actual / source line -> results.json ("fixture") + 5. Run each deliberate mutant in a temporary copy (never in the real + source); require the named regression test to pass on the original and + fail on the mutant -> results.json ("mutants") + 6. Run the repository test script in non-watch mode + (`npm test` = `vitest run`); require a non-zero test count and zero + failures -> results.json ("full_suite") + +Every command actually executed is written to commands.log. The exit status +is non-zero if any step or assertion fails (or a step times out). +""" + +import json +import os +import platform +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +ROOT = HERE.parent.parent +CONFIG = json.loads((HERE / 'task.json').read_text()) +TASK = CONFIG['task'] +VITEST = str(ROOT / 'node_modules' / '.bin' / 'vitest') +TIMEOUT_SECONDS = 600 + +failures = [] +log = [] + + +def show(text): + """Hide machine-specific absolute paths in recorded evidence.""" + text = text.replace(str(ROOT) + os.sep, '').replace(str(ROOT), '.') + return text.replace(tempfile.gettempdir(), '$TMPDIR') + + +def run(cmd, cwd=ROOT, check=False): + """Run a command, log it exactly, and never wait forever.""" + shown = show(' '.join(cmd)) + log.append('$ ' + shown) + try: + proc = subprocess.run(cmd, cwd=cwd, capture_output=True, text=True, + timeout=TIMEOUT_SECONDS) + except subprocess.TimeoutExpired: + log.append(f' -> timed out after {TIMEOUT_SECONDS}s') + failures.append(f'timed out: {shown}') + return subprocess.CompletedProcess(cmd, 124, '', 'timeout') + log.append(f' -> exit {proc.returncode}') + if check and proc.returncode != 0: + print(proc.stdout[-4000:]) + print(proc.stderr[-4000:], file=sys.stderr) + return proc + + +def version(cmd): + try: + return run(cmd).stdout.strip().splitlines()[0] + except Exception as exc: # best effort only + return f'unavailable ({exc})' + + +def test_list(report): + return [ + {'name': t.get('fullName') or t.get('title'), 'status': t.get('status')} + for suite in report.get('testResults', []) + for t in suite.get('assertionResults', []) + ] + + +def read_report(proc, out): + if not out.exists(): + print(proc.stdout[-4000:]) + print(proc.stderr[-4000:], file=sys.stderr) + return None + report = json.loads(out.read_text()) + out.unlink() + return report + + +def summary(cmd, proc, report): + return { + 'command': show(' '.join(cmd)), + 'exit': proc.returncode, + 'total': report and report['numTotalTests'], + 'passed': report and report['numPassedTests'], + 'failed': report and report['numFailedTests'] + } + + +def require_green(label, info, report): + if info['exit'] != 0 or not report or report['numTotalTests'] == 0 or \ + report['numFailedTests'] != 0: + failures.append(f'{label} failed: {info}') + if report: + failures.extend(' failed: ' + t['name'] + for t in test_list(report) + if t['status'] == 'failed') + + +def main(): + results = {'task': TASK} + + # 1. Tool versions + versions = { + 'python': platform.python_version(), + 'node': version(['node', '--version']), + 'npm': version(['npm', '--version']), + 'platform': platform.platform() + } + + # 2. Install from the lockfile + if os.environ.get('SKIP_INSTALL') == '1': + results['install'] = 'skipped (SKIP_INSTALL=1)' + else: + cmd = ['npm', 'ci', '--ignore-scripts', '--no-audit', '--no-fund'] + proc = run(cmd, check=True) + results['install'] = {'command': ' '.join(cmd), + 'exit': proc.returncode} + if proc.returncode != 0: + failures.append('npm ci failed') + return finish(results, versions) + versions['vitest'] = version([VITEST, '--version']) + + # 3. Focused tests + out = HERE / 'vitest-focused.raw.json' + cmd = [VITEST, 'run', *CONFIG['focused_tests'], '--reporter=json', + f'--outputFile={out}'] + proc = run(cmd) + focused_report = read_report(proc, out) + results['focused_tests'] = summary(cmd, proc, focused_report) + require_green('focused tests', results['focused_tests'], focused_report) + if focused_report: + (HERE / 'vitest-focused.json').write_text(json.dumps({ + 'command': results['focused_tests']['command'], + 'numTotalTests': focused_report['numTotalTests'], + 'numPassedTests': focused_report['numPassedTests'], + 'numFailedTests': focused_report['numFailedTests'], + 'tests': test_list(focused_report) + }, indent=2) + '\n') + + # 4. Fixture evidence (input / expected / actual / source line) + proc = run(['node', str(HERE / 'evidence.mjs')]) + rows = [] + if proc.returncode != 0: + failures.append('evidence.mjs crashed: ' + show(proc.stderr[-2000:])) + else: + rows = json.loads(proc.stdout) + results['fixture'] = rows + for row in rows: + print(f"[{'PASS' if row['pass'] else 'FAIL'}] {row['name']}") + print(f" input: {json.dumps(row['input'])}") + print(f" expected: {json.dumps(row['expected'])}") + print(f" actual: {json.dumps(row['actual'])}") + if row.get('precondition'): + print(f" source: {row['precondition']}") + if not row['pass']: + failures.append(f"fixture mismatch: {row['name']}") + if not rows: + failures.append('no fixture rows were produced') + + # 5. Deliberate mutants, in temporary copies only + original_tests = test_list(focused_report) if focused_report else [] + mutants = [run_mutant(m, original_tests) for m in CONFIG.get('mutants', [])] + if mutants: + results['mutants'] = mutants + + # 6. Repository test script in non-watch mode: `npm test` (vitest run) + out = HERE / 'vitest-full.raw.json' + cmd = ['npm', 'test', '--', '--reporter=json', f'--outputFile={out}'] + proc = run(cmd) + full_report = read_report(proc, out) + results['full_suite'] = summary(cmd, proc, full_report) + require_green('repository test script', results['full_suite'], full_report) + + return finish(results, versions) + + +def run_mutant(mutant, original_tests): + """Copy the source and its tests into a temp dir, apply one edit there, + and require the named test to pass on the original and fail here.""" + original = (ROOT / mutant['file']).read_text() + named = [t for t in original_tests if mutant['must_fail'] in t['name']] + entry = { + 'name': mutant['name'], + 'file': mutant['file'], + 'edit': {'from': mutant['find'], 'to': mutant['replace']}, + 'named_test': mutant['must_fail'], + 'named_test_on_original': [t['status'] for t in named], + 'killed': False + } + if len(named) != 1 or named[0]['status'] != 'passed': + failures.append(f"mutant {mutant['name']}: named test must match " + f"exactly one passing test on the original") + return entry + if original.count(mutant['find']) != 1: + failures.append(f"mutant {mutant['name']}: edit must match once") + return entry + with tempfile.TemporaryDirectory(prefix=f'{TASK}-mutant-') as tmp: + tmp = Path(tmp) + for rel in [mutant['file'], *mutant['tests']]: + dest = tmp / rel + dest.parent.mkdir(parents=True, exist_ok=True) + shutil.copy(ROOT / rel, dest) + (tmp / mutant['file']).write_text( + original.replace(mutant['find'], mutant['replace'])) + out = tmp / 'mutant-report.json' + cmd = [VITEST, 'run', *mutant['tests'], '--root', str(tmp), + '--globals', '--reporter=json', f'--outputFile={out}'] + proc = run(cmd) + report = read_report(proc, out) + failed = [t['name'] for t in test_list(report) + if t['status'] == 'failed'] if report else [] + entry['exit'] = proc.returncode + entry['failed_tests_on_mutant'] = failed + entry['killed'] = proc.returncode != 0 and any( + mutant['must_fail'] in name for name in failed) + print(f"[{'KILLED' if entry['killed'] else 'SURVIVED'}] mutant " + f"{mutant['name']}: {mutant['find']!r} -> {mutant['replace']!r}") + for name in failed: + print(f' failed: {name}') + if not entry['killed']: + failures.append(f"mutant {mutant['name']} was not detected by " + f"'{mutant['must_fail']}'") + return entry + + +def finish(results, versions): + results['ok'] = not failures + results['failures'] = failures + (HERE / 'versions.txt').write_text( + ''.join(f'{k}: {v}\n' for k, v in versions.items())) + (HERE / 'results.json').write_text(json.dumps(results, indent=2) + '\n') + (HERE / 'commands.log').write_text('\n'.join(log) + '\n') + print() + for key, label in [('focused_tests', 'focused tests'), + ('full_suite', 'npm test')]: + if key in results: + info = results[key] + print(f"{label + ':':15}{info['passed']}/{info['total']} passed" + f" ({info['command']})") + if failures: + print('\nFAILED:') + for item in failures: + print(' - ' + item) + return 1 + print(f'\n{TASK}: all checks passed') + return 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/work/R50-T007/commands.log b/work/R50-T007/commands.log new file mode 100644 index 0000000000..bcb10f2afe --- /dev/null +++ b/work/R50-T007/commands.log @@ -0,0 +1,16 @@ +$ node --version + -> exit 0 +$ npm --version + -> exit 0 +$ npm ci --ignore-scripts --no-audit --no-fund + -> exit 0 +$ node_modules/.bin/vitest --version + -> exit 0 +$ node_modules/.bin/vitest run Graphs/test/KruskalMST.test.js --reporter=json --outputFile=work/R50-T007/vitest-focused.raw.json + -> exit 0 +$ node work/R50-T007/evidence.mjs + -> exit 0 +$ node_modules/.bin/vitest run Graphs/test/KruskalMST.test.js --root $TMPDIR/R50-T007-mutant-zseu1sjh --globals --reporter=json --outputFile=$TMPDIR/R50-T007-mutant-zseu1sjh/mutant-report.json + -> exit 1 +$ npm test -- --reporter=json --outputFile=work/R50-T007/vitest-full.raw.json + -> exit 0 diff --git a/work/R50-T007/evidence.mjs b/work/R50-T007/evidence.mjs new file mode 100644 index 0000000000..622ab53f70 --- /dev/null +++ b/work/R50-T007/evidence.mjs @@ -0,0 +1,155 @@ +// R50-T007 evidence: hand-calculated states for DisjointSetTreeNode compared +// with a traced execution of the real source, printed as JSON rows. +import { execFileSync } from 'child_process' +import { + copyFileSync, + mkdtempSync, + readFileSync, + rmSync, + writeFileSync +} from 'fs' +import { tmpdir } from 'os' +import { join } from 'path' +import { + DisjointSetTreeNode, + DisjointSetTree, + GraphWeightedUndirectedAdjacencyList +} from '../../Graphs/KruskalMST.js' + +const SRC = 'KruskalMST.js' +const same = (a, b) => JSON.stringify(a) === JSON.stringify(b) +const row = (name, input, expected, actual, precondition) => ({ + name, + input, + expected, + actual, + pass: same(expected, actual), + precondition +}) + +const node = new DisjointSetTreeNode('a') +const rows = [ + row( + 'smallest valid input: new node', + "new DisjointSetTreeNode('a')", + { key: 'a', parentIsSelf: true, rank: 0 }, + { key: node.key, parentIsSelf: node.parent === node, rank: node.rank }, + `${SRC}:38-39 parent = this, rank = 0` + ) +] + +// state = [parent key of a, b, c] and [rank of a, b, c] +const state = (s) => ({ + parents: ['a', 'b', 'c'].map((k) => s.map[k].parent.key), + ranks: ['a', 'b', 'c'].map((k) => s.map[k].rank) +}) +const sets = new DisjointSetTree() +sets.makeSet('a') +sets.makeSet('b') +sets.makeSet('c') +rows.push( + row( + 'after makeSet a, b, c', + 'makeSet x3', + { parents: ['a', 'b', 'c'], ranks: [0, 0, 0] }, + state(sets), + `${SRC}:50-53 makeSet creates a root node` + ) +) +sets.union('a', 'b') +rows.push( + row( + "after union('a', 'b') — equal ranks (decisive transition)", + "union('a', 'b')", + { parents: ['b', 'b', 'c'], ranks: [0, 1, 0] }, + state(sets), + `${SRC}:73-75 x.parent = y; equal ranks -> y.rank += 1` + ) +) +sets.union('c', 'a') +rows.push( + row( + "after union('c', 'a') — ranks 0 vs 1", + "union('c', 'a')", + { parents: ['b', 'b', 'b'], ranks: [0, 1, 0] }, + state(sets), + `${SRC}:68-78 lower rank goes below, no rank change` + ) +) + +const graph = new GraphWeightedUndirectedAdjacencyList() +graph.addEdge(1, 2, 1) +graph.addEdge(2, 3, 2) +graph.addEdge(3, 4, 1) +graph.addEdge(3, 5, 100) +graph.addEdge(4, 5, 5) +const mst = graph.KruskalMST().connections +const sortKeys = (o) => + Object.fromEntries( + Object.keys(o) + .sort() + .map((k) => [k, typeof o[k] === 'object' ? sortKeys(o[k]) : o[k]]) + ) +rows.push( + row( + 'KruskalMST on the example at the bottom of the file', + '1-2:1, 2-3:2, 3-4:1, 3-5:100, 4-5:5', + { + 1: { 2: 1 }, + 2: { 1: 1, 3: 2 }, + 3: { 2: 2, 4: 1 }, + 4: { 3: 1, 5: 5 }, + 5: { 4: 5 } + }, + sortKeys(mst), + `${SRC}: KruskalMST uses DisjointSetTree to skip 3-5` + ) +) + +// Run the @example exactly as written (real import line, real console) as an +// ES module placed next to a copy of KruskalMST.js, and compare its stdout +// with the output documented in the comments. +const sourceUrl = new URL('../../Graphs/KruskalMST.js', import.meta.url) +const source = readFileSync(sourceUrl, 'utf8') +const start = source.indexOf('@example') +const exampleLines = source + .slice(start + '@example'.length, source.indexOf('*/', start)) + .split('\n') + .map((line) => line.replace(/^\s*\* ?/, '')) +const documented = exampleLines + .filter((line) => line.includes('console.log(')) + .map((line) => line.split('// ')[1].trim()) +const dir = mkdtempSync(join(tmpdir(), 'R50-T007-example-')) +let printed +try { + copyFileSync(sourceUrl, join(dir, 'KruskalMST.js')) + writeFileSync(join(dir, 'package.json'), '{"type":"module"}') + writeFileSync(join(dir, 'example.js'), exampleLines.join('\n')) + printed = execFileSync(process.execPath, [join(dir, 'example.js')], { + encoding: 'utf8' + }) + .trim() + .split('\n') +} finally { + rmSync(dir, { recursive: true, force: true }) +} +rows.push( + row( + 'JSDoc @example run verbatim with node (stdout vs documented comments)', + exampleLines.filter((l) => l.trim()).length + ' example lines', + ['a true 0', 'b 1', 'b 1', '0 0'], + printed, + `${SRC}:17-33 @example block` + ) +) +rows.push( + row( + 'documented comments match the pinned output', + 'comments after each console.log', + ['a true 0', 'b 1', 'b 1', '0 0'], + documented, + `${SRC}:21,29,32,33` + ) +) + +console.log(JSON.stringify(rows)) diff --git a/work/R50-T007/results.json b/work/R50-T007/results.json new file mode 100644 index 0000000000..486c087535 --- /dev/null +++ b/work/R50-T007/results.json @@ -0,0 +1,163 @@ +{ + "task": "R50-T007", + "install": { + "command": "npm ci --ignore-scripts --no-audit --no-fund", + "exit": 0 + }, + "focused_tests": { + "command": "node_modules/.bin/vitest run Graphs/test/KruskalMST.test.js --reporter=json --outputFile=work/R50-T007/vitest-focused.raw.json", + "exit": 0, + "total": 5, + "passed": 5, + "failed": 0 + }, + "fixture": [ + { + "name": "smallest valid input: new node", + "input": "new DisjointSetTreeNode('a')", + "expected": { + "key": "a", + "parentIsSelf": true, + "rank": 0 + }, + "actual": { + "key": "a", + "parentIsSelf": true, + "rank": 0 + }, + "pass": true, + "precondition": "KruskalMST.js:38-39 parent = this, rank = 0" + }, + { + "name": "after makeSet a, b, c", + "input": "makeSet x3", + "expected": { + "parents": ["a", "b", "c"], + "ranks": [0, 0, 0] + }, + "actual": { + "parents": ["a", "b", "c"], + "ranks": [0, 0, 0] + }, + "pass": true, + "precondition": "KruskalMST.js:50-53 makeSet creates a root node" + }, + { + "name": "after union('a', 'b') \u2014 equal ranks (decisive transition)", + "input": "union('a', 'b')", + "expected": { + "parents": ["b", "b", "c"], + "ranks": [0, 1, 0] + }, + "actual": { + "parents": ["b", "b", "c"], + "ranks": [0, 1, 0] + }, + "pass": true, + "precondition": "KruskalMST.js:73-75 x.parent = y; equal ranks -> y.rank += 1" + }, + { + "name": "after union('c', 'a') \u2014 ranks 0 vs 1", + "input": "union('c', 'a')", + "expected": { + "parents": ["b", "b", "b"], + "ranks": [0, 1, 0] + }, + "actual": { + "parents": ["b", "b", "b"], + "ranks": [0, 1, 0] + }, + "pass": true, + "precondition": "KruskalMST.js:68-78 lower rank goes below, no rank change" + }, + { + "name": "KruskalMST on the example at the bottom of the file", + "input": "1-2:1, 2-3:2, 3-4:1, 3-5:100, 4-5:5", + "expected": { + "1": { + "2": 1 + }, + "2": { + "1": 1, + "3": 2 + }, + "3": { + "2": 2, + "4": 1 + }, + "4": { + "3": 1, + "5": 5 + }, + "5": { + "4": 5 + } + }, + "actual": { + "1": { + "2": 1 + }, + "2": { + "1": 1, + "3": 2 + }, + "3": { + "2": 2, + "4": 1 + }, + "4": { + "3": 1, + "5": 5 + }, + "5": { + "4": 5 + } + }, + "pass": true, + "precondition": "KruskalMST.js: KruskalMST uses DisjointSetTree to skip 3-5" + }, + { + "name": "JSDoc @example run verbatim with node (stdout vs documented comments)", + "input": "14 example lines", + "expected": ["a true 0", "b 1", "b 1", "0 0"], + "actual": ["a true 0", "b 1", "b 1", "0 0"], + "pass": true, + "precondition": "KruskalMST.js:17-33 @example block" + }, + { + "name": "documented comments match the pinned output", + "input": "comments after each console.log", + "expected": ["a true 0", "b 1", "b 1", "0 0"], + "actual": ["a true 0", "b 1", "b 1", "0 0"], + "pass": true, + "precondition": "KruskalMST.js:21,29,32,33" + } + ], + "mutants": [ + { + "name": "rank grows by 2 on equal-rank link", + "file": "Graphs/KruskalMST.js", + "edit": { + "from": " y.rank += 1\n", + "to": " y.rank += 2\n" + }, + "named_test": "prints exactly what the comments next to each console.log say", + "named_test_on_original": ["passed"], + "killed": true, + "exit": 1, + "failed_tests_on_mutant": [ + " DisjointSetTreeNode documentation example prints exactly what the comments next to each console.log say", + " DisjointSetTreeNode states (calculated by hand) ordinary input: union of equal ranks, then unequal ranks" + ] + } + ], + "full_suite": { + "command": "npm test -- --reporter=json --outputFile=work/R50-T007/vitest-full.raw.json", + "exit": 0, + "total": 11975, + "passed": 11975, + "failed": 0 + }, + "ok": true, + "failures": [] +} diff --git a/work/R50-T007/task.json b/work/R50-T007/task.json new file mode 100644 index 0000000000..2243927eaf --- /dev/null +++ b/work/R50-T007/task.json @@ -0,0 +1,14 @@ +{ + "task": "R50-T007", + "focused_tests": ["Graphs/test/KruskalMST.test.js"], + "mutants": [ + { + "name": "rank grows by 2 on equal-rank link", + "file": "Graphs/KruskalMST.js", + "find": " y.rank += 1\n", + "replace": " y.rank += 2\n", + "tests": ["Graphs/test/KruskalMST.test.js"], + "must_fail": "prints exactly what the comments next to each console.log say" + } + ] +} diff --git a/work/R50-T007/trace.txt b/work/R50-T007/trace.txt new file mode 100644 index 0000000000..5c40a637bf --- /dev/null +++ b/work/R50-T007/trace.txt @@ -0,0 +1,4 @@ +trace: a true 0 +after union(a,b): a.parent= b b.parent= b ranks a,b,c= 0 1 0 +after union(c,a): c.parent= b ranks a,b,c= 0 1 0 +MST of commented example: {"1":{"2":1},"2":{"1":1,"3":2},"3":{"2":2,"4":1},"4":{"3":1,"5":5},"5":{"4":5}} diff --git a/work/R50-T007/versions.txt b/work/R50-T007/versions.txt new file mode 100644 index 0000000000..b405ff9cb4 --- /dev/null +++ b/work/R50-T007/versions.txt @@ -0,0 +1,5 @@ +python: 3.12.10 +node: v26.13.1 +npm: 11.20.0 +platform: macOS-27.2.1-arm64-arm-64bit +vitest: vitest/1.2.1 darwin-arm64 node-v26.13.1 diff --git a/work/R50-T007/vitest-focused.json b/work/R50-T007/vitest-focused.json new file mode 100644 index 0000000000..b31bc6b37e --- /dev/null +++ b/work/R50-T007/vitest-focused.json @@ -0,0 +1,28 @@ +{ + "command": "node_modules/.bin/vitest run Graphs/test/KruskalMST.test.js --reporter=json --outputFile=work/R50-T007/vitest-focused.raw.json", + "numTotalTests": 5, + "numPassedTests": 5, + "numFailedTests": 0, + "tests": [ + { + "name": " DisjointSetTreeNode documentation example imports real public names from this file", + "status": "passed" + }, + { + "name": " DisjointSetTreeNode documentation example prints exactly what the comments next to each console.log say", + "status": "passed" + }, + { + "name": " DisjointSetTreeNode states (calculated by hand) smallest valid input: a new node is the root of its own set", + "status": "passed" + }, + { + "name": " DisjointSetTreeNode states (calculated by hand) ordinary input: union of equal ranks, then unequal ranks", + "status": "passed" + }, + { + "name": " KruskalMST example from the bottom of KruskalMST.js keeps the 4 cheapest edges that do not form a cycle", + "status": "passed" + } + ] +}