Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/load-test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ jobs:
-e POSTGRES_DB=jobtracker \
-e POSTGRES_USER=jobtracker \
-e POSTGRES_PASSWORD=jobtracker \
postgres:17
pgvector/pgvector:pg17

- name: Wait for PostgreSQL
run: |
Expand Down
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -62,3 +62,6 @@ Thumbs.db
.aiox/install-log.txt

.aiox-core

__pycache__/
*.pyc
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -868,12 +868,12 @@ of applications with at least one completed interview, rather than interviews di

## PostgreSQL migration and rollback

The PostgreSQL backend uses native UUID columns, PostgreSQL Flyway migrations V1-V37 and a generated full-text index. **Flyway migrates the schema, not the existing MariaDB records.** For a one-time data cutover, use [scripts/migrate_mariadb_to_postgresql.py](scripts/migrate_mariadb_to_postgresql.py). It uses PyMySQL + psycopg 3 (streaming PostgreSQL COPY), without pgloader.
The PostgreSQL backend uses native UUID columns, PostgreSQL Flyway migrations V1-V38 and a generated full-text index. **Flyway migrates the schema, not the existing MariaDB records.** For a one-time data cutover, use [scripts/migrate_mariadb_to_postgresql.py](scripts/migrate_mariadb_to_postgresql.py). It uses PyMySQL + psycopg 3 (streaming PostgreSQL COPY), without pgloader.

### Prerequisites

1. Verify the MariaDB backup can be restored, and restore it into an **isolated, read-only MariaDB source**. The Python tool connects to a running MariaDB instance; it does **not** parse a .sql/.gz dump directly.
2. Provision a **new, dedicated, empty PostgreSQL database**. Start the new backend **once** with this database to let Flyway apply V1-V37, then **stop it**. Disable app seeding/scheduled jobs while preparing the target. Only the Flyway seeds (nine `application_statuses` rows and the `assistant-global` row in `assistant_quota_locks`) are allowed before import.
2. Provision a **new, dedicated, empty PostgreSQL database**. Start the new backend **once** with this database to let Flyway apply V1-V38, then **stop it**. Disable app seeding/scheduled jobs while preparing the target. Only the Flyway seeds (nine `application_statuses` rows and the `assistant-global` row in `assistant_quota_locks`) are allowed before import.
3. Keep the application stopped so nothing writes to PostgreSQL during the copy. Confirm the MariaDB backup and database version represent the latest application data. Maintain the old MariaDB backup and old backend image for rollback.
4. Use least-privilege credentials: read-only MariaDB user and a PostgreSQL user allowed to COPY/DELETE and reset the identity sequence. Do not commit credentials to the repository.

Expand Down Expand Up @@ -911,7 +911,7 @@ The tool validates exact source/target table and writable-column sets, refuses u

### Cutover / rollback

1. For the final cutover, stop writes to the old MariaDB and restore a **final** consistent backup into the isolated MariaDB source. Recreate an empty PostgreSQL target and allow Flyway V1-V37 to initialize it before running the Python migrator.
1. For the final cutover, stop writes to the old MariaDB and restore a **final** consistent backup into the isolated MariaDB source. Recreate an empty PostgreSQL target and allow Flyway V1-V38 to initialize it before running the Python migrator.
2. Confirm counts, UUID samples, referential integrity, login, Google Drive, OAuth, MCP, assistant search and export using the new backend and migrated data.
3. Switch traffic to the PostgreSQL-backed new backend only after validation; do not run both backends writing in parallel.
4. For rollback, **stop the new backend, restore the old MariaDB-compatible backend image and its DB_URL**, and reconcile any writes accepted after cutover. Repointing the new PostgreSQL-only application at MariaDB is not supported. Keep MariaDB and the backups until acceptance.
Expand Down
2 changes: 1 addition & 1 deletion docker-compose.yml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
services:
postgres:
image: postgres:17
image: pgvector/pgvector:pg17
environment:
POSTGRES_DB: ${DB_NAME:-jobtracker}
POSTGRES_USER: ${DB_USERNAME:-jobtracker}
Expand Down
4 changes: 4 additions & 0 deletions docs/ask-applywell-backend.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@ enforced before the provider is called. Rejections return HTTP 429 before the st
`GET /api/v1/assistant/usage` returns the caller's daily usage. See
[assistant-quota.md](assistant-quota.md).

