Skip to content

Block.get() raises unhelpful KeyError when path traverses through a CID link #27

Description

@sumanjeet0012

When Block.get() encounters a CID (link) while traversing a path, it tries to use the CID as a dict/list and raises a generic KeyError. It should either stop at the link boundary and return the CID, or raise a more informative error indicating that the path crosses a block boundary.

Problem

In dag/block.py:

def get(self, path: str) -> Any:
    segments = [s for s in path.split("/") if s]
    current: Any = self._value
    for seg in segments:
        if isinstance(current, dict):
            current = current[seg]
        elif isinstance(current, list):
            current = current[int(seg)]
        else:
            raise KeyError(f"Cannot traverse into {type(current).__name__} with {seg!r}")
    return current

When a value is a CID:

block = Block.encode(
    value={"link": some_cid, "data": "hello"},
    codec=dag_cbor.codec,
)

# This raises: KeyError: "Cannot traverse into CIDv1 with 'nested'"
block.get("link/nested")

The error message doesn't explain that the path crosses a block boundary and that the caller needs to load the linked block.

Proposed Solution

Add explicit CID handling:

def get(self, path: str) -> Any:
    segments = [s for s in path.split("/") if s]
    current: Any = self._value
    for i, seg in enumerate(segments):
        if is_cid(current):
            remaining = "/".join(segments[i:])
            raise LinkBoundaryError(
                f"Path crosses block boundary at CID {current}. "
                f"Remaining path: {remaining!r}. "
                f"Load the linked block to continue traversal."
            )
        if isinstance(current, dict):
            current = current[seg]
        elif isinstance(current, list):
            current = current[int(seg)]
        else:
            raise KeyError(f"Cannot traverse into {type(current).__name__} with {seg!r}")
    return current

Add a new exception class:

class LinkBoundaryError(Exception):
    """Raised when path traversal crosses a block boundary (CID link)."""
    pass

Related

  • File: dag/block.py

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions