Skip to content

Bug: ID collision after deleting items causes duplicate IDs #7

Description

@manish-jangra

Description

The create_item() function generates new item IDs using len(_get_items()) + 1. This approach causes duplicate IDs when items are deleted from the middle or beginning of the list.

Steps to Reproduce

  1. Create item A → id=1
  2. Create item B → id=2
  3. Delete item A (id=1) — list now contains only item B (id=2), length = 1
  4. Create item C → len([B]) + 1 = 2id=2 (duplicate!)

Now two items (B and C) both have id=2.

Expected Behavior

Each item should have a globally unique ID that is never reused, regardless of deletions.

Actual Behavior

IDs can collide after deletions because the ID generation is based on the current list length rather than a monotonically increasing counter.

Impact

  • PATCH /items/:id and DELETE /items/:id will only operate on the first item found with the duplicate ID (via next()), making the second item inaccessible.
  • Clients caching items by ID will get stale/incorrect data.

Suggested Fix

Replace the length-based ID with an auto-incrementing counter:

_next_id = 1

def _new_id():
    global _next_id
    current = _next_id
    _next_id += 1
    return current

And update create_item():

item = {
    "id": _new_id(),
    "name": data["name"],
    "done": False,
}

Also update reset_items() to reset the counter for tests:

def reset_items():
    global _next_id
    _items_store.clear()
    _next_id = 1

Affected File

  • app.pycreate_item() function (line ~29)

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions