From 3556eeb7b049ebf3712d46f0540d1cc019ec7b3e Mon Sep 17 00:00:00 2001 From: adityamishra-hydradb <321510987+adityamishra-hydradb@users.noreply.github.com> Date: Sat, 5 Dec 2026 02:15:15 +0530 Subject: [PATCH] Walk a hub row alone and reuse a walk for later pages in the Postgres store Signed-off-by: adityamishra-hydradb <321510987+adityamishra-hydradb@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 --- src/selfgraph/stores/pg_hydradb.py | 58 +++++++++++++++---- tests/test_pg_hydradb_store.py | 26 +++++++++ typescript/src/stores/pgHydradb.ts | 77 ++++++++++++++++++++------ typescript/test/pgHydradbStore.test.ts | 27 +++++++++ 4 files changed, 159 insertions(+), 29 deletions(-) diff --git a/src/selfgraph/stores/pg_hydradb.py b/src/selfgraph/stores/pg_hydradb.py index 5959e498..7216f4fe 100644 --- a/src/selfgraph/stores/pg_hydradb.py +++ b/src/selfgraph/stores/pg_hydradb.py @@ -41,6 +41,8 @@ _SEEDS_PER_WALK = 128 _MAX_EDGES = 5000 _SEED_TERMS = 16 +_CACHED_PAGES = 8 +_CACHED_HUBS = 4096 _GRAPH = "SELECT needs_refresh FROM hydradb.graphs WHERE name = $1" _TABLES = """SELECT t.label, n.nspname, c.relname, t.key_column::text AS key, format_type(k.atttypid, NULL) AS key_type, has_table_privilege(c.oid, 'SELECT') AS readable, {extra} @@ -173,6 +175,8 @@ def __init__( self._vertices: dict[str, _Table] = {} self._edges: dict[str, _Table] = {} self._draft: dict[str, Any] = {} + self._pages: dict[tuple, tuple[list[dict], bool]] = {} + self._hubs: set[tuple] = set() async def initialize(self) -> None: """Connect and read the graph's registration once, failing when it is missing, paused, or unreadable.""" @@ -491,11 +495,12 @@ async def match_nodes( rows.sort(key=lambda p: (str(p.get(order_by)), p["id"])) return rows[skip : skip + limit] - async def _walk(self, seeds: list[tuple[str, Any]], direction: str) -> list[list[str]]: + async def _walk(self, seeds: list[tuple[str, Any]], direction: str, flags: list[bool]) -> list[list[str]]: """List the edges one hop from the seeds with reachable_edges, halving the seeds when a walk is cut short. @param seeds (list[tuple[str, Any]]): (vertex label, key) pairs, at most _SEEDS_PER_WALK. @param direction (str): "outgoing" or "incoming". + @param flags (list[bool]): gets an entry when one seed alone is cut. @return (list[list[str]]): the reached edges as [label, key text]; marks the read partial when one seed alone is cut. """ @@ -504,28 +509,57 @@ async def _walk(self, seeds: list[tuple[str, Any]], direction: str) -> list[list grouped.setdefault(label, []).append(key) options = {"max_depth": 1, "direction": direction, "max_edges": _MAX_EDGES, "max_sources": _SEEDS_PER_WALK} [row] = await self._fetch(_WALK, self._graph, json.dumps(grouped), json.dumps(options)) - if any(reason != "depth" for reason in json.loads(row["truncated"])): - if len(seeds) > 1: - half = len(seeds) // 2 - return [*await self._walk(seeds[:half], direction), *await self._walk(seeds[half:], direction)] + cut = any(reason != "depth" for reason in json.loads(row["truncated"])) + if cut and len(seeds) > 1: + half = len(seeds) // 2 + return [ + *await self._walk(seeds[:half], direction, flags), + *await self._walk(seeds[half:], direction, flags), + ] + if len(seeds) == 1: + self._hubs.discard((direction, *seeds[0])) + if cut: + if len(self._hubs) >= _CACHED_HUBS: + self._hubs.clear() + self._hubs.add((direction, *seeds[0])) + flags.append(True) mark_partial() return json.loads(row["items"]) - async def _adjacent(self, ns: str, ids: list[str], direction: str) -> list[dict]: - """Read every edge one hop from some entities, a walk per batch of rows and a key lookup per edge table. + async def _adjacent(self, ns: str, ids: list[str], direction: str, more: bool) -> list[dict]: + """Read every edge one hop from some entities, reusing the last read of the same entities for a later page. + + A row whose edges a walk once cut short is walked on its own after that, so it does not cut the others. @param ns (str): namespace. - @param ids (list[str]): the entity ids. + @param ids (list[str]): the entity ids, sorted. @param direction (str): "outgoing" or "incoming". + @param more (bool): whether the caller is reading a later page of the same edges. @return (list[dict]): the edges, as _edge_rows returns them. """ await self._open(ns) + key = (ns, direction, tuple(ids)) + if more and key in self._pages: + edges, partial = self._pages[key] + if partial: + mark_partial() + return edges seeds = [(self._vertices[p].label, k) for p, keys in self._keys(self._vertices, ids).items() for k in keys] + hubs = [seed for seed in seeds if (direction, *seed) in self._hubs] + rest = [seed for seed in seeds if (direction, *seed) not in self._hubs] items: list[list[str]] = [] - for at in range(0, len(seeds), _SEEDS_PER_WALK): - items += await self._walk(seeds[at : at + _SEEDS_PER_WALK], direction) + flags: list[bool] = [] + for batch in [[hub] for hub in hubs] + [ + rest[at : at + _SEEDS_PER_WALK] for at in range(0, len(rest), _SEEDS_PER_WALK) + ]: + items += await self._walk(batch, direction, flags) prefixes = {t.label: t.prefix for t in self._edges.values()} - return await self._edge_rows(ns, [f"relation:{prefixes[label]}:{key}" for label, key in items]) + edges = await self._edge_rows(ns, [f"relation:{prefixes[label]}:{key}" for label, key in items]) + self._pages.pop(key, None) + self._pages[key] = (edges, bool(flags)) + while len(self._pages) > _CACHED_PAGES: + self._pages.pop(next(iter(self._pages))) + return edges async def _edge_rows(self, ns: str, ids: Iterable[str]) -> list[dict]: """Read edge rows by relation id, one key lookup per table. @@ -601,7 +635,7 @@ async def match_edges( start, direction = (froms, "outgoing") if froms is not None else (tos, "incoming") rows = [ e - for e in await self._adjacent(ns, sorted(start), direction) + for e in await self._adjacent(ns, sorted(start), direction, id_gt is not None or skip > 0) if (froms is None or e["from_id"] in froms) and (tos is None or e["to_id"] in tos) and (type is None or e["type"] == type) diff --git a/tests/test_pg_hydradb_store.py b/tests/test_pg_hydradb_store.py index 1545d2e8..83799dcd 100644 --- a/tests/test_pg_hydradb_store.py +++ b/tests/test_pg_hydradb_store.py @@ -178,3 +178,29 @@ async def together(): assert [p["name"] for p in found] == ["Ann Lee", "Bob Stone", "ChloƩ Durand", "Ann"] run(fresh.close()) run(_owner(f"SELECT hydradb.drop_graph('{name}_x'); SELECT hydradb.drop_graph('{name}_y')")) + + +def test_a_row_a_walk_cut_is_walked_alone_after_that(work): + name = work[0] + run(_owner(f"INSERT INTO {name}.people SELECT g, 'P' || g FROM generate_series(100, 5200) g")) + run(_owner(f"INSERT INTO {name}.employment SELECT g, g, 'globex' FROM generate_series(100, 5200) g")) + g = _graph(work) + run(g.initialize()) + walks, query = [], g.store._query + + async def counted(sql, *args): + walks.extend([args[1]] if "reachable_edges" in sql else []) + return await query(sql, *args) + + g.store._query = counted + first = run(g.retrieve(entity_ids=["company:acme", "company:globex"], depth=1)) + cold, walks[:] = list(walks), [] + second = run(g.retrieve(entity_ids=["company:acme", "company:globex"], depth=1)) + assert first.truncated and second.truncated + assert '{"company": ["globex"]}' in walks and len(walks) < len(cold) + walks[:] = [] + assert len(run(g.neighbors("company:globex", limit=10_000)).neighbors) >= 5000 + assert walks.count('{"company": ["globex"]}') == 2 + run(g.store.close()) + later_page = g.store.match_edges("default", from_label="Entity", to_in=["company:globex"], skip=500) + assert _code(lambda: later_page) == "store_closed" diff --git a/typescript/src/stores/pgHydradb.ts b/typescript/src/stores/pgHydradb.ts index 72176e1e..65b6d4d6 100644 --- a/typescript/src/stores/pgHydradb.ts +++ b/typescript/src/stores/pgHydradb.ts @@ -41,6 +41,8 @@ const CASTS: Record = { smallint: "bigint", integer: "bigint", b const SEEDS_PER_WALK = 128; const MAX_EDGES = 5000; const SEED_TERMS = 16; +const CACHED_PAGES = 8; +const CACHED_HUBS = 4096; const WRITES = "lockNode upsertNode upsertNodes createEdge createEdges updateCurrentEdge removeNodeLabel deleteNode deleteNodes deleteNodesBy deleteEdges deleteEdgesTouchingByType"; const GRAPH = "SELECT needs_refresh FROM hydradb.graphs WHERE name = $1"; @@ -132,6 +134,16 @@ function keyOf(table: Table, text: string): string | bigint | null { return text; } +/** + * The key a row is remembered under once a walk in one direction cut its edges short. + * @param direction (string): "outgoing" or "incoming". + * @param seed ([string, string | bigint]): the vertex label and key. + * @return (string): the key. + */ +function hubKey(direction: string, seed: [string, string | bigint]): string { + return JSON.stringify([direction, seed[0], `${seed[1]}`]); +} + /** * Build the fixed read of some columns of a table's rows. * @param table (Table): the table. @@ -205,6 +217,8 @@ export class PgHydraDBStore implements GraphStore { private pool: Pool | null = null; private closed = false; private starting: Promise | null = null; + private pages = new Map(); + private hubs = new Set(); private vertices = new Map(); private edges = new Map(); private draft: Record = {}; @@ -612,9 +626,14 @@ export class PgHydraDBStore implements GraphStore { * List the edges one hop from the seeds with reachable_edges, halving the seeds when a walk is cut short. * @param seeds (Array<[string, string | bigint]>): (vertex label, key) pairs, at most SEEDS_PER_WALK. * @param direction (string): "outgoing" or "incoming". + * @param flags (boolean[]): gets an entry when one seed alone is cut. * @return (string[][]): the reached edges as [label, key text]; marks the read partial when one seed alone is cut. */ - private async walk(seeds: Array<[string, string | bigint]>, direction: string): Promise { + private async walk( + seeds: Array<[string, string | bigint]>, + direction: string, + flags: boolean[], + ): Promise { const grouped = new Map(); for (const [label, key] of seeds) { grouped.set(label, [...(grouped.get(label) ?? []), typeof key === "bigint" ? `${key}` : JSON.stringify(key)]); @@ -622,41 +641,63 @@ export class PgHydraDBStore implements GraphStore { const json = `{${[...grouped].map(([label, keys]) => `${JSON.stringify(label)}: [${keys.join(", ")}]`).join(", ")}}`; const options = { max_depth: 1, direction, max_edges: MAX_EDGES, max_sources: SEEDS_PER_WALK }; const [result] = await this.fetch(WALK, this.graph, json, JSON.stringify(options)); - if ((result!.truncated as string[]).some((reason) => reason !== "depth")) { - if (seeds.length > 1) { - const half = Math.floor(seeds.length / 2); - return [ - ...(await this.walk(seeds.slice(0, half), direction)), - ...(await this.walk(seeds.slice(half), direction)), - ]; - } + const cut = (result!.truncated as string[]).some((reason) => reason !== "depth"); + if (cut && seeds.length > 1) { + const half = Math.floor(seeds.length / 2); + return [ + ...(await this.walk(seeds.slice(0, half), direction, flags)), + ...(await this.walk(seeds.slice(half), direction, flags)), + ]; + } + const hub = seeds.length === 1 ? hubKey(direction, seeds[0]!) : ""; + if (seeds.length === 1) this.hubs.delete(hub); + if (cut) { + if (this.hubs.size >= CACHED_HUBS) this.hubs.clear(); + this.hubs.add(hub); + flags.push(true); markPartial(); } return result!.items as string[][]; } /** - * Read every edge one hop from some entities, a walk per batch of rows and a key lookup per edge table. + * Read every edge one hop from some entities, reusing the last read of the same entities for a later page. + * + * A row whose edges a walk once cut short is walked on its own after that, so it does not cut the others. * @param ns (string): namespace. - * @param ids (string[]): the entity ids. + * @param ids (string[]): the entity ids, sorted. * @param direction (string): "outgoing" or "incoming". + * @param more (boolean): whether the caller is reading a later page of the same edges. * @return (EdgeRow[]): the edges. */ - private async adjacent(ns: string, ids: string[], direction: string): Promise { + private async adjacent(ns: string, ids: string[], direction: string, more: boolean): Promise { await this.open(ns); + const key = JSON.stringify([ns, direction, ids]); + const cached = this.pages.get(key); + if (more && cached !== undefined) { + if (cached.partial) markPartial(); + return cached.edges; + } const seeds: Array<[string, string | bigint]> = []; for (const [prefix, keys] of this.keys(this.vertices, ids)) { for (const k of keys) seeds.push([this.vertices.get(prefix)!.label, k]); } + const hubs = seeds.filter((seed) => this.hubs.has(hubKey(direction, seed))); + const rest = seeds.filter((seed) => !this.hubs.has(hubKey(direction, seed))); + const batches = hubs.map((hub) => [hub]); + for (let at = 0; at < rest.length; at += SEEDS_PER_WALK) batches.push(rest.slice(at, at + SEEDS_PER_WALK)); const items: string[][] = []; - for (let at = 0; at < seeds.length; at += SEEDS_PER_WALK) { - items.push(...(await this.walk(seeds.slice(at, at + SEEDS_PER_WALK), direction))); - } + const flags: boolean[] = []; + for (const batch of batches) items.push(...(await this.walk(batch, direction, flags))); const prefixes = new Map([...this.edges.values()].map((t) => [t.label, t.prefix])); - return this.edgeRows( + const edges = await this.edgeRows( ns, items.map(([label, k]) => `relation:${prefixes.get(label)}:${k}`), ); + this.pages.delete(key); + this.pages.set(key, { edges, partial: flags.length > 0 }); + while (this.pages.size > CACHED_PAGES) this.pages.delete(this.pages.keys().next().value!); + return edges; } /** @@ -709,7 +750,9 @@ export class PgHydraDBStore implements GraphStore { const tos = wanted(options.to_id, options.to_in); if (froms === null && tos === null) throw unsupportedRead("list every relation"); const [start, direction] = froms !== null ? [froms, "outgoing"] : [tos!, "incoming"]; - const rows = (await this.adjacent(ns, [...start].sort(comparePy), direction)).filter( + const rows = ( + await this.adjacent(ns, [...start].sort(comparePy), direction, options.id_gt != null || (options.skip ?? 0) > 0) + ).filter( (e) => (froms === null || froms.has(e.from_id)) && (tos === null || tos.has(e.to_id)) && diff --git a/typescript/test/pgHydradbStore.test.ts b/typescript/test/pgHydradbStore.test.ts index 6212ccb0..206b445e 100644 --- a/typescript/test/pgHydradbStore.test.ts +++ b/typescript/test/pgHydradbStore.test.ts @@ -188,6 +188,33 @@ describe.skipIf(!OWNER_URI)("PgHydraDBStore", () => { await owner(`SELECT hydradb.drop_graph('${name}_x'); SELECT hydradb.drop_graph('${name}_y')`); }); + it("a row a walk cut is walked alone after that", async () => { + await owner(`INSERT INTO ${name}.people SELECT g, 'P' || g FROM generate_series(100, 5200) g`); + await owner(`INSERT INTO ${name}.employment SELECT g, g, 'globex' FROM generate_series(100, 5200) g`); + const g = open(); + await g.store.initialize(); + const walks: string[] = []; + const store = g.store as unknown as { query: (sql: string, ...args: unknown[]) => Promise }; + const query = store.query.bind(store); + store.query = async (sql, ...args) => { + if (sql.includes("reachable_edges")) walks.push(args[1] as string); + return query(sql, ...args); + }; + const first = await g.retrieve(null, { entity_ids: ["company:acme", "company:globex"], depth: 1 }); + const cold = walks.splice(0); + const second = await g.retrieve(null, { entity_ids: ["company:acme", "company:globex"], depth: 1 }); + expect([first.truncated, second.truncated]).toEqual([true, true]); + expect(walks).toContain('{"company": ["globex"]}'); + expect(walks.length).toBeLessThan(cold.length); + walks.splice(0); + expect((await g.neighbors("company:globex", { limit: 10_000 })).neighbors.length).toBeGreaterThanOrEqual(5000); + expect(walks.filter((w) => w === '{"company": ["globex"]}')).toHaveLength(2); + await g.store.close!(); + const laterPage = () => + g.store.matchEdges("default", { from_label: "Entity", to_in: ["company:globex"], skip: 500 }); + expect(await codeOf(laterPage)).toBe("store_closed"); + }); + it("a walk cut by pg_hydradb marks the result truncated", async () => { await owner(`INSERT INTO ${name}.people SELECT g, 'P' || g FROM generate_series(100, 5200) g`); await owner(`INSERT INTO ${name}.employment SELECT g, g, 'globex' FROM generate_series(100, 5200) g`);