{"record":{"id":"3b0a06f3f176ee51","repo":"shareAI-lab/learn-claude-code","slug":"could-not-allocate-a-unique-task-id","errorCode":null,"errorMessage":"Could not allocate a unique task ID","messagePattern":"Could not allocate a unique task ID","errorType":"exception","errorClass":"RuntimeError","httpStatus":null,"severity":"error","filePath":"s10_task_system/code.py","lineNumber":129,"sourceCode":"        self._root(create=True)\n        for _ in range(100):\n            task = Task(\n                id=f\"task_{secrets.token_hex(4)}\",\n                subject=subject,\n                description=description,\n                status=\"pending\",\n                owner=None,\n                blockedBy=dependencies,\n            )\n            try:\n                with self._path(task.id, create_root=True).open(\n                    \"x\", encoding=\"utf-8\"\n                ) as handle:\n                    json.dump(asdict(task), handle, indent=2)\n                return task\n            except FileExistsError:\n                continue\n        raise RuntimeError(\"Could not allocate a unique task ID\")\n\n    def save(self, task: Task) -> None:\n        self._path(task.id, create_root=True).write_text(\n            json.dumps(asdict(task), indent=2),\n            encoding=\"utf-8\",\n        )\n\n    def load(self, task_id: str) -> Task:\n        data = json.loads(self._path(task_id).read_text(encoding=\"utf-8\"))\n        task = Task(**data)\n        if task.id != task_id:\n            raise ValueError(f\"Task file ID does not match {task_id}\")\n        if task.status not in (\"pending\", \"in_progress\", \"completed\"):\n            raise ValueError(f\"Invalid task status: {task.status}\")\n        return task\n\n    def list(self) -> list[Task]:\n        if not self.directory.exists():","sourceCodeStart":111,"sourceCodeEnd":147,"githubUrl":"https://github.com/shareAI-lab/learn-claude-code/blob/985456f4adea6f4df8fbad4112245dbd97444eae/s10_task_system/code.py#L111-L147","documentation":"Raised by TaskStore.create() in s10_task_system/code.py:129 after 100 attempts to allocate a collision-free task ID all hit FileExistsError. IDs are 'task_' + secrets.token_hex(4) (32 bits) and are created with open(mode='x') so a race with another writer is detected atomically; on collision the loop retries. Exhausting 100 tries means either ~2^31 tasks exist, the 'x' open is failing with FileExistsError for a structural reason (a directory of the same name exists), or a pathological environment.","triggerScenarios":"Practically unreachable by random chance (birthday collisions among 100 draws against even millions of IDs are still vanishingly rare). Realistic triggers: a directory named like 'task_xxxxxxxx.json' exists in the store (open 'x' then raises FileExistsError on Windows/dirs), or a filesystem/permission quirk mapping other errors to FileExistsError, making every attempt 'collide'.","commonSituations":"Corrupted store where files were replaced by directories; exotic filesystems (some network mounts) not honoring O_EXCL semantics; extremely large test fixture stores created by writing ID files exhaustively.","solutions":["Inspect the store directory for entries that are directories or have wrong names (ls -l .tasks) and remove/repair them.","If genuinely near the ID-space limit, widen the ID (e.g. token_hex(8)) and migrate existing files, or archive the store and start fresh.","Run create() again after cleanup; treat a second occurrence as a filesystem-level issue and check mount type/permissions."],"exampleFix":"# before\nid=f'task_{secrets.token_hex(4)}'  # 4 bytes\n\n# after: widen the ID space (requires migrating old files)\nid=f'task_{secrets.token_hex(8)}'  # and TASK_ID_PATTERN updated to {16}","handlingStrategy":"retry","validationCode":"import re\nfrom pathlib import Path\n\ndef store_has_no_dir_named_like_tasks(store_dir: Path) -> bool:\n    return not any(p.is_dir() for p in store_dir.glob('task_*.json')) if store_dir.exists() else True","typeGuard":null,"tryCatchPattern":"try:\n    task = store.create(subject)\nexcept RuntimeError as e:\n    if 'unique task ID' in str(e):\n        # inspect store, remove stray directories, then retry once\n        audit_store(store.directory)\n        task = store.create(subject)\n    else:\n        raise","preventionTips":["Never create files/directories manually inside .tasks that mimic task filenames.","Create tasks only through TaskStore.create().","If the store grows toward millions of IDs, widen the ID format and migrate."],"tags":["tasks","ids","race-condition","filesystem"],"backgroundTag":null,"analyzedSha":"985456f4adea6f4df8fbad4112245dbd97444eae","analyzedAt":"2026-08-14T22:02:26.028Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}