graphiti icon indicating copy to clipboard operation
graphiti copied to clipboard

[Bug] Edges with a future invalid_at are created already expired (expired_at = now)

Open zk1ppy opened this issue 1 month ago • 9 comments

Before you file

  • [x] I searched existing issues and did not find a duplicate.
  • [x] I read the contributing guide and included a minimal reproduction.

Affected component

graphiti-core (root cause). The bug also surfaces through the MCP server, whose add_memory / add_triplet tools funnel into the same resolution step.

Bug description

When temporal extraction infers a future invalid_at for a fact (e.g. "Alice works for Acme Corp until October 23, 2027"), the extracted edge is persisted with expired_at set to the current time — i.e. the edge is born expired. In the bi-temporal model, a future invalid_at means "this fact will stop being true at that date", not "it already has". The edge should remain active until invalid_at is reached.

Root cause — graphiti_core/utils/maintenance/edge_operations.py, resolve_extracted_edge() (lines 820–823 in 0.30.1):

now = utc_now()

if resolved_edge.invalid_at and not resolved_edge.expired_at:
    resolved_edge.expired_at = now

Any resolved edge carrying an invalid_at — past or future — is immediately marked expired at ingestion time. This affects both code paths: single-episode ingestion (add_episode → resolve_extracted_edges) and bulk ingestion (add_episode_bulk → the same resolve_extracted_edge), which means the MCP server's add_memory tool is affected as well.

Minimal reproduction

import asyncio
from datetime import datetime, timezone

from graphiti_core import Graphiti
from graphiti_core.llm_client import LLMConfig
from graphiti_core.llm_client.openai_generic_client import OpenAIGenericClient

NEO4J_URI = "bolt://localhost:7687"
OPENAI_BASE_URL = "https://your-openai-compatible-endpoint/v1"
MODEL = "your-model"  # any chat model with decent temporal extraction

async def main():
    llm = OpenAIGenericClient(
        config=LLMConfig(api_key="sk-...", base_url=OPENAI_BASE_URL, model=MODEL)
    )
    g = Graphiti(NEO4J_URI, ("neo4j", "password"), llm_client=llm)
    await g.build_indices_and_constraints()

    await g.add_episode(
        name="repro-born-expired",
        episode_body="Alice works for Acme Corp until October 23, 2027.",
        source_description="repro",
        reference_time=datetime.now(timezone.utc),
    )

    # temporal extraction correctly sets invalid_at = 2027-10-23
    # but the resolution step also sets expired_at = now
    records, _, _ = await g.driver.execute_query(
        "MATCH ()-[e]->() WHERE e.invalid_at IS NOT NULL "
        "RETURN e.fact AS fact, e.invalid_at AS invalid_at, e.expired_at AS expired_at"
    )
    for r in records:
        print(r["fact"], "| invalid_at:", r["invalid_at"], "| expired_at:", r["expired_at"])

asyncio.run(main())

Output observed on 0.30.1 (three consecutive runs, 3/3 reproduced):

Alice works for Acme Corp | invalid_at: 2027-10-23 00:00:00+00:00 | expired_at: 2026-10-15 13:14:58+00:00

The same born-expired result is obtained when the fact is re-ingested via add_triplet while an equivalent edge already exists (dedup → resolution → same block).

Note on how this was observed: in our deployment the path was exercised through the MCP server (add_memory / add_triplet), which funnels into the same resolve_extracted_edge step — the printed output above comes from those runs (3/3 reproduced). The Python snippet is the minimal equivalent of that path, written to be runnable standalone.

Expected behavior

A future invalid_at describes the end of validity in the future. The edge should be persisted with expired_at = null and simply stop being "current" once invalid_at is in the past. Downstream consumers filtering on expired_at IS NULL currently lose these facts immediately — e.g. a search-based pipeline never returns "Alice works for Acme Corp" even though the fact is true today.

Actual behavior

The edge is persisted with both invalid_at (future) and expired_at (≈ ingestion time), i.e. expired on creation.

Suggested fix

Expire only when the invalidation is not in the future:

if (
    resolved_edge.invalid_at
    and not resolved_edge.expired_at
    and ensure_utc(resolved_edge.invalid_at) <= now
):
    resolved_edge.expired_at = now

This preserves the existing semantics for genuinely past invalid_at values (e.g. an edge resolved against a newer candidate) and keeps the subsequent invalidation-candidates block untouched.

