fix(memory/graph): apply relation_type filter to both sides of a BOTH subgraph query (#3236)

## Description

`SQLiteGraphStore.query_subgraph` builds the relationship query for a
`direction=BOTH` traversal without parenthesizing the `OR`, then appends
the `relation_types` filter:

```python
else:  # BOTH
    rel_query = "SELECT * FROM relationships WHERE source_id = ? OR target_id = ?"
    rel_params = [current_id, current_id]

if relation_types is not None and len(relation_types) > 0:
    rel_query += f" AND relation_type IN ({placeholders})"
```

The resulting SQL is `WHERE source_id = ? OR target_id = ? AND
relation_type IN (...)`. In SQL, `AND` binds tighter than `OR`, so this
parses as:

```sql
WHERE source_id = ?  OR  (target_id = ? AND relation_type IN (...))
```

The type filter therefore applies **only to the incoming (`target_id`)
side**. Every **outgoing** edge from the current node is returned
regardless of type, so a `direction=BOTH` subgraph traversal with a
`relation_types` filter pulls in relationships — and the entities they
point to — that should have been excluded. `get_relationships` already
groups this correctly (`"(source_id = ? OR target_id = ?)"`);
`query_subgraph` was the outlier.

Reproduction (X has `likes->Liked` and `dislikes->Disliked`):

```python
subgraph = await store.query_subgraph([X], max_hops=1,
                                       direction=RelationshipDirection.BOTH,
                                       relation_types=["likes"])
# BEFORE: subgraph.relationships includes the 'dislikes' edge; entities include 'Disliked'
# AFTER:  only the 'likes' edge and {'X', 'Liked'}
```

## Type of Change

- [x] Bug fix (non-breaking change that fixes an issue)
- [ ] New feature (non-breaking change that adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)
- [ ] Documentation update
- [ ] Performance improvement
- [ ] Code refactoring (no functional changes)

## Changes Made

- `headroom/memory/adapters/sqlite_graph.py`: parenthesize the `BOTH`
predicate — `WHERE (source_id = ? OR target_id = ?)` — so the appended
`AND relation_type IN (...)` filters both directions. A comment records
the precedence trap and points at the already-correct
`get_relationships`.
- `tests/test_sqlite_graph_store.py`: added
`test_query_subgraph_both_direction_respects_relation_type_filter` — a
node with two outgoing edges of different types, queried `BOTH` +
`relation_types=["likes"]`, must not return the other-typed edge or its
entity. Red→green: it fails on the un-parenthesized query and passes
with the fix.

## Testing

- [x] Unit tests pass (`pytest`)
- [x] Linting passes (`ruff check`)
- [x] Type checking passes (`mypy headroom`)
- [x] New tests added for new functionality

### Test Output

```text
tests/test_sqlite_graph_store.py::...both_direction_respects_relation_type_filter  ->  passes with fix, FAILS without it (verified via git stash)
uvx ruff@0.16.2 check headroom/memory/adapters/sqlite_graph.py tests/test_sqlite_graph_store.py  ->  All checks passed!
uvx mypy@1.20.2 headroom/memory/adapters/sqlite_graph.py  ->  Success: no issues found in 1 source file
```

(Note: this test file has pre-existing, unrelated failures on `main` in
`TestSQLiteGraphStoreMemoryTrackerIntegration` — present before and
after this change; my new test and the traversal suite are unaffected.)

## Real Behavior Proof

- Environment: Windows 11, Python 3.12.11, project venv, pytest 9.1.1,
ruff 0.16.2 and mypy 1.20.2 via uvx.
- Exact command / steps: built a store with X --likes--> Liked and X
--dislikes--> Disliked, then `query_subgraph([X], max_hops=1,
direction=BOTH, relation_types=["likes"])`. Before the fix the returned
relationships contained the `dislikes` edge and the entity set contained
`Disliked`; after the fix only the `likes` edge and `{X, Liked}` are
returned. Confirmed at the raw-SQL level too: `source_id = ? OR
target_id = ? AND relation_type IN (?)` returns the wrong-typed row,
`(source_id = ? OR target_id = ?) AND relation_type IN (?)` does not.
- Observed result: the type filter now applies to both directions;
unfiltered and single-direction queries are unchanged.
- Not tested: no change to `OUTGOING`/`INCOMING` branches
(single-condition, unaffected); their existing tests still pass.

## Runtime Rollout Safety

- Rollout-managed feature(s): none. This is a SQLite graph-store query
in the memory subsystem, not a rollout-channel-gated runtime feature.
- Minimum rollout channel: N/A.
- Stable/default behavior changed: only the incorrect result is
corrected — a `BOTH` subgraph query with a `relation_types` filter now
excludes outgoing edges of other types, as intended. Queries without a
type filter, and `OUTGOING`/`INCOMING` queries, are unchanged.
- Kill switch / disable path: N/A.
- Unsafe override required: no.
- Qualification impact: none.
- Rollback path: revert this PR.

## Review Readiness

- [x] I have performed a self-review
- [x] This PR is ready for human review

## Checklist

- [x] My code follows the project's style guidelines
- [x] I have performed a self-review of my code
- [x] I have commented my code, particularly in hard-to-understand areas
- [ ] I have made corresponding changes to the documentation (N/A:
internal behavior)
- [x] My changes generate no new warnings
- [x] I have added tests that prove my fix is effective or that my
feature works
- [x] New and existing unit tests pass locally with my changes
- [x] I did **not** edit `CHANGELOG.md`
This commit is contained in:
Abhay Singh
2026-09-25 10:44:18 -05:00
committed by GitHub
parent 76ec363a60
commit 1a6f941908
2 changed files with 47 additions and 1 deletions
+7 -1
View File
@@ -485,8 +485,14 @@ class SQLiteGraphStore:
rel_query = "SELECT * FROM relationships WHERE target_id = ?"
rel_params = [current_id]
else: # BOTH
# The OR must be parenthesized: a later ``AND relation_type
# IN (...)`` binds tighter than ``OR`` in SQL, so without
# the parens the type filter would apply only to the
# ``target_id`` (incoming) side, letting outgoing edges of
# every type leak into the subgraph. (``get_relationships``
# already groups this correctly.)
rel_query = (
"SELECT * FROM relationships WHERE source_id = ? OR target_id = ?"
"SELECT * FROM relationships WHERE (source_id = ? OR target_id = ?)"
)
rel_params = [current_id, current_id]
+40
View File
@@ -412,6 +412,46 @@ class TestSQLiteGraphStoreTraversal:
assert "C" in entity_names
assert "A" in entity_names
@pytest.mark.asyncio
async def test_query_subgraph_both_direction_respects_relation_type_filter(self, tmp_path):
"""A relation_types filter must apply to BOTH the outgoing and incoming
sides of a ``direction=BOTH`` traversal.
Regression: the BOTH query was ``WHERE source_id = ? OR target_id = ?``
without parentheses, then ``AND relation_type IN (...)`` was appended.
SQL binds ``AND`` tighter than ``OR``, so the type filter applied only to
the incoming (target_id) side, letting outgoing edges of every type leak
into the subgraph.
"""
store = SQLiteGraphStore(db_path=str(tmp_path / "graph.db"))
x = Entity(user_id="u", name="X", entity_type="node")
liked = Entity(user_id="u", name="Liked", entity_type="node")
disliked = Entity(user_id="u", name="Disliked", entity_type="node")
for entity in (x, liked, disliked):
await store.add_entity(entity)
# Two OUTGOING edges from X of different types.
await store.add_relationship(
Relationship(user_id="u", source_id=x.id, target_id=liked.id, relation_type="likes")
)
await store.add_relationship(
Relationship(
user_id="u", source_id=x.id, target_id=disliked.id, relation_type="dislikes"
)
)
subgraph = await store.query_subgraph(
[x.id],
max_hops=1,
direction=RelationshipDirection.BOTH,
relation_types=["likes"],
)
types = {r.relation_type for r in subgraph.relationships}
assert types == {"likes"}, f"type filter leaked non-'likes' edges: {types}"
names = {e.name for e in subgraph.entities}
assert "Disliked" not in names
assert names == {"X", "Liked"}
@pytest.mark.asyncio
async def test_find_path_direct(self, store_with_graph):
"""Test finding a direct path."""