pgvector backend: support halfvec so a native-2048-dim embedding can be indexed (pg0/Windows has no other path)
feat: support halfvec indexing on the pgvector backend for embeddings above 2000 dimensions
Target: https://github.com/vectorize-io/hindsight/issues Environment: Windows 11, Hindsight API 1.2.1 (1.2.3 is current on PyPI), default pg0 deployment (embedded PostgreSQL 18.1 + pgvector 0.8.5).
On the default pg0 deployment -- the embedded PostgreSQL that
HINDSIGHT_API_DATABASE_URL defaults to -- an embedding model above 2000
dimensions has no working path on Windows 11: creating an HNSW index on a
vector(2048) column fails outright, and all three high-dimensional extension
backends Hindsight exposes are unavailable on that platform. The gap is
unnecessary. pgvector has been able to index halfvec up to 4000 dimensions
since 0.7, Hindsight's existing query SQL already works unchanged against a
halfvec column, and switching an existing vector column over is one DDL
statement. What is missing is the wiring in the pgvector backend.
Problem
A 2048-dimension model is an ordinary choice: WeMM-Embedding-2B is fixed at
2048 dimensions, and passing dimensions=1024 is silently ignored by the
server, which still returns 2048.
With the default HINDSIGHT_API_VECTOR_EXTENSION=pgvector, index creation on
that column fails:
ERROR: column cannot have more than 2000 dimensions for hnsw index
Storage is not the limit -- pgvector stores vector columns up to 16000
dimensions. Only indexing stops at 2000, and without an index the workload
falls back to a sequential scan over every partition.
Self-service is also blocked: three guards stack, and there is no order of operations that gets a user out.
admin/reembed.py:
if index_type_keyword(ext) == "hnsw" and dim > 2000:
raise RuntimeError("pgvector HNSW indexes stop at 2000 dimensions...")
migrations.py::_migrate_table_embedding_dimension raises as soon as the
table holds rows:
Cannot change embedding dimension from 1024 to 2048: memory_units table contains N rows with embeddings
migrations.py::_create_embedding_vector_index, on boot:
Embedding dimension 2048 exceeds pgvector HNSW index limit of 2000
The daemon will not start because of the dimension mismatch, while
hindsight-admin reembed needs a running daemon (the CLI ensures one starts),
so re-embedding cannot be reached from the broken state either.
Why the existing escape hatches don't cover pg0 users
CONFIGURABLE_EXTENSIONS = ("pgvector", "pgvectorscale", "vchord", "scann") --
all three non-default backends handle high dimensions, but none of them is
reachable from a pg0 install:
| extension | above 2000 dims | on Windows / pg0 |
|---|---|---|
vchord |
yes | no -- VectorChord 1.1.1 publishes 20 GitHub release assets, all Linux (.deb and *-linux-gnu.zip); the official docs require a Rust + MSVC source build on Windows |
pgvectorscale |
yes | no -- Linux only |
scann |
yes | no -- AlloyDB only |
pg0 is the default value of HINDSIGHT_API_DATABASE_URL, so a default
Windows or macOS install with a model above 2000 dimensions is left with no
route at all, without ever having opted into a Linux-only constraint. Telling
those users to run Linux, or to compile VectorChord from source with a Rust +
MSVC toolchain, is not a migration path.
Proposed fix
When vector_extension == "pgvector" and 2000 < dim <= 4000:
-
Store the column as
halfvec(dim)instead ofvector(dim), in both places that create it -- theADD COLUMNinadmin/reembed.pyand theALTER COLUMN ... TYPEinmigrations.py. -
Return
USING hnsw (embedding halfvec_cosine_ops)from the index-using clause. -
Relax the three raises above so they only fire for
dim > 4000, keeping the existing behaviour for anything past whathalfveccan index. -
Leave the query SQL untouched. This is the decisive point, and it was verified rather than assumed: pgvector permits
halfvec <=> vectorcomparison across types, so every existingORDER BY embedding <=> $1::vectorkeeps matching thehalfvecindex.EXPLAIN (ANALYZE)showsIndex Scan using idx_mu_emb_hv_81313a72_observationat 2.599 ms on a 3687-row partition. -
No re-embed is required: assigning
'[...]'::vector(N)into ahalfveccolumn converts implicitly onINSERT, so an existing install moves over with a single statement:ALTER TABLE public.memory_units ALTER COLUMN embedding TYPE halfvec(2048) USING embedding::halfvec(2048);Measured on a live table: 15864 rows converted in 1675 ms.
-
Pick
hnsw, notivfflat, for this path. The ANN tuning in_vector_index.pyonly sets HNSW GUCs --_ANN_TUNING_LOW_LATENCY = {"pgvector": (("hnsw.ef_search", "60"), ("hnsw.iterative_scan", "off"))}, and_ANN_TUNING_HIGH_RECALLwithef_search200 plusiterative_scanstrict_orderandmax_scan_tuples. Anivfflatindex is faster in the microbenchmark below but silently loses all of that tuning. -
An explicit opt-in flag and an automatic decision (use
halfvecwhenevervector_extension == "pgvector"and2000 < dim <= 4000) both work. The maintainers can pick whichever fits the existing config style better than a patch would.
Measured trade-off
All index and query numbers below come from the same pg0 instance (PostgreSQL 18.1, pgvector 0.8.5) against 7203 real vectors:
| path | result |
|---|---|
vector(2048) + HNSW |
index creation fails: column cannot have more than 2000 dimensions for hnsw index |
vector(2048), no index (sequential scan) |
59.035 ms |
halfvec(2048) column + HNSW |
4.079 ms |
halfvec(2048) column + ivfflat |
0.583 ms |
vector column + halfvec expression index, query rewritten with a cast |
5.046 ms |
vector column + halfvec expression index, query left unchanged |
459.373 ms |
The expression index is not a substitute for changing the column type: it only pays off if every query is rewritten (5.046 ms), and is worse than no index at all when it is not (459.373 ms versus 59.035 ms for the plain sequential scan).
Recall was checked separately, and the fp16 quantisation was isolated from every
other variable. The pre-migration table was recovered from a Hindsight backup
taken before the column type changed -- 16,261 rows of vector(2048), read
straight out of the PGCOPY blob, so the float32 values are the originals. Both arms then ran the same queries against the same row set, one
reading the float32 dump and one reading the halfvec column:
| arm | top-10 identical | overlap | R@1 | R@5 |
|---|---|---|---|---|
float32 (vector(2048)) |
-- | -- | 38/48 | 47/48 |
fp16 (halfvec(2048)) |
48/48 | 1.0000 | 38/48 | 47/48 |
Top-10 results are byte-identical on every question. The vectors of the one question that changed rank differ by 0.10 and 0.07 in cosine distance, while fp16's own perturbation is on the order of 1e-3 -- two orders of magnitude smaller. Half-precision indexing costs nothing measurable in recall.
(A caution for anyone reproducing end-to-end numbers: a live Hindsight bank grows continuously. Between two of our own runs 27 minutes apart the candidate pool grew 17.7%, which alone moved R@1 by 6.5 points. Any recall comparison must pin the row count, or it measures corpus growth rather than the change under test.)
Prior art
Three closed issues touch this wall. None of them covers pg0-on-Windows, and one of them closes on a fix that does not apply to a native-2048 model:
- #372 / #343 -- "PGVector is used when VectorChord should be used
instead". Both resolve by pointing at
vchord. That is the right answer for users who can install it; it is no answer at all forpg0, which on Windows ships only the extensions it was built with. VectorChord 1.1.1 publishes twenty release assets, every one of them.debor*-linux-gnu.zip, and its docs say a Windows build means Rust + MSVC from source. - #738, fixed by #755 -- per-bank index creation ignored
HINDSIGHT_API_VECTOR_EXTENSIONand always emitted HNSW. Same 2000-dimension wall, but only for users who already have a >2000-dimension backend installed. The pgvector path was never in scope. - #6197 -- an OpenAI-compatible server ignored
dimensions, leaving a 4096-dimension model unusable. Closed with "we would rather not truncate vectors client-side; the right fix is upstream". That reasoning does not reach this case: the model here is natively 2048 and not Matryoshka-trained, so there is nothing to truncate and no upstream fix to wait for. The only question is whether Hindsight can index 2048 dimensions on pgvector -- and it can, viahalfvec, without touching the model or the vectors.
Patch
A working patch against v1.2.1 is in the next comment (548 lines, 5 files,
git apply-clean on the upstream tree). It is not a proposal sketch: it is what
this instance is running now.
Patch against v1.2.1 (hindsight-api-slim). 548 lines across 5 files; git apply-clean on the upstream tree, and applying it reproduces the running instance byte for byte.
What each file changes
| file | change |
|---|---|
_vector_index.py |
halfvec_mode(), embedding_column_type(), index_using_clause(ext, dim); dim decides the opclass so a 1024-dim deployment is untouched |
admin/reembed.py |
dimension guard admits >2000 when halfvec is on; ADD COLUMN uses the column-type helper |
migrations.py |
ALTER COLUMN ... TYPE uses the helper; the two index-creation guards stop raising; HINDSIGHT_API_ALLOW_PENDING_REEMBED breaks the boot/re-embed deadlock |
engine/embeddings.py |
optional HINDSIGHT_API_EMBEDDINGS_OPENAI_FALLBACK_BASE_URL with a three-state breaker (primary/fallback/down) — unrelated to halfvec, included because this instance needs it |
engine/cross_encoder.py |
reranker member cooldown made configurable (unrelated to halfvec; drop it if you only want the vector change) |
--- a/hindsight_api/_vector_index.py
+++ b/hindsight_api/_vector_index.py
@@ -3,6 +3,7 @@
from __future__ import annotations
import logging
+import os
from typing import TYPE_CHECKING
# sqlalchemy is imported where it is used, not here: config.py imports this module, and
@@ -203,9 +204,46 @@
return _EXTENSION_NAMES[validate_extension(ext)]
-def index_using_clause(ext: str) -> str:
- """Return the CREATE INDEX USING clause for the vector backend."""
- return _INDEX_USING_CLAUSES[_normalize_resolved(ext)]
+# [LOCAL PATCH 2026-11-21 halfvec] pgvector cannot build an hnsw index past 2000
+# dimensions, but halfvec (fp16) can go to 4000. Opt in explicitly: the switch asserts
+# that the embedding columns were already converted to halfvec.
+PGVECTOR_HNSW_MAX_DIM = 2000
+PGVECTOR_HALFVEC_MAX_DIM = 4000
+
+_PGVECTOR_HALFVEC_CLAUSE = "USING hnsw (embedding halfvec_cosine_ops)"
+
+
+def halfvec_mode() -> bool:
+ """True when pgvector is configured to store/index embeddings as halfvec."""
+ return os.getenv("HINDSIGHT_API_PGVECTOR_HALFVEC", "").strip().lower() in ("1", "true", "yes")
+
+
+def embedding_column_type(ext: str, dim: int) -> str:
+ """The SQL column type for an embedding column of ``dim`` dimensions."""
+ if _normalize_resolved(ext) == "pgvector" and halfvec_mode() and dim > PGVECTOR_HNSW_MAX_DIM:
+ if dim > PGVECTOR_HALFVEC_MAX_DIM:
+ raise ValueError(
+ f"halfvec indexes stop at {PGVECTOR_HALFVEC_MAX_DIM} dimensions; the model has {dim}"
+ )
+ return f"halfvec({dim})"
+ return f"vector({dim})"
+
+
+def index_using_clause(ext: str, dim: int | None = None) -> str:
+ """Return the CREATE INDEX USING clause for the vector backend.
+
+ [LOCAL PATCH 2026-11-21 halfvec-dim] ``dim`` decides the opclass, not just the
+ flag. A ``vector(1024)`` column given ``halfvec_cosine_ops`` would silently
+ become an expression index that no ``embedding <=> $1::vector`` query can use,
+ so the planner falls back to a sequential scan with no error anywhere.
+ ``dim=None`` keeps halfvec: those call sites predate this switch and only
+ exist in a halfvec deployment.
+ """
+ resolved = _normalize_resolved(ext)
+ if resolved == "pgvector" and halfvec_mode():
+ if dim is None or dim > PGVECTOR_HNSW_MAX_DIM:
+ return _PGVECTOR_HALFVEC_CLAUSE
+ return _INDEX_USING_CLAUSES[resolved]
def index_type_keyword(ext: str) -> str:
--- a/hindsight_api/migrations.py
+++ b/hindsight_api/migrations.py
@@ -42,9 +42,15 @@
from ._pg_search import normalize_pg_search_tokenizer, pg_search_bm25_columns
from ._text_search import mental_models_text_document
from ._vector_index import (
+ # [LOCAL PATCH 2026-11-21 halfvec-imports-2]
+ PGVECTOR_HNSW_MAX_DIM,
+ # [LOCAL PATCH 2026-11-21 halfvec-imports]
+ PGVECTOR_HALFVEC_MAX_DIM,
bootstrap_extension,
configured_vector_extension,
detect_vector_extension,
+ embedding_column_type,
+ halfvec_mode,
index_type_keyword,
index_using_clause,
minimum_rows_for_index,
@@ -692,6 +698,19 @@
).scalar()
if row_count > 0:
+ # [LOCAL PATCH 2026-11-21 pending-reembed] `admin reembed` builds embedding_next and
+ # swaps under a lock, so the live column must keep its old dimension until that swap.
+ # With the explicit opt-in below we let the server boot (queries against the vector
+ # arm fail until the swap lands) instead of hard-failing the whole daemon.
+ if os.getenv("HINDSIGHT_API_ALLOW_PENDING_REEMBED", "").strip().lower() in ("1", "true", "yes"):
+ logger.warning(
+ "%s.embedding stays at %s dims while the model requires %s: "
+ "a pending re-embed must migrate it (HINDSIGHT_API_ALLOW_PENDING_REEMBED is set)",
+ table_name,
+ current_dim,
+ required_dimension,
+ )
+ return
raise RuntimeError(
f"Cannot change embedding dimension from {current_dim} to {required_dimension}: "
f"{table_name} table contains {row_count} rows with embeddings. "
@@ -704,7 +723,11 @@
_drop_embedding_vector_indexes(conn, schema_name, table_name)
conn.execute(
- text(f"ALTER TABLE {schema_name}.{table_name} ALTER COLUMN embedding TYPE vector({required_dimension})")
+ # [LOCAL PATCH 2026-11-21 halfvec] >2000 dims lands in a halfvec column.
+ text(
+ f"ALTER TABLE {schema_name}.{table_name} ALTER COLUMN embedding TYPE "
+ f"{embedding_column_type(vector_ext, required_dimension)}"
+ )
)
conn.commit()
@@ -735,12 +758,15 @@
# index here is never used and doubles the vector write cost (#5707).
logger.debug(f"Per-bank vector backend ({vector_ext}); no global vector index on memory_units")
return
- if vector_ext == "pgvector" and dimension > 2000:
- raise RuntimeError(
- f"Embedding dimension {dimension} exceeds pgvector HNSW index limit of 2000. "
- f"Use an embedding model with <= 2000 dimensions, or switch to a vector extension "
- f"that supports higher dimensions (e.g., pgvectorscale/DiskANN or AlloyDB ScaNN)."
+ if vector_ext == "pgvector" and dimension > 2000 and not halfvec_mode():
+ # [LOCAL PATCH 2026-11-21 halfvec] only reachable with halfvec mode off.
+ logger.warning(
+ "%s.embedding is %d dims, past the pgvector hnsw ceiling of 2000, and halfvec "
+ "mode is off; no vector index will be built (sequential scan)",
+ table_name,
+ dimension,
)
+ return
index_type = index_type_keyword(vector_ext)
if should_defer_index_creation(vector_ext, row_count):
@@ -817,6 +843,49 @@
vector_ext = _detect_vector_extension(conn, vector_extension)
logger.info(f"Using vector extension: {vector_ext}")
+ # [LOCAL PATCH 2026-11-21 storage-mode-check] MF-3: the switch means "a pending
+ # re-embed owns the column", so it must短-circuit the WHOLE reconcile, not just
+ # the ALTER inside _migrate_table_embedding_dimension. Otherwise the index backfill
+ # below sizes an index for required_dimension while the column still holds the old one.
+ if os.getenv("HINDSIGHT_API_ALLOW_PENDING_REEMBED", "").strip().lower() in ("1", "true", "yes"):
+ logger.warning(
+ "Schema %s: skipping the whole embedding-dimension reconcile because "
+ "HINDSIGHT_API_ALLOW_PENDING_REEMBED is set (column expected to be migrated "
+ "by `hindsight-admin reembed`). Required dimension is %s.",
+ schema_name,
+ required_dimension,
+ )
+ return
+
+ # [LOCAL PATCH 2026-11-21 storage-mode-check] MF-2: warn when the flag and the
+ # column disagree. Read-only; a mismatch only breaks the next index creation.
+ for _tbl in ("memory_units", "mental_models"):
+ try:
+ _actual = conn.execute(
+ text(
+ f"SELECT format_type(a.atttypid, a.atttypmod) "
+ f"FROM pg_attribute a WHERE a.attrelid = '{schema_name}.{_tbl}'::regclass "
+ f"AND a.attname = 'embedding' AND NOT a.attisdropped"
+ )
+ ).scalar()
+ except Exception:
+ continue
+ if not _actual:
+ continue
+ _wants_halfvec = halfvec_mode() and required_dimension > PGVECTOR_HNSW_MAX_DIM
+ _is_halfvec = _actual.startswith("halfvec")
+ if _wants_halfvec != _is_halfvec:
+ logger.warning(
+ "HINDSIGHT_API_PGVECTOR_HALFVEC=%s but %s.%s.embedding is %s "
+ "(required dim %s). Index creation will fail or produce an index no "
+ "query can use until they agree.",
+ halfvec_mode(),
+ schema_name,
+ _tbl,
+ _actual,
+ required_dimension,
+ )
+
if not store_owned_memories:
_migrate_table_embedding_dimension(conn, schema_name, "memory_units", required_dimension, vector_ext)
_migrate_table_embedding_dimension(
@@ -1059,12 +1128,15 @@
{"schema": schema_name, "table_name": table_name},
).scalar()
- if embed_dim and embed_dim > 2000:
- raise RuntimeError(
- f"Embedding dimension {embed_dim} on {table_name} exceeds pgvector HNSW index limit of 2000. "
- f"Use an embedding model with <= 2000 dimensions, or switch to a vector extension "
- f"that supports higher dimensions (e.g., pgvectorscale/DiskANN or AlloyDB ScaNN)."
+ if embed_dim and embed_dim > 2000 and not halfvec_mode():
+ # [LOCAL PATCH 2026-11-21 halfvec] see _create_embedding_vector_index.
+ logger.warning(
+ "%s.embedding is %s dims, past the pgvector hnsw ceiling of 2000, "
+ "and halfvec mode is off; skipping index creation (sequential scan)",
+ table_name,
+ embed_dim,
)
+ continue
logger.info(f"Creating {target_index_type} index on {table_name}")
conn.execute(
--- a/hindsight_api/admin/reembed.py
+++ b/hindsight_api/admin/reembed.py
@@ -37,7 +37,13 @@
from sqlalchemy.pool import NullPool
from .._vector_index import (
+ # [LOCAL PATCH 2026-11-21 halfvec-imports-2]
+ PGVECTOR_HNSW_MAX_DIM,
+ # [LOCAL PATCH 2026-11-21 halfvec-imports]
+ PGVECTOR_HALFVEC_MAX_DIM,
detect_vector_extension,
+ embedding_column_type,
+ halfvec_mode,
index_type_keyword,
index_using_clause,
should_defer_index_creation,
@@ -351,7 +357,10 @@
async def _build_next_indexes(conn: asyncpg.Connection, schema: str, ext: str) -> None:
"""Vector indexes over ``embedding_next``; the rename at the swap carries them to ``embedding``."""
- clause = index_using_clause(ext).replace("(embedding ", f"({NEXT} ")
+ # [LOCAL PATCH 2026-11-21 halfvec] index_using_clause() returns the halfvec clause when
+ # halfvec mode is on; the column was created as halfvec above, so this index is valid.
+ _dim = await _column_dimension(conn, schema, "memory_units", NEXT)
+ clause = index_using_clause(ext, _dim).replace("(embedding ", f"({NEXT} ")
for table in TABLES:
if table == "memory_units" and uses_per_bank_vector_indexes(ext):
continue
@@ -414,13 +423,30 @@
ext = await asyncio.to_thread(_resolve_vector_extension, sync_url)
if index_type_keyword(ext) == "hnsw" and dim > 2000:
- raise RuntimeError(f"pgvector HNSW indexes stop at 2000 dimensions; the new model has {dim}")
+ # [LOCAL PATCH 2026-11-21 halfvec] pgvector's vector type cannot be hnsw-indexed past
+ # 2000 dims, but halfvec (fp16) reaches 4000. With HINDSIGHT_API_PGVECTOR_HALFVEC=1 the
+ # column and the index clause both switch to halfvec, so a >2000-dim model is a normal
+ # indexed setup rather than a sequential scan.
+ if not halfvec_mode():
+ raise RuntimeError(
+ f"pgvector hnsw indexes stop at 2000 dimensions and halfvec mode is off; "
+ f"the new model has {dim}. Set HINDSIGHT_API_PGVECTOR_HALFVEC=1 to store these "
+ f"as halfvec, or use a model with <= 2000 dimensions."
+ )
+ if dim > PGVECTOR_HALFVEC_MAX_DIM:
+ raise RuntimeError(
+ f"halfvec indexes stop at {PGVECTOR_HALFVEC_MAX_DIM} dimensions; the new model has {dim}"
+ )
for table in TABLES:
if await _column_dimension(conn, schema, table, NEXT) not in (None, dim):
# Left by an earlier run for a different model: its vectors are useless now.
await conn.execute(f"ALTER TABLE {_table(schema, table)} DROP COLUMN {NEXT}")
- await conn.execute(f"ALTER TABLE {_table(schema, table)} ADD COLUMN IF NOT EXISTS {NEXT} vector({dim})")
+ # [LOCAL PATCH 2026-11-21 halfvec] >2000 dims lands in a halfvec column.
+ await conn.execute(
+ f"ALTER TABLE {_table(schema, table)} ADD COLUMN IF NOT EXISTS {NEXT} "
+ f"{embedding_column_type(ext, dim)}"
+ )
await _install_function(conn, schema, table, _fill_body(table))
await conn.execute(f"DROP TRIGGER IF EXISTS {_TRIGGER} ON {_table(schema, table)}")
await conn.execute(
--- a/hindsight_api/engine/embeddings.py
+++ b/hindsight_api/engine/embeddings.py
@@ -17,6 +17,7 @@
import socket
import struct
import threading
+import time
import warnings
from abc import ABC, abstractmethod
from collections.abc import Awaitable, Callable
@@ -987,6 +988,16 @@
EMBEDDINGS_QUOTA_DEFER_SECONDS = 900
+# [LOCAL PATCH 2026-11-21 embed-breaker-v4] One breaker per (primary, fallback) pair.
+# Keyed, not process-global: a second instance with a different endpoint pair must not
+# inherit the first one's outage. The query and passage instances share the same pair,
+# so they still share a breaker (which was the point of v3).
+_EMBED_FAILOVER: dict[tuple[str, str], dict[str, object]] = {}
+# [LOCAL PATCH 2026-11-21 embed-breaker-v4] Floor for the probe window. Below this a
+# misconfigured value would hammer the dead endpoint.
+_EMBED_FALLBACK_MIN_PROBE = 60.0
+
+
class OpenAIEmbeddings(Embeddings):
"""
OpenAI embeddings implementation using the OpenAI API.
@@ -1009,6 +1020,7 @@
api_key: str,
model: str = DEFAULT_EMBEDDINGS_OPENAI_MODEL,
base_url: str | None = None,
+ fallback_base_url: str | None = None,
batch_size: int = 100,
dimensions: int | None = None,
max_retries: int = 3,
@@ -1036,6 +1048,7 @@
self.api_key = api_key
self.model = model
self.base_url = base_url
+ self.fallback_base_url = fallback_base_url or None
self.batch_size = batch_size
self.dimensions = dimensions
self.max_retries = max_retries
@@ -1052,6 +1065,7 @@
# One AsyncOpenAI per event loop: its pooled connections belong to the loop that
# opened them, and initialize() is not guaranteed to run on the serving loop.
self._clients: LoopLocal[Any] | None = None
+ self._fallback_clients: LoopLocal[Any] | None = None
self._dimension: int | None = None
@property
@@ -1108,6 +1122,32 @@
self.base_url = clean_url
else:
client_kwargs["base_url"] = self.base_url
+ if self.fallback_base_url:
+ # [LOCAL PATCH 2026-11-21 embed-failover] dead primary must not wait 60s.
+ # [LOCAL PATCH 2026-11-21 embed-breaker-v4] The two clients get different
+ # timeouts on purpose: the primary is the one we expect to be dead, so it keeps
+ # a short connect budget; the fallback is the one that must work, so it keeps
+ # retries (a VPN 502 blip must not fail a recall) and a pool wide enough for
+ # max_concurrent_requests.
+ import httpx
+ client_kwargs["max_retries"] = 0
+ client_kwargs["timeout"] = httpx.Timeout(connect=3.0, read=60.0, write=30.0, pool=5.0)
+ fb_kwargs = dict(client_kwargs)
+ # The fallback URL may be a plain host; the primary's Azure-style default_query
+ # belongs to the primary only.
+ fb_kwargs.pop("default_query", None)
+ fb_kwargs["base_url"] = self.fallback_base_url.rstrip("/")
+ fb_kwargs["max_retries"] = 2
+ fb_kwargs["timeout"] = httpx.Timeout(connect=5.0, read=60.0, write=30.0, pool=30.0)
+ self._fallback_clients = LoopLocal(lambda kw=fb_kwargs: AsyncOpenAI(**kw))
+ logger.info("Embeddings: failover base %s", self.fallback_base_url)
+ logger.warning(
+ "Embeddings: assuming %s and %s serve the SAME model with the SAME "
+ "dimension. Mixed vectors from two different models would silently "
+ "degrade retrieval.",
+ self.base_url,
+ self.fallback_base_url,
+ )
self._clients = LoopLocal(lambda: AsyncOpenAI(**client_kwargs))
# Try to get dimension from known models, otherwise do a test embedding
@@ -1120,7 +1160,7 @@
request: dict[str, Any] = {"model": self.model, "input": ["test"]}
if self.extra_body:
request["extra_body"] = self.extra_body
- response = await self._loop_client().embeddings.create(**request)
+ response = await self._embeddings_create(request)
if response.data:
self._dimension = len(response.data[0].embedding)
@@ -1144,6 +1184,159 @@
return await self._encode_batched(texts, self._embed_batch)
+ def _fallback_client(self):
+ if self._fallback_clients is None:
+ return None
+ client = self._fallback_clients.get()
+ if client.api_key != self.api_key:
+ client.api_key = self.api_key
+ return client
+
+ def _fb_entry(self) -> dict[str, object]:
+ """[LOCAL PATCH 2026-11-21 embed-breaker-v4] Breaker state for this endpoint pair."""
+ key = (self.base_url, getattr(self, "fallback_base_url", "") or "")
+ entry = _EMBED_FAILOVER.get(key)
+ if entry is None:
+ entry = {"state": "primary", "next_probe": 0.0}
+ _EMBED_FAILOVER[key] = entry
+ return entry
+
+ def _fb_env_seconds(self, name: str, default: float) -> float:
+ """[LOCAL PATCH 2026-11-21 embed-breaker-v4] 0 or negative disables probing."""
+ raw = os.getenv(name)
+ if not raw:
+ return default
+ try:
+ value = float(raw)
+ except ValueError:
+ return default
+ if value <= 0:
+ return float("inf")
+ return max(value, _EMBED_FALLBACK_MIN_PROBE)
+
+ async def _embeddings_create(self, request: dict[str, Any]):
+ """Primary/then-fallback with a three-state breaker.
+
+ [LOCAL PATCH 2026-11-21 embed-breaker-v4] A dead primary costs 3 s on EVERY call
+ otherwise (measured: generate_query_embedding=3.1 s per recall). States:
+
+ primary - normal. A connect failure switches to `fallback` immediately, with
+ no retry of the primary. If the fallback fails too, the state goes
+ straight to `down` (v3 stopped at `fallback` and let the exception
+ escape unlogged).
+ fallback - serves from the fallback URL. Once every FALLBACK_PROBE seconds ONE
+ request re-probes the primary, so a recovered intranet is picked back
+ up without waiting for the fallback to break too.
+ down - the fallback broke as well. Requests keep using the fallback, and
+ the primary is re-probed once every DOWN_COOLDOWN seconds.
+
+ State transitions are compare-and-set on the live entry, never on a snapshot
+ taken before an await: in v3 a stale `down` snapshot could overwrite the
+ `primary` written by a concurrent probe that had already succeeded, so one run
+ logged both "primary recovered" and "primary stays degraded".
+ """
+ from openai import APIConnectionError, APITimeoutError
+
+ fallback = self._fallback_client()
+ if fallback is None:
+ return await self._loop_client().embeddings.create(**request)
+
+ entry = self._fb_entry()
+
+ async def _call_primary():
+ return await self._loop_client().embeddings.create(**request)
+
+ async def _call_fallback():
+ return await fallback.embeddings.create(**request)
+
+ # ---- primary: the good path ----
+ if entry["state"] == "primary":
+ try:
+ return await _call_primary()
+ except (APIConnectionError, APITimeoutError) as exc:
+ # Only the coroutine that actually flipped the state logs, so 64 concurrent
+ # batches hitting a dead primary produce one WARNING, not 64.
+ transitioned = entry["state"] == "primary"
+ window = self._fb_env_seconds(
+ "HINDSIGHT_API_EMBEDDINGS_FALLBACK_PROBE_SECONDS", 300.0
+ )
+ entry["state"] = "fallback"
+ entry["next_probe"] = time.monotonic() + window
+ if transitioned:
+ logger.warning(
+ "Embeddings primary %s unreachable (%s); serving from %s "
+ "(re-probing the primary in %ss)",
+ self.base_url,
+ type(exc).__name__,
+ self.fallback_base_url,
+ int(window) if window != float("inf") else "never",
+ )
+ try:
+ return await _call_fallback()
+ except (APIConnectionError, APITimeoutError) as fallback_exc:
+ # v3 lost this: state stayed `fallback`, the ERROR never fired, and the
+ # exception escaped to _embed_batch, which only catches RateLimitError.
+ down_window = self._fb_env_seconds(
+ "HINDSIGHT_API_EMBEDDINGS_DOWN_COOLDOWN_SECONDS", 600.0
+ )
+ entry["state"] = "down"
+ entry["next_probe"] = time.monotonic() + down_window
+ logger.error(
+ "Embeddings both %s (%s) and %s (%s) unreachable",
+ self.base_url,
+ type(exc).__name__,
+ self.fallback_base_url,
+ type(fallback_exc).__name__,
+ )
+ raise
+
+ # ---- fallback / down: use the fallback, re-probe the primary on schedule ----
+ now = time.monotonic()
+ if now >= float(entry["next_probe"]):
+ interval = self._fb_env_seconds(
+ "HINDSIGHT_API_EMBEDDINGS_DOWN_COOLDOWN_SECONDS"
+ if entry["state"] == "down"
+ else "HINDSIGHT_API_EMBEDDINGS_FALLBACK_PROBE_SECONDS",
+ 600.0 if entry["state"] == "down" else 300.0,
+ )
+ # Claim the window before awaiting so concurrent coroutines cannot all probe.
+ entry["next_probe"] = now + interval
+ try:
+ response = await _call_primary()
+ except (APIConnectionError, APITimeoutError):
+ pass
+ else:
+ entry["state"] = "primary"
+ logger.warning(
+ "Embeddings primary %s recovered; serving from it again", self.base_url
+ )
+ return response
+
+ try:
+ response = await _call_fallback()
+ except (APIConnectionError, APITimeoutError) as exc:
+ if entry["state"] != "down":
+ down_window = self._fb_env_seconds(
+ "HINDSIGHT_API_EMBEDDINGS_DOWN_COOLDOWN_SECONDS", 600.0
+ )
+ entry["state"] = "down"
+ entry["next_probe"] = time.monotonic() + down_window
+ logger.error(
+ "Embeddings both %s and %s unreachable (%s)",
+ self.base_url,
+ self.fallback_base_url,
+ type(exc).__name__,
+ )
+ raise
+
+ if entry["state"] == "down":
+ entry["state"] = "fallback"
+ logger.warning(
+ "Embeddings fallback %s recovered; primary stays degraded",
+ self.fallback_base_url,
+ )
+ return response
+
async def _embed_batch(self, batch: list[str]) -> list[list[float]]:
"""Embed one batch-sized slice."""
request: dict[str, Any] = {
@@ -1159,7 +1352,7 @@
from openai import RateLimitError
try:
- response = await self._loop_client().embeddings.create(**request)
+ response = await self._embeddings_create(request)
except RateLimitError as e:
# Out of credits is not a blip: retrying it a few times a minute apart only
# dead-letters the operation. Park it instead and try again later (#5588).
@@ -2650,6 +2843,7 @@
api_key=api_key,
model=model,
base_url=base_url,
+ fallback_base_url=os.getenv("HINDSIGHT_API_EMBEDDINGS_OPENAI_FALLBACK_BASE_URL") or None,
batch_size=config.embeddings_openai_batch_size,
dimensions=config.embeddings_openai_dimensions,
max_retries=config.embeddings_max_retries,
--- a/hindsight_api/engine/cross_encoder.py
+++ b/hindsight_api/engine/cross_encoder.py
@@ -2691,7 +2691,10 @@
# Same idea as MultiLLMProvider's cooldown, minus its config and doubling: a
# reranker outage is a host being down, not an hours-long quota to back off from.
# ponytail: fixed cooldown, make it a setting if operators ask to tune it
- MEMBER_COOLDOWN_SECONDS = 30.0
+ # [LOCAL PATCH 2026-11-21 reranker-cooldown] 30 s is too short when the primary is
+ # unreachable for hours (intranet off / VPN on): a 50-question run lasts ~33 s and
+ # would re-probe the dead member every round, paying its timeout each time.
+ MEMBER_COOLDOWN_SECONDS = float(os.getenv("HINDSIGHT_API_RERANKER_MEMBER_COOLDOWN_SECONDS", "30"))
traces_calls = False # each member's predict() traces its own attempt
Still reproducible on 1.3.0 — and the capability already exists one directory over
Compared the published hindsight-api-slim 1.3.0 wheel against 1.2.1 on 2026-11-29:
| file | 1.2.1 → 1.3.0 |
|---|---|
hindsight_api/_vector_index.py |
byte-identical; index_using_clause(ext: str) still takes no dimension |
hindsight_api/migrations.py:738 |
still if vector_ext == "pgvector" and dimension > 2000: raise RuntimeError(...) |
hindsight_api/knowledge/store.py |
new in 1.3.0, and it does what this issue asks for: hnsw ((embedding::halfvec({dimension})) halfvec_cosine_ops), with line 31 reading "pgvector indexes vector up to 2000 dimensions and halfvec up to 4000" |
So this is not an open design question upstream — the new knowledge subsystem already builds halfvec expression indexes on the same plain pgvector this issue needs. The memories path just never got the same treatment, and migrations.py:738's hard RuntimeError is what blocks a native-2048-dim embedding from being indexed at all.
For anyone else tracking this: since _vector_index.py is unchanged in 1.3.0, the patch's main hunk still applies cleanly. The other four files it touches (migrations.py, admin/reembed.py, engine/embeddings.py, engine/cross_encoder.py) do carry upstream 1.3.0 edits, so those hunks need a 3-way merge.