Related (but distinct) issues

  • #1728 — edge invalidation searches the whole graph, retiring unrelated edges (different root cause: scope of the candidate search)
  • #1841 — facts invalidation not happening properly (previous-fact invalidation semantics)

Environment

  • Graphiti: graphiti-core 0.30.1 (verified in source; pinned standalone image zepai/knowledge-graph-mcp:1.1.0-graphiti-0.30.1-standalone)
  • Python: 3.11 (image runtime)
  • OS: Linux (container)
  • Installation: pinned Docker standalone image
  • Database: Neo4j 5.x
  • Model providers: DeepSeek-V4.1-Flash via an OpenAI-compatible endpoint — temporal extraction correctly returns the future invalid_at; the bug is in the resolution step, not the extraction

zk1ppy avatar Oct 15 '26 13:10 zk1ppy

AI-assisted source review only; I have not run the reproducer or the cases below.

In 0.30.1 and current main, the paths where both related_edges and existing_edges are empty, or the normalized fact and endpoints match exactly, return before expiration. The general resolution path can expire a finite-ended edge even when no contradictions are selected. Could you share sanitized candidate timestamps and duplicate/contradiction indices from a failing run?

Adding only invalid_at <= now also enables the following candidate loop. For an initially unexpired Oct 1–23 interval, with now = Oct 15 and a selected contradiction starting Nov 1, that loop would extend invalid_at to Nov 1 and set expired_at immediately.

#1867 already adds finite-end clipping and no-context expiration finalization, while retaining expiration for future ends. Could maintainers clarify the intended transaction-time meaning of expired_at when a future valid-time end is already known, and whether these changes should be coordinated with #1867? Regression coverage should distinguish context/no-context paths and ensure finite intervals are never extended.

Solaris-star avatar Oct 15 '26 14:10 Solaris-star

I ran a small known-answer check against graphiti-core 0.31.1, calling resolve_extracted_edge directly with a stub LLM that returns fixed dedupe answers. No Neo4j, no LLM key, so only the date logic is tested. Expected results were written before the run; now = 2026-10-16.

R1 future invalid_at (+365d), no candidates         expected expired_at None   PASS
R2 future invalid_at (+365d), 1 unrelated candidate expected expired_at None   FAIL (expired_at = now)
R3 control: invalid_at in the past (-45d)           expected expired_at set    PASS
R4 interval -15d..+7d, later contradiction at +16d  expected end kept, not expired
                                                    invalid_at kept (+7d) but expired_at = now  FAIL

R1 passes only because the no-candidates path returns early. Once there is any candidate, this line expires every edge that has an invalid_at, even one in the future:

if resolved_edge.invalid_at and not resolved_edge.expired_at: resolved_edge.expired_at = now

Comparing first (ensure_utc(resolved_edge.invalid_at) <= now) should make R2 and R4 pass while R3 still passes. Happy to rerun the script against a fix branch or #1867 and post the table. The script is about 100 lines and I can share it as a gist.

Adam

Adam13y avatar Oct 16 '26 12:10 Adam13y

@Adam13y Could you share the gist you offered, including the exact UTC clock, candidate timestamps and fixed duplicate/contradiction indices, plus the installation source or commit for 0.31.1? The credential-free setup should make it useful for comparing the same cases with #1867.

One point to check in that rerun: the proposed comparison alone can enable the following later-candidate loop, as outlined in my earlier comment. Please assert both that R4's finite end is not extended and that its expiration matches the intended semantics, rather than assuming the first guard fixes both. I haven't run your script or verified a fix; the maintainer question about expired_at for a known future end remains open.

Solaris-star avatar Oct 16 '26 13:10 Solaris-star

Your reading of the source matches what we saw in production. We hit this on 0.30.1 (standalone image, Neo4j backend).

What happens on our side: an edge with a future invalid_at gets persisted with expired_at set to the write time, even when no contradiction was selected. One run, UTC times:

13:14:34  add_triplet call received
13:14:58  edge persisted with invalid_at = 2026-10-23T00:00:00Z
          and expired_at = 2026-10-15T13:14:58Z (the write time)

Reproduced 3/3 across separate runs. The failing path was the existing-duplicate one you describe: the new edge matched an existing edge that was itself born-expired by an earlier ingestion. One caveat: the resolver doesn't log candidate indices at INFO level, so "no candidate selected" is inferred from the DB state, not from instrumentation.

