From 7a757b52644c4a3977ee707b58a9ac6be30ec739 Mon Sep 17 00:00:00 2001 From: Taewoon Kim Date: Fri, 27 Nov 2026 15:26:33 +0900 Subject: [PATCH 1/2] docs: an agent-memory how-to page, with every block run by a test Item 4 of #306 asks for one page on agent-memory use. The page builds a small memory in one database: messages as documents, facts as vertices linked to what they mention, and an embedding on each fact. It covers the six tasks that the docs did not show (store with links, upsert by key, latest rows as dicts, filtered nearest neighbours, delete an entity with its facts, remove duplicates), what a search sees right after a write, and how the vector index behaves as it grows. The statements are SQL and openCypher through db.command and db.query. The sizes and thresholds are read from the 26.12.1 engine sources, and the page says that it gives no size from which the graph beats an exact scan, because none was measured. tests/test_docs_agent_memory_page.py runs every block on both packages and compares the printed text, reports every block that differs, and calls the page's functions on more data. Refs #306 --- README.md | 2 +- docs/modules/ROOT/nav.adoc | 1 + .../ROOT/pages/how-to/agent-memory.adoc | 376 ++++++++++++++++++ docs/modules/ROOT/pages/how-to/vectors.adoc | 1 + tests/test_docs_agent_memory_page.py | 165 ++++++++ 5 files changed, 544 insertions(+), 1 deletion(-) create mode 100644 docs/modules/ROOT/pages/how-to/agent-memory.adoc create mode 100644 tests/test_docs_agent_memory_page.py diff --git a/README.md b/README.md index d7dff3e3..895d217a 100644 --- a/README.md +++ b/README.md @@ -101,7 +101,7 @@ Releases from this repository start with 26.11.1. The 26.10.x wheels were built ## Documentation -- Here: [`docs/`](https://github.com/ArcadeData/arcadedb-python/tree/main/docs/modules/ROOT/pages) is an Antora component (AsciiDoc) with Installation, [Which package?](https://github.com/ArcadeData/arcadedb-python/blob/main/docs/modules/ROOT/pages/which-package.adoc), Quickstart, the how-to pages (databases and queries, transactions, bulk loads, vectors, faceted queries, concurrency, durability, and more) and the development pages (Continuous integration, Release). It covers only what is specific to the Python bindings. +- Here: [`docs/`](https://github.com/ArcadeData/arcadedb-python/tree/main/docs/modules/ROOT/pages) is an Antora component (AsciiDoc) with Installation, [Which package?](https://github.com/ArcadeData/arcadedb-python/blob/main/docs/modules/ROOT/pages/which-package.adoc), Quickstart, the how-to pages (databases and queries, transactions, bulk loads, vectors, agent memory, faceted queries, concurrency, durability, and more) and the development pages (Continuous integration, Release). It covers only what is specific to the Python bindings. - Published at [docs.arcadedb.com/arcadedb-python](https://docs.arcadedb.com/arcadedb-python/), the same site as the main ArcadeDB manual, rebuilt daily from `main` (ArcadeData/arcadedb-docs#505). The `Docs` workflow builds it as a site of its own on every change under `docs/` and attaches it as the `docs-site` artifact. To build it locally, run `npx -p @antora/cli@3.2.1 -p @antora/site-generator@3.2.1 antora docs/antora-playbook.yml` and open `docs/build/site/index.html`. - ArcadeDB itself (SQL, openCypher, schema, server): [docs.arcadedb.com](https://docs.arcadedb.com). It is not repeated here. diff --git a/docs/modules/ROOT/nav.adoc b/docs/modules/ROOT/nav.adoc index 5bbb3b0f..52594595 100644 --- a/docs/modules/ROOT/nav.adoc +++ b/docs/modules/ROOT/nav.adoc @@ -19,6 +19,7 @@ ** xref:how-to/dataframes-and-columns.adoc[DataFrames, Arrow and columns] ** xref:how-to/functions-and-events.adoc[Python functions and record events] ** xref:how-to/vectors.adoc[Vectors] +** xref:how-to/agent-memory.adoc[Agent memory] ** xref:how-to/columnar-index.adoc[The COLUMNAR index and its settings] ** xref:how-to/facets.adoc[Faceted queries] * Development diff --git a/docs/modules/ROOT/pages/how-to/agent-memory.adoc b/docs/modules/ROOT/pages/how-to/agent-memory.adoc new file mode 100644 index 00000000..8c9b2081 --- /dev/null +++ b/docs/modules/ROOT/pages/how-to/agent-memory.adoc @@ -0,0 +1,376 @@ += Agent memory +:description: A small agent memory in one database: messages as documents, facts linked in a graph, filtered vector search, update, forget and de-duplicate, and what to expect after a write and as the collection grows. + +// Pinned by tests/test_docs_agent_memory_page.py, which runs every block on both packages. The sizes and thresholds in "As the collection grows" are those of the ArcadeDB 26.12.1 sources: LSMVectorIndex (ASYNC_REBUILD_MIN_GRAPH_SIZE, rebuildGraphBeforeSearch, smallGraphRebuildIsDue, computeRebuildThreshold, searchBeam) and the arcadedb.vectorIndex.* settings in GlobalConfiguration. + +This page builds the memory of a small agent in one database. The messages of a conversation are documents. The facts that the agent keeps are vertices, linked to the people and things that they mention. Each fact has an embedding for vector search. The statements are SQL and openCypher through `db.command(...)` and `db.query(...)`, as on xref:how-to/databases-and-queries.adoc[Databases and queries]. + +The blocks on this page run one after the other and open a database in the current directory, and a test in the repository runs them that way (`tests/test_docs_agent_memory_page.py`). Each block that prints something is followed by its output. The embeddings here are vectors of 4 numbers written by hand, so that the output is the same on every run. In your agent they come from your embedding model. NumPy is optional for the bindings, but the blocks use it; add it with `uv add numpy`. + +== Create the memory + +[source,python] +---- +import numpy as np + +import arcadedb + +db = arcadedb.open_or_create_database("./agent_memory") + +for statement in [ + "CREATE DOCUMENT TYPE Message IF NOT EXISTS", + "CREATE PROPERTY Message.turn IF NOT EXISTS LONG", + "CREATE INDEX IF NOT EXISTS ON Message (turn) NOTUNIQUE", + "CREATE VERTEX TYPE Memory IF NOT EXISTS", + "CREATE PROPERTY Memory.key IF NOT EXISTS STRING", + "CREATE PROPERTY Memory.user IF NOT EXISTS STRING", + "CREATE PROPERTY Memory.embedding IF NOT EXISTS ARRAY_OF_FLOATS", + "CREATE INDEX IF NOT EXISTS ON Memory (key) UNIQUE", + "CREATE INDEX IF NOT EXISTS ON Memory (user) NOTUNIQUE", + "CREATE INDEX IF NOT EXISTS ON Memory (embedding) LSM_VECTOR " + 'METADATA {"dimensions": 4, "similarity": "COSINE"}', + "CREATE VERTEX TYPE Entity IF NOT EXISTS", + "CREATE PROPERTY Entity.name IF NOT EXISTS STRING", + "CREATE INDEX IF NOT EXISTS ON Entity (name) UNIQUE", + "CREATE EDGE TYPE Mentions IF NOT EXISTS", +]: + db.command("sql", statement) +---- + +Every statement says `IF NOT EXISTS`, so the agent can run this at each start. The unique indexes on `Memory.key` and `Entity.name` are what `UPSERT` needs. The index on `Memory.user` serves the filtered search below. `dimensions` must match the length of your embeddings. + +== Store a fact, or update it by key + +`remember` writes one fact and its links in one transaction. `UPDATE ... UPSERT` updates the record with that key, or creates it when there is none. The function then replaces the links of the fact: it deletes the old ones, upserts each entity by name, and creates the edge. + +[source,python] +---- +def remember(key, user, text, vector, mentions): + def write(): + db.command( + "sql", + "UPDATE Memory SET user = ?, text = ?, embedding = ? UPSERT WHERE key = ?", + user, + text, + np.asarray(vector, dtype=np.float32), + key, + ) + db.command( + "sql", + "DELETE FROM (SELECT expand(outE('Mentions')) FROM Memory WHERE key = ?)", + key, + ) + for name in mentions: + db.command( + "sql", "UPDATE Entity SET name = ? UPSERT WHERE name = ?", name, name + ) + db.command( + "sql", + "CREATE EDGE Mentions FROM (SELECT FROM Memory WHERE key = ?) " + "TO (SELECT FROM Entity WHERE name = ?) IF NOT EXISTS", + key, + name, + ) + + db.run_in_transaction(write) + + +def counts(): + return [db.count_type(name) for name in ("Memory", "Entity", "Mentions")] + + +remember("ann-coffee", "ann", "Ann drinks espresso every morning", + [0.9, 0.1, 0.0, 0.0], ["Ann", "espresso"]) +remember("ann-running", "ann", "Ann trains for a marathon in May", + [0.1, 0.9, 0.0, 0.0], ["Ann", "marathon"]) +remember("ann-travel", "ann", "Ann wants to visit Lisbon", + [0.0, 0.0, 0.9, 0.1], ["Ann", "Lisbon"]) +remember("ben-coffee", "ben", "Ben prefers tea to espresso", + [0.8, 0.0, 0.0, 0.2], ["Ben", "espresso"]) +remember("ann-standup", "ann", "Ann moved her stand-up to 10:00", + [0.0, 0.0, 0.1, 0.9], ["Ann"]) +print(counts()) +---- + +[source,text] +---- +[5, 5, 9] +---- + +The counts are facts, entities, and links. A second call with the same key updates the fact and adds no record: + +[source,python] +---- +remember("ann-running", "ann", "Ann finished her marathon in May", + [0.1, 0.9, 0.0, 0.0], ["Ann", "marathon"]) +print(counts()) +row = db.query("sql", "SELECT text FROM Memory WHERE key = ?", "ann-running").first() +print(row.get("text")) +---- + +[source,text] +---- +[5, 5, 9] +Ann finished her marathon in May +---- + +`db.run_in_transaction` runs the function again after a conflict with another writer, see xref:how-to/transactions.adoc[Transactions]. + +== Keep the conversation and read the latest messages + +The raw messages need no links, so they are documents. One transaction around the loop commits once (see xref:how-to/transactions.adoc#commit-cost[What a commit costs]). `to_list()` returns each row as a `dict`. + +[source,python] +---- +messages = [ + "Hi", + "I drink espresso every morning", + "I run too", + "My marathon is in May", + "I want to see Lisbon", + "Move my stand-up to 10:00", + "Thanks", +] +with db.transaction(): + for turn, text in enumerate(messages, start=1): + db.command("sql", "INSERT INTO Message SET turn = ?, text = ?", turn, text) + +latest = db.query( + "sql", "SELECT turn, text FROM Message ORDER BY turn DESC LIMIT 5" +).to_list() +for row in latest: + print(row) +---- + +[source,text] +---- +{'turn': 7, 'text': 'Thanks'} +{'turn': 6, 'text': 'Move my stand-up to 10:00'} +{'turn': 5, 'text': 'I want to see Lisbon'} +{'turn': 4, 'text': 'My marathon is in May'} +{'turn': 3, 'text': 'I run too'} +---- + +== Search the nearest facts of one user + +`vectorNeighbors` returns the `k` records nearest to a query vector, and `where` restricts the search to the records that match, before the top `k` is taken. A lower `distance` is closer. + +[source,python] +---- +def nearest(vector, user, k=3): + rows = db.query( + "sql", + "SELECT key, distance FROM (SELECT expand(vectorNeighbors(" + "'Memory[embedding]', :vector, :k, {where: {user: :user}}))) " + "ORDER BY distance", + {"vector": np.asarray(vector, dtype=np.float32), "k": k, "user": user}, + ) + return [row.get("key") for row in rows] + + +question = [0.8, 0.3, 0.1, 0.0] +print(nearest(question, "ann")) +print(nearest(question, "ben")) +---- + +[source,text] +---- +['ann-coffee', 'ann-running', 'ann-travel'] +['ben-coffee'] +---- + +`where` is applied during the search, so a user with few facts still gets them when many facts of other users are nearer. The other options of the function, and the Python method `find_nearest`, are on xref:how-to/vectors.adoc#search[Vectors]. + +== Follow the links + +The graph answers questions that similarity does not. Which facts mention espresso, in openCypher: + +[source,python] +---- +rows = db.query( + "opencypher", + "MATCH (m:Memory)-[:Mentions]->(:Entity {name: $name}) " + "RETURN m.key AS memory ORDER BY memory", + {"name": "espresso"}, +) +print([row.get("memory") for row in rows]) +---- + +[source,text] +---- +['ann-coffee', 'ben-coffee'] +---- + +One statement can search by vector and then follow the links of each hit, through the `record` of the hit. Here it takes the two nearest facts of all users: + +[source,python] +---- +rows = db.query( + "sql", + "SELECT key, distance, record.out('Mentions').name AS mentions FROM " + "(SELECT expand(vectorNeighbors('Memory[embedding]', ?, 2))) ORDER BY distance", + np.asarray(question, dtype=np.float32), +) +for row in rows: + print(row.get("key"), sorted(row.get("mentions"))) +---- + +[source,text] +---- +ann-coffee ['Ann', 'espresso'] +ben-coffee ['Ben', 'espresso'] +---- + +== Forget an entity + +`forget` deletes the facts that mention an entity, and then the entity, in one transaction. It deletes such a fact also when the fact mentions others too, so change the function if your agent should keep those. Deleting a vertex deletes its edges (see xref:how-to/sql-for-sql-users.adoc#delete-with-delete-from[Delete with DELETE FROM]). + +[source,python] +---- +def forget(name): + def delete(): + about = db.query( + "sql", "SELECT expand(in('Mentions')) FROM Entity WHERE name = ?", name + ) + keys = [row.get("key") for row in about] + db.command("sql", "DELETE FROM Memory WHERE key IN :keys", {"keys": keys}) + db.command("sql", "DELETE FROM Entity WHERE name = ?", name) + + db.run_in_transaction(delete) + + +forget("Ben") +print(counts()) +print(nearest(question, "ben")) +---- + +[source,text] +---- +[4, 4, 7] +[] +---- + +== Remove duplicate facts + +An agent can store one fact twice under two keys. Group the facts by user and text, collect the keys of each group, keep the first key, and delete the rest: + +[source,python] +---- +remember("ann-coffee-again", "ann", "Ann drinks espresso every morning", + [0.9, 0.1, 0.0, 0.0], ["Ann", "espresso"]) +print(counts()) + +groups = db.query( + "sql", "SELECT user, text, list(key) AS ids FROM Memory GROUP BY user, text" +).to_list() +extra = [key for group in groups for key in sorted(group["ids"])[1:]] +db.command("sql", "DELETE FROM Memory WHERE key IN :keys", {"keys": extra}) +print(extra) +print(counts()) +---- + +[source,text] +---- +[5, 4, 9] +['ann-coffee-again'] +[4, 4, 7] +---- + +== What to expect right after a write + +A search that starts after a transaction has committed sees what the transaction wrote. A new fact is found, a changed embedding is searched with its new value, and a deleted fact is gone, as `forget` showed. You do not call a rebuild or a refresh. + +[source,python] +---- +remember("ann-decaf", "ann", "Ann switched to decaf", question, ["Ann"]) +print(nearest(question, "ann", k=1)) + +remember("ann-decaf", "ann", "Ann switched to decaf", [0.0, 0.0, 0.0, 1.0], ["Ann"]) +print(nearest(question, "ann", k=1)) +---- + +[source,text] +---- +['ann-decaf'] +['ann-coffee'] +---- + +This holds for committed writes. A search from another thread or task sees them too: see xref:how-to/vectors.adoc#agents-that-write-as-they-go[Agents that write as they go], which also shows how to choose the moment of a rebuild, and xref:how-to/asyncio.adoc[asyncio: AsyncDatabase] for an agent written with `async def`. Several agents in one process share one `Database`, see xref:how-to/concurrency.adoc#threads[Concurrency, processes and crashes]. + +== As the collection grows + +A vector index holds a graph. Vectors written since the graph was built wait beside it and are compared with the query one by one, until a rebuild puts them into the graph. `get_stats()` shows after how many changes that happens: + +[source,python] +---- +index = db.schema.get_vector_index("Memory", "embedding") +stats = index.get_stats() +print(db.count_type("Memory"), stats["effectiveMutationsThreshold"]) +---- + +[source,text] +---- +5 100 +---- + +The threshold is 100 changes, or one fifth of the vectors in the graph when that is more (the fifth counts up to 50,000). With the default settings of ArcadeDB 26.12.1, the size of an index also changes how a rebuild runs and how widely a search looks: + +[cols="1,3,2",options="header"] +|=== +| Vectors in the index | Rebuild after writes | Default search width for `k` results + +| under 1,000 +| A search that finds the threshold reached rebuilds before it answers. After 15 seconds without a write, any pending change is rebuilt in the background. +| `max(k, 100)` + +| 1,000 to 9,999 +| In the background, while searches keep answering. It starts at the threshold, or earlier when searches spend much of their time on the waiting vectors. +| `max(k, 100)` + +| 10,000 or more +| As above. +| `max(2k, 100)` +|=== + +A type has one index for each bucket, and one bucket by default. The first build of a graph runs in the search that needs it, and after a reopen the first search loads the saved graph (see xref:how-to/vectors.adoc#rebuild-the-graph[Rebuild the graph]). To trade speed for recall, pass `efSearch` in the options of `vectorNeighbors`. + +=== When the graph index pays off + +A search that is narrowed to one user can do little work in the graph: when the `where` keeps few records and the filtered property has an index, the engine scores those records directly (see xref:how-to/vectors.adoc#filtered-search[Filtered search]). + +For a search over the whole collection, this page gives no size from which the graph is faster than reading every record. That depends on the dimensions, the hardware, `k` and `efSearch`, and it was not measured for this page. Compare the two on your own data. The first statement below reads every record, so its answer is exact and its cost grows with the collection. The second uses the index: + +[source,python] +---- +query = np.asarray(question, dtype=np.float32) +exact = db.query( + "sql", + "SELECT key, vectorCosineSimilarity(embedding, ?) AS similarity " + "FROM Memory ORDER BY similarity DESC LIMIT 3", + query, +) +indexed = db.query( + "sql", + "SELECT key, distance FROM " + "(SELECT expand(vectorNeighbors('Memory[embedding]', ?, 3))) ORDER BY distance", + query, +) +print([row.get("key") for row in exact]) +print([row.get("key") for row in indexed]) +db.close() +---- + +[source,text] +---- +['ann-coffee', 'ann-running', 'ann-travel'] +['ann-coffee', 'ann-running', 'ann-travel'] +---- + +Time both at the size you expect to reach, and count how many of the exact keys the index returns. + +== Next steps + +* xref:how-to/vectors.adoc[Vectors] +* xref:how-to/transactions.adoc[Transactions] +* xref:how-to/asyncio.adoc[asyncio: AsyncDatabase] +* xref:how-to/bulk-loads.adoc[Bulk loads and commit size] diff --git a/docs/modules/ROOT/pages/how-to/vectors.adoc b/docs/modules/ROOT/pages/how-to/vectors.adoc index e280d15b..1d29d0d8 100644 --- a/docs/modules/ROOT/pages/how-to/vectors.adoc +++ b/docs/modules/ROOT/pages/how-to/vectors.adoc @@ -545,6 +545,7 @@ For vector search the JVM package is faster still: see xref:which-package.adoc#v == Next steps +* xref:how-to/agent-memory.adoc[Agent memory] * xref:how-to/databases-and-queries.adoc[Databases and queries] * xref:how-to/bulk-loads.adoc[Bulk loads and commit size] * {arcadedb-docs-url}/concepts/vector-search[Vector search in the ArcadeDB manual] diff --git a/tests/test_docs_agent_memory_page.py b/tests/test_docs_agent_memory_page.py new file mode 100644 index 00000000..c7c17277 --- /dev/null +++ b/tests/test_docs_agent_memory_page.py @@ -0,0 +1,165 @@ +"""Every Python block of the Antora page ``docs/modules/ROOT/pages/how-to/agent-memory.adoc`` runs, and prints what the page says. + +The blocks of the page are chained on purpose: they run in the order of the page, in one namespace. The page opens its own database +under the current directory, so the run happens in a temporary directory. A block that is followed by a ``[source,text]`` block must +print exactly that text, a block without one must print nothing, and every block that differs is reported, not only the first. The +other tests call the functions that the page defines on more data than the page uses, and pin what its text says. The tests use no +Java object, so they run on the JVM build and the native build alike. +""" + +import contextlib +import io +import re +from pathlib import Path + +import numpy as np +import pytest + +import arcadedb +from arcadedb import ArcadeDBError + +PAGE = ( + Path(__file__).resolve().parents[1] + / "docs" + / "modules" + / "ROOT" + / "pages" + / "how-to" + / "agent-memory.adoc" +) + +# a Python listing, then (optionally, directly after it) the text listing with its output +BLOCK_RE = re.compile( + r"\[source,python[^\]\n]*\]\n----\n(?P.*?)\n----\n" + r"(?:\n\[source,text\]\n----\n(?P.*?)\n----\n)?", + re.DOTALL, +) + + +def _blocks(): + text = PAGE.read_text(encoding="utf-8") + found = [(m.group("code"), m.group("out")) for m in BLOCK_RE.finditer(text)] + # no Python listing may escape the extraction (a different spelling of the block header would run nowhere) + assert text.count("[source,python") == len(found) + return found + + +@pytest.fixture +def page(tmp_path, monkeypatch): + """The namespace that the blocks of the page run in. Its database is closed afterwards.""" + monkeypatch.chdir(tmp_path) # the page opens ./agent_memory + namespace = {"__name__": "agent_memory_page"} + yield namespace + db = namespace.get("db") + if db is not None and db.is_open(): + db.close() + + +def _run_block(namespace, number, code): + captured = io.StringIO() + compiled = compile(code, f"agent-memory.adoc python block {number}", "exec") + with contextlib.redirect_stdout(captured): + exec(compiled, namespace) # nosec B102 - the page of this repository + return captured.getvalue().strip() + + +def _run_page(namespace): + wrong = [] + for number, (code, expected) in enumerate(_blocks(), start=1): + printed = _run_block(namespace, number, code) + shown = (expected or "").strip() + if printed != shown: + wrong.append( + f"block {number} printed:\n{printed}\nthe page shows:\n{shown}" + ) + assert not wrong, "\n\n".join(wrong) + + +def _reopened(namespace): + """The whole page, then its database open again: the functions of the page use the name ``db``.""" + _run_page(namespace) + namespace["db"] = arcadedb.open_database("./agent_memory") + return namespace["db"] + + +def _mentions(db, key): + rows = db.query( + "opencypher", + "MATCH (:Memory {key: $key})-[:Mentions]->(e:Entity) " + "RETURN e.name AS name ORDER BY name", + {"key": key}, + ) + return [row.get("name") for row in rows] + + +def test_the_page_has_its_blocks(): + blocks = _blocks() + assert len(blocks) >= 10 + assert sum(1 for _, out in blocks if out is not None) >= 9 + + +def test_every_block_runs_in_order_and_prints_what_the_page_says(page): + _run_page(page) + + +def test_the_first_block_runs_again_at_the_next_start(page): + first = _blocks()[0][0] + _run_block(page, 1, first) + page["db"].close() + _run_block(page, 1, first) + assert page["db"].count_type("Memory") == 0 + + +def test_remember_replaces_every_link_of_a_fact(page): + db = _reopened(page) + links = db.count_type("Mentions") + many = [f"thing-{number}" for number in range(100)] + page["remember"]("bulk", "ann", "many things", [0.0, 0.0, 1.0, 0.0], many) + assert _mentions(db, "bulk") == sorted(many) + + few = ["thing-1", "thing-2", "new-thing"] + page["remember"]("bulk", "ann", "few things", [0.0, 0.0, 1.0, 0.0], few) + assert _mentions(db, "bulk") == sorted(few) + assert db.count_type("Mentions") == links + len(few) + + +def test_forget_deletes_every_fact_that_mentions_the_entity(page): + db = _reopened(page) + memories, entities, links = page["counts"]() + for number in range(100): + vector = [0.0, 0.0, 1.0, number / 1000] + page["remember"]( + f"cat-{number}", "cat", f"fact {number}", vector, ["Cat", "tea"] + ) + assert db.count_type("Memory") == memories + 100 + + page["forget"]("Cat") + # "tea" stays: only the entity that was named is deleted, with the facts that mention it + assert page["counts"]() == [memories, entities + 1, links] + assert page["nearest"]([0.0, 0.0, 1.0, 0.0], "cat") == [] + + +def test_upsert_needs_a_unique_index(temp_db): + temp_db.command("sql", "CREATE DOCUMENT TYPE Plain") + with pytest.raises(ArcadeDBError): + result = temp_db.command( + "sql", "UPDATE Plain SET name = ? UPSERT WHERE name = ?", "a", "a" + ) + if result is not None: + result.to_list() + assert temp_db.count_type("Plain") == 0 + + +def test_the_rebuild_threshold_is_a_fifth_of_a_larger_graph(temp_db): + temp_db.command("sql", "CREATE VERTEX TYPE Memory") + temp_db.command("sql", "CREATE PROPERTY Memory.embedding ARRAY_OF_FLOATS") + vectors = np.random.default_rng(0).random((2000, 4), dtype=np.float32) + temp_db.insert_many("Memory", [{"embedding": vector} for vector in vectors]) + temp_db.command( + "sql", + "CREATE INDEX ON Memory (embedding) LSM_VECTOR " + 'METADATA {"dimensions": 4, "similarity": "COSINE"}', + ) + index = temp_db.schema.get_vector_index("Memory", "embedding") + index.build_graph_now() + assert index.get_stats()["effectiveMutationsThreshold"] == 400 From 37ce812c22c7531dc9395c21844a80b29b6fdfba Mon Sep 17 00:00:00 2001 From: Taewoon Kim Date: Fri, 27 Nov 2026 15:45:53 +0900 Subject: [PATCH 2/2] docs(#306): give the agent-memory page tests an absolute database path The tests that reopen the page's database failed in CI on both packages: they ran the page after os.chdir and its path is relative. On the native package the run-again test counted the 5 facts of an earlier test, and on both packages the reopened database had no type Memory. The tests now replace the page's path with an absolute one, the run-again test checks that a row survives, and the page says to use an absolute path after os.chdir. --- .../ROOT/pages/how-to/agent-memory.adoc | 2 +- tests/test_docs_agent_memory_page.py | 31 +++++++++++++------ 2 files changed, 22 insertions(+), 11 deletions(-) diff --git a/docs/modules/ROOT/pages/how-to/agent-memory.adoc b/docs/modules/ROOT/pages/how-to/agent-memory.adoc index 8c9b2081..86908535 100644 --- a/docs/modules/ROOT/pages/how-to/agent-memory.adoc +++ b/docs/modules/ROOT/pages/how-to/agent-memory.adoc @@ -37,7 +37,7 @@ for statement in [ db.command("sql", statement) ---- -Every statement says `IF NOT EXISTS`, so the agent can run this at each start. The unique indexes on `Memory.key` and `Entity.name` are what `UPSERT` needs. The index on `Memory.user` serves the filtered search below. `dimensions` must match the length of your embeddings. +Every statement says `IF NOT EXISTS`, so the agent can run this at each start. If your program changes its working directory (`os.chdir`), give the database an absolute path. The unique indexes on `Memory.key` and `Entity.name` are what `UPSERT` needs. The index on `Memory.user` serves the filtered search below. `dimensions` must match the length of your embeddings. == Store a fact, or update it by key diff --git a/tests/test_docs_agent_memory_page.py b/tests/test_docs_agent_memory_page.py index c7c17277..57f8ec3f 100644 --- a/tests/test_docs_agent_memory_page.py +++ b/tests/test_docs_agent_memory_page.py @@ -1,10 +1,13 @@ """Every Python block of the Antora page ``docs/modules/ROOT/pages/how-to/agent-memory.adoc`` runs, and prints what the page says. -The blocks of the page are chained on purpose: they run in the order of the page, in one namespace. The page opens its own database -under the current directory, so the run happens in a temporary directory. A block that is followed by a ``[source,text]`` block must -print exactly that text, a block without one must print nothing, and every block that differs is reported, not only the first. The -other tests call the functions that the page defines on more data than the page uses, and pin what its text says. The tests use no -Java object, so they run on the JVM build and the native build alike. +The blocks of the page are chained on purpose: they run in the order of the page, in one namespace. A block that is followed by a +``[source,text]`` block must print exactly that text, a block without one must print nothing, and every block that differs is +reported, not only the first. The other tests call the functions that the page defines on more data than the page uses, and pin what +its text says. The tests use no Java object, so they run on the JVM build and the native build alike. + +The page opens ``./agent_memory``. The tests put an absolute path of their own in that place and do not change the working +directory: after ``os.chdir`` a relative database path did not name one directory on either build (a later test opened the database +of an earlier one, or one without its types), as if the engine keeps the working directory that it started in. """ import contextlib @@ -27,6 +30,8 @@ / "how-to" / "agent-memory.adoc" ) +PAGE_PATH = '"./agent_memory"' +DATABASE = "__database_path__" # the namespace key of a test's path for the page # a Python listing, then (optionally, directly after it) the text listing with its output BLOCK_RE = re.compile( @@ -45,10 +50,12 @@ def _blocks(): @pytest.fixture -def page(tmp_path, monkeypatch): +def page(tmp_path): """The namespace that the blocks of the page run in. Its database is closed afterwards.""" - monkeypatch.chdir(tmp_path) # the page opens ./agent_memory - namespace = {"__name__": "agent_memory_page"} + namespace = { + "__name__": "agent_memory_page", + DATABASE: str(tmp_path / "agent_memory"), + } yield namespace db = namespace.get("db") if db is not None and db.is_open(): @@ -56,6 +63,7 @@ def page(tmp_path, monkeypatch): def _run_block(namespace, number, code): + code = code.replace(PAGE_PATH, repr(namespace[DATABASE])) captured = io.StringIO() compiled = compile(code, f"agent-memory.adoc python block {number}", "exec") with contextlib.redirect_stdout(captured): @@ -78,7 +86,7 @@ def _run_page(namespace): def _reopened(namespace): """The whole page, then its database open again: the functions of the page use the name ``db``.""" _run_page(namespace) - namespace["db"] = arcadedb.open_database("./agent_memory") + namespace["db"] = arcadedb.open_database(namespace[DATABASE]) return namespace["db"] @@ -96,6 +104,8 @@ def test_the_page_has_its_blocks(): blocks = _blocks() assert len(blocks) >= 10 assert sum(1 for _, out in blocks if out is not None) >= 9 + # the one place where the tests put their own path + assert sum(code.count(PAGE_PATH) for code, _ in blocks) == 1 def test_every_block_runs_in_order_and_prints_what_the_page_says(page): @@ -105,9 +115,10 @@ def test_every_block_runs_in_order_and_prints_what_the_page_says(page): def test_the_first_block_runs_again_at_the_next_start(page): first = _blocks()[0][0] _run_block(page, 1, first) + page["db"].command("sql", "INSERT INTO Message SET turn = 1, text = 'kept'") page["db"].close() _run_block(page, 1, first) - assert page["db"].count_type("Memory") == 0 + assert page["db"].count_type("Message") == 1 def test_remember_replaces_every_link_of_a_fact(page):