Skip to content
Merged
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
5 changes: 4 additions & 1 deletion .github/workflows/backend.yml
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,9 @@ jobs:
timeout-minutes: 20

steps:
# Only the app service is managed here. PostgreSQL holds production data and is
# upgraded by hand (pgvector image, backups); --no-deps keeps compose from pulling,
# recreating or starting it, and no --remove-orphans so it can't remove other containers.
- name: Deploy latest image over SSH
run: |
mkdir -p ~/.ssh
Expand All @@ -154,6 +157,6 @@ jobs:
-o ConnectTimeout=30 \
-o StrictHostKeyChecking=no \
"${{ secrets.VPS_USER }}@${{ secrets.VPS_IP }}" \
"set -eu && cd /docker/jobpplytracker-api && docker compose pull && docker compose up -d --remove-orphans && docker image prune -f" && break
"set -eu && cd /docker/jobpplytracker-api && docker compose pull app && docker compose up -d --no-deps app && docker image prune -f" && break
[ $i -lt 3 ] && sleep 15
done
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:0.8.7-pg18

- 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
14 changes: 11 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -303,6 +303,14 @@ Development (build locally):
docker-compose up -d
```

> **Upgrading from the PostgreSQL 17 dev setup:** the local database now runs PostgreSQL 18 with pgvector
> (`pgvector/pgvector:0.8.7-pg18`, same major as production). A major version can't open the old data
> directory, so compose uses a new volume, `postgres18_data`, and starts with an empty database (Flyway
> recreates the schema). The old `postgres_data` volume is left untouched. To keep its data, dump it with
> PostgreSQL 17 before switching (`docker compose exec postgres pg_dump -U jobtracker jobtracker > dump.sql`
> on the old setup), then restore it into the new container with `psql`. Once you no longer need it,
> remove it with `docker volume rm <project>_postgres_data`.

Production (use pre-built image from GitHub Container Registry):

1. Log in to GHCR (requires a Personal Access Token with `read:packages`):
Expand Down Expand Up @@ -868,12 +876,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 +919,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
8 changes: 5 additions & 3 deletions docker-compose.yml
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
services:
postgres:
image: postgres:17
# Same major as production (postgres:18) plus pgvector.
image: pgvector/pgvector:0.8.7-pg18
environment:
POSTGRES_DB: ${DB_NAME:-jobtracker}
POSTGRES_USER: ${DB_USERNAME:-jobtracker}
POSTGRES_PASSWORD: ${DB_PASSWORD:-jobtracker}
ports:
- "5432:5432"
volumes:
- postgres_data:/var/lib/postgresql/data
# PostgreSQL 18 images keep data under /var/lib/postgresql/18/docker; the volume mounts the parent.
- postgres18_data:/var/lib/postgresql
healthcheck:
test: ["CMD-SHELL", "pg_isready -U ${DB_USERNAME:-jobtracker} -d ${DB_NAME:-jobtracker}"]
interval: 5s
Expand Down Expand Up @@ -55,4 +57,4 @@ services:
start_period: 60s

volumes:
postgres_data:
postgres18_data:
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
91 changes: 91 additions & 0 deletions docs/semantic-search.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
# 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 installed.
Flyway `V38` runs `CREATE EXTENSION IF NOT EXISTS vector`, which only registers an extension whose
binaries are already on the server; with the stock `postgres` image it fails and the app will not start.
Production runs `postgres:18`: switch it to `pgvector/pgvector:0.8.7-pg18-<debian>` **before** deploying,
matching the Debian release of the current image (`cat /etc/os-release` in the container) so glibc
collations, and therefore text indexes, don't change. It is built from the official `postgres:18`
image, so the existing volume is reused as is. Back up first. Do not `apt-get install` the package
inside a running container: it disappears when the container is recreated while the database still
references the extension. The CI deploy only manages the `app` service, so this step is manual.
`docker-compose.yml`, the load test and Testcontainers use `pgvector/pgvector:0.8.7-pg18`. 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 @@ -36,7 +39,7 @@
# Flyway-seeded rows that are replaced by the source data during import.
SEED_QUOTA_LOCKS = (("assistant-global",),)
SEED_ROLE_NAMES = {"USER", "BETA", "ADMIN"}
TARGET_FLYWAY_VERSION = "37"
TARGET_FLYWAY_VERSION = "38"
NAME = re.compile(r"[a-z][a-z0-9_]*\Z")


Expand Down Expand Up @@ -179,6 +182,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 @@ -233,6 +238,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
Loading
Loading