[Perf] Entity resolution: index perfect-match fingerprints before fuzzy and co-occurrence work

Open
#7,244 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

Difficulty
5/5
Estimated time
Over a week
Newbie friendliness
35/100
Issue type
Feature
Clarity
Mostly clear
Activity status
Active
Tech stack
postgresql, python

Research direction

Start with hindsight-api-slim/hindsight_api/engine/memories/pg/entity_resolver.py, especially _resolve_entities_batch_trigram and _resolve_from_candidates; read the existing scorer and candidate ordering first. Then inspect the entity schema and creation or update paths to understand how an indexed fingerprint could be maintained. Done means an opt-in fast path preserves existing candidate caps, tie-breaking, scope and stats, with fallback when equivalence is uncertain; the issue suggests validating resolved IDs and queued stats across its listed edge cases.

Written by the indexing model from the issue text.

Description

core
Use Case

Steady-state retain traffic often mentions entities the bank already knows: the same services, projects, tools and people. This proposes a bank-scoped lookup for matches the current entity scorer can already determine without co-occurrence or temporal evidence.

The goal is to reuse the existing matching rules and skip unnecessary fuzzy/co-occurrence work, rather than change the merge threshold.

Problem Statement

In EntityResolver._resolve_entities_batch_trigram, candidate discovery and co-occurrence loading happen before _resolve_from_candidates scores the names:

  1. Probe similar names with the trigram index.
  2. Fetch every co-occurrence edge incident to the candidate IDs.
  3. Build the Python co-occurrence index.
  4. Score candidates.

But _resolve_from_candidates already contains a deterministic branch:

if name_trigram_similarity >= _IDENTICAL_TRIGRAMS:  # currently 1.0
    score = 1.0

The preceding word-compatibility checks still apply. This branch uses neither co-occurrence nor time. The other branch combines name similarity (up to 0.5), co-occurrence (up to 0.3) and temporal proximity (up to 0.2).

For a batch whose matching winners are already determined by the perfect-name condition, the preceding history read and much of the candidate scoring cannot affect the result.

Source inspected and benchmarked: d8d03e044ce172437dfa99079791947adc7781b4.

How This Feature Would Help

A successful perfect-match lookup could avoid building a large co-occurrence graph merely to reach a decision the name evidence already determines.

I tested this with a disposable local PostgreSQL instance and the repository's actual resolver functions:

Measure Current trigram resolver Fingerprint-lookup prototype
Median entity-resolution time 632.926 ms 0.676 ms
Rows fetched 86,903 40
Fetch calls 2 1
Resolved IDs, canonical names and entity kinds reference identical
Queued mention-stat updates reference identical

Setup:

  • 10,020 entities in the tested bank, including 20 punctuation aliases.
  • 209,959 canonical co-occurrence edges, including a hub.
  • 20 existing regular names, resolve=True, with nearby-entity context.
  • Another bank contains some of the same names.
  • One warm-up round, then three alternating rounds; timings are medians.
  • Current path calls _resolve_entities_batch_trigram directly.
  • Prototype uses an indexed fingerprint lookup, then the same _resolve_from_candidates for assignment and mention-stat accounting.

This is a synthetic, deliberately favorable steady-state workload, and a resolver-stage measurement. It is not evidence that end-to-end retain becomes 936 times faster. The measured speedup is about 936x for this stage; hit rates and benefits on real traffic remain to be measured.

Proposed Solution

For regular mentions with resolve=True:

  1. Build an indexable fingerprint from the normalized trigram set used by the current scorer, scoped by bank.
  2. Look up the perfect-match candidate class before running the broad fuzzy/co-occurrence path.
  3. Check the actual trigram set and existing word-compatibility rules; the fingerprint is a lookup key, not a new matching rule.
  4. When the winner can be established under the existing candidate-cap and tie-breaking rules, reuse it through the normal assignment/stat path.
  5. Otherwise fall back to the existing resolver.

A prototype key is sha256("\0".join(sorted(trigram_set(name)))), with a B-tree on (bank_id, trigram_fingerprint). The persisted-key design is open for discussion.

Why not just lookup the canonical name? Different spellings can have identical trigram sets. For example, the benchmark includes service-000000 and service 000000. The current resolver may select either according to its existing ordering. A raw-name shortcut can change the chosen ID. The prototype therefore queries the whole fingerprint class, keeps the existing PostgreSQL similarity/ID ordering and candidate cap, and tests punctuation aliases.

