-
Notifications
You must be signed in to change notification settings - Fork 10
fix(rfc64): resolve cold selected CG name hashes #2043
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
branarakic
wants to merge
4
commits into
codex/rfc64-m1-first-boot-periodic-scope
Choose a base branch
from
codex/rfc64-m1-cold-historical-binding
base: codex/rfc64-m1-first-boot-periodic-scope
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 3 commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
169 changes: 169 additions & 0 deletions
169
packages/agent/test/context-graph-historical-name-binding.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,169 @@ | ||
| import { describe, expect, it, vi } from 'vitest'; | ||
| import type { TripleStore } from '@origintrail-official/dkg-storage'; | ||
| import { ContextGraphRegistryMethods } from '../src/dkg-agent-cg-registry.js'; | ||
|
|
||
| const LOCAL_ID = 'selected-public-cg'; | ||
| const NAME_HASH = `0x${'ab'.repeat(32)}`; | ||
|
|
||
| function selectedFixture(resolved: bigint | null = 42n) { | ||
| const query = vi.fn<TripleStore['query']>(async () => ({ | ||
| type: 'bindings', | ||
| bindings: [], | ||
| })); | ||
| const resolveContextGraphIdByNameHash = vi.fn(async () => resolved); | ||
| const bindOnChainContextGraphIdFromNameHash = vi.fn(() => LOCAL_ID); | ||
| const subscription = { | ||
| subscribed: true, | ||
| synced: false, | ||
| syncMode: 'always-on', | ||
| syncAdmission: 'explicit', | ||
| onChainHash: NAME_HASH, | ||
| }; | ||
| return { | ||
| query, | ||
| resolveContextGraphIdByNameHash, | ||
| bindOnChainContextGraphIdFromNameHash, | ||
| agent: { | ||
| store: { query } as unknown as TripleStore, | ||
| chain: { resolveContextGraphIdByNameHash }, | ||
| subscribedContextGraphs: new Map([[LOCAL_ID, subscription]]), | ||
| contextGraphWireId: (id: string) => id === LOCAL_ID ? NAME_HASH : id.toLowerCase(), | ||
| contextGraphNameCommitment: (id: string) => id === LOCAL_ID ? NAME_HASH : id.toLowerCase(), | ||
| localCgIdForWireId: (id: string) => id.toLowerCase() === NAME_HASH ? LOCAL_ID : id, | ||
| bindOnChainContextGraphIdFromNameHash, | ||
| }, | ||
| }; | ||
| } | ||
|
|
||
| describe('cold historical Context Graph name binding', () => { | ||
| it('resolves and binds an explicit cleartext selection without ontology data', async () => { | ||
| const fixture = selectedFixture(); | ||
| const signal = new AbortController().signal; | ||
|
|
||
| await expect( | ||
| ContextGraphRegistryMethods.prototype.getContextGraphOnChainId.call( | ||
| fixture.agent as never, | ||
| LOCAL_ID, | ||
| { signal }, | ||
| ), | ||
| ).resolves.toBe('42'); | ||
|
|
||
| expect(fixture.resolveContextGraphIdByNameHash).toHaveBeenCalledWith( | ||
| NAME_HASH, | ||
| { signal }, | ||
| ); | ||
| expect(fixture.bindOnChainContextGraphIdFromNameHash).toHaveBeenCalledWith( | ||
| NAME_HASH, | ||
| '42', | ||
| ); | ||
| expect(fixture.query).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it('uses the same binding for a selected wire-hash request', async () => { | ||
| const fixture = selectedFixture(); | ||
| await expect( | ||
| ContextGraphRegistryMethods.prototype.getContextGraphOnChainId.call( | ||
| fixture.agent as never, | ||
| NAME_HASH, | ||
| ), | ||
| ).resolves.toBe('42'); | ||
| expect(fixture.resolveContextGraphIdByNameHash).toHaveBeenCalledWith( | ||
| NAME_HASH, | ||
| ); | ||
| }); | ||
|
|
||
| it('never lets an arbitrary unselected id trigger a historical chain scan', async () => { | ||
| const fixture = selectedFixture(); | ||
| await expect( | ||
| ContextGraphRegistryMethods.prototype.getContextGraphOnChainId.call( | ||
| fixture.agent as never, | ||
| 'unselected-remote-cg', | ||
| ), | ||
| ).resolves.toBeNull(); | ||
| expect(fixture.resolveContextGraphIdByNameHash).not.toHaveBeenCalled(); | ||
| expect(fixture.query).toHaveBeenCalledTimes(1); | ||
| }); | ||
|
|
||
| it('does not let a passive non-admitted local record trigger a historical chain scan', async () => { | ||
| const fixture = selectedFixture(); | ||
| fixture.agent.subscribedContextGraphs.get(LOCAL_ID)!.syncAdmission = 'none'; | ||
| await expect( | ||
| ContextGraphRegistryMethods.prototype.getContextGraphOnChainId.call( | ||
| fixture.agent as never, | ||
| LOCAL_ID, | ||
| ), | ||
| ).resolves.toBeNull(); | ||
| expect(fixture.resolveContextGraphIdByNameHash).not.toHaveBeenCalled(); | ||
| expect(fixture.query).toHaveBeenCalledTimes(1); | ||
| }); | ||
|
|
||
| it('allows a host-only Core record to recover its historical binding', async () => { | ||
| const fixture = selectedFixture(); | ||
| const subscription = fixture.agent.subscribedContextGraphs.get(LOCAL_ID)!; | ||
| subscription.subscribed = false; | ||
| subscription.syncAdmission = 'none'; | ||
| subscription.coreHosted = true; | ||
|
|
||
| await expect( | ||
| ContextGraphRegistryMethods.prototype.getContextGraphOnChainId.call( | ||
| fixture.agent as never, | ||
| LOCAL_ID, | ||
| ), | ||
| ).resolves.toBe('42'); | ||
| expect(fixture.resolveContextGraphIdByNameHash).toHaveBeenCalledWith(NAME_HASH); | ||
| }); | ||
|
|
||
| it('hashes the original spelling of a hash-shaped cleartext subscription id', async () => { | ||
| const fixture = selectedFixture(); | ||
| const localId = `0x${'AB'.repeat(32)}`; | ||
| const committedHash = `0x${'cd'.repeat(32)}`; | ||
| const subscription = fixture.agent.subscribedContextGraphs.get(LOCAL_ID)!; | ||
| fixture.agent.subscribedContextGraphs = new Map([[ | ||
| localId, | ||
| { ...subscription, onChainHash: undefined }, | ||
| ]]); | ||
| fixture.agent.contextGraphWireId = (id: string) => id.toLowerCase(); | ||
| fixture.agent.localCgIdForWireId = (id: string) => id.toLowerCase(); | ||
| fixture.agent.contextGraphNameCommitment = vi.fn((id: string) => | ||
| id === localId ? committedHash : NAME_HASH); | ||
| fixture.bindOnChainContextGraphIdFromNameHash.mockReturnValue(localId); | ||
|
|
||
| await expect( | ||
| ContextGraphRegistryMethods.prototype.getContextGraphOnChainId.call( | ||
| fixture.agent as never, | ||
| localId, | ||
| ), | ||
| ).resolves.toBe('42'); | ||
| expect(fixture.agent.contextGraphNameCommitment).toHaveBeenCalledWith(localId); | ||
| expect(fixture.resolveContextGraphIdByNameHash).toHaveBeenCalledWith(committedHash); | ||
| }); | ||
|
|
||
| it('retains the legacy ontology fallback for a selected pre-name-hash miss', async () => { | ||
| const fixture = selectedFixture(null); | ||
| fixture.query.mockResolvedValueOnce({ | ||
| type: 'bindings', | ||
| bindings: [{ id: '"7"' }], | ||
| }); | ||
| await expect( | ||
| ContextGraphRegistryMethods.prototype.getContextGraphOnChainId.call( | ||
| fixture.agent as never, | ||
| LOCAL_ID, | ||
| ), | ||
| ).resolves.toBe('7'); | ||
| expect(fixture.bindOnChainContextGraphIdFromNameHash).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it('propagates ambiguous or failed chain resolution instead of trusting local metadata', async () => { | ||
| const fixture = selectedFixture(); | ||
| fixture.resolveContextGraphIdByNameHash.mockRejectedValueOnce( | ||
| new Error('ambiguous name hash'), | ||
| ); | ||
| await expect( | ||
| ContextGraphRegistryMethods.prototype.getContextGraphOnChainId.call( | ||
| fixture.agent as never, | ||
| LOCAL_ID, | ||
| ), | ||
| ).rejects.toThrow('ambiguous name hash'); | ||
| expect(fixture.query).not.toHaveBeenCalled(); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,79 @@ | ||
| // SPDX-License-Identifier: Apache-2.0 | ||
|
|
||
| import { ethers } from 'ethers'; | ||
| import { ReadThroughTtlCache } from './keyed-ttl-single-flight-cache.js'; | ||
|
|
||
| const CONTEXT_GRAPH_NAME_HASH_NEGATIVE_TTL_MS = 30_000; | ||
|
|
||
| export interface ContextGraphNameHashResolverDependencies { | ||
| /** One concrete adapter-owned lookup for a normalized bytes32 commitment. */ | ||
| readonly load: (nameHash: string) => Promise<bigint | null>; | ||
| } | ||
|
|
||
| /** | ||
| * Deployment-scoped, single-flight reverse lookup for cold Context Graphs. | ||
| * | ||
| * Only misses are cached. A positive binding is returned to the caller and | ||
| * persisted by the Agent subscription layer, but it is deliberately not kept | ||
| * here: ContextGraphStorage does not enforce name-hash uniqueness, so a later | ||
| * duplicate event must be visible to the next independent lookup. | ||
| */ | ||
| export class ContextGraphNameHashResolver { | ||
| private readonly cache = new ReadThroughTtlCache<string, bigint | null>({ | ||
| ttlMs: (value) => value === null | ||
| ? CONTEXT_GRAPH_NAME_HASH_NEGATIVE_TTL_MS | ||
| : 0, | ||
| }); | ||
|
|
||
| constructor( | ||
| private readonly dependencies: ContextGraphNameHashResolverDependencies, | ||
| ) {} | ||
|
|
||
| async resolve( | ||
| rawNameHash: string, | ||
| signal?: AbortSignal, | ||
| ): Promise<bigint | null> { | ||
| signal?.throwIfAborted(); | ||
| const nameHash = normalizeContextGraphNameHash(rawNameHash); | ||
| if (nameHash === ethers.ZeroHash) return null; | ||
|
|
||
| const shared = this.cache.getOrLoad( | ||
| nameHash, | ||
| nameHash, | ||
| () => this.dependencies.load(nameHash), | ||
| ); | ||
| return waitForResolution(shared, signal); | ||
| } | ||
|
|
||
| invalidateAll(): void { | ||
| this.cache.invalidateAll(); | ||
| } | ||
| } | ||
|
|
||
| function normalizeContextGraphNameHash(value: string): string { | ||
| if (!ethers.isHexString(value, 32)) { | ||
| throw new TypeError('resolveContextGraphIdByNameHash requires a bytes32 nameHash'); | ||
| } | ||
| return value.toLowerCase(); | ||
| } | ||
|
|
||
| function waitForResolution<T>( | ||
| work: Promise<T>, | ||
| signal: AbortSignal | undefined, | ||
| ): Promise<T> { | ||
| if (!signal) return work; | ||
| signal.throwIfAborted(); | ||
| return new Promise<T>((resolve, reject) => { | ||
| const onAbort = () => reject( | ||
| signal.reason instanceof Error | ||
| ? signal.reason | ||
| : Object.assign(new Error('Context Graph name-hash resolution aborted'), { | ||
| name: 'AbortError', | ||
| }), | ||
| ); | ||
| signal.addEventListener('abort', onAbort, { once: true }); | ||
| work.then(resolve, reject).finally(() => { | ||
| signal.removeEventListener('abort', onAbort); | ||
| }); | ||
| }); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.