diff --git a/.changeset/fix-graph-path-parallel-relations.md b/.changeset/fix-graph-path-parallel-relations.md new file mode 100644 index 00000000..57a78c13 --- /dev/null +++ b/.changeset/fix-graph-path-parallel-relations.md @@ -0,0 +1,7 @@ +--- +'@inkcre/core': patch +--- + +图谱寻路按 Block 数量计算探索预算。大量平行关系占满 PostgREST 返回的一页时,继续检查较早的关系。 +图谱邻域和寻路跳过缺少端点的关系,保留可用的邻域和路径。 +从自环关系打开邻域时,返回该关系及其唯一的端点 Block。 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ddd5402b..3413f572 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -129,6 +129,7 @@ jobs: with: ref: ${{ github.sha }} persist-credentials: false + submodules: true - name: Install the pinned pnpm release uses: pnpm/action-setup@ea17c68df8912ef543352723c149a84f56e3d413 # v6.1.0 diff --git a/packages/core/src/graph-navigation-retrieval/main.ts b/packages/core/src/graph-navigation-retrieval/main.ts index d869a6e7..2215b929 100644 --- a/packages/core/src/graph-navigation-retrieval/main.ts +++ b/packages/core/src/graph-navigation-retrieval/main.ts @@ -61,6 +61,7 @@ const MAX_MAX_HOPS = 8 const DEFAULT_MAX_EXPLORED_BLOCKS = 1000 const MAX_MAX_EXPLORED_BLOCKS = 10000 const FRONTIER_QUERY_SIZE = 200 +const FRONTIER_RELATION_PAGE_SIZE = 1000 type PathStep = { block: BlockRef; relation: RelationRef } | null @@ -134,10 +135,13 @@ export class GraphNavigationRetrievalManager { static async getRelationNeighborhood( focalRelation: RelationRef ): Promise { - const relation = await Relation.find(focalRelation) + const relation = await Relation.find(focalRelation, { requireEndpoints: true }) if (!relation) return null - const blocks = await Block.getMany([relation.from_, relation.to_]) - if (new Set(blocks.map((block) => block.id)).size !== 2) return null + const endpoints = new Set([relation.from_, relation.to_]) + const blocks = await Block.getMany(endpoints) + const blockIds = new Set(blocks.map((block) => block.id)) + if (blockIds.size !== endpoints.size || [...endpoints].some((id) => !blockIds.has(id))) + return null return RelationNeighborhoodSchema.parse({ focal_relation: focalRelation, graph: { blocks, relations: [relation] }, @@ -176,6 +180,7 @@ export class GraphNavigationRetrievalManager { relation_path: [], }) as PathResult } + if (maxExplored < 2) return { status: 'limit_reached' } const forwardSteps = new Map([[fromBlock, null]]) const backwardSteps = new Map([[toBlock, null]]) @@ -184,6 +189,7 @@ export class GraphNavigationRetrievalManager { let forwardFrontier = new Set([fromBlock]) let backwardFrontier = new Set([toBlock]) const traversedRelations = new Map() + const exploredBlocks = new Set([fromBlock, toBlock]) while (forwardFrontier.size > 0 && backwardFrontier.size > 0) { const forwardLevel = forwardDepths.get(forwardFrontier.values().next().value!)! @@ -199,13 +205,13 @@ export class GraphNavigationRetrievalManager { ownDepths: expandForward ? forwardDepths : backwardDepths, otherDepths: expandForward ? backwardDepths : forwardDepths, maxHops, + maxExplored, + exploredBlocks, traversedRelations, }) + if (!expanded) return { status: 'limit_reached' } if (expandForward) forwardFrontier = expanded.frontier else backwardFrontier = expanded.frontier - if (new Set([...forwardSteps.keys(), ...backwardSteps.keys()]).size > maxExplored) { - return { status: 'limit_reached' } - } if (expanded.meeting !== null) { return this.assemblePath({ fromBlock, @@ -229,22 +235,23 @@ export class GraphNavigationRetrievalManager { ownDepths: Map otherDepths: Map maxHops: number + maxExplored: number + exploredBlocks: Set traversedRelations: Map - }): Promise<{ frontier: Set; meeting: BlockRef | null }> { + }): Promise<{ frontier: Set; meeting: BlockRef | null } | null> { const blocks = [...options.frontier] const nextFrontier = new Set() let meeting: BlockRef | null = null let bestHops = Number.POSITIVE_INFINITY for (let offset = 0; offset < blocks.length; offset += FRONTIER_QUERY_SIZE) { const chunk = new Set(blocks.slice(offset, offset + FRONTIER_QUERY_SIZE)) - const relations = await this.getFrontierRelations( + const relations = this.getFrontierRelations( chunk, options.direction, options.contents, options.reverse ) - for (const relation of relations) { - options.traversedRelations.set(relation.id, relation) + for await (const relation of relations) { for (const [current, neighbor] of this.relationSteps( relation, chunk, @@ -252,6 +259,9 @@ export class GraphNavigationRetrievalManager { options.reverse )) { if (options.ownSteps.has(neighbor)) continue + options.exploredBlocks.add(neighbor) + if (options.exploredBlocks.size > options.maxExplored) return null + options.traversedRelations.set(relation.id, relation) options.ownSteps.set(neighbor, { block: current, relation: relation.id }) options.ownDepths.set(neighbor, options.ownDepths.get(current)! + 1) nextFrontier.add(neighbor) @@ -268,36 +278,34 @@ export class GraphNavigationRetrievalManager { return { frontier: nextFrontier, meeting } } - private static async getFrontierRelations( + private static async *getFrontierRelations( frontier: Set, direction: GraphDirection, contents: string[], reverse: boolean - ): Promise { + ): AsyncGenerator { const needsFrom = reverse ? direction !== 'out' : direction !== 'in' const needsTo = reverse ? direction !== 'in' : direction !== 'out' - const queries: Promise[] = [] - if (needsFrom) { - queries.push( - Relation.getEndpointPage({ - blockIds: frontier, - endpoint: 'from_', - contents, - limit: MAX_MAX_EXPLORED_BLOCKS, - }) - ) - } - if (needsTo) { - queries.push( - Relation.getEndpointPage({ + const endpoints: ('from_' | 'to_')[] = [] + if (needsFrom) endpoints.push('from_') + if (needsTo) endpoints.push('to_') + for (const endpoint of endpoints) { + let cursor: RelationRef | undefined + // Parallel edges do not exhaust the Block budget, and PostgREST may shorten a page. + while (true) { + const page = await Relation.getEndpointPage({ blockIds: frontier, - endpoint: 'to_', + endpoint, contents, - limit: MAX_MAX_EXPLORED_BLOCKS, + cursor, + limit: FRONTIER_RELATION_PAGE_SIZE, }) - ) + const last = page.at(-1) + if (!last) break + yield* page + cursor = last.id + } } - return [...new Map((await Promise.all(queries)).flat().map((item) => [item.id, item])).values()] } private static relationSteps( diff --git a/packages/core/src/info-base/relation.ts b/packages/core/src/info-base/relation.ts index 9c31091d..fc899a4c 100644 --- a/packages/core/src/info-base/relation.ts +++ b/packages/core/src/info-base/relation.ts @@ -34,8 +34,13 @@ export class Relation extends Z.class({ return relation } - static async find(id: RelationRef): Promise { - const result = await this.dbApi.from().select().eq('id', id).maybeSingle() + static async find( + id: RelationRef, + options: { requireEndpoints?: boolean } = {} + ): Promise { + let query = this.dbApi.from().select().eq('id', id) + if (options.requireEndpoints) query = query.not('from_', 'is', null).not('to_', 'is', null) + const result = await query.maybeSingle() if (result.error) throw result.error return result.data ? Relation.parse(result.data) : null } @@ -53,10 +58,12 @@ export class Relation extends Z.class({ }): Promise { const blockIds = [...new Set(options.blockIds)] if (blockIds.length === 0 || options.limit <= 0) return [] + const opposite = options.endpoint === 'from_' ? 'to_' : 'from_' let query = this.dbApi .from() .select() .in(options.endpoint, blockIds) + .not(opposite, 'is', null) .order('id', { ascending: false }) .limit(options.limit) const contents = [...new Set(options.contents ?? [])] diff --git a/tests/e2e/graph-navigation.mjs b/tests/e2e/graph-navigation.mjs new file mode 100644 index 00000000..47b6cd82 --- /dev/null +++ b/tests/e2e/graph-navigation.mjs @@ -0,0 +1,288 @@ +import assert from 'node:assert/strict' +import { randomUUID } from 'node:crypto' +import { readFile } from 'node:fs/promises' +import { test } from '@playwright/test' + +const postgrestUrl = process.env.INKCRE_E2E_POSTGREST_URL +let graph +let headers + +async function createRows(table, rows) { + const response = await fetch(new URL(table, postgrestUrl), { + method: 'POST', + headers: { ...headers, Prefer: 'return=representation' }, + body: JSON.stringify(rows), + }) + assert.equal(response.status, 201, `Cannot create graph fixture in ${table}`) + return response.json() +} + +async function removeBlocks(ids) { + if (ids.length === 0) return + const response = await fetch(new URL(`blocks?id=in.(${ids.join(',')})`, postgrestUrl), { + method: 'DELETE', + headers: { ...headers, Prefer: 'return=minimal' }, + }) + assert.equal(response.status, 204, 'Cannot remove graph fixture Blocks') +} + +async function createBlock(alias) { + const [{ id }] = await createRows('blocks', { + resolver: 'core.text.v1', + storage: null, + content: `graph-contract.${randomUUID()}.${alias}`, + }) + return id +} + +async function readScenario({ operation, input }, blocks, relations) { + const { direction, contents, limit } = input + switch (operation) { + case 'block_neighborhood': + return graph.getBlockNeighborhood(blocks.get(input.focal), { direction, contents, limit }) + case 'relation_neighborhood': + return graph.getRelationNeighborhood(relations.get(input.focal)) + case 'find_path': + return graph.findPath(blocks.get(input.from), blocks.get(input.to), { + direction, + contents, + maxHops: input.max_hops, + maxExploredBlocks: input.max_explored_blocks, + }) + default: + assert.fail(`Unknown graph operation ${operation}`) + } +} + +function verifyPath(result, input, blocks) { + const { block_path: blockPath, relation_path: relationPath, graph: actual } = result + assert.equal(blockPath[0], blocks.get(input.from)) + assert.equal(blockPath.at(-1), blocks.get(input.to)) + assert.equal(blockPath.length, relationPath.length + 1) + assert.deepEqual(new Set(blockPath), new Set(actual.blocks.map((block) => block.id))) + assert.deepEqual(new Set(relationPath), new Set(actual.relations.map((edge) => edge.id))) + const edges = new Map(actual.relations.map((edge) => [edge.id, edge])) + for (const [index, relationId] of relationPath.entries()) { + const relation = edges.get(relationId) + assert.ok(relation) + const from = blockPath[index] + const to = blockPath[index + 1] + const follows = relation.from_ === from && relation.to_ === to + const reverses = relation.from_ === to && relation.to_ === from + assert.ok((input.direction !== 'in' && follows) || (input.direction !== 'out' && reverses)) + if (input.contents?.length) assert.ok(input.contents.includes(relation.content)) + } +} + +function verifyScenario(scenario, result, blocks, relations) { + const { operation, input, assert: expected } = scenario + const status = result === null ? 'missing' : (result.status ?? 'found') + assert.equal(status, expected.status) + if (status !== 'found') return + + const blockIds = new Set(result.graph.blocks.map((block) => block.id)) + const relationIds = new Set(result.graph.relations.map((edge) => edge.id)) + if (expected.focal) assert.equal(result.focal_block, blocks.get(expected.focal)) + if (operation === 'relation_neighborhood') { + assert.equal(result.focal_relation, relations.get(input.focal)) + } + if (expected.block_set) { + assert.deepEqual(blockIds, new Set(expected.block_set.map((alias) => blocks.get(alias)))) + } + if (expected.relation_set) { + assert.deepEqual( + relationIds, + new Set(expected.relation_set.map((alias) => relations.get(alias))) + ) + } + if (expected.endpoint_closed) { + for (const edge of result.graph.relations) { + assert.ok(blockIds.has(edge.from_) && blockIds.has(edge.to_)) + } + } + if (expected.block_path) { + assert.deepEqual( + result.block_path, + expected.block_path.map((alias) => blocks.get(alias)) + ) + } + if (expected.relation_path) { + assert.deepEqual( + result.relation_path, + expected.relation_path.map((alias) => relations.get(alias)) + ) + } + if (expected.hop_count !== undefined) + assert.equal(result.relation_path.length, expected.hop_count) + if (operation === 'find_path') verifyPath(result, input, blocks) +} + +export function registerGraphNavigationTests() { + test.describe('Graph navigation SDK', () => { + test.beforeAll(async () => { + const jwtSecret = process.env.INKCRE_E2E_JWT_SECRET + assert.ok(postgrestUrl && jwtSecret, 'Run this test with the isolated Web E2E database') + const { GraphNavigationRetrievalManager, configStore } = + await import('../../packages/core/dist/index.js') + const { signDatabaseToken } = await import('../../packages/core/dist/sdk/sdk.js') + graph = GraphNavigationRetrievalManager + Object.assign(configStore.metaConfig, { + INKCRE_PGREST_URL: postgrestUrl, + INKCRE_JWT_SECRET: jwtSecret, + telemetry_enabled: false, + }) + headers = { + Authorization: `Bearer ${await signDatabaseToken(jwtSecret)}`, + 'Content-Type': 'application/json', + } + }) + + test('Web Core matches the shared graph navigation corpus over PostgREST', async () => { + const corpus = JSON.parse( + await readFile( + new URL( + '../../docs/_shared/20-product-tdd/graph-navigation-retrieval.corpus.json', + import.meta.url + ), + 'utf8' + ) + ) + assert.equal(corpus.contract, 'core.graph_navigation_retrieval.v1') + const blocks = new Map() + const relations = new Map() + try { + for (const alias of [...corpus.topology.blocks, 'missing']) { + blocks.set(alias, await createBlock(alias)) + } + await removeBlocks([blocks.get('missing')]) + for (const edge of corpus.topology.relations) { + const [{ id }] = await createRows('relations', { + from_: blocks.get(edge.from), + to_: blocks.get(edge.to), + content: edge.content, + }) + relations.set(edge.alias, id) + } + for (const scenario of corpus.scenarios) { + await test.step(scenario.name, async () => { + verifyScenario( + scenario, + await readScenario(scenario, blocks, relations), + blocks, + relations + ) + }) + } + } finally { + await removeBlocks([...blocks.values()]) + } + }) + + test('graph navigation preserves relations whose endpoints are present', async () => { + const start = await createBlock('start') + const blockIds = [start] + try { + const target = await createBlock('target') + blockIds.push(target) + const [connected, ...incomplete] = await createRows('relations', [ + { from_: start, to_: target, content: 'connected' }, + { from_: start, to_: null, content: 'first absent target' }, + { from_: start, to_: null, content: 'second absent target' }, + { from_: null, to_: target, content: 'first absent source' }, + { from_: null, to_: target, content: 'second absent source' }, + ]) + assert.equal(incomplete.filter((relation) => relation.to_ === null).length, 2) + assert.equal(incomplete.filter((relation) => relation.from_ === null).length, 2) + for (const focal of blockIds) { + const result = await graph.getBlockNeighborhood(focal, { limit: 1 }) + assert.equal(result.focal_block, focal) + assert.deepEqual(new Set(result.graph.blocks.map((block) => block.id)), new Set(blockIds)) + assert.deepEqual( + result.graph.relations.map((relation) => relation.id), + [connected.id] + ) + assert.equal(result.next_cursor, null) + } + + const outgoing = await graph.findPath(start, target, { direction: 'out' }) + const incoming = await graph.findPath(target, start, { direction: 'in' }) + for (const [path, expectedBlocks] of [ + [outgoing, [start, target]], + [incoming, [target, start]], + ]) { + assert.equal(path.status, 'found') + assert.deepEqual(path.block_path, expectedBlocks) + assert.deepEqual(path.relation_path, [connected.id]) + } + + const { Relation } = await import('../../packages/core/dist/index.js') + for (const relation of incomplete) { + assert.equal(await graph.getRelationNeighborhood(relation.id), null) + await assert.rejects(() => Relation.find(relation.id), { name: 'ZodError' }) + } + + const [selfLoop] = await createRows('relations', { + from_: start, + to_: start, + content: 'self loop', + }) + const neighborhood = await graph.getRelationNeighborhood(selfLoop.id) + assert.equal(neighborhood.focal_relation, selfLoop.id) + assert.deepEqual( + neighborhood.graph.blocks.map((block) => block.id), + [start] + ) + assert.deepEqual( + neighborhood.graph.relations.map((relation) => relation.id), + [selfLoop.id] + ) + } finally { + await removeBlocks(blockIds) + } + }) + + test('parallel relations cannot mask a path within the Block budget', async () => { + const [start, bridge, target, noise] = await createRows( + 'blocks', + ['start', 'bridge', 'target', 'noise'].map((alias) => ({ + resolver: 'core.text.v1', + storage: null, + content: `graph-parallel.${randomUUID()}.${alias}`, + })) + ) + try { + const path = await createRows('relations', [ + { from_: start.id, to_: bridge.id, content: 'path' }, + { from_: bridge.id, to_: target.id, content: 'path' }, + ]) + const response = await fetch(new URL('relations', postgrestUrl), { + method: 'POST', + headers: { ...headers, Prefer: 'return=minimal' }, + body: JSON.stringify( + Array.from({ length: 10_000 }, (_, index) => ({ + from_: start.id, + to_: noise.id, + content: `parallel-${index}`, + })) + ), + }) + assert.equal(response.status, 201) + const options = { direction: 'out', maxHops: 4, maxExploredBlocks: 10 } + const result = await graph.findPath(start.id, target.id, options) + assert.equal(result.status, 'found') + assert.deepEqual(result.block_path, [start.id, bridge.id, target.id]) + assert.deepEqual( + result.relation_path, + path.map((relation) => relation.id) + ) + const insufficient = await graph.findPath(start.id, target.id, { + ...options, + maxExploredBlocks: 3, + }) + assert.deepEqual(insufficient, { status: 'limit_reached' }) + } finally { + await removeBlocks([start.id, bridge.id, target.id, noise.id]) + } + }) + }) +} diff --git a/tests/e2e/peer-database.spec.ts b/tests/e2e/peer-database.spec.ts index 7a59ba1d..ab1e36b2 100644 --- a/tests/e2e/peer-database.spec.ts +++ b/tests/e2e/peer-database.spec.ts @@ -2,6 +2,7 @@ import { expect, test, type Page } from '@playwright/test' import { SignJWT } from 'jose' import { readFileSync } from 'node:fs' import { registerGitHubNativeTests } from './github-native' +import { registerGraphNavigationTests } from './graph-navigation.mjs' const postgrestUrl = process.env.INKCRE_E2E_POSTGREST_URL! const jwtSecret = process.env.INKCRE_E2E_JWT_SECRET! @@ -2012,3 +2013,4 @@ test('Sources preserve the draft after a lost creation response and reopen the s }) registerGitHubNativeTests() +registerGraphNavigationTests()