homelab-codex-ws/services/kb-postgres
oskar 569f95005d feat(kb): faza 3 krok 2 — migracja 004 (document_summary) + pilot streszczeń A/B
Migracja 004: document_summary (envelope_id, summary, tags JSONB, model, embedding
VECTOR(1024) + HNSW cosine, embedding_model, UNIQUE(envelope_id, model) od razu — wzorzec
002/003). Zastosowana na żywej bazie kb-postgres@PIHA.

Job documents-ingest-summarize: wejście = document_chunk.text WHERE excluded_reason IS NULL
per koperta source='paperless' (duplikaty przez entities[duplicate_of] pomijane w całości),
wymuszony JSON {summary, tags} przez --backend ollama|anthropic, słownik tagów kontrolowany
(tags-vocab.yaml) z max 3 free-form, map-reduce dla dokumentów >200k znaków (grupy ~20
chunków), bilans + idempotencja + izolacja błędów per wiersz wg wzorców rodziny jobów.
Osobny --embed-summaries (bge-m3, reużywa chunk_embed.embed_chunk).

Bug znaleziony i naprawiony w trakcie pilota: brak options.num_ctx w wywołaniach Ollamy
powodował, że gemma3:12b używał domyślnego runtime kontekstu (~2048 tok), nie
zadeklarowanego 128k — dla 71/157 dokumentów (45%, >8k znaków) treść była cicho ucinana
(zweryfikowane: prompt_eval_count=2051 dla dokumentu 93k znaków). Naprawa: compute_num_ctx()
liczy num_ctx z długości promptu (~3 znaki/token, cap 131072). Cały tor lokalny przeliczony
od zera po naprawie.

Wynik pilota (186 dok. paperless, 3 duplikaty, 26 bez aktywnych chunków → 157 oczekiwanych
na tor): tor lokalny (gemma3:12b) 155/157 (2 izolowane błędy JSON po retry: paperless:24,
paperless:61), tor referencyjny (claude-haiku-4-5) 157/157, 0 błędów JSON, 0 tagów
ucinanych — słownik przestrzegany w 100% przypadków. Oba komplety zembedowane (bge-m3).
Znaleziony przy okazji: prompt do tagów wymagał dopracowania — pierwsza wersja pozwalała
modelowi zwracać tagi po angielsku spoza słownika; wzmocniona instrukcja (słownik w
pierwszej kolejności, "nigdy po angielsku") poprawiła zgodność w 2/3 przypadków testowych.

Porównanie A/B (~15 dok.) i weryfikacja końcowa (bilans, sanity SQL, retrieval po summary)
odłożone do następnej sesji.

Testy: 157 (152 nowe/summarize.py + istniejące), mocki API/Ollama/DB, bilans, idempotencja,
regresja num_ctx.

Co najmniej 3 decyzje wymagały zatrzymania i potwierdzenia z Oskarem w sesji (sposób podania
klucza API, wybór modelu lokalnego gemma3:12b, naprawa+przeliczenie całego toru lokalnego po
odkryciu buga num_ctx) — udokumentowane w transkrypcie sesji.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-17 13:30:47 +02:00
..
init feat(kb): faza 3 krok 2 — migracja 004 (document_summary) + pilot streszczeń A/B 2026-07-17 13:30:47 +02:00
docker-compose.yml feat(kb-mail): fundament — pgvector spine, koperta, archiwum, pakiet domeny 2026-06-19 20:02:25 +02:00
env.example feat(kb-mail): fundament — pgvector spine, koperta, archiwum, pakiet domeny 2026-06-19 20:02:25 +02:00
healthcheck.sh feat(kb-mail): fundament — pgvector spine, koperta, archiwum, pakiet domeny 2026-06-19 20:02:25 +02:00
README.md refactor(kb-postgres): relokacja SOLARIA→PIHA — arm64, mem_limit 1g, tuning pod małą maszynę 2026-06-22 19:59:58 +02:00
service.yaml refactor(kb-postgres): relokacja SOLARIA→PIHA — arm64, mem_limit 1g, tuning pod małą maszynę 2026-06-22 19:59:58 +02:00