Search can combine full-text and pgvector similarity, and `matchApplicationsToProfile` ranks
applications against the user's profile documents. Both are opt-in; see
[semantic-search.md](semantic-search.md).

Enable with `APP_ASSISTANT_ENABLED=true`, set `OPENAI_API_KEY`, and optionally set
`OPENAI_CHAT_MODEL`. The feature is disabled by default. Every tool is read-only and binds
the user ID captured from the authenticated request; the model never receives a user ID.
Expand Down
85 changes: 85 additions & 0 deletions docs/semantic-search.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
# Ask ApplyWell: hybrid FTS + pgvector search

Ask ApplyWell's `searchApplications` tool combines PostgreSQL full-text search with vector similarity
from OpenRouter embeddings, and a new `matchApplicationsToProfile` tool ranks applications against the
user's own profile documents (Drive "base information"). Everything is off by default and FTS keeps
working unchanged when it is off or when the embeddings provider is down.

## Enabling it

1. The database server needs the [pgvector](https://github.com/pgvector/pgvector) extension.
`docker-compose.yml` uses `pgvector/pgvector:pg17`; a production server on the stock `postgres`
image must switch to it (or install `postgresql-17-pgvector`) **before** deploying, because Flyway
`V38` runs `CREATE EXTENSION IF NOT EXISTS vector` and the app will not start without it. If the
application's DB user is not a superuser (the Docker image's `POSTGRES_USER` is), have a superuser run
`CREATE EXTENSION vector;` in the database first.
2. Set `APP_SEMANTIC_SEARCH_ENABLED=true` and `OPENROUTER_API_KEY` (the same key the OpenRouter chat
provider uses). The chat model and embedding model are independent.

| Variable | Default | Meaning |
| --- | --- | --- |
| `APP_SEMANTIC_SEARCH_ENABLED` | `false` | Master switch. |
| `APP_SEMANTIC_SEARCH_MODEL` | `qwen/qwen3-embedding-8b` | OpenRouter embedding model. |
| `APP_SEMANTIC_SEARCH_DIMENSIONS` | `1024` | Must equal the `vector(N)` column. Sent as `dimensions`. |
| `APP_SEMANTIC_SEARCH_TRUNCATE_TO_DIMENSIONS` | `true` | If the provider ignores `dimensions`, keep the first N and re-normalise. Only valid for Matryoshka models (Qwen3-Embedding is). |
| `APP_SEMANTIC_SEARCH_MAX_EMBEDDINGS_PER_RUN` | `64` | Cost guard: documents embedded per scheduler run. |
| `APP_SEMANTIC_SEARCH_SCHEDULER_INTERVAL_MS` | `60000` | Sync/backfill cadence. |
| `APP_SEMANTIC_SEARCH_MAX_INPUT_CHARS` / `_MAX_QUERY_CHARS` | `8000` / `500` | Request size caps. |
| `APP_SEMANTIC_SEARCH_MAX_ATTEMPTS` | `5` | Retries per content version, exponential backoff from `RETRY_BASE_DELAY` (`1m`), capped at 6h. |
| `APP_SEMANTIC_SEARCH_PROFILE_REFRESH_INTERVAL` | `24h` | How often Drive profile documents are re-read to detect changes. |
| `APP_SEMANTIC_SEARCH_MAX_COSINE_DISTANCE` | `0.65` | Vector-only hits further than this are dropped. Model-specific: retune when switching models. |
| `APP_SEMANTIC_SEARCH_CANDIDATE_LIMIT` / `_RRF_K` | `50` / `60` | Candidates per list and the RRF constant. |
| `APP_SEMANTIC_SEARCH_PROVIDER_COOLDOWN` | `60s` | After a failed query embedding, interactive search skips the provider (FTS only) for this long. |

## How it works