On the candidate loop, agreed. With only invalid_at <= now added, the loop becomes reachable for future-ended edges, and your example holds: a contradiction starting Nov 1 would extend an Oct 1–23 interval and expire it at once. Extending a finite interval feels wrong to me. Either bound the candidate (its valid_at should fall inside the current window), or leave invalid_at alone and record the contradiction as a separate edge.

We run a pinned image, so in the meantime we ship a small monkey-patch: it clears expired_at only when invalid_at is in the future and wasn't derived from a selected candidate, and never touches invalid_at itself. Happy to share the diff if that's useful as a reference.

One more thing we learned the hard way: resolve_extracted_edge is reachable through several import sites. Our patch wrapped two of them and add_triplet kept producing born-expired edges until we covered the third — graphiti.py captures its own reference at import time. A fix probably needs to cover every call path, not just the resolver logic.

Also agreed on coordinating with #1867 — the semantics of expired_at when a future valid-time end is known should be settled first.

zk1ppy avatar Oct 16 '26 13:10 zk1ppy

Sure, here it is inline instead of a gist so it stays with the issue.

Install source: pip install graphiti-core from PyPI resolved to 0.31.1 (Python 3.14, macOS arm64). For anyone rerunning: openai 3.x no longer pulls in httpx, so I also needed pip install httpx "openai<2".

Clock: utc_now() at start; my run printed now=2026-10-16T11:53:33.168792+00:00. All dates are relative to that:

  • R1: valid_at now-10d, invalid_at now+365d, no candidates.
  • R2: same edge, plus one related edge "Alice likes coffee" (valid_at now-100d). Stub dedupe answer: duplicate_facts=[], contradicted_facts=[].
  • R3: valid_at now-400d, invalid_at now-45d, same unrelated related edge, same stub answer.
  • R4: valid_at now-15d, invalid_at now+7d, no related edges, one invalidation candidate "Carol leads project X" (valid_at now+16d). Stub: duplicate_facts=[], contradicted_facts=[0].

R4 already asserts both points you raised: invalid_at == now+7d (end not extended) AND expired_at is None. On 0.31.1 the end stays at +7d and the failure is only the expiry. You're right that a <= now guard alone is not enough: with it, the later-candidate loop would run for R4. Its candidate.valid_at > resolved_edge.valid_at branch would then set invalid_at to +16d (end extended) and expired_at to now again, so R4 would still fail, just differently. So a fix probably needs both the guard and a rule that the loop only shortens an existing invalid_at (candidate.valid_at < resolved_edge.invalid_at), never extends it. I'll rerun the same rows against #1867 and post the table.

known_answer_2012.py
#!/usr/bin/env python3
"""Known-answer check for getzep/graphiti #2012. No Neo4j, no LLM key: calls
resolve_extracted_edge() with a stub LLM that returns fixed dedupe answers."""
import asyncio
from datetime import timedelta
from importlib.metadata import version
from types import SimpleNamespace

from graphiti_core.edges import EntityEdge
from graphiti_core.utils.datetime_utils import utc_now
from graphiti_core.utils.maintenance.edge_operations import resolve_extracted_edge

NOW = utc_now()
D = lambda days: NOW + timedelta(days=days)  # noqa: E731


class StubLLM:
    def __init__(self, duplicate_facts=None, contradicted_facts=None):
        self.answer = {'duplicate_facts': duplicate_facts or [],
                       'contradicted_facts': contradicted_facts or []}

    async def generate_response(self, *args, prompt_name=None, **kwargs):
        return dict(self.answer) if prompt_name == 'dedupe_edges.resolve_edge' else {}


def edge(fact, valid_at=None, invalid_at=None):
    return EntityEdge(source_node_uuid='A', target_node_uuid='B', name='RELATES_TO',
                      group_id='ka-2012', fact=fact, episodes=[], created_at=NOW,
                      valid_at=valid_at, invalid_at=invalid_at)


EPISODE = SimpleNamespace(uuid='ep-ka-2012', valid_at=NOW)


