Skip to content

Feature/neo4j - #18

Open
araadhay-py wants to merge 15 commits into
ResearchifyLabs:mainfrom
araadhay-py:feature/Neo4j
Open

araadhay-py wants to merge 15 commits into
ResearchifyLabs:mainfrom
araadhay-py:feature/Neo4j

Conversation

@araadhay-py

Copy link
Copy Markdown
Contributor

What does this PR do?

Why?

Checklist

  • Tests pass (PYTHONPATH=src:tests python -m unittest discover -s tests -p 'test_*.py')
  • New code has tests (if applicable)
  • CHANGELOG.md updated under [Unreleased] (if user-facing)

…tion

- Implement Neo4jGraphStore with full GraphStore protocol compliance
- Create comprehensive graph model with Cluster, Decision, Topic, Entity, Constraint, Fact, and Initiator nodes
- Add idempotent operations using MERGE for safe upserts
- Include 7 unique constraints for data integrity
- Support batch processing for performance optimization
- Add comprehensive error handling and logging
- Create complete test suite with 20+ test cases
- Add ready-to-run demo with mock and real data support
- Update documentation with Neo4j usage examples
- Fix Python 3.9 compatibility issues across core modules
- Add neo4j dependency to pyproject.toml

Files added:
- src/decision_graph/backends/neo4j/__init__.py
- src/decision_graph/backends/neo4j/stores.py
- tests/test_neo4j_graphstore.py
- examples/complete_neo4j_demo.py
- examples/neo4j_demo.py
- NEO4J_IMPLEMENTATION_SUMMARY.md
- NEO4J_IMPLEMENTATION_EMAIL.md

Files modified:
- README.md (Neo4j documentation and examples)
- pyproject.toml (neo4j dependency)
- src/decision_graph/core/domain.py (Python 3.9 compatibility)
- src/decision_graph/enrichment_service.py (Python 3.9 compatibility)
- src/decision_graph/retrieval.py (Python 3.9 compatibility)
- src/decision_graph/core/decision_trace_profiles.py (Python 3.9 compatibility)

The Neo4j backend enables persistent graph storage with powerful Cypher queries
for decision analytics while maintaining seamless integration with existing pipeline.
- Merge latest changes from main branch
- Include viewer.html and run.py updates
- Resolve merge conflicts
- Fix relationship names to match context_graph registry (HAS_DECISION,
  MENTIONS_ENTITY, INITIATED_BY, HAS_COUNTERPARTY)
- Switch Entity/Topic to shared concept nodes for proper graph traversal
- Add Neo4jGraphReader implementing the GraphReader protocol
- Extract counterparty_names in ingestion and write HAS_COUNTERPARTY edges
- Add pytest config and switch CI from unittest discover to pytest
- Add 34 unit tests covering Neo4jGraphStore and Neo4jGraphReader
- Update EXPECTED_BREAKDOWN_KEYS in ingestion tests
- Neo4jGraphStore: materialises hydrated clusters into Neo4j using
  correct relationship names (HAS_DECISION, MENTIONS_ENTITY, INITIATED_BY)
  matching context_graph/registry.py so all Cypher templates work
- Neo4jGraphReader: implements GraphReader protocol (resolve,
  execute_template, run_query) required by ContextGraphService
- Topic and Entity nodes modelled as shared concept nodes so graph
  traversal works correctly across decisions
- Unit tests in tests/unit/decision_graph/backends/neo4j/ using unittest
- Replace Optional[str] with str | None throughout domain.py
- Replace Optional[str] with str | None in decision_trace_profiles.py
- Remove Optional import from both files (not needed with 3.10+ syntax)
- Remove unused MagicMock and call imports from Neo4j test file
decision_ids = [d["decision_id"] for d in arrays["decisions"]]
self._delete_enrichment_edges(session, decision_ids)

self._upsert_topics(session, arrays["decision_topics"])

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No batching — entire list goes into a single UNWIND. Will timeout/OOM on 1000+ decisions. Chunk it (500-1000 per batch).

len(arrays["decisions"]),
len(arrays["decision_topics"]),
len(arrays["decision_constraints"]),
len(arrays["decision_entities"]),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This runs on every ingest() call. Move to a separate ensure_schema() or run_migration() called once at startup — not on every write.

self._link_clusters_decisions(session, arrays["decision_cluster"])

decision_ids = [d["decision_id"] for d in arrays["decisions"]]
self._delete_enrichment_edges(session, decision_ids)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

session.run() is auto-commit. Use session.execute_write(lambda tx: tx.run(...)) for proper transaction safety and retry handling.

len(arrays["decision_constraints"]),
len(arrays["decision_entities"]),
len(arrays["decision_facts"]),
len(arrays["decision_initiators"]),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Topic uniqueness is global (name only). Two groups with a topic called "pricing" will share one node. If that is intentional, document it. If not, scope by namespace.

props = dict(node)
cid = props.get("decision_id", "")
if cid and cid not in seen:
seen.add(cid)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Returns raw neo4j.Record objects — couples consumers to the driver. Return [record.data() for record in records] instead.

self,
text: str,
types: Optional[List[str]] = None,
top_k: int = 8,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fallback only fires when candidates is empty. Fire when len(candidates) < top_k to supplement partial results — better recall for ambiguous queries.

Comment thread examples/complete_neo4j_demo.py Outdated

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what is difference between this demo file, neo4j demo and run.py - do we really need 3 of them ?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why this change ?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why this file has changed ?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why this file has changed

- Move _create_constraints out of ingest() into ensure_schema() — schema
  setup should run once at startup, not on every write
- Batch all UNWIND calls into chunks of 500 to prevent timeout/OOM on
  large datasets
- Use session.execute_write() for all DML — proper transaction safety
  and automatic retry handling
- Document intentional global Topic node design in class docstring
- Return record.data() from execute_template to decouple consumers
  from the neo4j driver type
- Fire resolve() fallback when len(candidates) < top_k, not only when
  empty — better recall for ambiguous queries
- Revert retrieval.py to main (only had Optional[str] instead of str | None,
  a leftover Python 3.9 compat change unrelated to Neo4j)
- Remove test_graph_config.py which tests GraphConfig propagation through
  enrichment_service — out of scope for this PR
Replace Optional[str] / Optional[dict] with str | None / dict | None
and remove Optional from typing imports — consistent with domain.py
- reader.py: replace Dict/List from typing with built-in dict/list
- stores.py: replace Dict/List from typing with built-in dict/list
- domain.py: remove trailing comma after Literal
- delete examples/complete_neo4j_demo.py (had MockNeo4jDriver, redundant
  with neo4j_demo.py which is the single clean Neo4j demo)

This branch has not been deployed

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants