Skip to content

feat(search): add hybrid FTS + pgvector job matching with OpenRouter embeddings - #112

Open
hugoalves-dev wants to merge 4 commits into
mainfrom
hugo/intelligent-volta-t10sqs
Open

hugoalves-dev wants to merge 4 commits into
mainfrom
hugo/intelligent-volta-t10sqs

Conversation

@hugoalves-dev

@hugoalves-dev hugoalves-dev commented Nov 23, 2026 •

Copy link
Copy Markdown
Owner

Closes #111

The blocker, #107 (the PostgreSQL migration), is already on main.

What it does

  • Flyway V38: adds CREATE EXTENSION vector and a new semantic_embeddings table. The vector column is vector(1024). Each row has a real foreign key with ON DELETE CASCADE to its application or profile document and to its user. It also stores the embedded text, its SHA-256, the model, the dimensions, a status (PENDING/READY/FAILED/EMPTY/SOURCE_ERROR), the number of attempts and timestamps. All access goes through JDBC, so Hibernate never sees the vector type and ddl-auto: validate and the H2 test schema stay unchanged.
  • OpenRouter embeddings client: a direct RestClient call to POST /embeddings with batching and timeouts. It sends dimensions: 1024. If the provider ignores that field, the client keeps the first 1024 values and re-normalises. That is only valid for Matryoshka-trained models such as Qwen3-Embedding, and it can be turned off in config.
  • Sync (EmbeddingSyncService, every minute): one polling loop handles backfill, change detection, model switches and retries:
    • Change detection uses a hash of the embedded text, so a status-only edit does not trigger a new embedding.
    • Due rows are leased with FOR UPDATE SKIP LOCKED, so several instances never embed the same row twice.
    • Failed rows retry with exponential backoff.
    • No transaction stays open during HTTP calls.
    • A result is stored only if the row still holds the content and model it was computed for.
    • Recruiter names are never sent to the provider.
  • Hybrid searchApplications: full-text search and per-user cosine search each fetch up to 50 candidates with the same user and filters. The two lists are combined with Reciprocal Rank Fusion. Each result has a matchedBy field (KEYWORD, SEMANTIC or KEYWORD_AND_SEMANTIC).
  • Fallbacks: search uses full-text only when the feature is disabled, the provider fails (a 60s cooldown follows), the vector query fails, or the column dimensions don't match the config. Short tokens (Go, C#) and filter-only queries stay on the existing path. Aggregates still come from plain SQL.
  • New tool matchApplicationsToProfile: ranks applications against the user's own Drive profile documents. It checks requiredTerms (stack, seniority, location, work modality, salary wording) literally against the vacancy text, ignoring case and accents and respecting word boundaries, so Java does not match JavaScript. It returns evidence snippets and ranks only, never distances or percentages. The system prompt now tells the model not to turn similarity into a fit score and not to invent qualifications.
  • Metrics:
    • semantic.embeddings.{latency, tokens, cost.usd, inputs, failures}
    • gauges for coverage, backlog, exhausted and source_errors
    • assistant.search.latency{mode}

Decisions worth reviewing

  • No HNSW index, on purpose. Every vector query is scoped to one user. An ANN index would rank across all tenants first and filter by user afterwards, which silently drops valid neighbours for small tenants. Instead, a MATERIALIZED CTE scans one user's rows exactly, using the (user_id, source_type, status) index. At 1024 dimensions an HNSW index can still be added later; docs/semantic-search.md explains when it would be worth it.
  • Polling instead of events from the write path. Nothing can be lost, the code is not coupled to ApplicationService or Drive, and backfill and retries reuse the same code. The cost is up to about one minute of delay before new content becomes searchable by meaning, while keyword search covers it immediately.
  • Hard constraints are checked as text. The schema has no structured salary, location or modality fields. Adding them would be a separate issue.
  • Switching models is safe. Vectors from a different model are never compared. Rows re-embed in the background, and keyword search covers the gap. A change in dimensions needs a new migration; until then the app disables semantic search and logs SEMANTIC_SEARCH_DISABLED.

MariaDB → PostgreSQL migrator

scripts/migrate_mariadb_to_postgresql.py pins the Flyway version and requires identical table sets on both sides. It now targets V38 and treats semantic_embeddings as PostgreSQL-only derived data: it is not compared or copied, it must be empty in the target, and the app's backfill rebuilds it after the cutover. The README cutover steps now say V1-V38, and a new unit test covers the exclusion.