async def run():
    rows = []
    e = edge('Alice is on parental leave until next year', D(-10), D(365))
    out, _, _ = await resolve_extracted_edge(StubLLM(), e, [], [], EPISODE)
    rows.append(('R1 future invalid_at, no candidates', 'expired_at None', out.expired_at is None, out.expired_at))

    e = edge('Alice is on parental leave until next year', D(-10), D(365))
    other = edge('Alice likes coffee', D(-100))
    out, _, _ = await resolve_extracted_edge(StubLLM(), e, [other], [], EPISODE)
    rows.append(('R2 future invalid_at, unrelated candidate', 'expired_at None', out.expired_at is None, out.expired_at))

    e = edge('Alice worked at Acme', D(-400), D(-45))
    out, _, _ = await resolve_extracted_edge(StubLLM(), e, [edge('Alice likes coffee', D(-100))], [], EPISODE)
    rows.append(('R3 control: past invalid_at', 'expired_at set', out.expired_at is not None, out.expired_at))

    end = D(7)
    e = edge('Bob leads project X', D(-15), end)
    later = edge('Carol leads project X', D(16))
    out, _, _ = await resolve_extracted_edge(StubLLM(contradicted_facts=[0]), e, [], [later], EPISODE)
    rows.append(('R4 interval + later contradiction', 'invalid_at unchanged AND expired_at None',
                 out.invalid_at == end and out.expired_at is None,
                 f'invalid_at={out.invalid_at} expired_at={out.expired_at}'))

    print(f'graphiti-core {version("graphiti-core")}  now={NOW.isoformat()}')
    for name, exp, ok, obs in rows:
        print(f'{name:44} {exp:40} {"PASS" if ok else "FAIL":6} {obs}')


asyncio.run(run())

Adam

Adam13y avatar Oct 16 '26 13:10 Adam13y

Reran the same script against #1867 (installed from refs/pull/1867/head, package 0.30.2), now = 2026-10-17T08:45:45Z:

R1 future invalid_at, no candidates         expected expired_at None   FAIL (expired_at = now)
R2 future invalid_at, unrelated candidate   expected expired_at None   FAIL (expired_at = now)
R3 control: past invalid_at                 expected expired_at set    PASS
R4 interval -15d..+7d, later contradiction  invalid_at kept (+7d) but expired_at = now  FAIL

1/4 pass. R1 passes on 0.31.1 but fails on #1867, so as it stands the PR doesn't fix the future-end case and adds a regression on the no-candidate path. Happy to rerun if the branch changes.

Adam

Adam13y avatar Oct 17 '26 09:10 Adam13y

@Adam13y Thanks for rerunning. AI-assisted source review only; I haven't executed your script. Your F/F/P/F result is consistent with current #1867 head a30934e: its no-candidate path now sets expired_at for any finite end, and its general resolution path retains that rule while preventing R4's end from being extended.

@thantiklermcirony and maintainers: should a known future invalid_at leave expired_at as None across both paths? That decision determines the regression expectation for R1 and how this issue should be coordinated with #1867.

For reproducibility, @Adam13y could you add the installed commit SHA and imported edge_operations module path, with personal path details redacted? The PR ref can move, and package version 0.30.2 alone doesn't identify the installed source.

Solaris-star avatar Oct 17 '26 10:10 Solaris-star

Sure. The #1867 run was on:

refs/pull/1867/head -> a30934e18b9582fbea3aca742269fc2174b67f07
graphiti-core 0.30.2 (pip install from git+https://github.com/getzep/graphiti.git@refs/pull/1867/head)
imported module: <venv>/lib/python3.14/site-packages/graphiti_core/utils/maintenance/edge_operations.py

So it matches the head you linked. The 0.31.1 run was the PyPI wheel. Happy to rerun both once the maintainers decide on the expired_at semantics for a known future invalid_at.

Adam

Adam13y avatar Oct 17 '26 20:10 Adam13y

Thank you all for the detailed reports and tests. I want to explain how these fields work.

  1. Each edge has two kinds of time:
    • valid_at and invalid_at show when the fact is true in the real world. For "Alice works at Acme until March 31", invalid_at is March 31.
    • created_at and expired_at show when Graphiti recorded or changed the edge. They do not show whether the fact is true.
  2. expired_at = now is intended. When an edge has an end date, also a future one, Graphiti marks the edge at ingestion. So expired_at is the time of ingestion, and the fact is still true until invalid_at.
  3. To find facts that are true now, use invalid_at: invalid_at IS NULL OR invalid_at > now. Do not use expired_at for this. Graphiti search does not filter on expired_at unless you ask for it.
  4. Next steps: We will make the expired_at field description clearer.

@Adam13y Thank you for the script and the #1867 rerun. With this meaning of expired_at, all four results on 0.31.1 are correct, and R4 shows that the end date is not extended. R1 has no expired_at because the resolver returns early when it finds no other facts to compare with. This does not change invalid_at, and default search does not filter on expired_at.

mehulp93 avatar Nov 19 '26 04:11 mehulp93