- **Storage** (`semantic_embeddings`, Flyway `V38`): one row per application or profile document, with
real foreign keys (`ON DELETE CASCADE`), `user_id`, the exact embedded text, its SHA-256, model,
dimensions, status (`PENDING`, `READY`, `FAILED`, `EMPTY`, `SOURCE_ERROR`), attempts and timestamps.
Accessed through JDBC only; Hibernate never sees the `vector` type.
- **Sync** (`EmbeddingSyncService`, every minute): one polling loop does backfill (sources without a row),
change detection (hash of the embedded text, so status-only edits cost nothing), model switches and
retries. Due rows are leased with `FOR UPDATE SKIP LOCKED`, so several instances never embed the same
row twice, and no transaction is held open across HTTP calls. A result is stored only if the row still
holds the content and model it was computed for.
- **Embedded text**: vacancy name, organization and notes for applications; extracted text for profile
documents. Recruiter names and other personal fields are not sent to the provider.
- **Search**: FTS (`websearch_to_tsquery`) and cosine similarity each return up to 50 candidates under the
**same** user and structured filters, fused with Reciprocal Rank Fusion. Results carry `matchedBy`
(`KEYWORD`, `SEMANTIC`, `KEYWORD_AND_SEMANTIC`). Short tokens (`Go`, `C#`, `AI`) and filter-only queries
keep the old literal path. Counts/aggregates (`getApplicationStats`) remain pure SQL.
- **Profile matching**: applications are ordered by distance to the closest profile document;
`requiredTerms` (stack, seniority, location, modality, salary wording) are checked literally against the
vacancy text with evidence snippets. The tool returns ranks and evidence, never distances or percentages.
- **No ANN index, on purpose**: every vector query is scoped to one user and scanned exactly
(`MATERIALIZED` CTE over the `(user_id, source_type, status)` index). HNSW/IVFFlat would rank across all
tenants and filter afterwards, silently dropping valid neighbours. Revisit (pgvector ≥ 0.8
`hnsw.iterative_scan`) only if a single user reaches tens of thousands of vectors.

## Switching models

- Same dimensions: change `APP_SEMANTIC_SEARCH_MODEL`. Rows from the old model are excluded from queries
immediately (vectors from different models are never compared) and re-embedded in the background.
Coverage drops to 0 and recovers; FTS covers the gap.
- Different dimensions: add a Flyway migration that alters `semantic_embeddings.embedding` to
`vector(N)` (and sets `embedding = NULL`), then change `APP_SEMANTIC_SEARCH_DIMENSIONS`. If config and
column disagree, semantic search disables itself and logs `SEMANTIC_SEARCH_DISABLED`.

## Metrics

| Metric | Meaning |
| --- | --- |
| `semantic.embeddings.latency{purpose,model,outcome}` | Provider call latency (document batches and queries). |
| `semantic.embeddings.tokens{purpose}` / `semantic.embeddings.cost.usd{purpose}` | Usage reported by OpenRouter. |
| `semantic.embeddings.inputs{purpose}` | Texts embedded. |
| `semantic.embeddings.failures{stage}` | `provider`, `source_read` (Drive) or `stale_result`. |
| `semantic.embeddings.coverage` | READY / non-empty applications for the active model. |
| `semantic.embeddings.backlog`, `.exhausted`, `.source_errors` | Queue health. Exhausted rows retry only when their content changes. |
| `assistant.search.latency{mode}` | `hybrid` or `fts_fallback` search latency. |

## Known limits

- The schema has no structured salary, location, seniority or modality fields, so those constraints are
checked as explicit text evidence in the vacancy name/notes, not as typed comparisons.
- `APP_SEMANTIC_SEARCH_MAX_COSINE_DISTANCE` was not calibrated against real data; tune it after enabling.
- Model availability, pricing and `dimensions` support on OpenRouter must be confirmed at deploy time.
16 changes: 14 additions & 2 deletions scripts/migrate_mariadb_to_postgresql.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
#!/usr/bin/env python3
"""One-time ApplyWell MariaDB -> PostgreSQL data cutover.

The PostgreSQL schema must already have been created by Flyway V1-V37.
The PostgreSQL schema must already have been created by Flyway V1-V38.
The MariaDB source should be restored from a verified backup and kept immutable.
"""

Expand All @@ -22,6 +22,9 @@
# without a running MariaDB or PostgreSQL instance.

