db-connection-pool #1

Merged
jakubm merged 8 commits from db-connection-pool into main 2026-10-18 02:25:31 +00:00
Owner
No description provided.
`jina_pg.db.Database.connect()` opened a fresh connection — full TCP + TLS
handshake to the external Postgres, plus a `register_vector` type-OID lookup —
on every single request, and closed it afterwards. That was the bulk of the
~2.5s baseline latency on every search, grounded or not, and README has been
flagging it as the highest-leverage optimization available.

It now borrows from a process-wide `psycopg_pool.ConnectionPool`, memoized per
(DSN, sizing) tuple behind a lock — the same idiom `embedder._get_model` already
uses for OpenVINO models, so the API lifespan and the three CLI commands share
one pool rather than each opening their own connections.

`connect()` keeps its contract exactly: `ConnectionPool.connection()` applies
the standard connection-context behaviour (commit on clean exit, rollback on
exception), then returns the connection to the pool instead of closing it,
replacing it if it came back broken. Nothing upstream changed — `main.py` is
untouched. `register_vector` moves to the pool's `configure` callback, so the
type lookup happens once per physical connection rather than per request.

Measured against a local Postgres over the same 1195-row index,
`search(limit=50)` went 31.7ms → 14.4ms; end-to-end through the container,
`/api/search` went ~2.5-3s → 43-65ms warm and `/api/status` to ~3ms. Against
the real remote host the win is the handshake itself, which is larger. Verified
functionally identical results (same ids, same similarities), preserved
commit/rollback semantics, and 16 concurrent threads x 10 searches with no
errors.

Two behavioural notes:

- The pool opens in the background, so the API now starts even when Postgres is
  unreachable and requests fail with `PoolTimeout` after `DB_POOL_TIMEOUT`
  (default 10s) instead of hanging until the Cloud Run request timeout. Confirmed
  against a blackholed address: HTTP 500 in 8.02s at `DB_POOL_TIMEOUT=8`.
- `DB_POOL_CHECK` (default on) verifies a connection before handing it out,
  costing one empty round trip. ~0.3ms locally but a full RTT to the remote host;
  it defaults on because that host can drop idle connections silently and, with
  Cloud Run not allocating CPU while idle, the pool's maintenance threads cannot
  run between requests to notice.

Sizing is configurable via DB_POOL_MIN_SIZE / MAX_SIZE / TIMEOUT / MAX_LIFETIME
/ CHECK, threaded through compose, deploy.sh and the env examples.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
POST /api/search/batch runs many queries in one request, for bursts of 30-50 searches.
With grounding off its results are identical to GET /api/search (52 queries: same order, ids
and similarities). With grounding on they use a different, compact prompt, so a query can
differ by an item or two; on 24 clear-intent queries precision was 0.723 vs 0.748 for
/api/search, with zero exclusion violations in either.

Embedding (jina_pg.embedder): queries are tokenized once, sorted by token length, cut into
chunks of EMBED_QUERY_BATCH_SIZE (8), and run concurrently across the OpenVINO request pool,
each chunk padded only to its own longest row. 50 mixed-length queries on 2 cores: 3,528 ms
one at a time, 1,403-1,459 ms this way. Batching in arrival order wastes 28-57% of compute on
padding and is slower than singles; padding to a multiple of 8 is slower too. Embeddings are
bit-identical to embedding each query alone. Chunks are yielded as they finish so downstream
work can start early.

Search (jina_pg.db): Database.search_many does every search in one LATERAL statement, i.e. one
round trip to the remote Postgres instead of N.

