No description
  • HTML 79.5%
  • Python 15.3%
  • Shell 1.9%
  • TypeScript 1%
  • CSS 0.9%
  • Other 1.4%
Find a file
Repository files (latest commit first)
Filename Latest commit message Latest commit date
jakubm 0068580633 Merge pull request 'db-connection-pool' (#1) from db-connection-pool into main
Reviewed, merges latency optimizations, instead of starting new db connection with each req, runs a pool, optimizes prompts and makes sure the latency is as low as possible.
2026-10-18 02:25:30 +00:00
.claude code 2026-09-24 02:47:32 +00:00
api latency optimizations 2026-10-18 02:21:03 +00:00
deploy Fix stale Gemini model/location defaults in compose, deploy and .env 2026-10-17 13:39:15 +00:00
ingestion Add switchable INT8 query encoder (QUERY_PRECISION, default fp16) 2026-10-17 07:03:05 +00:00
model-compare latency optimizations 2026-10-18 02:21:03 +00:00
profiles latency optimizations 2026-10-18 02:21:03 +00:00
webapp code 2026-09-24 02:47:32 +00:00
.dockerignore code 2026-09-24 02:47:32 +00:00
.env Fix stale Gemini model/location defaults in compose, deploy and .env 2026-10-17 13:39:15 +00:00
.gcloudignore code 2026-09-24 02:47:32 +00:00
.gitignore latency optimizations 2026-10-18 02:21:03 +00:00
API.md Docs: record grounded INT8 gate (G5) result and end-to-end timings 2026-10-17 07:59:26 +00:00
cloudbuild.yaml code 2026-09-24 02:47:32 +00:00
docker-compose.yml latency optimizations 2026-10-18 02:21:03 +00:00
Makefile code 2026-09-24 02:47:32 +00:00
MODEL-SIZE-LATENCY.md Docs: rebase the size sweep on the pooled budget, add the grounding findings 2026-10-17 14:09:00 +00:00
README.md Docs: record grounded INT8 gate (G5) result and end-to-end timings 2026-10-17 07:59:26 +00:00

Word Search

Polish word/referent search: embed short referent phrases with a Polish retrieval model, store them in Postgres/pgvector, search by cosine similarity, and optionally re-rank the top candidates with Gemini to fix homonym confusion (e.g. "pilot" the TV remote vs. "pilot" the person who flies planes).

Three moving parts:

webapp/     Static TS/HTML frontend (search box + add-word form)
api/        FastAPI service — /api/status, /api/words, /api/search + serves webapp/
ingestion/  Embedding model, CLI (jina-pg), Postgres schema, batch ingest jobs
deploy/     Cloud Run deploy scripts + env files (not committed with real secrets — see below)

api/ and ingestion/ share the jina_pg package (embedding + DB code lives in ingestion/src/jina_pg, the API imports it as a dependency).

How a search request actually works

GET /api/search?query=... in api/src/word_api/main.py:

  1. Embed the query — jina_pg.embedder.OpenVINOEmbedder.embed_query() runs the query through PolDense-150M (OPI-PIB/PolDense-150M), prefixed with [query]: (queries and indexed passages use different prefixes by the model's own convention). ~80ms steady-state on 2 vCPU (~35-45ms on a 12-core box).
  2. Vector search — jina_pg.db.Database.search() runs a pgvector cosine-similarity query against Postgres, returning RAG_POOL_SIZE (default 50) candidates if grounding is on, or just limit if it's off. Tens of ms on a warm pooled connection — this used to open a fresh connection per request and cost ~2.5s (see Connection pooling).
  3. Grounding (optional, on by default) — api/src/word_api/grounder.py sends the candidate list to Gemini (gemini-3.1-flash-lite via Vertex AI) and asks it to return only the IDs that genuinely match the query's intent, structured as JSON. This is what fixes the homonym problem that pure embedding similarity can't. ~0.85s measured (~2,020 input / ~110 output tokens).
  4. Candidates get mapped back to full rows, truncated to limit, and returned.

GROUNDING_ENABLED=false skips steps 3-4's Gemini call entirely (much faster, no disambiguation).

Connection pooling

jina_pg.db.Database borrows from a process-wide psycopg_pool.ConnectionPool instead of calling psycopg.connect() per request. Database.connect() keeps its old contract — a context manager yielding a connection, committing on clean exit and rolling back on exception — so nothing upstream changed; the connection is returned to the pool rather than closed.

Why it matters: the old path paid a full TCP + TLS handshake to an external Postgres on every request (plus a register_vector type lookup, now done once per connection in the pool's configure callback). That was the bulk of the old ~2.5s baseline. Measured on a local Postgres with the same 1195-row index, search(limit=50) went 31.7ms → 14.4ms; against the real remote host the saving is the handshake itself, which is far larger.

One pool is shared per (DSN, sizing) tuple — same memoize-by-key idiom as embedder._get_model. Tune via env (see api/.env.example):

var default notes
DB_POOL_MIN_SIZE 1 Connections kept warm. One covers the steady case.
DB_POOL_MAX_SIZE 10 Ceiling for a burst. FastAPI's sync endpoints run on a thread pool, so concurrent requests really do want their own connections.
DB_POOL_TIMEOUT 10 Seconds to wait for a free connection before PoolTimeout.
DB_POOL_MAX_LIFETIME 1800 Recycle connections to survive silent server-side drops.
DB_POOL_CHECK true Verify a connection before handing it out. Costs one empty round trip — ~0.3ms locally but a full RTT to the remote host, so this is the first knob to turn off if that matters more than a stale-connection error.

Side effect worth knowing: the pool opens in the background (open=False then open()), so the API starts even when Postgres is unreachable, and requests then fail with PoolTimeout after DB_POOL_TIMEOUT instead of hanging until the Cloud Run request timeout. jina_pg.db.close_pools() exists for tests and clean shutdown.

POST /api/search/batch (API.md) runs many queries in one request. It exists for bursts — a client firing 30–50 searches at once. With grounding off, results are identical to GET /api/search (52 queries: same order, ids and similarities). With grounding on they are the same model but not the same prompt (see "Packing queries into Gemini requests"), so a query can differ by an item or two; on 24 clear-intent queries scored against expected sets, precision was 0.723 (batch default) vs 0.748 (/api/search), with zero exclusion violations in either.

What it shares, versus N independent requests:

  • Embedding. Queries are tokenized once, sorted by token length, cut into chunks of EMBED_QUERY_BATCH_SIZE (8), and the chunks run concurrently across the OpenVINO request pool. Each chunk is right-padded only to its own longest row.
  • Vector search. With grounding off, one LATERAL statement does every search in a single round trip (Database.search_many) — against the remote Postgres each statement costs a full round trip (~113ms by ping), so 50 separate searches would pay that 50 times. With grounding on, each chunk is searched as soon as it is embedded (one statement per chunk).
  • Gemini. Queries are packed into groups of GROUNDING_QUERIES_PER_REQUEST (5) — one request per group, not per query — and each group is sent the moment it fills, with at most GROUNDING_CONCURRENCY (64) requests in flight. A failed request is reported on its queries' items; it does not fail the batch.
  • Duplicates within a batch are computed once.

Why those defaults — measured, 2 pinned cores, 50 mixed-length queries

Embedding all 50 (total ms; token lengths 5–36, median 13):

batch size arrival order sorted by length sorted + pad to multiple of 8
1 (sequential) 3,528 – –
4, across both infer requests 2,002 1,403 1,569
8, across both infer requests 1,873 1,459 1,668
16, across both infer requests 2,357 2,248 2,192
50 (one batch) 4,095 4,060 4,565
  • Batching in arrival order is a trap. A padded batch costs rows x longest row, and mixed lengths waste 28–57% of the compute on padding — a single batch of 50 is slower than doing them one at a time. Sorting cuts the waste to 2–15% at small sizes.
  • Optimal chunk size is 4–8 (a plateau); 16 and up gets slower again as padding returns.
  • Padding to a multiple of 8 is slower, not faster: more padded tokens, and OpenVINO runs variable shapes without needing bucketed ones. Don't add it.
  • Chunks must run concurrently. A THROUGHPUT-compiled request is single-threaded, so one chunk at a time leaves a core idle (sequential 3,528 vs 1,795 across both requests).
  • Padded/sorted embeddings are bit-identical to embedding each query alone (max difference 0), because right-padding with a zero attention mask doesn't touch the CLS token.

Packing queries into Gemini requests

Several queries share one request: the prompt lists N independent searches, each with its own numbered candidates, and Gemini returns {"search": n, "relevant": [positions]} for each. Candidates are sent as number: referent only (not id/word/writing/similarity) and replies are positions, which cuts input tokens ~77% versus the per-query prompt. A group closes at whichever comes first: GROUNDING_QUERIES_PER_REQUEST, GROUNDING_MAX_INPUT_TOKENS (40k) or GROUNDING_MAX_OUTPUT_TOKENS (4k), using character-based estimates (Polish is ~2.0–2.4 characters per token on Gemini; the estimate ran 5–8% low at 2.2, so 2.0 is used). A reply that omits a search is retried for just that query; an unparseable reply is retried per query; an API error is not retried (it fails every query in that group with the same error), so an outage or quota problem doesn't multiply into N more calls.

Token limits are not the constraint — output decoding is. All 50 queries are only ~18k input / ~2k output tokens, far under any limit, but a request costs about 600 ms plus ~2.4 ms per output token, and the reply is decoded serially inside one request. So fewer requests is not faster. Through the real API, concurrency 64, 8 rows per chunk, 50 queries:

queries per request requests batch wall time precision*
1 50 2.65s 0.784
5 (default) 10 2.80s 0.723
10 5 3.71s 0.744
50 1 7.14s 0.715

*On 24 clear-intent queries (4 with exclusions) scored against expected sets I wrote from the corpus, so absolute precision is a lower bound; vector-only is 0.471 and returns 10 forbidden items across the 4 exclusion queries, every Gemini setting returns 0. An earlier test with random word-pair queries showed ~0.5–0.6 agreement between group sizes, but those queries have no right answer (the model reads "opryskiwacz związane z legitymacja" as about either noun depending on context), so it measured ambiguity, not quality.

Why 5: it cuts requests 5x and total input tokens ~33% for ~6% more time and a few points of precision. If latency or precision matter more than request count, set GROUNDING_QUERIES_PER_REQUEST=1 — it was fastest and most precise here. One request for everything is 2.7x slower.

GROUNDING_CONCURRENCY only binds once there are more than 64 requests; at 5 per request that is 320+ queries, above BATCH_MAX_QUERIES. (Before grouping, with one request per query, the cap mattered: 8 → 6.9s, 16 → 4.7s, 32 → 3.5s, 50 → 2.9s for 50 queries, no 429s at any setting.)

End to end, 50 queries, 2 pinned cores

batch 50 concurrent GET /api/search
grounding off 1.4s 2.1s (p95 1.9s)
grounding on (5 queries/request) 2.9s 3.2s

The grounded batch is about embed time plus one Gemini request because of the pipelining; an earlier version that did embed → search → ground in strict sequence took 3.1s and was no better than the singles, which overlap those phases naturally.

Caveats: measured on a 12-core machine pinned to 2 cores, not on Cloud Run; Postgres was local, so the one-round-trip advantage of search_many and the extra per-chunk statements on the grounded path are reasoned from the 113ms ping, not measured; Gemini was called from this machine, so its absolute times are indicative. Application Default Credentials for the test account expired twice during these runs ("Reauthentication is needed"); that is the test account's session policy, not the service, and the batch endpoint reported it as per-item errors with HTTP 200 rather than failing.

INT8 query encoder (QUERY_PRECISION=int8)

Embedding is almost all of the latency once Postgres is pooled and Gemini is overlapped (~95% of an ungrounded batch, about half of a grounded one), so the query encoder can be switched to an INT8-quantized copy of the same model. It is off by default (QUERY_PRECISION=fp16), and it is not results-identical — read the gates below before turning it on.

What it does and doesn't touch:

  • Only queries use INT8. Passages (jina-pg ingest, POST /api/words) always use fp16, so the stored corpus vectors stay valid and nothing needs re-indexing. The fp16 model is loaded lazily, so a search-only deployment never pays for it.
  • The Docker image quantizes at build time (scripts/quantize_openvino.py, NNCF post-training quantization, calibrated on 400 query-shaped lines in ingestion/eval/calibration_queries.txt) and ships both IRs: about +150 MB, and ~1 minute of build time. /api/status reports query_precision.
  • A missing INT8 directory fails at boot with an error naming the quantize script.

Speed, measured through the real API on 2 pinned cores (ungrounded, local Postgres):

fp16 int8
one query 62 ms 28 ms
batch of 50 1,724 ms 582 ms
50 concurrent GET /api/search 2,062 ms 1,162 ms

In isolation the 50-query embed went 1,278 → 491 ms (2.6x).

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

encoder queries per Gemini request Gemini requests batch of 50 random-pair queries batch of the 50 regression queries
fp16 5 (default) 10 2,947 ms [2,879–3,045] 2,571 ms [2,419–2,730]
int8 5 (default) 10 1,980 ms [1,894–2,017] 1,833 ms [1,713–3,094]
fp16 1 50 2,531 ms [2,423–2,718] 2,306 ms [2,102–2,447]
int8 1 50 1,951 ms [1,609–2,540] 1,684 ms [1,586–2,170]

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 (1,980 vs 1,951 ms at 5 vs 1 per request); with fp16, one per request was 400 ms faster. Quantized weights are 150 MB vs 298 MB. This machine has AVX512-VNNI; Cloud Run's CPU may not, in which case the gain could be smaller.

Are the results the same? Gates, fixed before looking

ingestion/scripts/compare_encoders.py runs the 50-query regression set (ingestion/eval/regression_queries.json: 20 categories, 12 natural-language, 8 homonym senses, 6 exclusions, 4 short/typo; every expected/forbidden term is checked against the corpus; the set is disjoint from the calibration lines) through both encoders with the production embedder path and the live index, and exits non-zero if a gate fails. Result on ingestion/test.csv (1,195 rows):

gate what it protects result
G1 fp16's top-10 still inside int8's top-50 (mean >= 0.99, worst >= 0.90) grounded path — Gemini only sees the pool 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 drops <= 0.02; forbidden items not higher quality PASS: 0.384 → 0.378; forbidden 18 → 17
G5 (--grounded) final Gemini results vs an fp16-vs-fp16 repeat end to end FAIL: Jaccard 0.78 (fp16 repeated against itself: 1.00); precision 0.685 → 0.643; forbidden 0 → 0

So: INT8 embeddings are cosine 0.988 (worst 0.979) of fp16, the candidate pool Gemini sees is unchanged, and quality against the expected sets is flat — but the ordering is not identical. In the end-to-end batch test no ordered top-10 list was exactly the same (0/50), sets overlapped 0.90, and the #1 hit moved on 6–8 of 50. The #1 changes are near-ties: in all 8 regression cases the fp16 winner is still int8's #1–#3, and the fp16 score gap is a median 0.0017 against a typical #1-to-#2 gap of 0.0108 (e.g. łoś→żuk for "owady", zoo→słoń for "zwierzęta afrykańskie", traktor↔ciągnik; but also zoo→dom for "zwierzęta domowe").

Grounded, G5 (real Gemini, 50 regression queries, one query per request). G1 passing is necessary but not sufficient: the pool contains every fp16 top-10 hit, yet Gemini's final answers still change, because the pool's membership and order differ slightly and the prompt with it. Identical final sets on only 11–14 of 50 queries (fp16 repeated is identical on all 50), though mostly by an item or two. Paired per query, INT8 returns the same number of items (8.62 vs 8.38) and finds slightly fewer expected ones: 5.64 vs 5.78 per query at one query per request (precision −0.040, 95% bootstrap CI [−0.077, −0.005], worse on 18 queries, better on 8), and 5.50 vs 5.56 at the default five per request (precision +0.023, CI [−0.017, +0.068], worse on 12, better on 14 — not distinguishable from zero). The precision figure overstates the loss on queries with only 1–3 results, where one extra item swings the ratio. Fp16 itself moves by 0.04–0.06 precision depending on which queries share a prompt, which is the same size as the encoder effect. Forbidden items: 0 at one per request, 1 at five (dentysta for "zawody medyczne ale bez lekarzy", arguably a doctor).

Practical reading: INT8 is a small, real change to the answers, not a free speedup. With grounding off, expect the top result to differ on roughly 1 query in 6; with grounding on, expect most queries to differ by an item or two with expected-set hits down roughly 1–2%, and decide whether that is acceptable. The quantization recipe is not the lever — five recipes (default, MIXED preset, skipping attention matmuls, skipping the first/last 3 layers) landed within noise on a separate 100-query validation set (cosine 0.989–0.993, top-1 96–97%), and protecting more layers only cost speed (2.8x → 1.85x). Re-run compare_encoders.py against the production corpus before enabling it there: the test corpus is flat single words, while production carries sense annotations.

Model: PolDense-150M, compiled to OpenVINO

The model is OPI-PIB/PolDense-150M (ModernBERT / ettin-encoder, 149M params, 768-dim, CLS-token pooling + L2 normalize). It beat MMLW-v2 on this corpus — especially homonym disambiguation — at ~2× lower query latency and ~⅓ the IR size. Earlier experiments (see ingestion/sql/00[3-6]_*.sql) were reverted; 006 switches the column from vector(1024) → vector(768) and requires a re-ingest.

It's compiled once at Docker build time via ingestion/scripts/export_openvino.py: PyTorch → ONNX (legacy TorchScript exporter, dynamo=False — dynamo IRs break batch>1) → OpenVINO IR (fp16). The runtime image ships no torch/CUDA — just the OpenVINO runtime and a tokenizer.

Inference is served through jina_pg.embedder.OpenVINOEmbedder (embedder.py): a pool of pre-created OpenVINO InferRequest objects, borrowed/returned via a queue.Queue. A single InferRequest isn't safe to call from two threads at once, but the pool means concurrent requests each get their own — this is what makes it safe for multiple simultaneous users to hit one Cloud Run instance (FastAPI's sync def endpoints run on a thread pool, so concurrent HTTP requests are real concurrent threads). Pool size auto-detects via OpenVINO's OPTIMAL_NUMBER_OF_INFER_REQUESTS, or set OPENVINO_NUM_INFER_REQUESTS to pin it.

To run jina-pg or the API outside Docker, export the model once:

cd ingestion
pip install -r requirements-export.txt --index-url https://download.pytorch.org/whl/cpu --extra-index-url https://pypi.org/simple/
python scripts/export_openvino.py --output-dir ../models/poldense-150m-openvino
# optional, for QUERY_PRECISION=int8 (needs `pip install nncf`):
python scripts/quantize_openvino.py --model-dir ../models/poldense-150m-openvino \
    --output-dir ../models/poldense-150m-openvino-int8

Docker builds do this automatically in a model-export build stage — see api/Dockerfile.

Local development

cp deploy/db.env.example deploy/db.env   # fill in real Postgres creds (or run the
                                          # optional local one: docker compose --profile local-db up -d postgres)
make up                                  # syncs env, builds, runs the API on :8001 (API_PORT)

UI: http://localhost:8001 · Swagger docs: http://localhost:8001/docs

See api/README.md and ingestion/README.md for service-specific detail, and API.md for the API contract (for teams integrating against this service rather than running it).

Deployment (Cloud Run)

cp deploy/cloudrun.env.example deploy/cloudrun.env   # fill in real values
make deploy

deploy/deploy.sh does not build/push the image itself (that step is commented out — build with docker build -f api/Dockerfile -t <artifact-registry-image> . and docker push, or wire up gcloud builds submit --config=cloudbuild.yaml yourself, then run make deploy to point Cloud Run at that image + sync env vars/sizing).

Current production config (deploy/cloudrun.env):

  • Service account: backend-service-account@snappy-helper-438617-d0.iam.gserviceaccount.com. The originally-intended wordsearch-api@... service account doesn't exist and creating it requires iam.serviceAccounts.create, which the deploying identity doesn't have — if you get that permission later, create a narrower-scoped SA (needs only roles/aiplatform.user for Gemini) and swap SERVICE_ACCOUNT in cloudrun.env.
  • Sizing: 4Gi memory / 2 CPU, min-instances=1 (always-on, no cold start for normal traffic — see cost notes below), max-instances=3.
  • Gemini: gemini-3.1-flash-lite via Vertex AI. This model is only available on Vertex AI's global endpoint — GOOGLE_CLOUD_LOCATION=global is required; a regional endpoint like us-central1 returns a 404 model-not-found.

Cost profile (Cloud Run + Vertex AI, us-central1/global, as of mid-2026)

Rough estimate, not measured from GCP's billing console — check Cloud Billing reports against actual traffic for ground truth, especially the Gemini token counts which are estimated from the prompt-building code, not GCP's tokenizer.

Fixed cost (min-instances=1 keeps one instance warm 24/7):

  • ~4 GiB × ~2.59M seconds/month × $0.0000025/GiB-s ≈ $25-26/month, memory only — Cloud Run doesn't bill CPU while an instance is idle (default "CPU allocated during request processing" mode, not "CPU always allocated").

Marginal cost per 1000 grounded searches (steady-state, ~1.15s/request, 2 vCPU / 4Gi):

Component Rate Per request Per 1000
Cloud Run CPU $0.000024/vCPU-s 2 × 1.15s ~$0.06
Cloud Run memory $0.0000025/GiB-s 4 × 1.15s ~$0.01
Cloud Run requests $0.40/1M — ~$0.0004
Gemini input (~2,020 tok) $0.25/1M tok ~$0.51
Gemini output (~110 tok) $1.50/1M tok ~$0.17
Total ~$0.74 / 1000 searches

GCP's free tier (180,000 vCPU-s, 360,000 GiB-s, 2M requests per month) covers roughly the first 78,000 grounded searches/month of Cloud Run compute, so at low-to-moderate volume the practical marginal cost is closer to just the Gemini portion ($0.68/1000), stacked on top of the ~$25/month idle baseline. GROUNDING_ENABLED=false search requests are essentially free at that volume (no Gemini call, DB + embed only).

Known limitations / things the next engineer should know

  • Postgres is a single external host, not managed by GCP (178.105.237.149 in deploy/db.env / deploy/cloudrun.env) — Cloud Run needs outbound access to it, and there's no HA/failover.
  • Grounding is a real per-request cost and latency hit (~0.85s with gemini-3.1-flash-lite, was ~11-16s with gemini-2.5-flash). It's what makes homonym disambiguation work. A local cross-encoder reranker was built and measured as a replacement and rejected: sdadas/polish-reranker-base-ranknet costs ~2.3s at pool 50 on 2 vCPU (~2.7x slower than Gemini), only partly honours exclusions like "nie związane ze szkołą", and smaller or INT8 variants were either wrong or unstable.
  • No auth on the API — --allow-unauthenticated, CORS is *. Fine for an internal tool; revisit before exposing this beyond the current product surface.
  • See API.md for the actual request/response contract.