The prototype only measures cases where an existing exact spelling and its alias class are present. It is not a complete production implementation of miss/fallback handling. It does not establish equivalence for every Unicode normalization case or oversized tie class.

A production implementation would need:

  • Agreement with the current scorer's normalization and existing candidate visibility/order/cap.
  • Existing resolve=False and label exact-only behavior preserved.
  • Fallback when equivalence or a winner cannot be established.
  • Fingerprint backfill and maintenance through entity creation, import, edits/reassertion, and any normalization changes.
  • Existing scope isolation and mention-count/date accounting retained.

The safe starting point could be an opt-in PostgreSQL fast path; other stores can keep their existing resolver while the lookup representation is evaluated.

Alternatives Considered
  • #5368's co-occurrence projection/degree aggregation: reduce the data shipped when co-occurrence is needed. This proposal instead tries to determine that co-occurrence is unnecessary and skip that read. The approaches are complementary.
  • Exact canonical-name lookup alone: cheaper but can change the winner among perfect-score punctuation variants.
  • Caching resolved names: requires invalidation after entity edits/deletes/merges; an indexed lookup reads the current registry.
  • Keep current behavior if the extra lookup rarely hits or cannot preserve existing decisions on representative traffic.
Priority

Nice to have — a measured performance proposal for discussion, with result equivalence as an acceptance condition.

Additional Context

Suggested validation:

  • Existing names, genuinely new names, misspellings, punctuation/case variants, same-surname people and numerical identifiers.
  • Mixed batches, literal names, labels, perfect-score ties and the current candidate cap.
  • Compare resolved IDs and queued stats, not only displayed names.
  • Measure hit rate, fallback overhead, database rows transferred, event-loop CPU and end-to-end retain latency on real batches.

Questions:

  1. Would exposing the perfect-match branch as an indexed lookup fit the entity-store design?
  2. Is a stored fingerprint, an expression index or another representation preferable?
  3. Can the equivalence guard be narrow enough to ship useful steady-state savings without changing fuzzy resolution?

The standalone probe below creates a uniquely named pg0 instance and drops that instance in finally. Save it as /tmp/entity_exact_probe.py, then run from a checkout with the embedded-db dependencies available:

uv run --project hindsight-api-slim --extra embedded-db python /tmp/entity_exact_probe.py

Python/asyncpg run the probe; no LLM or embedding provider is called. The schema is reduced to the tables/indexes needed by the resolver. Index creation and fingerprint backfill are excluded from the timed path.

Standalone reproduction script
"""Compare current entity resolution with an exact-name winner shortcut on disposable PG."""

from __future__ import annotations

import asyncio
import hashlib
import json
import statistics
import time
import uuid
from dataclasses import asdict, dataclass
from pathlib import Path
from typing import Any

import asyncpg
from hindsight_api.engine.memories.pg.entity_resolver import EntityResolver
from hindsight_api.engine.retain.types import ResolvedEntity
from hindsight_api.engine.trigram import trigram_set
from hindsight_api.pg0 import EmbeddedPostgres


@dataclass
class ReadCounts:
    queries: int = 0
    rows: int = 0


class ObservedConnection:
    backend_type = "postgresql"

    def __init__(self, conn: asyncpg.Connection):
        self.conn = conn
        self.reads = ReadCounts()

    async def fetch(self, query: str, *args: Any) -> list[Any]:
        rows = await self.conn.fetch(query, *args)
        self.reads.queries += 1
        self.reads.rows += len(rows)
        return rows

    async def execute(self, query: str, *args: Any) -> str:
        return await self.conn.execute(query, *args)


@dataclass(frozen=True)
class EntityResult:
    entity_count: int
    cooccurrence_count: int
    mentions: int
    original_ms: float
    shortcut_ms: float
    speedup: float
    original_rows_read: int
    shortcut_rows_read: int
    original_queries: int
    shortcut_queries: int
    same_ids: bool
    same_mention_updates: bool
    scope: str


