harbor run -t openthoughts/tasktrove-exp-rpt-curriculum-hard-curriculum-hard-0046harbor download openthoughts/tasktrove-exp-rpt-curriculum-hard-curriculum-hard-0046Harder version: multi-file, highly-performant Cirq subset with concurrency-safe primitives
Objective
Build a self-contained, high-performance subset of Cirq that satisfies stricter testing surface and constraints. The solution must live as a small, importable package under /app/ named cirq (i.e., /app/cirq with an __init__.py and optional submodules). The public API, behavior, and string representations must remain compatible with the original tests, but the implementation should be robust to parallel access, edge cases, and larger inputs.
What to implement (harder version)
1) Package layout and packaging constraints
- Create a small Cirq-like package under /app/cirq with the following structure (at minimum):
- /app/cirq/__init__.py
- /app/cirq/device.py (defines Device)
- /app/cirq/qubits.py (defines LineQubit, GridQubit, NamedQubit)
- /app/cirq/pairs.py (defines QidPair and SymmetricalQidPair)
- /app/cirq/utils.py (optional helper utilities)
- The top-level import "import cirq" should resolve to this package (i.e., /app is on sys.path during tests). Do not rely on a single module named cirq.py.
- Expose a clean public API via cirq.__all__ (or equivalent) to match expected usage in tests.
2) Core device interface (thread-safe, lazy, and cache-friendly)
- Class: Device (in device.py)
- Method: qubit_set(self) -> Optional[FrozenSet[Qubit]]
- Behavior:
- If the instance has a qubit source, return a frozenset of those qubits.
- Support multiple sources:
- Public attribute: self.qubits
- Public method: self.qubits()
- Private attribute: self._qubits
- Private method: self._qubits()
- If no source is found, return None.
- Concurrency and caching:
- Implement a thread-safe, lazy evaluation: the first successful source access caches the result; subsequent calls return the cached frozenset.
- Use a reentrant lock to guard initialization. If the qubit source changes after caching, document and decide whether to invalidate cache or keep the cached value (pick one and enforce consistently).
- Method: qid_pairs(self) -> Optional[List[QidPair]]
- Behavior:
- If qubit_set() is None, return None.
- If qubits form a LineQubit sequence with consecutive indices (e.g., LineQubit.range(n)), return adjacent pairs as SymmetricalQidPair objects: (q0, q1), (q1, q2), ..., (q(n-2), q(n-1)).
- If qubits form a full rectangular GridQubit set (GridQubit.rect(rows, cols)), return all adjacent neighbor pairs (horizontal and vertical) as SymmetricalQidPair objects.
- Otherwise (e.g., a plain list of arbitrary qubits like NamedQubit), return all unordered pairs as QidPair objects, preserving the input order for each pair (i.e., for a pair from indices i < j, yield QidPair(q[i], q[j])).
- Performance guarantees:
- LineQubit.range(n): O(n) pairs.
- GridQubit.rect(r, c): O(r*c) pairs (approximately r*(c-1) + (r-1)*c).
- Generic list of m qubits: O(m*(m-1)/2) pairs.
- Caching: cache the computed list unless the underlying qubit_set changes (document this behavior and enforce a clear policy).
- Considerations:
- RawDevice-like objects with no qubits should yield None for qubit_set() and None for qid_pairs().
- Be robust to unusual inputs (e.g., empty lists, duplicates) while preserving deterministic output.
3) Qid pair representations and behavior
- Class: QidPair (in pairs.py)
- Purpose: Represents an ordered pair of qubits (used when the test requires all-pairs in a generic case).
- Constructor: QidPair(q0: Qubit, q1: Qubit)
- Methods/behavior:
- __iter__ yields (q0, q1)
- __len__ returns 2
- __contains__(qubit) returns True if qubit is q0 or q1
- __repr__ returns "cirq.QidPair(repr(q0), repr(q1))"
- Compatibility:
- Tests rely on representation like "cirq.QidPair(cirq.LineQubit(0), cirq.LineQubit(1))" so ensure that repr uses the exact string format shown.
- Class: SymmetricalQidPair (unordered pair)
- Constructor: SymmetricalQidPair(q0: Qubit, q1: Qubit)
- If q0 and q1 are identical, raise ValueError with exact message:
A QidPair cannot have identical qids.
- Normalization:
- Canonical ordering by repr(q) (or a deterministic key) such that:
- SymmetricalQidPair(q0, q1) == SymmetricalQidPair(q1, q0)
- Iteration order is consistent with the canonical order
- Methods/behavior:
- __iter__ yields (q0, q1) in canonical order
- __len__ returns 2
- __contains__(qubit) returns True if qubit is q0 or q1
- __eq__(other) returns True if both pairs contain the same two qubits (order-insensitive)
- __hash__ returns a hash based on a frozenset({q0, q1}) to ensure equal pairs hash identically
- __repr__ returns "cirq.QidPair(repr(q0), repr(q1))" (note: same representation as QidPair, test harness expects this pattern)
- Normalization and equality semantics are important for the tests; ensure deterministic behavior and proper hashing/equality across swapped inputs.
4) Minimal qubit classes used by tests (in qubits.py)
- Class: LineQubit
- Constructor: LineQubit(index: int)
- Attributes: index
- Static method: range(n: int) -> List[LineQubit]
- __repr__: "cirq.LineQubit(index)"
- __eq__/__hash__ implemented so two LineQubit(index) with the same index compare equal
- Class: GridQubit
- Constructor: GridQubit(row: int, col: int)
- Attributes: row, col
- Static method: rect(rows: int, cols: int) -> List[GridQubit]
- __repr__: "cirq.GridQubit(row, col)"
- __eq__/__hash__ implemented
- Class: NamedQubit
- Constructor: NamedQubit(name: str)
- Attribute: name
- __repr__: "cirq.NamedQubit(name)"
- __eq__/__hash__ implemented
- Design constraints:
- All qubit classes must be comparable by value (i.e., two LineQubit(3) are equal, etc.)
- __hash__ must be defined to allow usage in sets/dicts
5) Performance, edge cases, and design details
- Performance
- Provide O(n) generation for all LineQubit pairs and O(rows*cols) for GridQubit pairs.
- For arbitrary qubit lists, ensure the O(m^2) behavior is implemented with careful iteration to minimize Python overhead.
- Use minimal allocations and avoid unnecessary intermediate structures where possible.
- Edge cases
- Empty inputs should be handled gracefully:
- qubit_set() returns None if there is no source
- qid_pairs() returns None when qubit_set() is None
- Unicode and exotic names in NamedQubit should not break representation or comparisons
- Duplicates in input sequences should be treated deterministically (e.g., deduplicate before pair generation or document behavior; pick one and enforce consistently)
- Concurrency and safety
- All lazy initializations must be thread-safe.
- Use a reentrant lock (threading.RLock) to guard access to cached state.
- Ensure that the module’s behavior remains deterministic under concurrent access.
6) API guarantees and representations
- Exact string representations required by tests:
- LineQubit: "cirq.LineQubit(0)"
- GridQubit: "cirq.GridQubit(row, col)"
- NamedQubit: "cirq.NamedQubit(name)"
- QidPair / SymmetricalQidPair: "cirq.QidPair(repr(q0), repr(q1))"
- The tests rely on:
- SymmetricalQidPair(LineQubit(0), LineQubit(1)) == SymmetricalQidPair(LineQubit(1), LineQubit(0))
- Length checks for qid_pairs in three scenarios:
- 10 LineQubits → 9 pairs
- 10x10 GridQubits → 180 pairs
- 10 NamedQubits → 45 pairs
- Proper behavior of __iter__, __len__, __contains__, and __repr__
- Equality and hashing behavior for SymmetricalQidPair
- Ensure the public API surface remains compatible with tests:
- Importable as cirq
- Public classes and methods callable as described
- No external dependencies beyond the Python standard library
7) Testing considerations (guidance)
- While you are not required to implement tests, design so that:
- The module passes the described tests that exercise:
- qubit_set and qubit source resolution (public/private sources)
- qid_pairs generation across LineQubit, GridQubit, and NamedQubit inputs
- QidPair and SymmetricalQidPair behavior including equality, hashing, and repr
- Document any non-obvious behavior (e.g., how cache invalidation is handled when qubit sources change) to aid future maintenance and testing.
Notes
- The final implementation must be purely Python, no third-party libraries.
- Keep the code readable, well-documented, and type-annotated where helpful.
- Ensure the code lives under /app/ and adheres to the packaging constraints described above.
Outcome
Deliver a self-contained, multi-file Cirq subset in /app/cirq that is robust to concurrency, supports lazy evaluation with caching, handles edge cases, and matches all specified string representations and behavior required by the tests.