shareAI-lab/learn-claude-code · error · RuntimeError

Could not allocate a unique task ID

Error message

Could not allocate a unique task ID

What it means

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.

Source

Thrown at s10_task_system/code.py:129

        self._root(create=True)
        for _ in range(100):
            task = Task(
                id=f"task_{secrets.token_hex(4)}",
                subject=subject,
                description=description,
                status="pending",
                owner=None,
                blockedBy=dependencies,
            )
            try:
                with self._path(task.id, create_root=True).open(
                    "x", encoding="utf-8"
                ) as handle:
                    json.dump(asdict(task), handle, indent=2)
                return task
            except FileExistsError:
                continue
        raise RuntimeError("Could not allocate a unique task ID")

    def save(self, task: Task) -> None:
        self._path(task.id, create_root=True).write_text(
            json.dumps(asdict(task), indent=2),
            encoding="utf-8",
        )

    def load(self, task_id: str) -> Task:
        data = json.loads(self._path(task_id).read_text(encoding="utf-8"))
        task = Task(**data)
        if task.id != task_id:
            raise ValueError(f"Task file ID does not match {task_id}")
        if task.status not in ("pending", "in_progress", "completed"):
            raise ValueError(f"Invalid task status: {task.status}")
        return task

    def list(self) -> list[Task]:
        if not self.directory.exists():

View on GitHub (pinned to 985456f4ad)

Solutions

  1. Inspect the store directory for entries that are directories or have wrong names (ls -l .tasks) and remove/repair them.
  2. 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.
  3. Run create() again after cleanup; treat a second occurrence as a filesystem-level issue and check mount type/permissions.

Example fix

# before
id=f'task_{secrets.token_hex(4)}'  # 4 bytes

# after: widen the ID space (requires migrating old files)
id=f'task_{secrets.token_hex(8)}'  # and TASK_ID_PATTERN updated to {16}
Defensive patterns

Strategy: retry

Validate before calling

import re
from pathlib import Path

def store_has_no_dir_named_like_tasks(store_dir: Path) -> bool:
    return not any(p.is_dir() for p in store_dir.glob('task_*.json')) if store_dir.exists() else True

Try / catch

try:
    task = store.create(subject)
except RuntimeError as e:
    if 'unique task ID' in str(e):
        # inspect store, remove stray directories, then retry once
        audit_store(store.directory)
        task = store.create(subject)
    else:
        raise

Prevention

When it happens

Trigger: 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'.

Common situations: 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.

Related errors


AI-assisted analysis of shareAI-lab/learn-claude-code@985456f4ad (2026-08-14). Data as JSON: /api/errors/3b0a06f3f176ee51. Report an issue: GitHub.