async def shortcut(
    resolver: EntityResolver,
    conn: ObservedConnection,
    mentions: list[dict[str, Any]],
) -> list[ResolvedEntity]:
    texts = list(dict.fromkeys(mention["text"] for mention in mentions))
    fingerprints = [hashlib.sha256("\0".join(sorted(trigram_set(text))).encode()).hexdigest() for text in texts]
    # Query the whole identical-trigram class, not just one spelling. The production
    # resolver may prefer a punctuation variant with a lower UUID when both score 1.
    rows = await conn.fetch(
        """
        SELECT q.query_text, c.id, c.canonical_name, c.metadata, c.last_seen, c.mention_count
        FROM unnest($2::text[], $3::text[]) AS q(query_text, fingerprint)
        CROSS JOIN LATERAL (
            SELECT e.id, e.canonical_name, e.metadata, e.last_seen, e.mention_count
            FROM entities e
            WHERE e.bank_id = $1 AND e.trigram_fingerprint = q.fingerprint
              AND e.entity_kind != 'label'
              AND LOWER(e.canonical_name) % LOWER(q.query_text)
            ORDER BY similarity(LOWER(e.canonical_name),LOWER(q.query_text)) DESC,e.id
            LIMIT $4
        ) c
        """,
        "probe-bank",
        texts,
        fingerprints,
        resolver.entity_resolution_max_candidates,
    )
    candidates: dict[str, list[Any]] = {}
    for row in rows:
        candidates.setdefault(row["query_text"], []).append(
            (row["id"], row["canonical_name"], row["metadata"], row["last_seen"], row["mention_count"])
        )
    assert all(candidates.get(mention["text"]) for mention in mentions)
    assert all(
        any(candidate[1].lower() == mention["text"].lower() for candidate in candidates[mention["text"]])
        for mention in mentions
    )
    # Reuse production assignment/stat-accounting; only the prefetch differs.
    return await resolver._resolve_from_candidates(
        conn,
        "probe-bank",
        mentions,
        None,
        candidates,
        {},
        taxonomy_lookup=set(),
        labels_cfg=None,
        cooccurrence_degrees={},
    )