Grounding (word_api.grounder): several queries share one Gemini request, closed by a
GroupPacker at GROUNDING_QUERIES_PER_REQUEST (5) or estimated input/output token budgets.
Candidates are sent as "number: referent" and replies are positions, ~77% fewer input tokens.
A reply missing a search is retried for just that query, an unparseable reply per query, and
an API error is not retried (it fails that group's queries, so an outage is not multiplied).
Queries are searched and sent to Gemini as their chunk finishes, so embedding and Gemini
overlap. A failed query is reported on its own item (HTTP 200); the batch does not fail.

Defaults, measured end to end through the API (50 queries, 2 cores, concurrency 64): queries
per request 1 / 5 / 10 / 50 take 2.65 / 2.80 / 3.71 / 7.14 s. Fewer requests is NOT faster:
a request costs ~600 ms plus ~2.4 ms per output token, decoded serially. 5 cuts requests 5x
for ~6% more time. Batch vs 50 concurrent singles: 2.8 vs 3.3 s grounded, 1.4 vs 2.1 s not.

Docs: README "Batch search" and API.md endpoint; corrected stale latency, token and cost
figures to measured values (Gemini ~0.85 s, ~2,020 input tokens, request ~1.1-1.2 s) and
recorded that a local cross-encoder reranker was built, measured and rejected.

Caveats: measured on 12 cores pinned to 2, not Cloud Run; Postgres was local, so the
round-trip savings are reasoned from a 113 ms ping; Vertex credentials expired mid-testing,
so some grounded runs predate that.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Embedding is ~95% of an ungrounded batch and about half of a grounded one, so the query
encoder can now be switched to an INT8-quantized copy of the same model:
QUERY_PRECISION=fp16 (default) or int8. It is OFF by default and is not results-identical.

What it touches: only QUERIES. Passages (jina-pg ingest, POST /api/words) always use fp16, so
the stored corpus stays valid and nothing is re-indexed. The fp16 model is loaded lazily when
int8 is on, so a search-only deployment does not pay for it at startup. A missing INT8
directory fails at boot with an error naming the quantize script, and a bad QUERY_PRECISION
value is rejected. /api/status reports query_precision.

Build: scripts/quantize_openvino.py (NNCF post-training quantization, TRANSFORMER model type)
calibrates on 400 query-shaped lines in eval/calibration_queries.txt. The API Dockerfile runs it
in the export stage and ships both IRs (+~150 MB, ~1 min of build); nncf added to the export
requirements. Five recipes were compared on a separate 100-query validation set; all landed
within noise (cosine 0.989-0.993, top-1 96-97%), and protecting more layers only cost speed
(2.8x -> 1.85x), so the default recipe is used.

Speed, through the real API, 2 pinned cores, no grounding: one query 62 -> 28 ms, batch of 50
1,724 -> 582 ms, 50 concurrent singles 2,062 -> 1,162 ms. This machine has AVX512-VNNI; Cloud
Run's CPU may not, so the gain there may be smaller.

Are results the same? scripts/compare_encoders.py runs eval/regression_queries.json (50 queries:
20 category, 12 natural-language, 8 homonym, 6 exclusion, 4 short/typo; disjoint from the
calibration lines) through both encoders on the live index and exits non-zero if a gate fails.
The gates were fixed before looking at results. On the 1,195-row test corpus:

  G1 fp16 top-10 still inside int8 top-50 (grounded path)   PASS  1.000, worst 1.00
  G2 top-1 unchanged >= 90% (ungrounded path)               FAIL  84%
  G3 top-10 overlap >= 0.90 (ungrounded path)               PASS  0.920
  G4 precision vs expected sets, forbidden items            PASS  0.384 -> 0.378; 18 -> 17
  G5 final Gemini results (--grounded)                      NOT RUN: needs Vertex credentials

The G2 failures are near-ties: in all 8 cases the fp16 winner is still int8's #1-#3, with a
median fp16 score gap of 0.0017 against a typical #1-to-#2 gap of 0.0108. No ordered top-10 list
was exactly identical in an end-to-end batch test. With grounding on (the default) G1 is the
gate that matters; without it, expect the top hit to differ on about 1 query in 6.

The corpus here is flat single words; production has sense annotations. Re-run
compare_encoders.py against the production index before enabling this there. The --grounded
path is only exercised with a stubbed Gemini.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
The INT8 commit (b1536d6) said the grounded gate G5 had not been run because Vertex credentials
had expired. It has now been run, and it FAILS. This corrects README.md and API.md accordingly.

G5, real Gemini, 50 regression queries, fp16 vs int8 final results: Jaccard 0.78 (fp16 repeated
against itself: 1.00); precision 0.685 -> 0.643 at one query per request; forbidden items 0 -> 0.
Together with G2 (top-1 unchanged, 84% vs 90%), two of the five gates fail. QUERY_PRECISION
stays off by default.

What the paired per-query analysis shows:
- G1 (fp16's top-10 inside int8's top-50) still passes, but Gemini's final answers still change,
  because the pool's membership and order differ slightly. Identical final sets on only 11-14 of
  50 queries; fp16 repeated is identical on all 50. Mostly an item or two.
- INT8 does not return longer lists (8.62 vs 8.38 items per query). It finds slightly fewer
  expected items: 5.64 vs 5.78 per query at one query per request, 5.50 vs 5.56 at five.
- At one query per request the precision drop is statistically real (-0.040, 95% bootstrap CI
  [-0.077, -0.005]; worse on 18 queries, better on 8). At the default five it is not
  (+0.023, CI [-0.017, +0.068]; worse on 12, better on 14).
- The precision figure overstates the loss on queries with only 1-3 results, where one extra
  item swings the ratio. fp16 itself moves 0.04-0.06 precision depending on which queries share
  a prompt, the same size as the encoder effect.
- Forbidden items: 0 at one query per request, 1 at five ("dentysta" for "zawody medyczne ale
  bez lekarzy", arguably a doctor).

End to end with grounding on (real Gemini, 50 queries, 2 pinned cores, concurrency 64, 8 rows per
chunk, 0 errors, median of 6):

  encoder  q/request  Gemini requests  50 random-pair queries   50 regression queries
  fp16     5          10               2,947 ms                 2,571 ms
  int8     5          10               1,980 ms                 1,833 ms
  fp16     1          50               2,531 ms                 2,306 ms
  int8     1          50               1,951 ms                 1,684 ms

50 concurrent GET /api/search (one Gemini call each): fp16 3,160 ms, int8 2,394 ms. With INT8
the cheaper embedding makes packing free; with fp16, one query per request was 400 ms faster.

Also updates the batch-vs-singles figures to the latest run (grounded 2.9 s vs 3.2 s, previously
2.8 s vs 3.3 s), and drops the "practical reading" claim that G1 alone was the gate that matters
when grounding is on, which these results contradict.

Caveats: 50 queries is a small sample and the expected sets are partial, so absolute precision
is a lower bound; Gemini results varied by 1-2 queries between repeated runs; measured on 2
pinned cores with a local Postgres, not on Cloud Run.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Grounding asks the model to pick matching IDs out of a fixed candidate list
against a fixed `response_schema`. Thinking buys nothing on that task and the
cost depends entirely on the model's default, which is not predictable from the
docs — so `thinking_config` is now set explicitly rather than left implicit.

Measured on a 50-candidate pool through `filter_with_gemini`, real Gemini,
median of 9 calls:

  model                  default                         thinking off
  gemini-3.1-flash-lite  733 ms (no thought tokens)      685 ms   (-7%, noise)
  gemini-2.5-flash       9,547 ms (~2.7k thought tokens) 575 ms   (-94%)

So on the model this repo actually targets the change is a no-op for latency:
3.1-flash-lite already reports no thought tokens by default, contrary to the
Gemini 3 guide's claim that unspecified thinking defaults to `high`. The value
here is the pin, not a speedup — grounding latency no longer moves when the
model or its defaults change underneath us.

`thinking_budget=0` rather than Gemini 3's `thinking_level`, because the budget
form is the portable one: 2.5-flash rejects `thinking_level` outright with
400 INVALID_ARGUMENT, while Vertex accepts `thinking_budget=0` on both families
and reports no thought tokens for either. That contradicts the public docs twice
over (they say Gemini 3 rejects `thinking_budget` and cannot fully disable
thinking), so re-check this on SDK or model bumps.

Raising thinking is a relevance knob, not a free win, and would need the G1-G5
gates rather than a latency check: `thinking_level=LOW` on 3.1-flash-lite cost
+30% latency and dropped mean kept items from 3.0 to 1.3.

Verified both call sites against real Gemini on both models, 0 errors:
`filter_with_gemini` 805 ms and `filter_group_with_gemini` (packed group of 5)
952 ms on 3.1-flash-lite; 610 ms and 1,060 ms on 2.5-flash.

Caveats: candidate pools were offset slices of `ingestion/test.csv`, not the
prod corpus; kept-item counts were unchanged on the single-query path (3.0 mean
both ways) but that is not a relevance gate; the external Postgres is
unreachable, so there is no end-to-end `/api/search` number behind this.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
`GEMINI_MODEL` and `GOOGLE_CLOUD_LOCATION` have been pointing at the previous
model in every place that supplies a fallback, so the intended
`gemini-3.1-flash-lite` was reached only when those vars happened to be exported
in the surrounding shell.

Root `.env` is what compose reads, and it set `GOOGLE_CLOUD_LOCATION=us-central1`
with no `GEMINI_MODEL` at all, so `${GEMINI_MODEL:-gemini-2.5-flash}` won: a
`make up` stack has been grounding on 2.5-flash from a regional endpoint, not
3.1-flash-lite on the global one. `api/.env` had the right values all along, but
compose never reads it. Confirmed by resolving `GroundingConfig.from_env()`
inside the running container, which reported `gemini-2.5-flash` / `us-central1`.

That cost more than the model choice suggests: on 2.5-flash the default thinking
budget spends ~2.7k thought tokens and ~9.5s per grounding call, against ~0.7s
for 3.1-flash-lite (see the preceding commit for the measurements). README
already recorded the same ratio end to end — ~11-16s on 2.5-flash.

`deploy/deploy.sh` carried the same two fallbacks, which is the riskier one: it
is the Cloud Run path, so a deploy run from a shell without those vars exported
would have shipped 2.5-flash to production. `deploy/cloudrun.env` sets both
explicitly, so a deploy that sourced it was unaffected.

Both vars have to move together — 3.1-flash-lite is served only on Vertex's
global endpoint and a regional one 404s — so compose now carries a comment
saying so. Root `.env` deliberately gets no comment: `deploy/sync-env.sh`
rewrites that file by parsing `KEY=value` lines and discarding everything else,
so a comment there would disappear on the next `make up`. The keys survive.

`GOOGLE_CLOUD_REGION=us-central1` in `deploy/cloudrun.env{,.example}` is left
alone — that is the Cloud Run deploy region, a different axis from the Vertex
endpoint, and changing it would move where the service runs.

Verified by recreating the container: it now resolves `gemini-3.1-flash-lite` /
`global`. The code change in the preceding commit needs an image rebuild to go
live; `make up` does both.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This file argued that shrinking PolDense would not fix latency, and it was right,
but it measured that case against a ~3,700 ms request budget with ~2,500 ms of
per-request Postgres connect. `1c6cefc` removed that connect, so the budget is
now ~1.1-1.2s steady with grounding on, per `API.md`. The size-sweep latency and
relevance measurements are untouched — only the denominator moved, which makes
embedding ~7% of the total rather than 1.2%. A blockquote records the revision so
the old framing is not silently rewritten.

Adds a section for the grounding measurements taken today, which is where the
budget now sits:

  model                  thinking default                thinking off
  gemini-3.1-flash-lite  733 ms (no thought tokens)      685 ms  (-7%, noise)
  gemini-2.5-flash       9,547 ms (~2.7k thought tokens) 575 ms  (-94%)

with the root cause of that second row — root `.env` set no `GEMINI_MODEL`, so
compose's stale `gemini-2.5-flash` fallback won and a `make up` stack grounded on
the wrong model from a regional endpoint (fixed in `9cb8295`) — and the finding
that thinking was not the lever it looked like: 3.1-flash-lite reports no thought
tokens by default, so the `thinking_budget=0` pin in `0c3153d` is insurance
against undocumented per-model defaults, not a speedup. That misconfiguration was
local only; the serving Cloud Run revision sets the model and location explicitly
from `deploy/cloudrun.env` and was never affected.

Two corrections to claims this file previously made:

- It called a local cross-encoder reranker "the sub-second path". README records
  that one was built and rejected at ~2.3s, ~2.7x slower than Gemini. Retracted
  explicitly rather than deleted, since the old claim is the memorable one.
- The "grounding did not run" caveat is narrowed, not dropped. The ADC expiry is
  resolved and grounding now runs, but only against the 150M pool, so every
  relevance number here is still pre-Gemini and which size wins after grounding
  is still open.

The "production is down" section now records that **`1c6cefc` is not deployed**.
Cloud Run serves `wordsearch-api-00003-6kt`, created 2026-08-23 and 55 days old,
and a Cloud Logging traceback from it shows `psycopg.connect` at `jina_pg/db.py:30`
— an exact line match for the pre-pool source at `829d18e`, where line 30 at
current HEAD is `def _get_pool(...)`. The revision carries no `DB_POOL_*` env vars
and nothing newer has been pushed to Artifact Registry, so the pool, the thinking
pin, the batch endpoint and the INT8 encoder are all absent from prod.

That also corrects the symptom this file first recorded: prod does not hang
indefinitely, it returns `500` after the OS TCP timeout, because the unpooled
connect has no `DB_POOL_TIMEOUT` to cut it short. The local container, which has
the pool, fails in 10s instead. A deploy would buy only the faster failure —
Postgres at 178.105.237.149:5432 is itself down, so none of the latency work here
is observable in prod until it comes back.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
jakubm merged commit 0068580633 into main 2026-10-18 02:25:31 +00:00
Sign in to join this conversation.
No reviewers
No labels
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
jakubm/wyszukiwanie-tematow!1
No description provided.