kb-postgres

Postgres 16 + pgvector — KB spine on PIHA (Raspberry Pi 5, always-on). Stores the frozen envelope schema shared by all KB pillars (mails, documents, photos, transactions).

Runs here because the KB store must answer queries 24/7; SOLARIA (GPU/compute) is powered down intermittently. Embeddings/models still run on SOLARIA's GPU — only the Postgres+pgvector store lives on PIHA. The pgvector/pgvector:pg16 image is multi-arch and runs natively on arm64 (the Pi 5).

Port: 5433 on PIHA (Tailscale-accessible to other nodes).

Standard deploy (from SATURN)

# On SATURN — pushes to master, then deploy.sh SSHes to PIHA and runs deploy-node.sh
git push origin master
scripts/deploy/deploy.sh piha

deploy-node.sh on PIHA automatically picks up the per-host override:

docker compose \
  -f services/kb-postgres/docker-compose.yml \
  -f hosts/piha/runtime/kb-postgres/docker-compose.override.yml \
  up -d --remove-orphans

The PIHA override caps memory (mem_limit: 1g) and tunes Postgres for a tight, HA-shared RAM budget. Data lives in the kb_postgres_data named volume, which must land on the NVMe (Docker data-root on /home), never the SD card — verify before first deploy (see the override file's DATA PLACEMENT note):

# On PIHA
docker info -f '{{.DockerRootDir}}'                       # expect an NVMe path
df -h "$(docker info -f '{{.DockerRootDir}}')"            # confirm it's the NVMe

First-time setup on PIHA (before first deploy)

The .env file must exist at services/kb-postgres/.env in the PIHA repo checkout (alongside the compose file — that's where env_file: .env resolves to):

# On PIHA
cd ~/homelab-codex-ws
cp services/kb-postgres/env.example services/kb-postgres/.env
# Edit .env: set POSTGRES_PASSWORD to something strong

.env is gitignored (*.env rule in root .gitignore) — it will never be committed.

Manual one-off (debugging / first boot)

# On PIHA, from repo root
docker compose \
  -f services/kb-postgres/docker-compose.yml \
  -f hosts/piha/runtime/kb-postgres/docker-compose.override.yml \
  up -d

Verify after first boot

# Host-side healthcheck
./services/kb-postgres/healthcheck.sh

# Inside the container
docker exec kb-postgres psql -U kb -d kb -c '\d envelope'
docker exec kb-postgres psql -U kb -d kb \
  -c "SELECT extname FROM pg_extension WHERE extname = 'vector';"

Expected \d envelope output:

                    Table "public.envelope"
  Column  |           Type           | Nullable |  Default
----------+--------------------------+----------+-----------
 id       | text                     | not null |
 source   | text                     | not null |
 ts       | timestamp with time zone | not null |
 geo      | jsonb                    |          |
 raw_ref  | text                     | not null |
 entities | jsonb                    | not null | '[]'::jsonb
Indexes:
    "envelope_pkey" PRIMARY KEY, btree (id)
    "envelope_source_idx" btree (source)
    "envelope_ts_idx" btree (ts)

Schema contract

The envelope table is the frozen cross-source envelope (see docs/kb/kb-00-overview.md §Zasady przekrojowe). Adding columns is OK; removing or renaming existing ones is NOT.

Future migrations go in init/ as 002_*.sql, 003_*.sql, …. Postgres runs initdb scripts only on a fresh volume — for existing instances apply migrations with psql directly.

Connection string

postgresql://kb:<POSTGRES_PASSWORD>@piha:5433/kb

Set KB_TEST_DSN to this value when running integration tests from packages/kb-mail/ (host = piha over Tailscale).