⚠️ Before deploying

  • Production Postgres needs pgvector (for example the pgvector/pgvector:pg17 image). V38 creates the extension unconditionally, so the app will not start without it. docker-compose.yml, the load-test workflow and Testcontainers have been switched to that image.
  • Confirm on OpenRouter that qwen/qwen3-embedding-8b is available, what it costs, and whether it supports dimensions. I couldn't reach OpenRouter from the build environment.
  • APP_SEMANTIC_SEARCH_MAX_COSINE_DISTANCE=0.65 is an initial value that hasn't been calibrated on real data.

Bugs found while testing

  1. Fixed here: the existing keyword search cast ts_rank (PostgreSQL real, which the driver returns as java.lang.Float) to Double. As a result, every ranked Ask ApplyWell keyword search threw a ClassCastException on PostgreSQL. The existing ITs missed it because they build the schema with ddl-auto, so the full-text search column never exists in them.
  2. Fixed on main since this PR opened: on a fresh PostgreSQL database, main did not boot because the assistant quota tables from feat(assistant): add per-user daily quota and anti-flood limits #110 had no PostgreSQL migration. fb0d05f added them as V37__add_assistant_quota.sql. That collided with this PR's V37, which broke CI, so I merged main in and renumbered this PR's migration to V38.

Tests

  • Unit tests: RRF fusion, requirement checks, hybrid search and every fallback path, profile matching, the sync service (idempotency, change and model detection, empty content, backoff, per-run budget, Drive errors), the OpenRouter client (MockRestServiceServer) and provider cooldown.
  • SemanticSearchPostgresIT: runs the real Flyway chain on pgvector (Testcontainers in CI). It covers tenant isolation, model and space filtering, the distance cutoff, structured filters, keyword vs semantic results, missing embeddings, profile matching, the sync lifecycle (backfill, idempotency, re-embedding on content or model change), retries and leases, exhausted rows and cascade deletes.
  • Run locally after merging main, against PostgreSQL 16 + pgvector 0.6 (no Docker here): 312 tests in 56 classes pass, covering all unit tests, SemanticSearchPostgresIT and JobTrackerApplicationTests. Flyway applies V37 (quota) and then V38 (embeddings). Migrator tests: 7/7.
  • Smoke-tested the built jar with the prod profile against a fresh database and a stub embeddings server. The scheduler embedded a seeded application, it recovered from a failure through retry, the 4096→1024 truncation worked, and the metrics showed up in /actuator/prometheus. That boot ran before main's quota fix, so it used ddl-auto=none.
  • Not run locally: the Docker-based ITs. CI runs them.

Docs: docs/semantic-search.md

🤖 Generated with Claude Code

https://claude.ai/code/session_01GfjfbRwirbsTBATemyhmxy

…embeddings

- Flyway V37: pgvector extension and semantic_embeddings (vector(1024), FKs with
  cascade, content hash, model/dimensions, status, attempts, timestamps)
- OpenRouter /embeddings client with batching, Matryoshka truncation, timeouts,
  token/cost/latency metrics
- Polling sync: backfill, hash-based change detection, model switches, retries
  with backoff and SKIP LOCKED leases; no transaction held across HTTP calls
- Hybrid searchApplications: FTS + per-user exact cosine search fused with RRF,
  matchedBy label, FTS-only fallback with provider cooldown
- matchApplicationsToProfile tool: ranks against the user's profile documents
  and checks must-have terms explicitly with evidence; no similarity scores
- Fix ts_rank Float->Double ClassCastException in existing FTS search
- pgvector image for docker-compose, load test and Testcontainers

Closes #111

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GfjfbRwirbsTBATemyhmxy
@github-actions

Copy link
Copy Markdown

Qodana for JVM

5 new problems were found

Inspection name Severity Problems
Constant values 🔶 Warning 3
Non-atomic operation on 'volatile' field 🔶 Warning 2
View the detailed Qodana report

To be able to view the detailed Qodana report, you can either:

To get *.log files or any other Qodana artifacts, run the action with upload-result option set to true,
so that the action will upload the files as the job artifacts:

      - name: 'Qodana Scan'
        uses: JetBrains/qodana-action@v2025.3.2
        with:
          upload-result: true
Contact Qodana team

Contact us at qodana-support@jetbrains.com

…'s V37

main added V37__add_assistant_quota.sql, which collided with this branch's
V37 ("Found more than one migration with version 37" in SemanticSearchPostgresIT).

The MariaDB-to-PostgreSQL migrator pins the Flyway version and requires
identical table sets, so it now targets V38 and treats semantic_embeddings as
PostgreSQL-only derived data: not compared or copied, required to be empty,
rebuilt by the application's backfill after cutover.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GfjfbRwirbsTBATemyhmxy
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(search): add hybrid FTS + pgvector job matching with OpenRouter embeddings

2 participants