feat(ml): fuse two embedding models and protect the ML service with a token
This commit is contained in:
1 parent
bc00d6901f
commit
b24e5ff906
63 files changed
+2287
-276
No files matched your search
@@ -834,13 +834,13 @@ Store each search as a search_run with its company, original need, filters, rank
|
||||
Implemented: embeddings of needs and published cards, `Sem` in Fit, a structured "why in the selection" explanation, candidate projects, and checks of their GitHub repositories. The basis is the LincodexMatch study (DEV 30 needs, TEST 70, 2594 synthetic profiles); its numbers come from synthetic data and are not product measurements.
|
||||
|
||||
- Model. `ai-sage/Giga-Embeddings-instruct-480M-0826` (MIT) at revision `1763d603adac8057bd6482a708001b0ed2e0a903`, float32, 1024 dimensions, up to 1024 tokens a text. On TEST it is best on indirect matches (nDCG@10 indirect 0.571 against 0.409 for Qwen3-Embedding-0.6B) and meets the CPU targets with 4 threads (profile p95 352 ms, search over 100k 591 ms in the study). The recipe repeats the study: the need and each requirement are encoded with the prompt `Instruct: Given a query, retrieve relevant passages\nQuery: `, the card and its items without a prompt, mean pooling over the attention mask including the prompt tokens, L2 normalization. The remote code of the model repository is neither fetched nor executed: the same bidirectional Qwen3 is written in `ml/src/lincodex_ml/inference/giga.py`, and `make -C ml test-model` compares the vectors with the study's (difference < 1e-6).
|
||||
- ML service. `POST /v1/embeddings` of the `api/ml` contract (up to 32 texts of 8000 characters, a body up to 2 MiB, an optional model id `model`, a response with id, revision, dimension, and `prompt_version`). The service loads one model now; a request for another model gets 400 with the pointer `/model`. The weights are fetched once at image build time from the lock file `ml/model/giga-embeddings-480m.lock.json` with SHA-256 verification (safetensors, configs, and the tokenizer only); the service runs offline. Readiness turns ready only after the load and a warm-up encode; before that it answers 503 `service_unavailable`. Texts are encoded one request at a time in micro-batches of a fixed size (default 1), ordered by length with the request position as the tie-breaker, so the same texts on the same image and thread count give the same vectors.
|
||||
- ML service. `POST /v1/embeddings` of the `api/ml` contract (up to 32 texts of 8000 characters, a body up to 2 MiB, an optional model id `model`, a response with id, revision, dimension, and `prompt_version`). The service loads the models of the `ML_EMBEDDER` list (`giga`, `qwen3`; the first answers a request without `model`); a request for a model it did not load gets 400 with the pointer `/model`. Each model is pinned by a lock file (`ml/model/giga-embeddings-480m.lock.json`, `ml/model/qwen3-embedding-0.6b.lock.json`) with SHA-256 verification (safetensors, configs, and the tokenizer only); no remote code runs and the service works offline. The device is `ML_DEVICE` (`cpu` by default or `cuda`), the precision `ML_DTYPE` (`float32`; `float16` and `bfloat16` on CUDA only), and `ML_CUDA_MEMORY_LIMIT_MB` caps the allocator of the process on a shared GPU. A lack of device memory never stops the process: a load is retried with a growing pause (15 s, up to 5 min), a request answers 503 `service_unavailable`, and `/readyz` answers 503 for 30 seconds, after which the service serves again. Readiness turns ready only after every model is loaded and a warm-up encode has finished. Texts are encoded one request at a time in micro-batches of a fixed size (default 1), ordered by length with the request position as the tie-breaker, so the same texts on the same installation, device, precision, and thread count give the same vectors (on CUDA checked by a repeated encode). Every route except `/healthz` and `/readyz` requires `Authorization: Bearer <token>` (see [SECURITY.md](SECURITY.md#outbound-requests-and-ml)).
|
||||
- Fields that rank. Only what the anonymous card of the candidate shows before cohort generalization: the roles of `self_assessment` and `categories` (`backend (middle)`), the recognized stack codes, and the published projects with the public metadata of verified repositories. Private profile text (resume, experience `summary`, employers) does not enter ranking, as before for ML ("Go sends only allowed inputs"). The study shows that private experience improves quality (proposal 3 of the report); allowing its server-side use without showing it is an open owner decision and needs an explicit privacy policy decision.
|
||||
- Vectors. Table `semantic_vectors` (migration `00049`): the subject (`candidate` or `need`), the item key (`whole`, `roles`, `stack`, `project:<n>`, `required_skill:<n>`, `desired_skill:<n>`, `task:<n>`), the SHA-256 of the text with the rendering version `semantic-views-v1`, the model, revision, prompt version, dimension, and the vector as little-endian float32 (4 KiB for 1024 dimensions: exact and the same on every platform; int8 is deferred until size becomes a problem). Rows cascade with the account or the need. A candidate keeps exactly one set per model, a need the set of its latest requirements snapshot.
|
||||
- Pipeline. A profile save, a publication change, a new requirements snapshot, and a finished repository check schedule a due job (`semantic.candidate`, `semantic.need`) in the same transaction; no user request waits for ML. The handler takes an advisory lock of the subject, renders the current card or snapshot, compares the digests with the stored ones (unchanged texts cost no ML call), encodes the texts, and replaces the set. The job encodes the texts with every model of the policy `members`, passing its id; the first model stores every item, the others store `whole` only. The model of the response (id, revision, prompt version) must equal the policy model, otherwise the job is retried. Up to 20 attempts with backoff outlast an ML outage; the job of an unpublished candidate removes their vectors. A C2 revocation closes the card in another usecase and schedules no job: the vectors stay until the next candidate job or a backfill, but an invisible card never enters a search. The `semantic-backfill` command schedules jobs for every candidate with a profile and every need page by page, idempotent per run label and resumable by cursor.
|
||||
- Sem and Fit. The search never calls ML: it renders the need snapshot, reads the vectors with matching digests and the `whole` vectors of the visible candidates for every policy model, computes the fused score Σ w·(cos - mean)/std, and turns it into `Sem` with the isotonic calibration of the policy (P(relevant | score) on DEV, ECE 0.015-0.049 against 0.17-0.57 for the raw cosine) by integer interpolation. By default there is one model with weight 1, mean 0, and std 1, so the score is the cosine. Without vectors of the need or the candidate for any policy model, or without ML, `Sem` is the neutral 0.5 with `ml_unavailable` for that entry, as before. The candidate set, filters, visibility, quotas, and cohort rules do not change; BM25 is not mixed into the score (on TEST it cuts indirect from 0.571 to 0.250).
|
||||
- Policy. `domain.DemoProductPolicyV5()` is V4 with the semantic section `matching.semantics` (`members` - one Giga model with revision, prompt version, weight 1, mean 0, and std 1; 80 calibration points `score_bp`, explanation thresholds, limit, source) and Fit weights 0.4167 / 0.0833 / 0.5. With the PRD weight 0.10 Fit reaches nDCG@10 0.649 on TEST against 0.818 for the encoder alone, with 0.5 it reaches 0.838; Cov and Dom keep the PRD ratio 5:1. V4 stays the previous version (the PRD point). Publication: `make -C backend policy-publish ARGS='semantic --actor operator:<handle>'`.
|
||||
- Ensemble. The design is ready for S5-DE of the study: `Sem` = calibration(0.4·z(Giga) + 0.6·z(Qwen3-Embedding-0.6B)), nDCG@10 0.842 on TEST against 0.818 for Giga alone, p95 about 0.85 s at 8 threads on 12 cores. It is not enabled now. To enable it: (1) add a second configured model `Qwen/Qwen3-Embedding-0.6B` at revision `97b0c614be4d77ee51c0cef4e5f07c00f9eb65b3` to the ML service with a lock file, its prompt, and a prompt version (the service picks the model by the `model` field; loading several models is separate work); (2) raise `ML_TORCH_THREADS` to 8 and the container limits; (3) on DEV, compute the mean and std of each model's cosine and refit the isotonic calibration and, if needed, the thresholds on the fused score (the study standardized z over the corpus of each need, the product uses global mean and std from the policy, so the numbers need a recheck); (4) publish a new policy version with two `members` (Giga first, it also explains entries; weights add up to 1) and the new calibration; (5) run `semantic-backfill` for candidates and needs as soon as the version takes effect. Jobs compute vectors for the effective policy only, so until the backfill ends, entries without vectors of the second model get the neutral `Sem`; switch at a quiet time. The Giga vectors are not recomputed (same digests), and vectors of earlier models stay, so a rollback to the previous policy version needs no recompute.
|
||||
- Ensemble. S5-DE of the study is implemented: `Sem` = calibration(0.4·z(Giga) + 0.6·z(Qwen3-Embedding-0.6B)), `domain.DemoProductPolicyV6()` (V5 with the section `DemoSemanticEnsembleMatchingPolicy`, the same Fit weights). The second model is `Qwen/Qwen3-Embedding-0.6B` (Apache-2.0) at revision `97b0c614be4d77ee51c0cef4e5f07c00f9eb65b3`, a stock Qwen3 without remote code: the need is encoded with the model's prompt `Instruct: Given a web search query, retrieve relevant passages that answer the query\nQuery:` (joined without a separator), the card without a prompt, the tokenizer appends end-of-text, and the vector is the hidden state of the last token, L2-normalized (`prompt_version` `qwen3-card-last-v1`, `ml/src/lincodex_ml/inference/qwen3.py`, compared with the study's vectors by `make -C ml test-model`). The weights 0.4 / 0.6 are the step 5 choice of the study (5-fold CV over the DEV needs, w_giga = 0.4 in four folds of five). The mean and std were computed again on product views: the study's needs and profiles were rendered by the product view builder (`domain.NewNeedSemanticDocument` gives the study's text for all 100 needs; the card has the catalog roles with the declared grade, the card stack codes, and one published project per study experience entry) and encoded by the ML service on CUDA in float16. The mean is over all DEV pairs (Giga 0.2497, Qwen3 0.3636), the std is the pooled within-need deviation (0.0741 and 0.0731), so the fixed z reproduces the study's z over the corpus of each need: DEV nDCG@10 all / indirect 0.809 / 0.518 against 0.809 / 0.518 for the study's form and 0.738 / 0.403 for Giga alone on the same views. The calibration is the isotonic regression of P(consensus >= 2) on the fused score of the 3220 judged DEV pairs (994 positive), computed with the rounded mean and std of the policy; 56 points, 5-fold CV ECE by need 0.025. The explanation thresholds stay those of Giga (the first model, which alone provides item vectors). The provenance is in the policy `source` and in [DEPLOY.md](DEPLOY.md#semantic-matching). Without projects on the card the signal is weak (DEV nDCG@10 0.21 for the ensemble and 0.23 for Giga alone on cards with roles and stack only), so the gain of the ensemble depends on candidates publishing projects. Publication and backfill: `make -C backend policy-publish ARGS='semantic-ensemble --actor operator:<handle>'`, then `semantic-backfill` for candidates and needs. Jobs compute vectors for every model of the effective policy, so until the backfill ends, entries without Qwen3 vectors get the neutral `Sem`; switch at a quiet time. The Giga vectors are not recomputed (same digests), and V5 stays the previous version: the vectors of both models stay, so a rollback to Giga needs no recompute.
|
||||
- Explanation. For a need search every confirmed requirement (required and desired skill, task) is paired with the closest card item by cosine. Thresholds from DEV: P(pair relevant | best cosine of the requirement) 0.5 and 0.7, for skills 0.3673 / 0.4607 (`medium` / `high`), for tasks 0.2997 / 0.4192. The response carries `semantic_evidence` items: the kind and text of the requirement (the organization's own need text), the item kind (`project`, `stack`, `roles`), the project title only when the candidate published the `projects` field and the title did not change since the vectors were computed, `repository_verified`, and the band; ordered `high` first, then by cosine, then by requirement order; at most 6 (policy). The stack and roles explain only while the card shows them to this organization after cohort generalization. No model text enters the explanation. Showing a project title is recorded in the candidate's access history as the `projects` field. The precision of the explanations was not checked: the study's sample of 50 pairs remained unlabeled.
|
||||
|
||||
#### Candidate projects and GitHub repositories
|
||||
|
||||
+39
-8
@@ -89,7 +89,7 @@ The eight-minute step-by-step guide with links to the screens and the logins is
|
||||
### 5. FSP, ML, and data
|
||||
|
||||
- FSP: there is no integration in any mode. This build has no off or mock switch, no fixture provider, and no call to an external API. The profile is filled in manually, linking an FSP ID is optional and not available yet, and the path to a category goes through the questionnaire and the test. The project has no official access to FSP data and does not promise it; an FSP link through a fixture provider is planned (see [ARCHITECTURE.md](ARCHITECTURE.md#identity-fsp-and-privacy)).
|
||||
- ML: by default the core and demo stands do not start ML and do not call it; search uses the neutral semantic similarity 0.5 with the `ml_unavailable` flag. Semantic matching is enabled separately: the ML project with the Giga-Embeddings-instruct-480M model on CPU, `SEMANTIC_MATCHING_ENABLED`, the semantic policy, and a backfill (see [Semantic matching](#semantic-matching)). No GPU or external inference keys are needed or read.
|
||||
- ML: by default the core and demo stands do not start ML and do not call it; search uses the neutral semantic similarity 0.5 with the `ml_unavailable` flag. Semantic matching is enabled separately: the ML service with the Giga-Embeddings-instruct-480M and Qwen3-Embedding-0.6B models (the ML Compose project on CPU or the [ML service on a GPU host](#ml-service-on-a-gpu-host)), the shared token `ML_SERVICE_TOKEN`, `SEMANTIC_MATCHING_ENABLED`, the semantic policy, and a backfill (see [Semantic matching](#semantic-matching)). No external inference keys are needed or read.
|
||||
- Data: the demo stand holds synthetic data only. Addresses on the reserved domain `@demo.lincodex.test` never receive mail, names are marked as synthetic, categories have the source `synthetic_demo` and are uncalibrated, and the item families are synthetic and had no subject review. Do not register real people on this stand. Synthetic categories are enabled (`ASSESSMENT_DEMO_CATEGORIES_ENABLED=true`) only by the demo overlay and by the overlay of the isolated registration browser suite (see [TESTING.md](TESTING.md#minimal-path-from-registration-to-disclosed-contacts)); `.env.example` sets `false`.
|
||||
|
||||
### 6. Checks
|
||||
@@ -493,6 +493,7 @@ make -C backend policy-publish ARGS='matching --actor operator:<handle>'
|
||||
- The new version takes effect at once for new searches and changes no stored result. It is also a new version of the whole product policy, so a category opening pinned to the earlier version has to be opened again (and attested again on a demonstration stand, see above) before new assessment attempts are created. Publish it before the candidates start attempts, or repeat the opening and the attestation afterwards.
|
||||
- The demo values (the coefficients of the PRD, the limit of 10 entries per group, and the small specialization-to-technology taxonomy) are in [architecture](ARCHITECTURE.md#product-policy-versions); they are not calibrated. The isolated browser fixture publishes the same section itself.
|
||||
- `policy-publish semantic` publishes the next version with the matching section replaced by the semantic one (`DemoSemanticMatchingPolicy`: Fit weights 0.4167 / 0.0833 / 0.5, the model, the calibration, and the explanation thresholds; see [Semantic matching](#semantic-matching)); when the latest version already has a semantic section, nothing changes. The version with the PRD point stays the previous one.
|
||||
- `policy-publish semantic-ensemble` publishes the next version with the semantic section replaced by the Giga + Qwen3-Embedding ensemble (`DemoSemanticEnsembleMatchingPolicy`: two models, their weights, mean, and std, and the calibration of the fused score; the Fit weights and explanation thresholds stay the same); when the semantic section of the latest version already names both models, nothing changes. The version with Giga alone stays the previous one. The ML service must serve both models, and a backfill follows the publication (see [Semantic matching](#semantic-matching)).
|
||||
|
||||
## Isolated demo stand
|
||||
|
||||
@@ -529,17 +530,25 @@ What the seed creates (all names carry a synthetic marker; addresses are on `@de
|
||||
|
||||
ML uses a separate Compose file and project; it needs no Redis or SeaweedFS. It joins the external network of the core project (`APP_NETWORK`) with the alias `ml`, so the backend reaches `http://ml:8000` without a published port; start the core project first. The host port binds only to 127.0.0.1:8000 by default for diagnostics; change ML_BIND_ADDRESS only after preparing a private address and firewall rules. Prometheus does not scrape remote ML while ML_METRICS_TARGET is empty.
|
||||
|
||||
The image is based on `python:3.14-slim` (PyTorch publishes glibc wheels only, so Alpine cannot be used; the minor version is fixed for `requires-python` and the lock). Dependencies, including the CPU build of PyTorch from the `download.pytorch.org/whl/cpu` index, are installed with uv only in the build stage; the runtime has no pip. A separate stage fetches the Giga-Embeddings-instruct-480M files at the pinned revision from `ml/model/giga-embeddings-480m.lock.json` and checks the size and SHA-256 of every file (about 0.98 GB of safetensors weights); at startup the service checks the SHA-256 again (`ML_VERIFY_WEIGHTS=true`, a few seconds) and runs with `HF_HUB_OFFLINE=1`. The expected image size is about 2.5 GB (Python and PyTorch CPU about 1.4 GB, the model about 1 GB); the image was not built on this machine because of free disk space.
|
||||
The image is based on `python:3.14-slim` (PyTorch publishes glibc wheels only, so Alpine cannot be used; the minor version is fixed for `requires-python` and the lock). Dependencies, including the CPU build of PyTorch from the `download.pytorch.org/whl/cpu` index, are installed with uv only in the build stage; the runtime has no pip. A separate stage fetches the files of both models at the pinned revisions from `ml/model/giga-embeddings-480m.lock.json` and `ml/model/qwen3-embedding-0.6b.lock.json` into `/opt/lincodex/models/giga-480m` and `/opt/lincodex/models/qwen3-0.6b` and checks the size and SHA-256 of every file (about 0.98 and 1.19 GB of safetensors weights); at startup the service checks the SHA-256 again (`ML_VERIFY_WEIGHTS=true`, a few seconds) and runs with `HF_HUB_OFFLINE=1`. The container listens on 0.0.0.0:8000 through `python -m lincodex_ml.serve`, so the service does not start without `ML_SERVICE_TOKEN`. The expected image size is about 3.7 GB (Python and PyTorch CPU about 1.4 GB, the models about 2.2 GB); the image was not built on this machine because of free disk space.
|
||||
|
||||
| Variable | Default | Purpose |
|
||||
| --- | --- | --- |
|
||||
| `ML_EMBEDDER` | `giga` in the image and Compose, `none` outside the image | `giga` - the model of the image, `fake` - a deterministic hash encoder for stands without the model (its model id does not match the policy, so its vectors are never used), `none` - the service stays not ready |
|
||||
| `ML_EMBEDDER` | `giga,qwen3` in the image and Compose, `none` outside the image | a comma list of models (`giga`, `qwen3`), the first answers a request without `model`; `fake` - a deterministic hash encoder for stands without the models (its model id does not match the policy, so its vectors are never used), `none` - the service stays not ready |
|
||||
| `ML_SERVICE_TOKEN` or `ML_SERVICE_TOKEN_FILE` | empty | the bearer token shared with the backend (at least 32 printable characters, a secret); without it the service answers loopback callers only and refuses to start on a non-loopback address |
|
||||
| `ML_LISTEN_HOST`, `ML_LISTEN_PORT` | 127.0.0.1, 8000 (0.0.0.0, 8000 in the image) | address and port of `python -m lincodex_ml.serve` |
|
||||
| `ML_GIGA_MODEL_DIR`, `ML_QWEN3_MODEL_DIR` | the image directories | the model files; a Hugging Face snapshot directory works too |
|
||||
| `ML_GIGA_MODEL_LOCK`, `ML_QWEN3_MODEL_LOCK` | `model.lock.json` in the model directory | the lock file the files are checked against |
|
||||
| `ML_DEVICE` | `cpu` | `cpu`, `cuda`, or `cuda:<index>` |
|
||||
| `ML_DTYPE` | `float32` | `float16` and `bfloat16` on CUDA only |
|
||||
| `ML_CUDA_MEMORY_LIMIT_MB` | 0 (no limit) | CUDA allocator limit of the process; the CUDA context adds about 130 MiB |
|
||||
| `ML_EXIT_ON_LOAD_FAILURE` | false | end the process after a load failure other than a lack of device memory, so a supervisor restarts it |
|
||||
| `ML_TORCH_THREADS` | 4 | torch threads; with 4 the study meets the CPU targets |
|
||||
| `ML_MICRO_BATCH` | 1 | micro-batch size; 1 gives every text the same vector whatever the request holds |
|
||||
| `ML_MAX_TOKENS` | 1024 | tokens a text, as in the study |
|
||||
| `ML_VERIFY_WEIGHTS` | true | check the SHA-256 of the weights at startup |
|
||||
|
||||
Container limits: 4 CPUs and 5 GiB (the float32 model takes about 3.6 GiB resident). Readiness turns 200 only after the load and the warm-up.
|
||||
Container limits: 4 CPUs and 8 GiB (on CPU in float32 Giga takes about 3.6 GiB resident and Qwen3-Embedding about 2.5 GiB more). Readiness turns 200 only after both models are loaded and warmed up. A lack of device memory never stops the process: a load is retried, a request answers 503, and `/readyz` answers 503 for 30 seconds.
|
||||
|
||||
make -C deploy ml-config
|
||||
make -C deploy ml-build
|
||||
@@ -547,14 +556,29 @@ Container limits: 4 CPUs and 5 GiB (the float32 model takes about 3.6 GiB reside
|
||||
make -C deploy ml-logs
|
||||
make -C deploy ml-down
|
||||
|
||||
For development without Docker: `make -C ml model-fetch` fetches and checks the same files into `ML_MODEL_DIR` (default `~/.cache/lincodex-ml/giga-480m`), and `make -C ml test-model` checks that the vectors match the study. Measured on an Apple M5 (CPU, 4 threads, over HTTP, 20 requests): a need view of 887 characters p50 296 ms / p95 707 ms, a profile of 500 characters 207 / 237 ms, a short requirement 74 / 166 ms, a card job batch of 13 texts 2.2 / 5.4 s. This is one laptop with other load, not a stand measurement.
|
||||
For development without Docker: `make -C ml model-fetch` fetches and checks the same files into `ML_GIGA_MODEL_DIR` and `ML_QWEN3_MODEL_DIR` (defaults `~/.cache/lincodex-ml/giga-480m` and `~/.cache/lincodex-ml/qwen3-0.6b`), and `make -C ml test-model` compares the vectors of both models with the study (`ML_TEST_DEVICE=cuda` on a GPU). Giga measured on an Apple M5 (CPU, 4 threads, over HTTP, 20 requests): a need view of 887 characters p50 296 ms / p95 707 ms, a profile of 500 characters 207 / 237 ms, a short requirement 74 / 166 ms, a card job batch of 13 texts 2.2 / 5.4 s. This is one laptop with other load, not a stand measurement.
|
||||
|
||||
## ML service on a GPU host
|
||||
|
||||
On a separate GPU host the service runs without Docker: as the systemd user unit `lincodex-ml.service` of the service user (template [deploy/ml-gpu/lincodex-ml.service](../../deploy/ml-gpu/lincodex-ml.service), lingering enabled for the user) with a virtualenv and models from local files. Both models in float16 take 2.2-2.4 GiB of VRAM, so the service fits next to another user of the same card.
|
||||
|
||||
1. Code: the `ml/` directory of the release (`git archive`) in `~/lincodex-ml/app/ml`.
|
||||
2. Virtualenv: the pinned uv 0.12.22 creates `~/lincodex-ml/venv`. `make -C ml cuda-requirements` writes the versions pinned in `uv.lock` with the CUDA build of torch (`torch==2.11.0+cu128`) to `ml/dist/requirements-cuda.txt`; install the torch line from the `https://download.pytorch.org/whl/cu128` index first, then the other lines from PyPI (`uv pip install --python ~/lincodex-ml/venv/bin/python ...`). A shared uv cache with `UV_LINK_MODE=hardlink` takes no space for wheels it already holds, but the cache is keyed by the index address: another spelling of the address downloads torch and the CUDA libraries again (about 6 GB). Exception: where disk is short, the virtualenv uses the system CPython 3.12 with the same package versions (the cp314 CUDA wheel of torch does not fit), and the package is not installed: the unit sets `PYTHONPATH` to `src`. The service unit tests pass on 3.12, but 3.14 stays the main version, so 3.13+ syntax in `ml/src` would break such a host.
|
||||
3. Models: Hugging Face snapshot directories at the pinned revisions (`HF_HOME` read-only) or `make -C ml model-fetch`; at startup the files are checked against the lock files of the release.
|
||||
4. Settings: copy [deploy/ml-gpu/ml.env.example](../../deploy/ml-gpu/ml.env.example) to `~/.config/lincodex-ml/ml.env` (directory 700, file 600). Generate the token on the host with a CSPRNG (`python3 -c 'import secrets; print(secrets.token_hex(32))'`); it lives only in this file and in the backend environment. The address is a private address of the host, never 0.0.0.0.
|
||||
5. Start: put the unit template in `~/.config/systemd/user/lincodex-ml.service`, then `systemctl --user daemon-reload` and `systemctl --user enable --now lincodex-ml.service`. Restart after a code or settings update with `systemctl --user restart lincodex-ml.service`, check it with `systemctl --user status lincodex-ml.service`, follow the log with `journalctl --user -u lincodex-ml.service -f`. The unit sets `Restart=on-failure`, `MemoryHigh=5G`, `MemoryMax=6G`, `CPUQuota=400%`, 4 torch and OMP threads, and `ML_EXIT_ON_LOAD_FAILURE=true`: a lack of device memory never stops the process, while other load failures (for example a driver that is not ready at host startup) end it and systemd restarts it after 15 seconds.
|
||||
6. Network: the unit changes no firewall or system setting. Restrict the port to the app host address at the host or network level; the traffic crosses the LAN without TLS, so the token and the texts are visible on that segment.
|
||||
|
||||
Precision and VRAM (RTX 5060 Ti 16 GB, measured 2026-10-11, a process budget of about 2.5 GB): in float32 Giga alone takes 1984 MiB after the load and up to 2750 MiB under a request of 1024-token texts, Qwen3 2404 and 3038 MiB, together about 4.3 GiB after the load, so float32 does not fit. In float16 both models in one process take 2252 MiB after the load and 2404 MiB under the worst request (32 texts of 1024 tokens), with the allocator capped by `ML_CUDA_MEMORY_LIMIT_MB=2300`. Quality of float16 against float32 on the study's DEV data (product views): vector cosine at least 0.99986 (Giga) and 0.99999 (Qwen3), nDCG@10 changed by -0.0004 and +0.0008, for the ensemble by +0.0002 (threshold 0.005), the ensemble top-10 is the same set for 30 of 30 DEV needs and in the same order for 28, and a repeated encode at micro-batch 1 gives the same bits. `bfloat16` was rejected: the top-10 matches for 27 of 30, the order for 14. Hence `ML_DTYPE=float16`; the mean, std, and calibration of the ensemble were computed on float16 vectors.
|
||||
|
||||
Latency over the LAN from the app host (40 requests, one text, micro-batch 1, CUDA float16): a need view - Giga p50 11.4 / p95 13.0 ms, Qwen3 12.5 / 14.5 ms; a profile - 11.2 / 12.9 and 12.1 / 13.8 ms; a card job batch of 13 texts - 132 / 135 and 143 / 160 ms. The process keeps about 2.6 GiB resident (peak 2.9 GiB). This is one host measured while the other model on the card was not loaded, not a load test.
|
||||
|
||||
## Semantic matching
|
||||
|
||||
The search never calls ML: it reads the vectors that background jobs computed (see [ARCHITECTURE.md](ARCHITECTURE.md#semantic-layer-and-explanations)). To enable it on a stand:
|
||||
|
||||
1. `make -C deploy up`, then `make -C deploy ml-up`, and wait for `/readyz` 200.
|
||||
2. Set `SEMANTIC_MATCHING_ENABLED=true` (and `ML_SERVICE_URL` if it differs) in the stand `.env` and restart the backend (`make -C deploy up`).
|
||||
1. `make -C deploy up`, then `make -C deploy ml-up` (or the [ML service on a GPU host](#ml-service-on-a-gpu-host)), and wait for `/readyz` 200.
|
||||
2. Set `SEMANTIC_MATCHING_ENABLED=true`, `ML_SERVICE_TOKEN` (the token of the ML service), and `ML_SERVICE_URL` if it differs (`http://<address>:<port>` for a GPU host) in the stand `.env` and restart the backend (`make -C deploy up`).
|
||||
3. Publish the semantic policy section: `make -C backend policy-publish ARGS='semantic --actor operator:<handle>'` (with the stand `DATABASE_URL`). Like the `matching` section, a new policy version requires opening and attesting the category again on the demo stand.
|
||||
4. Compute vectors for existing data: `make -C backend semantic-backfill ARGS='all --run <label>'`. The command needs only `DATABASE_URL`; it schedules jobs page by page and prints the cursor to resume with (`--after`). Repeating the same label schedules nothing twice; a new label recomputes, and unchanged texts cost no ML call. The backend worker runs the jobs.
|
||||
|
||||
@@ -562,6 +586,7 @@ The search never calls ML: it reads the vectors that background jobs computed (s
|
||||
| --- | --- | --- |
|
||||
| `SEMANTIC_MATCHING_ENABLED` | false | schedule and run vector jobs |
|
||||
| `ML_SERVICE_URL` | `http://ml:8000` in Compose | ML origin without a path or credentials |
|
||||
| `ML_SERVICE_TOKEN` | empty | bearer token of the ML service, 32-512 printable characters without spaces; required while `SEMANTIC_MATCHING_ENABLED=true`; a secret that never reaches a log |
|
||||
| `ML_REQUEST_TIMEOUT` | 30s | timeout of one ML request |
|
||||
| `ML_CIRCUIT_FAILURES`, `ML_CIRCUIT_OPEN` | 3, 30s | after that many consecutive failures the client does not call ML for that long |
|
||||
| `GITHUB_REPOSITORY_CHECKS_ENABLED` | false | run the checks of project repositories on `api.github.com` |
|
||||
@@ -571,7 +596,13 @@ The search never calls ML: it reads the vectors that background jobs computed (s
|
||||
|
||||
Without ML, or while it is unavailable, the search works as before: the neutral `Sem` 0.5 with the `ml_unavailable` flag; jobs retry up to 20 times and then wait for an operator (a new backfill). The isolated browser stand (e2e) does not start ML and uses policy V4; the demo stand also runs without ML by default, and enabling it takes the same steps with the project `lincodex-demo`. Metrics: `lincodex_scheduled_jobs_total{kind="semantic.candidate"|"semantic.need"|"profile.repository_check"}` in the backend, `lincodex_ml_embedding_request_seconds` and `lincodex_ml_embedding_texts_total` in ML.
|
||||
|
||||
The model ensemble (Giga + Qwen3-Embedding-0.6B) is not enabled; the steps to enable it - a second model in the ML service, 8 threads, a calibration of the fused score, a new policy with two `members`, and a backfill - are in [ARCHITECTURE.md](ARCHITECTURE.md#semantic-layer-and-explanations). The search never reads vectors of a model that the policy no longer names; they stay for a rollback to the previous policy version.
|
||||
The Giga + Qwen3-Embedding-0.6B ensemble (see [ARCHITECTURE.md](ARCHITECTURE.md#semantic-layer-and-explanations)) is enabled after the steps above, once the ML service serves both models (`ML_EMBEDDER=giga,qwen3`):
|
||||
|
||||
1. `make -C backend policy-publish ARGS='semantic-ensemble --actor operator:<handle>'` - a new policy version with two models; the version with Giga alone stays the previous one.
|
||||
2. Right after it, `make -C backend semantic-backfill ARGS='candidates --run <label>'` and `make -C backend semantic-backfill ARGS='needs --run <label>'` (or `all`). Jobs compute the vectors of every model of the effective policy: the Giga vectors do not change and cost no ML call, and Qwen3 encodes only the `whole` view of each card and need. Until the backfill ends, entries without Qwen3 vectors get the neutral `Sem` with `ml_unavailable`, so switch at a quiet time.
|
||||
3. Check: `SELECT model_id, count(*) FROM semantic_vectors WHERE item_key = 'whole' GROUP BY model_id` - the Qwen3 count catches up with the Giga count.
|
||||
|
||||
Provenance of the policy values: the DEV judgments of the LincodexMatch study (30 needs, 3220 judged pairs), the study's profiles and needs rendered by the product view builder, ML service vectors on CUDA in float16, and the weights of step 5 of the study; the encoding and fitting scripts and their outputs are kept next to the research run on the GPU host (`lincodex-ml/eval/`). The search never reads vectors of a model that the policy no longer names; they stay for a rollback to the previous policy version.
|
||||
|
||||
## Separate monitoring Compose project
|
||||
|
||||
|
||||
+1
-1
@@ -47,7 +47,7 @@ For any further exception, scope it to the specific finding and affected input,
|
||||
- GitHub. Project repository checks call only `https://api.github.com`: the profile accepts an address only as `https://github.com/<owner>/<repo>`, the owner and name are checked against the GitHub patterns and escaped into the path, the base origin is fixed in code (tests replace it only inside the package), no proxy from the environment is used, TLS 1.2+, connect and response timeouts, a redirect is followed only to the same origin (at most three), responses are capped at 1 MiB and the README at 64 KiB. User input therefore cannot point the server at another host (SSRF). The checks are off by default (`GITHUB_REPOSITORY_CHECKS_ENABLED`), a repeated check is limited per candidate (`REPOSITORY_CHECK_INTERVAL`), and the GitHub limit is respected from its headers.
|
||||
- Token. `GITHUB_TOKEN` is optional, needs read access to public data only, and is sent only to `api.github.com`; it never reaches logs, errors, jobs, or the database. The check log carries the job id, attempt, state, and error class, never the repository; the job key and payload carry only a digest of the repository.
|
||||
- GitHub data. The description, topics, languages, and README text are untrusted data: the README becomes plain text, is stored only for a public repository, is used only for ranking, and is never shown, let alone as HTML. The repository address and owner never reach an organization, neither in the card, nor in the explanation, nor after C4.
|
||||
- ML. Only the backend reaches the service, over the Compose network (`http://ml:8000`); the host port is loopback. The service has no credentials, so the network is its boundary. The backend sends ML only the texts of the published card and of the organization's need, with no contact and no private profile. The weights come from the image by SHA-256, the remote code of the model is never executed, no pickle is loaded, and the service runs offline.
|
||||
- ML. Every route of the service except `/healthz` and `/readyz` requires `Authorization: Bearer <token>`: a shared random token of at least 32 printable characters (`ML_SERVICE_TOKEN` in the backend, `ML_SERVICE_TOKEN` or `ML_SERVICE_TOKEN_FILE` in the service) is compared in constant time and never reaches a log, a response, or an error message; a missing or wrong token answers 401 `unauthenticated`, and the request is refused before its body is read. Without a token the service answers loopback callers only, and the entry point `python -m lincodex_ml.serve` refuses to listen on a non-loopback address; the backend does not enable semantic matching without a token. In Compose the backend reaches the service over the network (`http://ml:8000`) and the host port is loopback; on a GPU host it listens on a private LAN address without TLS, so restrict the port to the app host address with host or network rules. `/metrics` requires the token too. The backend sends ML only the texts of the published card and of the organization's need, with no contact and no private profile. The weights are pinned by lock files with SHA-256, no remote model code is executed, no pickle is loaded, and the service runs offline.
|
||||
|
||||
## CI and limits
|
||||
|
||||
|
||||
+3
-1
@@ -645,9 +645,11 @@ What the tests do not prove: isolation in the production VM until the suite has
|
||||
## Semantic matching tests
|
||||
|
||||
- ML service (`make -C ml test`, no model, no network): `tests/test_embeddings.py` checks the `POST /v1/embeddings` contract on the deterministic hash encoder: response order, normalization, equal vectors for two equal requests, micro-batches by length, 503 `service_unavailable` before readiness and ready only after the warm-up, 400 for too many texts, a length, and unknown fields, 413 for a body over the limit (with Content-Length and streamed), and no request text in the logs; `tests/test_model_files.py` checks the lock file (only safetensors and configs, a full revision, no code or pickle) and the size and SHA-256 verification.
|
||||
- The real model: `make -C ml model-fetch` and `make -C ml test-model` (marker `slow`, skipped by the ordinary checks) compare the Giga-480M vectors on CPU with the study's vectors for four texts (difference below 1e-4, measured below 1e-6) and a repeated encode (the same vector). This checks that the recipe is reproduced, not model quality.
|
||||
- Ensemble and ML token (`make -C ml test`): `tests/test_ensemble_and_auth.py` checks the choice of one of several loaded models by `model` and 400 for another one, readiness only after every model, a refusal of two encoders with one id, 503 and a readiness cool-down after a lack of device memory with recovery, a retried load on a lack of memory and the exit through `ML_EXIT_ON_LOAD_FAILURE` on another failure, 401 without a token, with a wrong token, with the Basic scheme, and on `/metrics`, open `/healthz` and `/readyz`, loopback only without a token, a refusal before the body is read, no token in logs or settings errors, and the entry point refusing a non-loopback address without a token. Checked by hand on CUDA: a load without enough memory is retried while the process stays alive and not ready; a request over the allocator limit answers 503, `/readyz` answers 503 for 30 seconds, and then the service answers 200 again.
|
||||
- The real models: `make -C ml model-fetch` and `make -C ml test-model` (marker `slow`, skipped by the ordinary checks) compare the Giga-480M and Qwen3-Embedding-0.6B vectors with the study's vectors for four texts (difference below 1e-4) and a repeated encode (the same vector); `ML_TEST_DEVICE=cuda` runs them on the GPU in float32. On 2026-10-11 both models passed on CPU and on CUDA on the GPU host. This checks that the recipe is reproduced, not model quality; the float16 against float32 comparison and the fit of the ensemble policy are a separate evaluation on the study's DEV data (see [DEPLOY.md](DEPLOY.md#ml-service-on-a-gpu-host)).
|
||||
- Backend unit: need and card views (`domain/semantic_test.go`: the exact study text, confirmed values only, metadata only for a verified repository), the float32 codec and cosine, the calibration (interpolation, steps, a monotone demo table), the thresholds, validation and the round trip of the V5 policy document; projects and GitHub addresses (`domain/candidate_project_test.go`: accepted and rejected addresses, normalization, limits, a repeated repository, no address in the card); explanation selection (`usecase/matching/semantic_test.go`: order, limit, a stale title, a hidden stack or hidden projects explain nothing, the `projects` field record); Fit with a known and the neutral Sem; the ML client (batches of 32, response checks, the circuit breaker, no text in errors); GitHub (`adapter/secondary/github`: httptest, public repositories only, the token only when set, ETag and 304, 403/429 limits with the wait, server errors, a refused redirect to another origin, size caps, README text without markup or HTML); jobs and the trigger (keys and payloads without the repository address, disabled features schedule nothing).
|
||||
- Integration (Testcontainers): `TestSemanticMatchingOverHTTP` runs over HTTP, PostgreSQL, and the real job worker with a fake ML service (httptest on the contract) and a fake GitHub: a profile save schedules jobs without the address in their keys, the repository check and the card vectors, the neutral Sem and flag before the need vectors, then the candidate with the close project first, the explanation names the project and `repository_verified`, and neither the response nor the card carries the repository address or owner; equal responses of two searches; the access history with the `projects` field; a repeated backfill with the same label schedules nothing twice and calls ML for no unchanged text; unpublishing `projects` removes the project vectors and the title from the explanation; an unavailable ML keeps the job in retry while the search answers; the refresh limit (429, then 202).
|
||||
- Ensemble and token in the backend: unit tests `domain/policy_matching_ensemble_test.go` (the ensemble policy validates, Giga explains with its thresholds, the fused score is 0 at the means, the calibration is monotone and clipped, the V6 document round trip), `usecase/policy` (the ensemble published on top of V5, a repeat publishes nothing, the single-model command leaves the ensemble alone), `cli/policypublish` (the `semantic-ensemble` track), `adapter/secondary/ml` (the bearer token on every request, 401 as unavailability without the token text, no client without a token), `config` (the token is required while matching is enabled, short and spaced tokens are refused, formatted settings hide the tokens). In `TestSemanticMatchingOverHTTP` the fake ML requires the token and serves both models; after the ensemble publication and before the backfill every entry has the neutral `Sem`, and the backfill adds Qwen3 `whole` vectors for the six cards and the need without re-encoding Giga and without Qwen3 item vectors, after which every entry has a known `Sem`.
|
||||
- Not checked: ranking quality and explanation precision on real data, latency on the production server, the ML image build on this machine, and a stand with the model. Tests never call the real GitHub.
|
||||
|
||||
## Future software validation
|
||||
|
||||
@@ -834,13 +834,13 @@ Checker задается для группы: `exact`, `tokens`, `numbers` (чи
|
||||
Реализовано: эмбеддинги потребностей и опубликованных карточек, `Sem` в Fit, структурированное объяснение "почему в подборке", проекты кандидата и проверка их репозиториев GitHub. Основание - исследование LincodexMatch (DEV 30 потребностей, TEST 70, 2594 синтетических профиля); его цифры получены на синтетике и не являются продуктовым замером.
|
||||
|
||||
- Модель. `ai-sage/Giga-Embeddings-instruct-480M-0826` (MIT) на ревизии `1763d603adac8057bd6482a708001b0ed2e0a903`, float32, 1024 измерения, до 1024 токенов на текст. На TEST она лучшая на косвенных совпадениях (nDCG@10 indirect 0.571 против 0.409 у Qwen3-Embedding-0.6B) и выполняет цели CPU при 4 потоках (p95 профиля 352 мс, поиск по 100k 591 мс в исследовании). Рецепт повторяет исследование: потребность и каждое требование кодируются с промптом `Instruct: Given a query, retrieve relevant passages\nQuery: `, карточка и ее элементы без промпта, среднее по маске внимания вместе с токенами промпта, L2-нормализация. Удаленный код репозитория модели не скачивается и не исполняется: тот же двунаправленный Qwen3 реализован в `ml/src/lincodex_ml/inference/giga.py`, а тест `make -C ml test-model` сверяет векторы с векторами исследования (разница < 1e-6).
|
||||
- ML-сервис. `POST /v1/embeddings` контракта `api/ml` (до 32 текстов по 8000 символов, тело до 2 MiB, необязательный id модели `model`, ответ с id, ревизией, размерностью и `prompt_version`). Сервис сейчас загружает одну модель; запрос другой модели получает 400 с указателем `/model`. Веса скачиваются один раз при сборке образа по lock-файлу `ml/model/giga-embeddings-480m.lock.json` с проверкой SHA-256 (только safetensors, конфиги и токенизатор), сервис работает офлайн. Readiness становится ready только после загрузки и прогревочного кодирования; до этого 503 `service_unavailable`. Тексты кодируются по одному запросу за раз, в микропакетах фиксированного размера (по умолчанию 1), отсортированных по длине с позицией запроса как тай-брейком, поэтому одни и те же тексты на одном образе и числе потоков дают одни и те же векторы.
|
||||
- ML-сервис. `POST /v1/embeddings` контракта `api/ml` (до 32 текстов по 8000 символов, тело до 2 MiB, необязательный id модели `model`, ответ с id, ревизией, размерностью и `prompt_version`). Сервис загружает модели из списка `ML_EMBEDDER` (`giga`, `qwen3`; первая отвечает на запрос без `model`), запрос модели, которую он не загрузил, получает 400 с указателем `/model`. Каждая модель закреплена lock-файлом (`ml/model/giga-embeddings-480m.lock.json`, `ml/model/qwen3-embedding-0.6b.lock.json`) с проверкой SHA-256 (только safetensors, конфиги и токенизатор), удаленный код не исполняется, сервис работает офлайн. Устройство - `ML_DEVICE` (`cpu` по умолчанию или `cuda`), точность - `ML_DTYPE` (`float32`; `float16` и `bfloat16` только на CUDA), `ML_CUDA_MEMORY_LIMIT_MB` ограничивает аллокатор процесса на общей видеокарте. Нехватка видеопамяти процесс не роняет: загрузка повторяется с растущей паузой (15 с, до 5 мин), запрос получает 503 `service_unavailable`, а `/readyz` 30 секунд отвечает 503, после чего сервис снова обслуживает запросы. Readiness становится ready только после загрузки и прогревочного кодирования всех моделей. Тексты кодируются по одному запросу за раз, в микропакетах фиксированного размера (по умолчанию 1), отсортированных по длине с позицией запроса как тай-брейком, поэтому одни и те же тексты на одной установке, устройстве, точности и числе потоков дают одни и те же векторы (на CUDA проверено повторным кодированием). Все маршруты, кроме `/healthz` и `/readyz`, требуют `Authorization: Bearer <token>` (см. [SECURITY.md](SECURITY.md#исходящие-запросы-и-ml)).
|
||||
- Какие поля ранжируют. Только то, что показывает анонимная карточка этого кандидата до когортного обобщения: роли из `self_assessment` и `categories` (`backend (middle)`), распознанные коды стека и опубликованные проекты с публичными метаданными проверенных репозиториев. Приватный текст профиля (резюме, `summary` опыта, работодатели) в ранжирование не попадает, как и раньше в ML (принцип "Go передает только разрешенные данные"). Исследование показывает, что приватный опыт улучшает качество (предложение 3 отчета); разрешение использовать его на сервере без показа - открытый вопрос владельца, и оно потребует явного решения в политике приватности.
|
||||
- Векторы. Таблица `semantic_vectors` (миграция `00049`): субъект (`candidate` или `need`), ключ элемента (`whole`, `roles`, `stack`, `project:<n>`, `required_skill:<n>`, `desired_skill:<n>`, `task:<n>`), SHA-256 текста с версией рендеринга `semantic-views-v1`, модель, ревизия, версия промпта, размерность и вектор как little-endian float32 (4 KiB на 1024 измерения: точно, одинаково на всех платформах; int8 отложен, пока объем не станет проблемой). Каскадное удаление вместе с аккаунтом или потребностью. У кандидата хранится ровно один набор на модель, у потребности - набор последнего снимка требований.
|
||||
- Конвейер. Сохранение профиля, изменение публикации, новый снимок требований и завершенная проверка репозитория ставят задание по сроку (`semantic.candidate`, `semantic.need`) в той же транзакции; запрос пользователя ML не ждет. Обработчик берет advisory-блокировку субъекта, рендерит текущую карточку или текущий снимок, сравнивает дайджесты с сохраненными (без изменений - без вызова ML), кодирует тексты и заменяет набор. Задание кодирует тексты каждой модели из `members` политики, передавая ее id; первая модель хранит все элементы, остальные только `whole`. Модель ответа (id, ревизия, версия промпта) должна совпадать с моделью политики, иначе задание повторяется. До 20 попыток с backoff переживают недоступность ML; задание кандидата без публикации удаляет его векторы. Отзыв C2 закрывает карточку в другом usecase и задание не ставит: векторы остаются до следующего задания кандидата или backfill, но невидимая карточка в поиск не попадает. Команда `semantic-backfill` ставит задания для всех кандидатов с профилем и всех потребностей постранично, идемпотентно по метке запуска и с курсором для продолжения.
|
||||
- Sem и Fit. Поиск никогда не вызывает ML: он рендерит снимок потребности, читает векторы с совпадающими дайджестами и векторы `whole` видимых кандидатов по каждой модели политики, считает слитый балл Σ w·(cos - mean)/std и переводит его в `Sem` изотонической калибровкой из политики (P(релевантно | балл) на DEV, ECE 0.015-0.049 против 0.17-0.57 у сырого косинуса), целочисленной интерполяцией. По умолчанию модель одна с весом 1, mean 0 и std 1, поэтому балл равен косинусу. Нет векторов потребности или кандидата хотя бы для одной модели политики или ML - `Sem` нейтральное 0.5 и флаг `ml_unavailable` для этой записи, как раньше. Множество кандидатов, фильтры, видимость, квоты и когортные правила не меняются; BM25 в оценку не смешивается (на TEST он режет indirect с 0.571 до 0.250).
|
||||
- Политика. `domain.DemoProductPolicyV5()` - V4 с семантическим разделом `matching.semantics` (`members` - одна модель Giga с ревизией, версией промпта, весом 1, mean 0 и std 1; 80 точек калибровки `score_bp`, пороги объяснений, лимит, источник) и весами Fit 0.4167 / 0.0833 / 0.5. При весе PRD 0.10 Fit дает на TEST nDCG@10 0.649 против 0.818 у самого эмбеддера, при 0.5 - 0.838; Cov и Dom сохраняют соотношение PRD 5:1. V4 остается предыдущей версией (точка PRD). Публикация: `make -C backend policy-publish ARGS='semantic --actor operator:<handle>'`.
|
||||
- Ансамбль. Схема готова к S5-DE из исследования: `Sem` = калибровка(0.4·z(Giga) + 0.6·z(Qwen3-Embedding-0.6B)), на TEST nDCG@10 0.842 против 0.818 у одной Giga, при 8 потоках p95 около 0.85 с на 12 ядрах. Сейчас не включено. Порядок включения: (1) добавить в ML-сервис вторую настроенную модель `Qwen/Qwen3-Embedding-0.6B` на ревизии `97b0c614be4d77ee51c0cef4e5f07c00f9eb65b3` с lock-файлом, своим промптом и версией промпта (сервис выбирает модель по полю `model`; загрузка нескольких моделей - отдельная доработка); (2) поднять `ML_TORCH_THREADS` до 8 и лимиты контейнера; (3) на DEV посчитать mean и std косинуса каждой модели и заново подобрать изотоническую калибровку и, при необходимости, пороги на слитом балле (исследование нормировало z по корпусу каждой потребности, продукт использует глобальные mean и std из политики, поэтому цифры нужно перепроверить); (4) опубликовать новую версию политики с двумя `members` (Giga первой, она же объясняет записи; сумма весов 1) и новой калибровкой; (5) сразу после вступления версии в силу запустить `semantic-backfill` для кандидатов и потребностей. Задания считают векторы только для действующей политики, поэтому до конца backfill записи без векторов второй модели получают нейтральное `Sem`; переход лучше проводить в тихое время. Векторы Giga при этом не пересчитываются (дайджесты те же), а векторы прежних моделей остаются и позволяют откатиться на прошлую версию политики без пересчета.
|
||||
- Ансамбль. Реализован S5-DE из исследования: `Sem` = калибровка(0.4·z(Giga) + 0.6·z(Qwen3-Embedding-0.6B)), `domain.DemoProductPolicyV6()` (V5 с разделом `DemoSemanticEnsembleMatchingPolicy`, веса Fit те же). Вторая модель - `Qwen/Qwen3-Embedding-0.6B` (Apache-2.0) на ревизии `97b0c614be4d77ee51c0cef4e5f07c00f9eb65b3`, обычный Qwen3 без удаленного кода: потребность кодируется с промптом модели `Instruct: Given a web search query, retrieve relevant passages that answer the query\nQuery:` (склейка без разделителя), карточка без промпта, токенизатор добавляет end-of-text, вектор - скрытое состояние последнего токена с L2-нормализацией (`prompt_version` `qwen3-card-last-v1`, `ml/src/lincodex_ml/inference/qwen3.py`, сверка с векторами исследования - `make -C ml test-model`). Веса 0.4 / 0.6 - выбор шага 5 исследования (5-кратная CV по потребностям DEV, w_giga = 0.4 в четырех фолдах из пяти). Mean и std посчитаны заново на продуктовых представлениях: потребности и профили исследования отрендерены продуктовым построителем (`domain.NewNeedSemanticDocument` дает тот же текст, что исследование, для всех 100 потребностей; карточка - роли каталога с заявленным грейдом, коды стека карточки и по одному опубликованному проекту на каждый опыт исследования) и закодированы ML-сервисом на CUDA в float16. Mean - по всем парам DEV (Giga 0.2497, Qwen3 0.3636), std - средняя внутри потребности (0.0741 и 0.0731), поэтому фиксированный z воспроизводит z по корпусу каждой потребности из исследования: DEV nDCG@10 all / indirect 0.809 / 0.518 против 0.809 / 0.518 у исследовательской формы и 0.738 / 0.403 у одной Giga на тех же представлениях. Калибровка - изотоническая регрессия P(consensus >= 2) на слитом балле 3220 размеченных пар DEV (994 положительных), посчитанном с округленными mean и std политики; 56 точек, ECE 5-кратной CV по потребностям 0.025. Пороги объяснений остаются порогами Giga (первая модель, она же дает векторы элементов). Источник и скрипты расчета записаны в `source` политики и в [DEPLOY.md](DEPLOY.md#семантический-подбор). Без проектов в карточке сигнал слабый (DEV nDCG@10 0.21 у ансамбля и 0.23 у одной Giga на картах только с ролями и стеком), поэтому выигрыш ансамбля зависит от того, публикуют ли кандидаты проекты. Публикация и backfill: `make -C backend policy-publish ARGS='semantic-ensemble --actor operator:<handle>'`, затем `semantic-backfill` для кандидатов и потребностей. Задания считают векторы для каждой модели действующей политики, поэтому до конца backfill записи без векторов Qwen3 получают нейтральное `Sem`; переход лучше проводить в тихое время. Векторы Giga не пересчитываются (дайджесты те же), а V5 остается предыдущей версией: векторы обеих моделей остаются, и откат на Giga не требует пересчета.
|
||||
- Объяснение. Для поиска по потребности каждое подтвержденное требование (обязательный и желательный навык, задача) сопоставляется с ближайшим элементом карточки по косинусу. Пороги из DEV: P(пара релевантна | лучший косинус требования) 0.5 и 0.7, для навыков 0.3673 / 0.4607 (`medium` / `high`), для задач 0.2997 / 0.4192. В ответ попадают `semantic_evidence` записи: вид и текст требования (текст самой потребности организации), вид элемента (`project`, `stack`, `roles`), название проекта, только если кандидат опубликовал поле `projects` и название не изменилось с момента расчета, признак `repository_verified` и полоса; порядок `high`, затем косинус, затем порядок требований; не больше 6 (политика). Стек и роли объясняют только пока карточка показывает их этой организации после когортного обобщения. Текст модели в объяснение не входит. Показ названия проекта записывается в историю доступа кандидата полем `projects`. Точность объяснений не проверялась: выборка исследования на 50 пар осталась без разметки.
|
||||
|
||||
#### Проекты кандидата и репозитории GitHub
|
||||
|
||||
+39
-8
@@ -89,7 +89,7 @@ Docker Engine с Compose plugin, GNU make, python3 (цели `deploy` запус
|
||||
### 5. ФСП, ML и данные
|
||||
|
||||
- ФСП: интеграции нет ни в каком режиме. В этой сборке нет переключателя off или mock, fixture-провайдера и обращений к внешнему API. Профиль заполняется вручную, привязка ФСП ID необязательна и пока недоступна, а путь до категории проходит через анкету и тест. Проект не имеет официального доступа к данным ФСП и не обещает его; связь с ФСП через fixture-провайдер запланирована (см. [ARCHITECTURE.md](ARCHITECTURE.md#идентификация-фсп-и-приватность)).
|
||||
- ML: основной и демонстрационный стенды по умолчанию не запускают ML и не обращаются к нему; поиск подставляет нейтральную смысловую близость 0.5 с флагом `ml_unavailable`. Семантический подбор включается отдельно: ML-проект с моделью Giga-Embeddings-instruct-480M на CPU, `SEMANTIC_MATCHING_ENABLED`, семантическая политика и backfill (см. [Семантический подбор](#семантический-подбор)). GPU и ключи внешнего inference не нужны и не читаются.
|
||||
- ML: основной и демонстрационный стенды по умолчанию не запускают ML и не обращаются к нему; поиск подставляет нейтральную смысловую близость 0.5 с флагом `ml_unavailable`. Семантический подбор включается отдельно: ML-сервис с моделями Giga-Embeddings-instruct-480M и Qwen3-Embedding-0.6B (ML Compose на CPU или [ML-сервис на GPU-хосте](#ml-сервис-на-gpu-хосте)), общий токен `ML_SERVICE_TOKEN`, `SEMANTIC_MATCHING_ENABLED`, семантическая политика и backfill (см. [Семантический подбор](#семантический-подбор)). Ключи внешнего inference не нужны и не читаются.
|
||||
- Данные: демонстрационный стенд содержит только синтетические данные. Адреса на зарезервированном домене `@demo.lincodex.test` никогда не получают почту, названия помечены как синтетические, категории имеют источник `synthetic_demo` и не откалиброваны, а семейства заданий синтетические и не прошли предметную проверку. Не регистрируйте на этом стенде реальных людей. Синтетические категории (`ASSESSMENT_DEMO_CATEGORIES_ENABLED=true`) включают только демонстрационный overlay и overlay изолированного браузерного набора регистрации (см. [TESTING.md](TESTING.md#минимальный-путь-от-регистрации-до-раскрытых-контактов)); в `.env.example` значение `false`.
|
||||
|
||||
### 6. Проверки
|
||||
@@ -495,6 +495,7 @@ make -C backend policy-publish ARGS='matching --actor operator:<handle>'
|
||||
- Новая версия действует для новых поисков сразу и не меняет сохраненных результатов. Это также новая версия всей политики product, поэтому открытие категории, привязанное к прежней версии, нужно открыть заново (и аттестовать заново на демонстрационном стенде, см. выше), прежде чем создавать новые попытки оценки. Публикуйте ее до начала попыток кандидатов либо повторите открытие и аттестацию после.
|
||||
- Демонстрационные значения (коэффициенты PRD, предел 10 записей на группу и небольшая таксономия «специализация - технология») описаны в [архитектуре](ARCHITECTURE.md#версии-продуктовой-политики); они не калиброваны. Изолированный браузерный стенд публикует тот же раздел сам.
|
||||
- `policy-publish semantic` публикует следующую версию, в которой раздел подбора заменен семантическим (`DemoSemanticMatchingPolicy`: веса Fit 0.4167 / 0.0833 / 0.5, модель, калибровка и пороги объяснений, см. [Семантический подбор](#семантический-подбор)); если у последней версии семантический раздел уже есть, ничего не меняется. Версия с точкой PRD остается предыдущей.
|
||||
- `policy-publish semantic-ensemble` публикует следующую версию, в которой семантический раздел заменен ансамблем Giga + Qwen3-Embedding (`DemoSemanticEnsembleMatchingPolicy`: две модели, их веса, mean и std, калибровка слитого балла; веса Fit и пороги объяснений те же); если семантический раздел последней версии уже называет обе модели, ничего не меняется. Версия с одной Giga остается предыдущей. ML-сервис должен обслуживать обе модели, а после публикации нужен backfill (см. [Семантический подбор](#семантический-подбор)).
|
||||
|
||||
## Изолированный демонстрационный стенд
|
||||
|
||||
@@ -531,17 +532,25 @@ make -C deploy demo-down DEMO_MODE=isolated
|
||||
|
||||
ML имеет отдельный Compose-файл и проект; Redis и SeaweedFS ему не требуются. Он входит во внешнюю сеть core-проекта (`APP_NETWORK`) с псевдонимом `ml`, поэтому backend обращается к `http://ml:8000` без опубликованного порта; поднимайте core-проект первым. Порт на хосте по умолчанию слушает только 127.0.0.1:8000 для диагностики; ML_BIND_ADDRESS меняйте только при подготовленном приватном адресе и firewall. Метрики удаленного ML target не собираются, пока ML_METRICS_TARGET пуст.
|
||||
|
||||
Образ основан на `python:3.14-slim` (PyTorch публикует только glibc-колеса, поэтому Alpine не подходит; минорная версия закреплена под `requires-python` и lock). Зависимости, включая CPU-сборку PyTorch с индекса `download.pytorch.org/whl/cpu`, ставятся через uv только на этапе сборки; runtime не содержит pip. Отдельная стадия скачивает файлы модели Giga-Embeddings-instruct-480M на закрепленной ревизии по `ml/model/giga-embeddings-480m.lock.json` и проверяет размер и SHA-256 каждого файла (около 0.98 GB весов safetensors); при старте сервис повторно сверяет SHA-256 (`ML_VERIFY_WEIGHTS=true`, несколько секунд) и работает с `HF_HUB_OFFLINE=1`. Ожидаемый размер образа около 2.5 GB (Python и PyTorch CPU около 1.4 GB, модель около 1 GB); на этой машине образ не собирался из-за свободного места на диске.
|
||||
Образ основан на `python:3.14-slim` (PyTorch публикует только glibc-колеса, поэтому Alpine не подходит; минорная версия закреплена под `requires-python` и lock). Зависимости, включая CPU-сборку PyTorch с индекса `download.pytorch.org/whl/cpu`, ставятся через uv только на этапе сборки; runtime не содержит pip. Отдельная стадия скачивает файлы обеих моделей на закрепленных ревизиях по `ml/model/giga-embeddings-480m.lock.json` и `ml/model/qwen3-embedding-0.6b.lock.json` в `/opt/lincodex/models/giga-480m` и `/opt/lincodex/models/qwen3-0.6b` и проверяет размер и SHA-256 каждого файла (около 0.98 и 1.19 GB весов safetensors); при старте сервис повторно сверяет SHA-256 (`ML_VERIFY_WEIGHTS=true`, несколько секунд) и работает с `HF_HUB_OFFLINE=1`. Контейнер слушает 0.0.0.0:8000 через `python -m lincodex_ml.serve`, поэтому без `ML_SERVICE_TOKEN` сервис не стартует. Ожидаемый размер образа около 3.7 GB (Python и PyTorch CPU около 1.4 GB, модели около 2.2 GB); на этой машине образ не собирался из-за свободного места на диске.
|
||||
|
||||
| Переменная | По умолчанию | Назначение |
|
||||
| --- | --- | --- |
|
||||
| `ML_EMBEDDER` | `giga` в образе и Compose, `none` вне образа | `giga` - модель из образа, `fake` - детерминированный хеш-кодировщик для стендов без модели (его model id не совпадает с политикой, векторы не используются), `none` - сервис не готов |
|
||||
| `ML_EMBEDDER` | `giga,qwen3` в образе и Compose, `none` вне образа | список моделей через запятую (`giga`, `qwen3`), первая отвечает на запрос без `model`; `fake` - детерминированный хеш-кодировщик для стендов без моделей (его model id не совпадает с политикой, векторы не используются), `none` - сервис не готов |
|
||||
| `ML_SERVICE_TOKEN` или `ML_SERVICE_TOKEN_FILE` | пусто | общий bearer-токен с backend (не короче 32 печатных символов, секрет); без него сервис отвечает только клиентам с loopback и не стартует на не-loopback адресе |
|
||||
| `ML_LISTEN_HOST`, `ML_LISTEN_PORT` | 127.0.0.1, 8000 (в образе 0.0.0.0, 8000) | адрес и порт `python -m lincodex_ml.serve` |
|
||||
| `ML_GIGA_MODEL_DIR`, `ML_QWEN3_MODEL_DIR` | каталоги образа | файлы моделей; каталог снимка Hugging Face тоже подходит |
|
||||
| `ML_GIGA_MODEL_LOCK`, `ML_QWEN3_MODEL_LOCK` | `model.lock.json` в каталоге модели | lock-файл, по которому сверяются файлы |
|
||||
| `ML_DEVICE` | `cpu` | `cpu`, `cuda` или `cuda:<номер>` |
|
||||
| `ML_DTYPE` | `float32` | `float16` и `bfloat16` только на CUDA |
|
||||
| `ML_CUDA_MEMORY_LIMIT_MB` | 0 (без предела) | предел аллокатора CUDA процесса; контекст CUDA добавляет около 130 MiB |
|
||||
| `ML_EXIT_ON_LOAD_FAILURE` | false | завершить процесс после ошибки загрузки, кроме нехватки видеопамяти, чтобы supervisor его перезапустил |
|
||||
| `ML_TORCH_THREADS` | 4 | потоки torch; при 4 потоках исследование выполняет цели CPU |
|
||||
| `ML_MICRO_BATCH` | 1 | размер микропакета; 1 дает каждому тексту одинаковый вектор при любом составе запроса |
|
||||
| `ML_MAX_TOKENS` | 1024 | токенов на текст, как в исследовании |
|
||||
| `ML_VERIFY_WEIGHTS` | true | сверять SHA-256 весов при старте |
|
||||
|
||||
Лимиты контейнера: 4 CPU и 5 GiB (float32-модель занимает около 3.6 GiB резидентной памяти). Readiness становится 200 только после загрузки и прогрева.
|
||||
Лимиты контейнера: 4 CPU и 8 GiB (на CPU в float32 Giga занимает около 3.6 GiB резидентной памяти, Qwen3-Embedding еще около 2.5 GiB). Readiness становится 200 только после загрузки и прогрева обеих моделей. Нехватка памяти устройства процесс не роняет: загрузка повторяется, запрос получает 503, `/readyz` 30 секунд отвечает 503.
|
||||
|
||||
make -C deploy ml-config
|
||||
make -C deploy ml-build
|
||||
@@ -549,14 +558,29 @@ ML имеет отдельный Compose-файл и проект; Redis и Seaw
|
||||
make -C deploy ml-logs
|
||||
make -C deploy ml-down
|
||||
|
||||
Для разработки без Docker: `make -C ml model-fetch` скачивает и проверяет те же файлы в `ML_MODEL_DIR` (по умолчанию `~/.cache/lincodex-ml/giga-480m`), `make -C ml test-model` проверяет совпадение векторов с исследованием. Замер на Apple M5 (CPU, 4 потока, HTTP, 20 запросов): представление потребности 887 символов p50 296 мс / p95 707 мс, профиль 500 символов 207 / 237 мс, короткое требование 74 / 166 мс, пакет задания карточки из 13 текстов 2.2 / 5.4 с. Это один ноутбук с другими нагрузками, а не замер стенда.
|
||||
Для разработки без Docker: `make -C ml model-fetch` скачивает и проверяет те же файлы в `ML_GIGA_MODEL_DIR` и `ML_QWEN3_MODEL_DIR` (по умолчанию `~/.cache/lincodex-ml/giga-480m` и `~/.cache/lincodex-ml/qwen3-0.6b`), `make -C ml test-model` сверяет векторы обеих моделей с исследованием (`ML_TEST_DEVICE=cuda` - на GPU). Замер Giga на Apple M5 (CPU, 4 потока, HTTP, 20 запросов): представление потребности 887 символов p50 296 мс / p95 707 мс, профиль 500 символов 207 / 237 мс, короткое требование 74 / 166 мс, пакет задания карточки из 13 текстов 2.2 / 5.4 с. Это один ноутбук с другими нагрузками, а не замер стенда.
|
||||
|
||||
## ML-сервис на GPU-хосте
|
||||
|
||||
На отдельном GPU-хосте сервис работает без Docker: под пользователем сервиса как systemd user-юнит `lincodex-ml.service` (шаблон [deploy/ml-gpu/lincodex-ml.service](../../deploy/ml-gpu/lincodex-ml.service), для пользователя включен linger) с virtualenv и моделями из локальных файлов. Обе модели в float16 занимают 2.2-2.4 GiB видеопамяти, поэтому сервис помещается рядом с другим потребителем той же карты.
|
||||
|
||||
1. Код: каталог `ml/` выпуска (`git archive`) в `~/lincodex-ml/app/ml`.
|
||||
2. Virtualenv: закрепленный uv 0.12.22 создает `~/lincodex-ml/venv`. `make -C ml cuda-requirements` пишет в `ml/dist/requirements-cuda.txt` закрепленные в `uv.lock` версии с CUDA-сборкой torch (`torch==2.11.0+cu128`); сначала поставьте строку torch с индекса `https://download.pytorch.org/whl/cu128`, затем остальные строки с PyPI (`uv pip install --python ~/lincodex-ml/venv/bin/python ...`). Общий кэш uv с `UV_LINK_MODE=hardlink` не занимает места под уже скачанные колеса, но кэш делится по адресу индекса: другое написание адреса скачивает torch и библиотеки CUDA заново (около 6 GB). Исключение: при нехватке диска virtualenv использует системный CPython 3.12 с теми же версиями пакетов (колесо torch для cp314 с CUDA не помещается), а пакет не устанавливается: юнит задает `PYTHONPATH` на `src`. Модульные тесты сервиса проходят на 3.12, но 3.14 остается основной версией, поэтому синтаксис 3.13+ в `ml/src` сломает этот хост.
|
||||
3. Модели: каталоги снимков Hugging Face на закрепленных ревизиях (`HF_HOME` только для чтения) или `make -C ml model-fetch`; при старте файлы сверяются с lock-файлами выпуска.
|
||||
4. Настройки: [deploy/ml-gpu/ml.env.example](../../deploy/ml-gpu/ml.env.example) копируется в `~/.config/lincodex-ml/ml.env` (каталог 700, файл 600). Токен генерируется на хосте CSPRNG (`python3 -c 'import secrets; print(secrets.token_hex(32))'`) и хранится только в этом файле и в окружении backend. Адрес - приватный адрес хоста, не 0.0.0.0.
|
||||
5. Запуск: шаблон юнита в `~/.config/systemd/user/lincodex-ml.service`, затем `systemctl --user daemon-reload` и `systemctl --user enable --now lincodex-ml.service`. Перезапуск после обновления кода или настроек - `systemctl --user restart lincodex-ml.service`, состояние - `systemctl --user status lincodex-ml.service`, журнал - `journalctl --user -u lincodex-ml.service -f`. Юнит задает `Restart=on-failure`, `MemoryHigh=5G`, `MemoryMax=6G`, `CPUQuota=400%`, 4 потока torch и OMP и `ML_EXIT_ON_LOAD_FAILURE=true`: нехватка видеопамяти не роняет процесс, а другие ошибки загрузки (например, недоступный драйвер при старте хоста) завершают его, и systemd перезапускает его через 15 секунд.
|
||||
6. Сеть: firewall и системные настройки юнит не меняет. Ограничьте порт адресом хоста приложения на уровне хоста или сети; трафик идет по LAN без TLS, поэтому токен и тексты видны в этом сегменте.
|
||||
|
||||
Точность и видеопамять (RTX 5060 Ti 16 GB, замер 2026-10-11, бюджет процесса около 2.5 GB): в float32 одна Giga занимает 1984 MiB после загрузки и до 2750 MiB под запросом из текстов по 1024 токена, Qwen3 - 2404 и 3038 MiB, вместе около 4.3 GiB после загрузки, поэтому float32 не помещается. В float16 обе модели в одном процессе занимают 2252 MiB после загрузки и 2404 MiB под худшим запросом (32 текста по 1024 токена), аллокатор ограничен `ML_CUDA_MEMORY_LIMIT_MB=2300`. Качество float16 против float32 на DEV исследования (продуктовые представления): косинус векторов не ниже 0.99986 (Giga) и 0.99999 (Qwen3), nDCG@10 изменился на -0.0004 и +0.0008, у ансамбля на +0.0002 (порог 0.005), top-10 ансамбля совпадает как множество для 30 из 30 потребностей DEV и по порядку для 28, повторное кодирование при микропакете 1 дает те же биты. `bfloat16` отклонен: top-10 совпадает для 27 из 30, порядок для 14. Поэтому `ML_DTYPE=float16`; mean, std и калибровка ансамбля посчитаны на векторах float16.
|
||||
|
||||
Задержка через LAN с хоста приложения (40 запросов, один текст, микропакет 1, CUDA float16): представление потребности - Giga p50 11.4 / p95 13.0 мс, Qwen3 12.5 / 14.5 мс; профиль - 11.2 / 12.9 и 12.1 / 13.8 мс; пакет задания карточки из 13 текстов - 132 / 135 и 143 / 160 мс. Резидентная память процесса около 2.6 GiB (пик 2.9 GiB). Это замер одного хоста, когда другая модель на карте не была загружена, а не нагрузочный тест.
|
||||
|
||||
## Семантический подбор
|
||||
|
||||
Поиск не вызывает ML: он читает векторы, которые фоновые задания посчитали заранее (см. [ARCHITECTURE.md](ARCHITECTURE.md#семантический-слой-и-объяснения)). Включение на стенде:
|
||||
|
||||
1. `make -C deploy up`, затем `make -C deploy ml-up` и дождаться `/readyz` 200.
|
||||
2. В `.env` стенда задать `SEMANTIC_MATCHING_ENABLED=true` (и при отличии `ML_SERVICE_URL`), перезапустить backend (`make -C deploy up`).
|
||||
1. `make -C deploy up`, затем `make -C deploy ml-up` (или [ML-сервис на GPU-хосте](#ml-сервис-на-gpu-хосте)) и дождаться `/readyz` 200.
|
||||
2. В `.env` стенда задать `SEMANTIC_MATCHING_ENABLED=true`, `ML_SERVICE_TOKEN` (тот же токен, что у ML-сервиса) и при отличии `ML_SERVICE_URL` (для GPU-хоста - `http://<адрес>:<порт>`), перезапустить backend (`make -C deploy up`).
|
||||
3. Опубликовать семантический раздел политики: `make -C backend policy-publish ARGS='semantic --actor operator:<handle>'` (с `DATABASE_URL` стенда). Новая версия политики, как и раздел `matching`, требует заново открыть и аттестовать категорию на демонстрационном стенде.
|
||||
4. Посчитать векторы существующих данных: `make -C backend semantic-backfill ARGS='all --run <метка>'`. Команде нужен только `DATABASE_URL`; она ставит задания постранично и печатает курсор, с которого продолжить (`--after`). Повтор с той же меткой ничего не ставит повторно; новая метка пересчитывает, а неизменившиеся тексты ML не вызывают. Задания выполняет worker backend.
|
||||
|
||||
@@ -564,6 +588,7 @@ ML имеет отдельный Compose-файл и проект; Redis и Seaw
|
||||
| --- | --- | --- |
|
||||
| `SEMANTIC_MATCHING_ENABLED` | false | ставить и выполнять задания векторов |
|
||||
| `ML_SERVICE_URL` | `http://ml:8000` в Compose | origin ML без пути и учетных данных |
|
||||
| `ML_SERVICE_TOKEN` | пусто | bearer-токен ML-сервиса, 32-512 печатных символов без пробелов; обязателен при `SEMANTIC_MATCHING_ENABLED=true`; секрет, в логи не попадает |
|
||||
| `ML_REQUEST_TIMEOUT` | 30s | таймаут одного запроса к ML |
|
||||
| `ML_CIRCUIT_FAILURES`, `ML_CIRCUIT_OPEN` | 3, 30s | после стольких подряд неудач клиент не вызывает ML указанное время |
|
||||
| `GITHUB_REPOSITORY_CHECKS_ENABLED` | false | выполнять проверки репозиториев проектов на `api.github.com` |
|
||||
@@ -573,7 +598,13 @@ ML имеет отдельный Compose-файл и проект; Redis и Seaw
|
||||
|
||||
Без ML или при его недоступности поиск работает как раньше: нейтральное `Sem` 0.5 и флаг `ml_unavailable`; задания повторяются до 20 раз и потом ждут оператора (повторный backfill). Изолированный браузерный стенд (e2e) ML не запускает и использует политику V4; демонстрационный стенд по умолчанию тоже работает без ML, включение на нем - те же шаги, что выше, с проектом `lincodex-demo`. Метрики: `lincodex_scheduled_jobs_total{kind="semantic.candidate"|"semantic.need"|"profile.repository_check"}` в backend, `lincodex_ml_embedding_request_seconds` и `lincodex_ml_embedding_texts_total` в ML.
|
||||
|
||||
Ансамбль моделей (Giga + Qwen3-Embedding-0.6B) не включен; порядок включения - вторая модель в ML-сервисе, 8 потоков, калибровка слитого балла, новая политика с двумя `members` и backfill - описан в [ARCHITECTURE.md](ARCHITECTURE.md#семантический-слой-и-объяснения). Векторы модели, которую политика больше не называет, поиск не читает; они остаются для отката на прошлую версию политики.
|
||||
Ансамбль Giga + Qwen3-Embedding-0.6B (см. [ARCHITECTURE.md](ARCHITECTURE.md#семантический-слой-и-объяснения)) включается после шагов выше, когда ML-сервис обслуживает обе модели (`ML_EMBEDDER=giga,qwen3`):
|
||||
|
||||
1. `make -C backend policy-publish ARGS='semantic-ensemble --actor operator:<handle>'` - новая версия политики с двумя моделями; версия с одной Giga остается предыдущей.
|
||||
2. Сразу после этого `make -C backend semantic-backfill ARGS='candidates --run <метка>'` и `make -C backend semantic-backfill ARGS='needs --run <метка>'` (или `all`). Задания считают векторы каждой модели действующей политики: векторы Giga не меняются и ML не вызывают, для Qwen3 кодируется только `whole` каждой карточки и потребности. До конца backfill записи без векторов Qwen3 получают нейтральное `Sem` с `ml_unavailable`, поэтому переход лучше проводить в тихое время.
|
||||
3. Проверка: `SELECT model_id, count(*) FROM semantic_vectors WHERE item_key = 'whole' GROUP BY model_id` - число векторов Qwen3 догоняет число векторов Giga.
|
||||
|
||||
Происхождение значений политики: DEV-разметка исследования LincodexMatch (30 потребностей, 3220 размеченных пар), профили и потребности исследования, отрендеренные продуктовым построителем представлений, векторы ML-сервиса на CUDA в float16, веса из шага 5 исследования; скрипты кодирования и расчета и их выводы хранятся рядом с исследовательским прогоном на GPU-хосте (`lincodex-ml/eval/`). Векторы модели, которую политика больше не называет, поиск не читает; они остаются для отката на прошлую версию политики.
|
||||
|
||||
## Отдельный monitoring Compose
|
||||
|
||||
|
||||
+1
-1
@@ -47,7 +47,7 @@ Gitleaks требует полный Git checkout. Отсутствие репо
|
||||
- GitHub. Проверка репозиториев проектов обращается только к `https://api.github.com`: адрес в профиле принимается только в форме `https://github.com/<owner>/<repo>`, владелец и имя проверяются по шаблонам GitHub и экранируются в путь, базовый origin зашит в коде (тесты подменяют его только внутри пакета), прокси из окружения не используется, TLS 1.2+, таймауты соединения и ответа, редирект допускается только на тот же origin (не больше трех), ответы ограничены 1 MiB, README - 64 KiB. Поэтому пользовательский ввод не может направить сервер на другой хост (SSRF). Проверки выключены по умолчанию (`GITHUB_REPOSITORY_CHECKS_ENABLED`), повторная проверка ограничена на кандидата (`REPOSITORY_CHECK_INTERVAL`), лимит GitHub соблюдается по заголовкам.
|
||||
- Токен. `GITHUB_TOKEN` необязателен, нужен только для чтения публичных данных и отправляется только на `api.github.com`; он не попадает в логи, ошибки, задания и базу. Журнал проверки содержит id задания, попытку, состояние и класс ошибки, но не репозиторий; ключ и payload задания несут только дайджест репозитория.
|
||||
- Данные GitHub. Описание, темы, языки и текст README - недоверенные данные: README превращается в простой текст, хранится только для публичного репозитория, используется только для ранжирования и никогда не выводится, тем более как HTML. Адрес и владелец репозитория не попадают организации ни в карточке, ни в объяснении, ни после C4.
|
||||
- ML. Сервис доступен backend только по сети Compose (`http://ml:8000`), порт на хосте - loopback; учетных данных у него нет, поэтому сеть - его граница. Backend передает в ML только тексты опубликованной карточки и потребности организации, без контактов и приватного профиля. Веса берутся из образа по SHA-256, удаленный код модели не исполняется, pickle не загружается, сервис работает офлайн.
|
||||
- ML. Все маршруты сервиса, кроме `/healthz` и `/readyz`, требуют `Authorization: Bearer <token>`: общий случайный токен не короче 32 печатных символов (`ML_SERVICE_TOKEN` у backend, `ML_SERVICE_TOKEN` или `ML_SERVICE_TOKEN_FILE` у сервиса) сравнивается за постоянное время и не попадает в логи, ответы и сообщения об ошибках; неверный или отсутствующий токен получает 401 `unauthenticated`, а запрос отклоняется до чтения тела. Без токена сервис отвечает только клиентам с loopback, а точка входа `python -m lincodex_ml.serve` отказывается слушать не-loopback адрес; backend без токена не включает семантический подбор. В Compose сервис доступен backend по сети `http://ml:8000`, порт на хосте - loopback; на GPU-хосте он слушает приватный адрес LAN без TLS, поэтому ограничьте порт адресом хоста приложения средствами хоста или сети. `/metrics` тоже требует токен. Backend передает в ML только тексты опубликованной карточки и потребности организации, без контактов и приватного профиля. Веса берутся по lock-файлам с SHA-256, удаленный код моделей не исполняется, pickle не загружается, сервис работает офлайн.
|
||||
|
||||
## CI и границы проверок
|
||||
|
||||
|
||||
+3
-1
@@ -645,9 +645,11 @@ Vitest работает в Node без DOM, поэтому ограничени
|
||||
## Тесты семантического подбора
|
||||
|
||||
- ML-сервис (`make -C ml test`, без модели и сети): `tests/test_embeddings.py` проверяет контракт `POST /v1/embeddings` на детерминированном хеш-кодировщике: порядок ответа, нормировку, одинаковые векторы двух одинаковых запросов, микропакеты по длине, 503 `service_unavailable` до готовности и ready только после прогрева, 400 на лишние тексты, длину и неизвестные поля, 413 на тело больше лимита (с Content-Length и потоком), отсутствие текстов запроса в логах; `tests/test_model_files.py` проверяет lock-файл (только safetensors и конфиги, полная ревизия, без кода и pickle) и сверку размера и SHA-256.
|
||||
- Реальная модель: `make -C ml model-fetch` и `make -C ml test-model` (маркер `slow`, обычные проверки его пропускают) сверяют векторы Giga-480M на CPU с векторами исследования для четырех текстов (разница меньше 1e-4, измерено меньше 1e-6) и повторное кодирование (тот же вектор). Это проверка воспроизводимости рецепта, а не оценка качества.
|
||||
- Ансамбль и токен ML (`make -C ml test`): `tests/test_ensemble_and_auth.py` проверяет выбор одной из нескольких загруженных моделей полем `model` и 400 для чужой, готовность только после всех моделей, отказ от двух кодировщиков с одним id, 503 и остывание readiness после нехватки видеопамяти с восстановлением, повтор загрузки при нехватке памяти и выход по `ML_EXIT_ON_LOAD_FAILURE` при другой ошибке, 401 без токена, с неверным токеном, со схемой Basic и на `/metrics`, открытые `/healthz` и `/readyz`, только loopback без токена, отказ до чтения тела, отсутствие токена в логах и ошибках настроек, отказ точки входа слушать не-loopback адрес без токена. На CUDA вручную проверено: загрузка при нехватке памяти повторяется, процесс жив и не готов; запрос сверх предела аллокатора получает 503, `/readyz` 30 секунд отвечает 503, затем сервис снова отвечает 200.
|
||||
- Реальные модели: `make -C ml model-fetch` и `make -C ml test-model` (маркер `slow`, обычные проверки его пропускают) сверяют векторы Giga-480M и Qwen3-Embedding-0.6B с векторами исследования для четырех текстов (разница меньше 1e-4) и повторное кодирование (тот же вектор); `ML_TEST_DEVICE=cuda` запускает их на GPU в float32. 2026-10-11 обе модели прошли и на CPU, и на CUDA на GPU-хосте. Это проверка воспроизводимости рецепта, а не оценка качества; сравнение точности float16 с float32 и расчет политики ансамбля - отдельная оценка на DEV исследования (см. [DEPLOY.md](DEPLOY.md#ml-сервис-на-gpu-хосте)).
|
||||
- Backend unit: представления потребности и карточки (`domain/semantic_test.go`: точный текст исследования, только подтвержденные значения, метаданные только у проверенного репозитория), кодек float32 и косинус, калибровка (интерполяция, ступени, монотонность демонстрационной таблицы), пороги, проверка и круговой проход документа политики V5; проекты и адрес GitHub (`domain/candidate_project_test.go`: допустимые и отклоненные адреса, нормализация, лимиты, повтор репозитория, отсутствие адреса в карточке); выбор объяснения (`usecase/matching/semantic_test.go`: порядок, лимит, устаревшее название, скрытые стек и проекты не объясняют, запись поля `projects`); Fit с известным и нейтральным Sem; клиент ML (пакеты по 32, проверка ответа, circuit breaker, отсутствие текста в ошибках); GitHub (`adapter/secondary/github`: httptest, только публичный репозиторий, токен только когда задан, ETag и 304, лимиты 403/429 с ожиданием, ошибки сервера, отказ от редиректа на другой origin, ограничения размера, текст README без разметки и HTML); задания и триггер (ключи и payload без адреса репозитория, отключенные функции ничего не ставят).
|
||||
- Интеграция (Testcontainers): `TestSemanticMatchingOverHTTP` проходит через HTTP, PostgreSQL и настоящий worker заданий с фиктивным ML-сервисом (httptest по контракту) и фиктивным GitHub: сохранение профиля ставит задания без адреса в ключах, проверка репозитория и векторы карточек, нейтральный Sem и флаг до векторов потребности, затем первым идет кандидат с близким проектом, объяснение называет проект и `repository_verified`, а в ответе и карточке нет адреса и владельца репозитория; одинаковые ответы двух поисков; история доступа с полем `projects`; повторный backfill с той же меткой ничего не ставит дважды и не вызывает ML для неизменных текстов; снятие поля `projects` удаляет векторы проектов и название из объяснения; недоступный ML оставляет задание в повторе, а поиск отвечает; лимит повторной проверки (429, затем 202).
|
||||
- Ансамбль и токен в backend: unit-тесты `domain/policy_matching_ensemble_test.go` (политика ансамбля проходит проверку, объясняет Giga с ее порогами, слитый балл в среднем равен 0, калибровка монотонна и обрезана, круговой проход документа V6), `usecase/policy` (публикация ансамбля поверх V5, повтор ничего не публикует, одиночная команда не трогает ансамбль), `cli/policypublish` (трек `semantic-ensemble`), `adapter/secondary/ml` (bearer-токен в каждом запросе, 401 как недоступность без текста токена, клиент без токена не создается), `config` (токен обязателен при включенном подборе, короткий и с пробелами отклоняются, форматирование настроек токены скрывает). В `TestSemanticMatchingOverHTTP` фиктивный ML требует токен и обслуживает обе модели; после публикации ансамбля и до backfill у всех записей нейтральное `Sem`, backfill добавляет векторы `whole` Qwen3 для шести карточек и потребности без повторного кодирования Giga и без векторов элементов Qwen3, после чего у всех записей `Sem` известен.
|
||||
- Не проверено: качество ранжирования и точность объяснений на реальных данных, задержка на рабочем сервере, сборка образа ML на этой машине и запуск стенда с моделью. Внешний GitHub в тестах не вызывается.
|
||||
|
||||
## Будущая программная валидация
|
||||
|
||||
Reference in new issue
Block a user