EXCLUDED = {"flyway_schema_history"}
# PostgreSQL-only derived data (pgvector embeddings, V38). Not copied or compared; it must be empty
# in the target and is rebuilt by the application's background backfill after the cutover.
POSTGRES_ONLY = {"semantic_embeddings"}
SEED_STATUSES = (
(1, "RH", 1),
(2, "Pending HR Response", 2),
Expand All @@ -35,7 +38,7 @@
)
# Flyway-seeded rows that are replaced by the source data during import.
SEED_QUOTA_LOCKS = (("assistant-global",),)
TARGET_FLYWAY_VERSION = "37"
TARGET_FLYWAY_VERSION = "38"
NAME = re.compile(r"[a-z][a-z0-9_]*\Z")


Expand Down Expand Up @@ -171,6 +174,8 @@ def target_schema(conn: object) -> tuple[set[str], dict[str, list[Column]]]:
columns.setdefault(table, [])
if generated != "ALWAYS":
columns[table].append(Column(name, pg_type))
for table in POSTGRES_ONLY:
columns.pop(table, None)
return set(columns) - EXCLUDED, columns


Expand Down Expand Up @@ -218,6 +223,13 @@ def inspect_target(conn: object, tables: set[str], sql: object) -> None:
raise ValueError("Target assistant_quota_locks differs from Flyway V37 seed; refusing overwrite")
elif count:
raise ValueError(f"Target {table} already contains {count} records; refusing to overwrite")
for table in sorted(POSTGRES_ONLY):
count_query = sql.SQL("SELECT COUNT(*) FROM public.{}").format(sql.Identifier(table))
with conn.cursor() as cursor:
cursor.execute(count_query)
count = cursor.fetchone()[0]
if count:
raise ValueError(f"Target {table} already contains {count} records; refusing to overwrite")


def fix_sequences(conn: object, tables: list[str], sql: object) -> None:
Expand Down
91 changes: 91 additions & 0 deletions src/main/java/com/jobtracker/config/SemanticSearchProperties.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
package com.jobtracker.config;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.time.Duration;

