Skip to content

fix(networkx): skip re-initialization when singleton adapter already exists - #694

Open
DevChiniwala wants to merge 1 commit into
topoteretes:mainfrom
DevChiniwala:fix/networkx-adapter-singleton
Open

DevChiniwala wants to merge 1 commit into
topoteretes:mainfrom
DevChiniwala:fix/networkx-adapter-singleton

Conversation

@DevChiniwala

Copy link
Copy Markdown

Closes #493

Summary

  • NetworkXAdapter.__init__ reinitializes database_name, filename, and graph on every construction, even though __new__ returns a singleton instance
  • This retargets existing handles to a different database file
  • Fix: guard __init__ to skip initialization when the instance already has a graph attribute

Test plan

  • Constructing a second NetworkXAdapter with different parameters no longer mutates the first handle
  • The singleton pattern continues to work as intended for same-database access

🤖 Generated with Claude Code

…exists

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Copilot AI balanced review requested due to automatic review settings November 20, 2026 20:17

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

@tonydzi tonydzi left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Read the whole networkx_adapter.py at the PR head, not just the diff. The guard stops the original handle from being retargeted, but it does not give the behavior #493 lists under "Expected Behavior", and it changes who gets the misdirected writes rather than removing them.

1. networkx_adapter.py:60-65 (the guard) + __new__ at :33-50: a second database now silently becomes the first one.
__new__ still returns the one process-wide _instance whatever database_name is passed, and the guard makes __init__ return early. So b = NetworkXAdapter(None, None, None, ".../beta") is the same object as a, with b.filename == ".../alpha.pkl". Every add_node / add_edge through b calls save_graph_to_file(self.filename) and writes beta's data into alpha.pkl.

I checked the constructor semantics in isolation (a stub with the same __new__ / guard, not the full adapter, and without cognee installed): a is b is True and b.filename is alpha.pkl. In the repro from #493 that means "same object for different files: True" and "original handle sees beta edge: True" stay as they are, and "later alpha write in beta file" just flips to "beta write in alpha file". The issue's expected result (alpha handle keeps alpha.pkl, nothing from alpha lands in beta.pkl) is not reached, and the data mixing is now harder to notice because nothing changes on the first handle.

2. Suggested shape: key the singleton by the resolved database name instead of a single _instance.

_instances: dict[str, "NetworkXAdapter"] = {}

def __new__(cls, graph_database_url, graph_database_username, graph_database_password, database_name, **kwargs):
    key = database_name if database_name else "cognee_graph"
    inst = cls._instances.get(key)
    if inst is None:
        inst = super().__new__(cls)
        inst._initialized = False
        cls._instances[key] = inst
    return inst

def __init__(self, ..., database_name="", **kwargs):
    if self._initialized:
        return
    ...  # existing body
    self._initialized = True

Same database name -> same handle, in-memory graph kept (which also covers the "same-store reset" half of #493). Different name -> separate handle, graph and file. If you would rather keep a true single instance, raising (or at least logging a warning) when a different database_name arrives is better than silently reusing the first store.

3. Minor. graph = None is a class attribute (:31), so hasattr(self, "graph") is always true and self.graph is not None carries the whole check. An explicit _initialized flag is clearer and does not depend on nothing ever assigning None to graph later.

4. Tests. packages/graph/networkx/tests/unit/ has no test for this. A regression test with two tmp_path database names would pin the contract: after constructing alpha and beta, a.filename != b.filename, a write through a shows up in alpha.pkl only, and re-constructing alpha keeps its in-memory edge. It should fail on current main and on this PR's guard alone, which is a good check that it tests the right thing.

Happy to be corrected if the singleton-per-process behavior is intentional for cognee's engine cache; in that case the thing to decide is what a second, different database_name should do (error vs. reuse), because the current guard picks "reuse and write into the wrong file" by default.

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.

[Bug]: NetworkX adapter reconstruction retargets existing handles to another graph file

3 participants