diff --git a/Data-Structures/Tree/Trie.js b/Data-Structures/Tree/Trie.js index 0d4018f74f..e4a5181067 100644 --- a/Data-Structures/Tree/Trie.js +++ b/Data-Structures/Tree/Trie.js @@ -1,3 +1,18 @@ +/** + * One node of the Trie: a single character (`key`), how many inserted words + * end exactly here (`count`), its `children` keyed by character and its + * `parent` (`null` for the root or when no parent is given). + * + * Absent results: the Trie never throws for a missing word. Instead, + * - `findPrefix` returns `null` when some character of the prefix has no + * child node, e.g. 'cab' after inserting 'car' and 'cat'; + * - a node that exists only as a prefix (e.g. 'ca') has `count === 0`, so + * `contains('ca')` is `false` and `findOccurrences('ca')` is `0`. + * Lookups never create nodes, so a failed lookup leaves the Trie unchanged. + * + * @param {string|null} key character stored in this node (`null` for root) + * @param {TrieNode|null} [parent] parent node; omitted means `null` + */ class TrieNode { constructor(key, parent) { this.key = key @@ -129,4 +144,4 @@ class Trie { } } -export { Trie } +export { Trie, TrieNode } diff --git a/Data-Structures/Tree/test/Trie.test.js b/Data-Structures/Tree/test/Trie.test.js new file mode 100644 index 0000000000..3b90dfb726 --- /dev/null +++ b/Data-Structures/Tree/test/Trie.test.js @@ -0,0 +1,94 @@ +import { Trie, TrieNode } from '../Trie' + +// Fixture: insert "car", "cat" and "dog". +const buildTrie = () => { + const trie = new Trie() + trie.insert('car') + trie.insert('cat') + trie.insert('dog') + return trie +} + +describe('TrieNode', () => { + // Trie.js lines 21-22: an omitted parent becomes null. + it('a node created without a parent has parent null and count 0', () => { + const node = new TrieNode('c') + expect(node.key).toBe('c') + expect(node.parent).toBeNull() + expect(node.count).toBe(0) + expect(Object.keys(node.children)).toEqual([]) + }) + + it('a child node keeps a reference to its parent', () => { + const root = new TrieNode(null, null) + const child = new TrieNode('c', root) + expect(child.parent).toBe(root) + }) +}) + +describe('Trie absent-result paths (no exceptions are thrown)', () => { + // Branch under test: findPrefix returns null at Trie.js line 76 + // ("No such prefix exists") when a character has no child node. + it("missing word 'cab' reaches the null branch of findPrefix", () => { + const trie = buildTrie() + // 'c' and 'a' exist, 'b' does not: the loop stops at i = 2. + expect(trie.findPrefix('ca')).toBeInstanceOf(TrieNode) + expect(trie.findPrefix('cab')).toBeNull() + expect(trie.contains('cab')).toBe(false) // line 135 + expect(trie.findOccurrences('cab')).toBe(0) // line 142 + expect(trie.findAllWords('cab')).toEqual([]) // line 126 + }) + + // Branch under test: node exists but count is 0 (Trie.js line 135). + it("prefix 'ca' is not a complete word, but 'car' is", () => { + const trie = buildTrie() + const prefixNode = trie.findPrefix('ca') + expect(prefixNode.count).toBe(0) + expect(trie.contains('ca')).toBe(false) + expect(trie.findOccurrences('ca')).toBe(0) + expect(trie.contains('car')).toBe(true) + expect(trie.findOccurrences('car')).toBe(1) + }) + + it('non-string input is ignored, not thrown (lines 52 and 70)', () => { + const trie = buildTrie() + expect(trie.insert(5)).toBeUndefined() + expect(trie.findPrefix(5)).toBeNull() + expect(trie.findAllWords('')).toEqual([ + { word: 'car', count: 1 }, + { word: 'cat', count: 1 }, + { word: 'dog', count: 1 } + ]) + }) + + it('failed lookups leave the trie unchanged and later calls succeed', () => { + const trie = buildTrie() + + expect(trie.contains('cab')).toBe(false) + expect(trie.findPrefix('zebra')).toBeNull() + expect(trie.findAllWords('')).toEqual([ + { word: 'car', count: 1 }, + { word: 'cat', count: 1 }, + { word: 'dog', count: 1 } + ]) + expect(trie.findPrefix('cab')).toBeNull() // no node was created + + // An ordinary valid call after the failure. + trie.insert('cab') + expect(trie.contains('cab')).toBe(true) + expect(trie.findOccurrences('cab')).toBe(1) + expect(trie.contains('car')).toBe(true) + }) + + it('repeated insertion increments the count of the same node', () => { + const trie = buildTrie() + const node = trie.findPrefix('car') + trie.insert('car') + expect(trie.findPrefix('car')).toBe(node) + expect(trie.findOccurrences('car')).toBe(2) + expect(trie.findAllWords('ca')).toEqual([ + { word: 'car', count: 2 }, + { word: 'cat', count: 1 } + ]) + }) +}) diff --git a/work/R50-T008/README.md b/work/R50-T008/README.md new file mode 100644 index 0000000000..154b17c305 --- /dev/null +++ b/work/R50-T008/README.md @@ -0,0 +1,91 @@ +# R50-T008 — Failure / absent-result behaviour of `TrieNode` + +Source: `Data-Structures/Tree/Trie.js`, `TrieNode` (line 16 after this change; line 1 at pinned commit `5c39e87`). + +## Recorded contract (before any change) + +| Aspect | Observation | +| ----------------------- | ----------------------------------------------------------------------------------------------------- | +| `TrieNode(key, parent)` | stores `key`, `count = 0`, prototype-less `children`; an omitted parent becomes `null` (lines 21-22). | +| Trie API | `insert`, `findPrefix`, `contains`, `findOccurrences`, `findAllWords`, `remove`. | +| Failure policy | **total**: nothing throws for a missing word. Missing results are `null`, `false`, `0` or `[]`. | +| Mutation | only `insert`/`remove` change nodes; lookups only read. | +| External dependencies | none. | +| Public interface | `Trie` unchanged; `TrieNode` is now also exported so tests can check node identity and shape. | + +Because the contract is total, the tests use the documented empty / missing results rather than +inventing an exception. + +## Branches exercised (source lines in the final file) + +| Branch | Line | Smallest input that reaches it | Result | +| ---------------------------------------------------- | ------ | ---------------------------------------- | ------------------------------- | +| `findPrefix`: `return null // No such prefix exists` | 76 | `'cab'` after car/cat/dog (stops at `b`) | `null` | +| `contains`: `node !== null && node.count !== 0` | 135 | `'ca'` (node exists, count 0) | `false` | +| `findOccurrences`: `if (node === null) return 0` | 142 | `'cab'` | `0` | +| `findAllWords`: `if (node === null) return output` | 126 | `'cab'` | `[]` | +| non-string guard in `insert` / `findPrefix` | 52, 70 | `5` | `undefined` / `null`, no change | + +## Fixture (expected values written before running) + +Insert `"car"`, `"cat"`, `"dog"`: + +- `contains('car') === true`, `contains('ca') === false` (prefix only), `findOccurrences('ca') === 0`. +- `findPrefix('cab') === null`, `contains('cab') === false`, `findAllWords('cab')` is `[]`. +- After the failed lookups `findAllWords('')` is unchanged and `findPrefix('cab')` is still `null` + (no node was created). +- **Successful call after the failure:** `insert('cab')` → `contains('cab') === true`, count 1. +- **Repeated insertion:** inserting `'car'` again reuses the same node and makes its count 2. + +Baseline (`baseline.txt`) matched every expected value; no defect in these paths. + +## Proof that the inputs reach the branches + +`evidence.mjs` loads an in-memory copy of the real `Trie.js` in which the two `return null` +statements of `findPrefix` also record a hit (the file on disk is not changed). Running the fixture +gives exactly: + +- `findPrefix('ca')` → no hit (returns the prefix node); +- `contains('cab')` → hit at **line 76** with `i = 2`, i.e. the missing child is `'b'`; +- `findPrefix(5)` → hit at **line 70** (non-string guard). + +## Sensitivity checks (temporary copies only) + +| Mutant applied by `check.py` | Named test that passes on the original and fails on the mutant | +| ------------------------------------------------------ | -------------------------------------------------------------- | +| `contains`: drop `&& node.count !== 0` (line 135) | `prefix 'ca' is not a complete word, but 'car' is` | +| `findPrefix`: `return null` → `return node` at line 76 | `missing word 'cab' reaches the null branch of findPrefix` | + +The real source is never modified. + +## Side observation (not changed) + +`remove` only prunes a node when `child.children.constructor === Object`, but `children` is created +with `Object.create(null)` and has no `constructor`, so pruning never runs. Removing `'car'` after +inserting `'car'` and `'cart'` therefore keeps `'cart'` (checked in `baseline.txt`). This leaves +empty nodes behind but returns correct answers, and it is outside this task's scope. + +## How to run + +From the repository root: + +```sh +python3 work/R50-T008/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 Data-Structures/Tree/test/Trie.test.js --reporter=json --outputFile=work/R50-T008/vitest-focused.raw.json` | 7/7 passed | +| Fixture evidence | `node work/R50-T008/evidence.mjs` | 8/8 rows match | +| Mutant: prefix-only node counted as a word (drop count check) | temporary copy | killed by `prefix 'ca' is not a complete word, but 'car' is` | +| Mutant: missing-child branch returns the partial prefix instead of null | temporary copy | killed by `missing word 'cab' reaches the null branch of findPrefix` | +| Repository test script | `npm test -- --reporter=json --outputFile=work/R50-T008/vitest-full.raw.json` | 11977/11977 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-T008/baseline.txt b/work/R50-T008/baseline.txt new file mode 100644 index 0000000000..a92b3def5a --- /dev/null +++ b/work/R50-T008/baseline.txt @@ -0,0 +1,7 @@ +contains car/ca/cab/x: true false false false +findPrefix ca is node: true count 0 | findPrefix cab: null +findOccurrences car/ca/cab: 1 0 0 +findAllWords cab: [] findAllWords ca: [{"word":"car","count":1},{"word":"cat","count":1}] +after second insert car, occurrences: 2 +insert(5): undefined findPrefix(5): null +side check (remove): insert car,cart; remove car -> contains(cart)= true diff --git a/work/R50-T008/check.py b/work/R50-T008/check.py new file mode 100644 index 0000000000..cf176aacaa --- /dev/null +++ b/work/R50-T008/check.py @@ -0,0 +1,267 @@ +#!/usr/bin/env python3 +"""Focused check runner for R50-T008. + +Run from the repository root: + + python3 work/R50-T008/check.py + +Steps (everything is recorded under work/R50-T008/): + 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-T008/commands.log b/work/R50-T008/commands.log new file mode 100644 index 0000000000..7a1fba97a3 --- /dev/null +++ b/work/R50-T008/commands.log @@ -0,0 +1,18 @@ +$ 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 Data-Structures/Tree/test/Trie.test.js --reporter=json --outputFile=work/R50-T008/vitest-focused.raw.json + -> exit 0 +$ node work/R50-T008/evidence.mjs + -> exit 0 +$ node_modules/.bin/vitest run Data-Structures/Tree/test/Trie.test.js --root $TMPDIR/R50-T008-mutant-lo6e8nzg --globals --reporter=json --outputFile=$TMPDIR/R50-T008-mutant-lo6e8nzg/mutant-report.json + -> exit 1 +$ node_modules/.bin/vitest run Data-Structures/Tree/test/Trie.test.js --root $TMPDIR/R50-T008-mutant-wnjsw24e --globals --reporter=json --outputFile=$TMPDIR/R50-T008-mutant-wnjsw24e/mutant-report.json + -> exit 1 +$ npm test -- --reporter=json --outputFile=work/R50-T008/vitest-full.raw.json + -> exit 0 diff --git a/work/R50-T008/evidence.mjs b/work/R50-T008/evidence.mjs new file mode 100644 index 0000000000..36f560af5b --- /dev/null +++ b/work/R50-T008/evidence.mjs @@ -0,0 +1,143 @@ +// R50-T008 evidence: absent-result paths of the Trie / TrieNode, evaluated on +// the real source. Expected values were written before running. +import { readFileSync } from 'fs' +import { Trie, TrieNode } from '../../Data-Structures/Tree/Trie.js' + +const SRC = 'Trie.js' +const same = (a, b) => JSON.stringify(a) === JSON.stringify(b) +const build = () => { + const t = new Trie() + t.insert('car') + t.insert('cat') + t.insert('dog') + return t +} +const row = (name, input, expected, actual, precondition) => ({ + name, + input, + expected, + actual, + pass: same(expected, actual), + precondition +}) + +const t = build() +const node = new TrieNode('c') +const rows = [ + row( + 'TrieNode without parent', + "new TrieNode('c')", + { parent: null, count: 0 }, + { parent: node.parent, count: node.count }, + `${SRC}:21-22 undefined parent -> null` + ), + row( + "findPrefix('cab') hits the no-such-prefix branch", + 'cab', + null, + t.findPrefix('cab'), + `${SRC}:76 return null // No such prefix exists` + ), + row( + "contains / findOccurrences / findAllWords for 'cab'", + 'cab', + { contains: false, occurrences: 0, words: [] }, + { + contains: t.contains('cab'), + occurrences: t.findOccurrences('cab'), + words: t.findAllWords('cab') + }, + `${SRC}:126,135,142 null node -> empty result` + ), + row( + "prefix 'ca' vs complete word 'car'", + ['ca', 'car'], + { ca: [false, 0], car: [true, 1] }, + { + ca: [t.contains('ca'), t.findOccurrences('ca')], + car: [t.contains('car'), t.findOccurrences('car')] + }, + `${SRC}:135 node.count !== 0` + ), + row( + 'trie unchanged after failed lookups', + 'findAllWords("") after the failed lookups', + [ + { word: 'car', count: 1 }, + { word: 'cat', count: 1 }, + { word: 'dog', count: 1 } + ], + t.findAllWords(''), + `${SRC}:69-80 findPrefix only reads children` + ) +] + +t.insert('cab') +rows.push( + row( + "successful call after the failure: insert('cab')", + 'cab', + { contains: true, occurrences: 1 }, + { contains: t.contains('cab'), occurrences: t.findOccurrences('cab') }, + `${SRC}:51-66 insert creates missing nodes` + ) +) + +const r = build() +r.insert('car') +rows.push( + row( + "repeated insertion of 'car'", + ['car', 'car'], + 2, + r.findOccurrences('car'), + `${SRC}:66 node.count += 1` + ) +) + +// Branch reach: an in-memory copy of the real source records which `return` +// in findPrefix fired and at which character index (the file on disk is not +// changed). Line 70 is the non-string guard, line 76 the missing-child branch. +const source = readFileSync( + new URL('../../Data-Structures/Tree/Trie.js', import.meta.url), + 'utf8' +) +const guard = " if (typeof word !== 'string') return null\n" +const missing = + ' if (node.children[word.charAt(i)] === undefined) return null // No such prefix exists\n' +if (!source.includes(guard) || !source.includes(missing)) { + throw new Error('findPrefix branches not found in source') +} +const probe = + 'export const hits = []\n' + + source + .replace( + guard, + " if (typeof word !== 'string') { hits.push({ line: 70, word }); return null }\n" + ) + .replace( + missing, + ' if (node.children[word.charAt(i)] === undefined) { hits.push({ line: 76, word, i }); return null }\n' + ) +const traced = await import('data:text/javascript,' + encodeURIComponent(probe)) +const tt = new traced.Trie() +tt.insert('car') +tt.insert('cat') +tt.insert('dog') +tt.findPrefix('ca') // reaches neither branch: returns the prefix node +tt.contains('cab') +tt.findPrefix(5) +rows.push( + row( + 'branch reach (instrumented copy): which return null fired', + ["findPrefix('ca')", "contains('cab')", 'findPrefix(5)'], + [ + { line: 76, word: 'cab', i: 2 }, + { line: 70, word: 5 } + ], + traced.hits, + `${SRC}:76 missing child at index 2 ('b'); ${SRC}:70 non-string guard` + ) +) + +console.log(JSON.stringify(rows)) diff --git a/work/R50-T008/results.json b/work/R50-T008/results.json new file mode 100644 index 0000000000..d658e574c2 --- /dev/null +++ b/work/R50-T008/results.json @@ -0,0 +1,194 @@ +{ + "task": "R50-T008", + "install": { + "command": "npm ci --ignore-scripts --no-audit --no-fund", + "exit": 0 + }, + "focused_tests": { + "command": "node_modules/.bin/vitest run Data-Structures/Tree/test/Trie.test.js --reporter=json --outputFile=work/R50-T008/vitest-focused.raw.json", + "exit": 0, + "total": 7, + "passed": 7, + "failed": 0 + }, + "fixture": [ + { + "name": "TrieNode without parent", + "input": "new TrieNode('c')", + "expected": { + "parent": null, + "count": 0 + }, + "actual": { + "parent": null, + "count": 0 + }, + "pass": true, + "precondition": "Trie.js:21-22 undefined parent -> null" + }, + { + "name": "findPrefix('cab') hits the no-such-prefix branch", + "input": "cab", + "expected": null, + "actual": null, + "pass": true, + "precondition": "Trie.js:76 return null // No such prefix exists" + }, + { + "name": "contains / findOccurrences / findAllWords for 'cab'", + "input": "cab", + "expected": { + "contains": false, + "occurrences": 0, + "words": [] + }, + "actual": { + "contains": false, + "occurrences": 0, + "words": [] + }, + "pass": true, + "precondition": "Trie.js:126,135,142 null node -> empty result" + }, + { + "name": "prefix 'ca' vs complete word 'car'", + "input": ["ca", "car"], + "expected": { + "ca": [false, 0], + "car": [true, 1] + }, + "actual": { + "ca": [false, 0], + "car": [true, 1] + }, + "pass": true, + "precondition": "Trie.js:135 node.count !== 0" + }, + { + "name": "trie unchanged after failed lookups", + "input": "findAllWords(\"\") after the failed lookups", + "expected": [ + { + "word": "car", + "count": 1 + }, + { + "word": "cat", + "count": 1 + }, + { + "word": "dog", + "count": 1 + } + ], + "actual": [ + { + "word": "car", + "count": 1 + }, + { + "word": "cat", + "count": 1 + }, + { + "word": "dog", + "count": 1 + } + ], + "pass": true, + "precondition": "Trie.js:69-80 findPrefix only reads children" + }, + { + "name": "successful call after the failure: insert('cab')", + "input": "cab", + "expected": { + "contains": true, + "occurrences": 1 + }, + "actual": { + "contains": true, + "occurrences": 1 + }, + "pass": true, + "precondition": "Trie.js:51-66 insert creates missing nodes" + }, + { + "name": "repeated insertion of 'car'", + "input": ["car", "car"], + "expected": 2, + "actual": 2, + "pass": true, + "precondition": "Trie.js:66 node.count += 1" + }, + { + "name": "branch reach (instrumented copy): which return null fired", + "input": ["findPrefix('ca')", "contains('cab')", "findPrefix(5)"], + "expected": [ + { + "line": 76, + "word": "cab", + "i": 2 + }, + { + "line": 70, + "word": 5 + } + ], + "actual": [ + { + "line": 76, + "word": "cab", + "i": 2 + }, + { + "line": 70, + "word": 5 + } + ], + "pass": true, + "precondition": "Trie.js:76 missing child at index 2 ('b'); Trie.js:70 non-string guard" + } + ], + "mutants": [ + { + "name": "prefix-only node counted as a word (drop count check)", + "file": "Data-Structures/Tree/Trie.js", + "edit": { + "from": " return node !== null && node.count !== 0\n", + "to": " return node !== null\n" + }, + "named_test": "prefix 'ca' is not a complete word, but 'car' is", + "named_test_on_original": ["passed"], + "killed": true, + "exit": 1, + "failed_tests_on_mutant": [ + " Trie absent-result paths (no exceptions are thrown) prefix 'ca' is not a complete word, but 'car' is" + ] + }, + { + "name": "missing-child branch returns the partial prefix instead of null", + "file": "Data-Structures/Tree/Trie.js", + "edit": { + "from": "=== undefined) return null // No such prefix exists\n", + "to": "=== undefined) return node // No such prefix exists\n" + }, + "named_test": "missing word 'cab' reaches the null branch of findPrefix", + "named_test_on_original": ["passed"], + "killed": true, + "exit": 1, + "failed_tests_on_mutant": [ + " Trie absent-result paths (no exceptions are thrown) missing word 'cab' reaches the null branch of findPrefix", + " Trie absent-result paths (no exceptions are thrown) failed lookups leave the trie unchanged and later calls succeed" + ] + } + ], + "full_suite": { + "command": "npm test -- --reporter=json --outputFile=work/R50-T008/vitest-full.raw.json", + "exit": 0, + "total": 11977, + "passed": 11977, + "failed": 0 + }, + "ok": true, + "failures": [] +} diff --git a/work/R50-T008/task.json b/work/R50-T008/task.json new file mode 100644 index 0000000000..77dae753e8 --- /dev/null +++ b/work/R50-T008/task.json @@ -0,0 +1,22 @@ +{ + "task": "R50-T008", + "focused_tests": ["Data-Structures/Tree/test/Trie.test.js"], + "mutants": [ + { + "name": "prefix-only node counted as a word (drop count check)", + "file": "Data-Structures/Tree/Trie.js", + "find": " return node !== null && node.count !== 0\n", + "replace": " return node !== null\n", + "tests": ["Data-Structures/Tree/test/Trie.test.js"], + "must_fail": "prefix 'ca' is not a complete word, but 'car' is" + }, + { + "name": "missing-child branch returns the partial prefix instead of null", + "file": "Data-Structures/Tree/Trie.js", + "find": "=== undefined) return null // No such prefix exists\n", + "replace": "=== undefined) return node // No such prefix exists\n", + "tests": ["Data-Structures/Tree/test/Trie.test.js"], + "must_fail": "missing word 'cab' reaches the null branch of findPrefix" + } + ] +} diff --git a/work/R50-T008/versions.txt b/work/R50-T008/versions.txt new file mode 100644 index 0000000000..b405ff9cb4 --- /dev/null +++ b/work/R50-T008/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-T008/vitest-focused.json b/work/R50-T008/vitest-focused.json new file mode 100644 index 0000000000..857e83705c --- /dev/null +++ b/work/R50-T008/vitest-focused.json @@ -0,0 +1,36 @@ +{ + "command": "node_modules/.bin/vitest run Data-Structures/Tree/test/Trie.test.js --reporter=json --outputFile=work/R50-T008/vitest-focused.raw.json", + "numTotalTests": 7, + "numPassedTests": 7, + "numFailedTests": 0, + "tests": [ + { + "name": " TrieNode a node created without a parent has parent null and count 0", + "status": "passed" + }, + { + "name": " TrieNode a child node keeps a reference to its parent", + "status": "passed" + }, + { + "name": " Trie absent-result paths (no exceptions are thrown) missing word 'cab' reaches the null branch of findPrefix", + "status": "passed" + }, + { + "name": " Trie absent-result paths (no exceptions are thrown) prefix 'ca' is not a complete word, but 'car' is", + "status": "passed" + }, + { + "name": " Trie absent-result paths (no exceptions are thrown) non-string input is ignored, not thrown (lines 52 and 70)", + "status": "passed" + }, + { + "name": " Trie absent-result paths (no exceptions are thrown) failed lookups leave the trie unchanged and later calls succeed", + "status": "passed" + }, + { + "name": " Trie absent-result paths (no exceptions are thrown) repeated insertion increments the count of the same node", + "status": "passed" + } + ] +}