/**
* Hybrid FTS + pgvector retrieval. Embeddings come from OpenRouter's OpenAI-compatible
* embeddings endpoint and are independent of the assistant chat provider.
*/
@Component
@ConfigurationProperties(prefix = "app.semantic-search")
public class SemanticSearchProperties {
private boolean enabled;
private String baseUrl = "https://openrouter.ai/api/v1";
private String apiKey;
private String model = "qwen/qwen3-embedding-8b";
/** Must match the vector(N) column created by Flyway. */
private int dimensions = 1024;
/**
* When the provider returns more dimensions than requested, keep the first {@code dimensions} and
* re-normalise. Only valid for Matryoshka-trained models (Qwen3-Embedding is); otherwise the
* response is rejected.
*/
private boolean truncateToDimensions = true;
private Duration requestTimeout = Duration.ofSeconds(10);
private int batchSize = 16;
private int maxEmbeddingsPerRun = 64;
private int maxSourcesScannedPerRun = 500;
private int maxInputChars = 8000;
private int maxQueryChars = 500;
private int maxAttempts = 5;
private Duration retryBaseDelay = Duration.ofMinutes(1);
private Duration claimLease = Duration.ofMinutes(5);
private long schedulerIntervalMs = 60_000;
private Duration profileRefreshInterval = Duration.ofHours(24);
private int candidateLimit = 50;
private int rrfK = 60;
/** Cosine distance above which a vector-only hit is treated as unrelated. Model-specific; tune per model. */
private double maxCosineDistance = 0.65;
/** After a provider failure, interactive searches skip the provider for this long and use FTS only. */
private Duration providerCooldown = Duration.ofSeconds(60);

public boolean isEnabled() { return enabled; }
public void setEnabled(boolean enabled) { this.enabled = enabled; }
public String getBaseUrl() { return baseUrl; }
public void setBaseUrl(String baseUrl) { this.baseUrl = baseUrl; }
public String getApiKey() { return apiKey; }
public void setApiKey(String apiKey) { this.apiKey = apiKey; }
public String getModel() { return model; }
public void setModel(String model) { this.model = model; }
public int getDimensions() { return dimensions; }
public void setDimensions(int dimensions) { this.dimensions = dimensions; }
public boolean isTruncateToDimensions() { return truncateToDimensions; }
public void setTruncateToDimensions(boolean value) { this.truncateToDimensions = value; }
public Duration getRequestTimeout() { return requestTimeout; }
public void setRequestTimeout(Duration requestTimeout) { this.requestTimeout = requestTimeout; }
public int getBatchSize() { return batchSize; }
public void setBatchSize(int batchSize) { this.batchSize = batchSize; }
public int getMaxEmbeddingsPerRun() { return maxEmbeddingsPerRun; }
public void setMaxEmbeddingsPerRun(int value) { this.maxEmbeddingsPerRun = value; }
public int getMaxSourcesScannedPerRun() { return maxSourcesScannedPerRun; }
public void setMaxSourcesScannedPerRun(int value) { this.maxSourcesScannedPerRun = value; }
public int getMaxInputChars() { return maxInputChars; }
public void setMaxInputChars(int maxInputChars) { this.maxInputChars = maxInputChars; }
public int getMaxQueryChars() { return maxQueryChars; }
public void setMaxQueryChars(int maxQueryChars) { this.maxQueryChars = maxQueryChars; }
public int getMaxAttempts() { return maxAttempts; }
public void setMaxAttempts(int maxAttempts) { this.maxAttempts = maxAttempts; }
public Duration getRetryBaseDelay() { return retryBaseDelay; }
public void setRetryBaseDelay(Duration retryBaseDelay) { this.retryBaseDelay = retryBaseDelay; }
public Duration getClaimLease() { return claimLease; }
public void setClaimLease(Duration claimLease) { this.claimLease = claimLease; }
public long getSchedulerIntervalMs() { return schedulerIntervalMs; }
public void setSchedulerIntervalMs(long value) { this.schedulerIntervalMs = value; }
public Duration getProfileRefreshInterval() { return profileRefreshInterval; }
public void setProfileRefreshInterval(Duration value) { this.profileRefreshInterval = value; }
public int getCandidateLimit() { return candidateLimit; }
public void setCandidateLimit(int candidateLimit) { this.candidateLimit = candidateLimit; }
public int getRrfK() { return rrfK; }
public void setRrfK(int rrfK) { this.rrfK = rrfK; }
public double getMaxCosineDistance() { return maxCosineDistance; }
public void setMaxCosineDistance(double value) { this.maxCosineDistance = value; }
public Duration getProviderCooldown() { return providerCooldown; }
public void setProviderCooldown(Duration providerCooldown) { this.providerCooldown = providerCooldown; }

public boolean isConfigured() {
return enabled && apiKey != null && !apiKey.isBlank() && model != null && !model.isBlank();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,11 @@
import java.time.LocalDateTime;
import java.util.UUID;

/**
* @param relevance full-text rank of a keyword match, when there is one. Ordering signal only.
* @param matchedBy which retrieval produced the hit: KEYWORD, SEMANTIC or KEYWORD_AND_SEMANTIC;
* null for non-search reads.
*/
public record AssistantApplicationView(
UUID id,
String vacancyName,
Expand All @@ -16,5 +21,19 @@ public record AssistantApplicationView(
LocalDateTime nextStepDateTime,
String noteExcerpt,
boolean archived,
Double relevance
) {}
Double relevance,
String matchedBy
) {
public AssistantApplicationView(UUID id, String vacancyName, String organization, String recruiterName,
String status, LocalDate applicationDate, String platform, int interviewCount,
LocalDateTime nextStepDateTime, String noteExcerpt, boolean archived,
Double relevance) {
this(id, vacancyName, organization, recruiterName, status, applicationDate, platform, interviewCount,
nextStepDateTime, noteExcerpt, archived, relevance, null);
}

public AssistantApplicationView withMatchedBy(String value) {
return new AssistantApplicationView(id, vacancyName, organization, recruiterName, status, applicationDate,
platform, interviewCount, nextStepDateTime, noteExcerpt, archived, relevance, value);
}
}
Loading
Loading