async def main() -> None:
    instance = EmbeddedPostgres(name=f"hindsight-original-probe-{uuid.uuid4().hex[:10]}")
    raw: asyncpg.Connection | None = None
    try:
        uri = await instance.start(max_retries=1)
        raw = await asyncpg.connect(uri)
        await raw.execute("CREATE EXTENSION IF NOT EXISTS pg_trgm")
        await raw.execute("CREATE EXTENSION IF NOT EXISTS btree_gin")
        await raw.execute("SET jit = off")
        await raw.execute("SET pg_trgm.similarity_threshold = 0.3")
        await raw.execute(
            """
            CREATE TABLE entities (
                id uuid PRIMARY KEY,
                bank_id text NOT NULL,
                canonical_name text NOT NULL,
                metadata jsonb NOT NULL DEFAULT '{}',
                last_seen timestamptz,
                mention_count int NOT NULL DEFAULT 1,
                entity_kind text NOT NULL DEFAULT 'regular',
                trigram_fingerprint text
            );
            CREATE UNIQUE INDEX idx_entity_exact ON entities(bank_id, LOWER(canonical_name));
            CREATE INDEX idx_entity_trigram
                ON entities USING gin(bank_id, LOWER(canonical_name) gin_trgm_ops)
                WHERE entity_kind != 'label';
            CREATE TABLE entity_cooccurrences (
                entity_id_1 uuid NOT NULL,
                entity_id_2 uuid NOT NULL,
                cooccurrence_count int NOT NULL DEFAULT 1,
                PRIMARY KEY(entity_id_1, entity_id_2),
                CHECK(entity_id_1 < entity_id_2)
            );
            CREATE INDEX idx_cooccurrence_second ON entity_cooccurrences(entity_id_2);
            INSERT INTO entities(id,bank_id,canonical_name)
            SELECT md5('entity-' || i)::uuid, 'probe-bank', 'service-' || lpad(i::text,6,'0')
            FROM generate_series(0,9999) AS i;
            INSERT INTO entities(id,bank_id,canonical_name)
            SELECT md5('other-entity-' || i)::uuid, 'other-bank', 'service-' || lpad(i::text,6,'0')
            FROM generate_series(0,19) AS i;
            INSERT INTO entity_cooccurrences(entity_id_1,entity_id_2)
            SELECT LEAST(md5('entity-' || i)::uuid, md5('entity-' || ((i+d)%10000))::uuid),
                   GREATEST(md5('entity-' || i)::uuid, md5('entity-' || ((i+d)%10000))::uuid)
            FROM generate_series(0,9999) i CROSS JOIN generate_series(1,20) d
            ON CONFLICT DO NOTHING;
            INSERT INTO entity_cooccurrences(entity_id_1,entity_id_2)
            SELECT LEAST(md5('entity-0')::uuid,md5('entity-' || i)::uuid),
                   GREATEST(md5('entity-0')::uuid,md5('entity-' || i)::uuid)
            FROM generate_series(1,9999) i
            ON CONFLICT DO NOTHING;
            ANALYZE entities;
            ANALYZE entity_cooccurrences;
            """
        )
        names = [f"service-{i * 401:06d}" for i in range(20)]
        await raw.executemany(
            "INSERT INTO entities(id,bank_id,canonical_name) VALUES ($1,'probe-bank',$2)",
            [(uuid.uuid5(uuid.NAMESPACE_DNS, name + "-alias"), name.replace("-", " ")) for name in names],
        )
        all_names = await raw.fetch("SELECT id,canonical_name FROM entities")
        fingerprint_rows = [
            (
                row["id"],
                hashlib.sha256("\0".join(sorted(trigram_set(row["canonical_name"]))).encode()).hexdigest(),
            )
            for row in all_names
        ]
        await raw.execute("CREATE TEMP TABLE fingerprints(id uuid, fingerprint text)")
        await raw.copy_records_to_table("fingerprints", records=fingerprint_rows, columns=["id", "fingerprint"])
        await raw.execute(
            """
            UPDATE entities e SET trigram_fingerprint = f.fingerprint FROM fingerprints f WHERE e.id=f.id;
            CREATE INDEX idx_entity_fingerprint ON entities(bank_id,trigram_fingerprint);
            ANALYZE entities;
            """
        )
        mentions = [
            {"text": name, "resolve": True, "nearby_entities": [{"text": peer} for peer in names if peer != name]}
            for name in names
        ]
        original_times: list[float] = []
        shortcut_times: list[float] = []
        reads_by_variant: dict[str, ReadCounts] = {}
        same_ids = True
        same_updates = True
        for repeat in range(4):
            outputs: dict[str, list[ResolvedEntity]] = {}
            stats: dict[str, list[Any]] = {}
            order = ("original", "shortcut") if repeat % 2 == 0 else ("shortcut", "original")
            for variant in order:
                observed = ObservedConnection(raw)
                resolver = EntityResolver(pool=None, entity_lookup="trigram")
                started = time.perf_counter()
                if variant == "original":
                    result = await resolver._resolve_entities_batch_trigram(
                        observed, "probe-bank", mentions, None, taxonomy_lookup=set(), labels_cfg=None
                    )
                else:
                    result = await shortcut(resolver, observed, mentions)
                elapsed = (time.perf_counter() - started) * 1000
                outputs[variant] = result
                stats[variant] = resolver._pending_stats[resolver._task_key()]
                reads_by_variant[variant] = observed.reads
                if repeat:
                    (original_times if variant == "original" else shortcut_times).append(elapsed)
            same_ids &= outputs["original"] == outputs["shortcut"]
            same_updates &= stats["original"] == stats["shortcut"]
        assert same_ids and same_updates
        original_ms = statistics.median(original_times)
        shortcut_ms = statistics.median(shortcut_times)
        report = EntityResult(
            entity_count=await raw.fetchval("SELECT count(*) FROM entities WHERE bank_id='probe-bank'"),
            cooccurrence_count=await raw.fetchval("SELECT count(*) FROM entity_cooccurrences"),
            mentions=len(mentions),
            original_ms=original_ms,
            shortcut_ms=shortcut_ms,
            speedup=original_ms / shortcut_ms,
            original_rows_read=reads_by_variant["original"].rows,
            shortcut_rows_read=reads_by_variant["shortcut"].rows,
            original_queries=reads_by_variant["original"].queries,
            shortcut_queries=reads_by_variant["shortcut"].queries,
            same_ids=same_ids,
            same_mention_updates=same_updates,
            scope=(
                "20 existing exact names and 20 punctuation aliases, resolve=True; "
                "fingerprint class preserves production tie order; synthetic PG graph, not end-to-end retain"
            ),
        )
        output = json.dumps(asdict(report), indent=2)
        Path(__file__).with_suffix(".json").write_text(output + "\n")
        print(output, flush=True)
    finally:
        if raw is not None:
            await raw.close()
        # This uniquely named instance was created solely for this probe.
        await asyncio.to_thread(instance._get_pg0().drop)


if __name__ == "__main__":
    asyncio.run(main())
Dominant language
Python
Stars
45.2k
Forks
5.9k
PR merge metrics
No merged PRs in 30d

Getting set up

This project ships no dev container, Dockerfile or contributing guide, so setting up is up to you: start from its README, and see our first-contribution guide for the general steps.

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from vectorize-io/hindsight

All issues in vectorize-io/hindsight

Similar issues

More Python issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.