feat(matching): rank with semantic embeddings and explain matches by evidence

This commit is contained in:
shira committed 2026-10-11 10:39:46 +03:00
1 parent facc1789b1
commit 24b64d698a
215 files changed
+16951 -327

No files matched your search

+27 -6
View File
@@ -767,7 +767,7 @@ What the checks cover: the fixture tests run the client against a local TLS 1.3
## Matching and explanations
Implemented as a deterministic search without ML: `POST /api/v1/organizations/{org_id}/matches` (`SearchOrganizationMatches`, [api/README.en.md](../../api/README.en.md#match-search)). Code: the usecase `backend/internal/usecase/matching/` (`search.go` the flow, `filter.go` the filters, `score.go` the integer scoring, `explain.go` the explanation), the card list `candidateview.Service.ListVisibleCards`, the policy section `domain.MatchingPolicy` (`policy_matching.go`), the skill relations `domain.RelateEvidenceSkill` (`evidence_relation.go`), the handler `adapter/primary/http/v1/matches.go`, and the wiring `bootstrap/matches.go`. There is no new table, migration, or query file: the search reuses the barrier queries that the card and the evidence already use, so there is one copy of the visibility rule.
Implemented as a deterministic search that never calls ML and reads precomputed vectors (see [Semantic layer and explanations](#semantic-layer-and-explanations)): `POST /api/v1/organizations/{org_id}/matches` (`SearchOrganizationMatches`, [api/README.en.md](../../api/README.en.md#match-search)). Code: the usecase `backend/internal/usecase/matching/` (`search.go` the flow, `filter.go` the filters, `score.go` the integer scoring, `explain.go` the explanation), the card list `candidateview.Service.ListVisibleCards`, the policy section `domain.MatchingPolicy` (`policy_matching.go`), the skill relations `domain.RelateEvidenceSkill` (`evidence_relation.go`), the handler `adapter/primary/http/v1/matches.go`, and the wiring `bootstrap/matches.go`. Visibility has no new query: the search reuses the barrier queries that the card and the evidence already use, so there is one copy of the visibility rule.
- Access before ranking. The search is one transaction. The owner role is checked under the membership lock before any card is read. `ListVisibleCards` then runs the checks of a card read: verified employer, then `ListVisibleCandidateViewSources`, which selects from `candidate_effective_publications` (published and backed by an unrevoked C2) and excludes the candidates that hide the reading organization with `NOT EXISTS` over `candidate_hidden_organizations`; then the account, C2, and publication locks, and the anonymous projection with its minimum cohort of five. The list is therefore exactly the set of handles that `GetOrganizationCandidateCard` opens at that moment: a card that the cohort rules suppress is not searched, a revoked C2, a closed publication, or a hidden organization takes effect on the next request, and nothing is cached or stored. The permitted evidence is read only through the organization-safe batch query `ListOrganizationVisibleEvidenceBatch` (one statement for the whole candidate set, with the barriers of the single read: the effective publication view, `NOT EXISTS` over the hiding, the `categories` field, visible measurements), and only when the request names skills. The locks are those of the card read and nothing else is locked; the writes of the search are limited to the candidates it returns.
- Owner only. For the MVP milestone the active owner of the organization searches. The HTTP boundary refuses every other role (`ownerCompanyOperations`), and the usecase repeats the role check under the membership lock, so a membership alone grants nothing. The full role and assignment matrix is later work and must not widen rights by one membership.
@@ -777,7 +777,7 @@ Implemented as a deterministic search without ML: `POST /api/v1/organizations/{o
- Filters, all applied before scoring. `confirmed_grade`, `confirmed_category`, and `confirmation_status: confirmed` keep only confirmed entries; a declared grade never satisfies them. `declared_grade` is a separate claim. `stack` requires every named tag in the card and also counts as a required skill of the request. `conditions.work_formats` needs one common format, and `conditions.salary_compatibility` needs the same value; an unknown card value never satisfies a condition. An unconfirmed category alone hides nothing: without a confirmed filter the declared specializations are listed.
- Requested skills. The skills of the Cov come from the confirmed required (weight 2) and desired (weight 1) skills of the need snapshot, with the tags of the `stack` filter as required. A code is counted once however often it is repeated. A skill without a taxonomy code has no reviewed mapping, matches nothing, and is a gap. An empty request uses the neutral Cov 0.5 instead of dividing by zero. The need is read by `requirements_version` (`GetVersion`); a general version that only changed the title is not a requirements snapshot and answers 404, and the snapshot of an older requirements version stays searchable and unchanged.
- Evidence of a skill. Each requested skill takes the best product of the trust, attribution, and relation coefficients over the permitted evidence, not their sum. The evidence is the stated stack tags of the card (trust 0, a claim) and, for a confirmed entry, the one assessment fact that supports its category (trust 1, personal). The relation is exact for the same code, broader for a specialization over a technology, and narrower the other way, by the `skill_taxonomy` of the policy version (demo: `backend` over `docker`, `go`, `kafka`, `postgresql`; `devops_sre` over `docker`); a version without a taxonomy relates only equal codes, so the version fully determines the result. The taxonomy is a demonstration mapping, not a measured one. An online Backend result is worth 0.6 * 1.0 * 0.4 = 0.24 for a requested Go and a stated Go tag 0.25; the near threshold is 0.25, so a candidate whose only evidence for a required technology is a Backend assessment is always in `near` for it, and a stated tag alone is enough to be in `main`. That consequence of the PRD values is an owner question. Repeating a tag or a skill adds nothing.
- Components and groups. `Cov` is the weighted mean of the contributions; `Dom = 0.5` (the anonymous card carries no domain) and `Sem = 0.5` for every entry (no ML), both named in `unknown_flags`; `T = 0.5` with a null percentile and the flag `cohort_below_30`, which the search proves instead of declaring: it counts the candidates who hold each returned category from a source other than a synthetic demonstration (`CountRealComparableCategories`, counts only) and compares the count with `percentile_min_cohort`; today the count is 0 because every stored category is a synthetic demonstration, which is never mixed with real results. A real cohort at the minimum would need the theta of its members, which the organization-safe projection does not carry, so the search never fails for it: T stays the neutral 0.5, the percentile stays null, the reason becomes `percentile_not_computed` instead of `cohort_below_30`, and the search logs one warning for each such category. Only the categories of the entries that passed the filters are counted; `V = 0` because no competition data exists, which is neither a penalty nor an unknown; `Fr = Rsp = 0.5` with the flags `no_freshness_history` and `no_response_history`. A confirmed entry with a required skill below the near threshold (0.25) is in `near`, otherwise in `main`; an unconfirmed entry is in `unconfirmed` with only Fit and Coverage, computed by a separate path that never calculates theta, T, P, a percentile, or S. The absence of FSP is not scored anywhere.
- Components and groups. `Cov` is the weighted mean of the contributions; `Dom = 0.5` (the anonymous card carries no domain) and `Sem = 0.5` for an entry without stored vectors, both named in `unknown_flags`; `T = 0.5` with a null percentile and the flag `cohort_below_30`, which the search proves instead of declaring: it counts the candidates who hold each returned category from a source other than a synthetic demonstration (`CountRealComparableCategories`, counts only) and compares the count with `percentile_min_cohort`; today the count is 0 because every stored category is a synthetic demonstration, which is never mixed with real results. A real cohort at the minimum would need the theta of its members, which the organization-safe projection does not carry, so the search never fails for it: T stays the neutral 0.5, the percentile stays null, the reason becomes `percentile_not_computed` instead of `cohort_below_30`, and the search logs one warning for each such category. Only the categories of the entries that passed the filters are counted; `V = 0` because no competition data exists, which is neither a penalty nor an unknown; `Fr = Rsp = 0.5` with the flags `no_freshness_history` and `no_response_history`. A confirmed entry with a required skill below the near threshold (0.25) is in `near`, otherwise in `main`; an unconfirmed entry is in `unconfirmed` with only Fit and Coverage, computed by a separate path that never calculates theta, T, P, a percentile, or S. The absence of FSP is not scored anywhere.
- Order and rounding. Scores are integers in micro units (six decimals), the shares are basis points, and the products are exact integers, so the same data and policy give the same order on every platform. `main` and `near` sort by S, then Cov (both descending), then the internal candidate identifier ascending (then the specialization code, which only separates two entries of one candidate); `unconfirmed` sorts by Fit, then Cov, then the identifier. The identifier never leaves the server, and the groups are not merged on one scale.
- Explanation. The summary and the flags are built from the same computed contributions: per skill group `supports` (every skill carried by a measurement at or above the threshold), `declared_only` (only stated tags), `partial` (a mix, or measurements below the threshold), or `gap` (nothing), plus the confirmed category, the declared grade, the work-format match against the need or the filter, and the salary compatibility. It uses bounded codes only, never free text, a contact, a candidate location, a salary value or minimum, a failed attempt, or a reason for withheld data. An unknown component appears only in `unknown_flags`.
- Policy. The search reads the effective `product` policy at the application time and its `matching` section. A policy without the section fails closed with an internal error (the ProblemCode enum has no code for a temporarily unavailable dependency, and none is added); the error log says that the effective product policy has no matching section and names the `policy-publish` operator command, the backend logs a warning at startup while the section is missing, and [DEPLOY.md](DEPLOY.md#match-search-policy-on-a-stand) describes the command. The response does not name the policy version, and no search is stored.
@@ -785,15 +785,36 @@ Implemented as a deterministic search without ML: `POST /api/v1/organizations/{o
- Accepted residual risks. `truncated` is one bit about the size of the visible bank (it says that more than the limit or the allowance exists) and the response time grows with the bank, so both leak a coarse size to the owner. The bit is bounded by the group limit and no count is returned; the risk is accepted for the demonstration and is listed with the owner questions.
- Checks. `internal/usecase/matching` unit tests (formulas with hand-computed values, ties and ordering, filters, explanation, the cut and the charge of the output), `internal/domain/policy_matching_test.go` (document round trip, strictness, validation), `v1/matches_test.go` (mapping and problems), and the integration test `TestMatchSearchOverHTTP` against PostgreSQL: hidden candidates and two organizations, a need and its edited requirements, repeated identical responses, Backend confirmed and Networks unconfirmed for one handle, a profile published without a grade through the real profile, consent, and publication operations and removed by a C2 revocation, a candidate alone in its cohort, no contact or identifier in the body, the charge and the access history of a search, an organization with an allowance smaller than its bank, the group limit, the batch evidence read, two concurrent searches under one allowance, the demo group limit, the policy taxonomy, the denials, and the policy without the section.
Not implemented: the percentile and a real T (they need the theta of a comparable real cohort of at least 30 people); the competition value V and the FSP data; the domain of a candidate; freshness and responsiveness histories; semantic similarity and the ML fallback flag beyond the neutral value; the stored `search_run` snapshots, refinement, comparison, and the shortlist; paging beyond the group limit; and the use of the grade of a need as a filter. Sending an invitation from a search result is not implemented either, so the revocation of C2 after an invitation is not checked here; the draft of an invitation resolves a handle of the search result through the same visibility barrier (see [Invitation drafts](#invitation-drafts)).
Not implemented: the percentile and a real T (they need the theta of a comparable real cohort of at least 30 people); the competition value V and the FSP data; the domain of a candidate; freshness and responsiveness histories; the stored `search_run` snapshots, refinement, comparison, and the shortlist; paging beyond the group limit; and the use of the grade of a need as a filter. Sending an invitation from a search result is not implemented either, so the revocation of C2 after an invitation is not checked here; the draft of an invitation resolves a handle of the search result through the same visibility barrier (see [Invitation drafts](#invitation-drafts)).
Before ranking, Go applies hard filters: published profile, specialty, verified grade, required skills, and other selected criteria. A strong resume or achievement cannot compensate for a missing mandatory requirement. Distinguish an unverified skill from evidence that the skill is absent. This is the first model, not an optimized or measured ranking: the plan compares keyword search, the verified-skill baseline, and an ML variant, adds a semantic signal only after an experiment, and never treats its score as a probability of hiring success.
Before ranking, Go applies hard filters: published profile, specialty, verified grade, required skills, and other selected criteria. A strong resume or achievement cannot compensate for a missing mandatory requirement. Distinguish an unverified skill from evidence that the skill is absent. This is the first model, not an optimized or measured ranking: the plan compares keyword search, the verified-skill baseline, and an ML variant, added the semantic signal after the study (see [Semantic layer and explanations](#semantic-layer-and-explanations)), and never treats its score as a probability of hiring success.
Store each search as a search_run with its company, original need, filters, ranking version, and parent version. Refinement creates another snapshot. search_items stores order, scores, and profile versions without contacts. An old snapshot does not preserve access: hidden or removed profiles disappear, stale ranking is marked, and retention is bounded. This is planned; the implemented search stores nothing.
### Semantic layer and explanations
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.
- 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.
- 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
- Profile. Section `projects` (up to 10): a title up to 100 characters, a description up to 500, up to 10 stack tags, an optional repository address. Only `https://github.com/<owner>/<repo>` is accepted (a trailing slash and `.git` are removed; other hosts, ports, credentials, paths, queries, and fragments are rejected), each repository at most once. Projects are trust level 0 claims in `candidate_profile_claims` (kind `project`, migration `00048`) versioned with the profile through `expected_version`. A body without `projects` keeps them, so an older client never deletes them.
- Card. A new publication field `projects`: the card shows the title, description, tags, and `repository_verified`, never the repository address or owner. The title is the candidate's text and can identify them, so the field is a separate choice, takes no part in cohort generalization, and the client must warn about it (open owner question).
- Check. A new or changed address schedules `profile.repository_check`; `POST /api/v1/me/profile/repository-checks` repeats the checks of all repositories at most once per `REPOSITORY_CHECK_INTERVAL` (default 10 minutes, else 429). The job key and payload carry only a digest of the repository. The handler reads `api.github.com` (metadata, languages, the beginning of the README), stores the state `pending`, `verified`, `not_found`, or `unavailable` in `candidate_project_repositories`, ETags for conditional requests, and the metadata only while the repository is public. The README becomes plain text (no code, HTML, links, or URLs); up to 4000 characters are stored and up to 600 enter the card text for ranking; none of these fields is returned by the API or shown. A GitHub limit (403/429) stores `unavailable` and reschedules the check at the reset time (1 minute to 1 hour); network and server failures are retried by the worker. "Verified" means only "the repository exists and is public": authorship is not proven, and the owner is not compared with an account of the candidate.
- Contacts after C4. The repository address is not added to the C4 disclosure: the C4 consent in the ledger fixes a closed field set (`full_name`, `email`, `phone`, `telegram`, CHECK in `00009` and `00030`), and extending it needs a new consent text version and a ledger migration. Until the owner decides, an organization gets the address neither before nor after C4.
## ML, documents, and background jobs
Planned ML operations are resume analysis, need analysis, and, after the baseline, embeddings and limited reranking. Go sends only allowed inputs and a short candidate list. Responses are limited to known IDs and validated against schema and version. ML failure falls back to the baseline. Models cannot set categories or expose contacts.
Embeddings for matching are implemented (see [Semantic layer and explanations](#semantic-layer-and-explanations)). Further planned ML operations are resume analysis, need analysis, and limited reranking. Go sends only allowed inputs and a short candidate list. Responses are limited to known IDs and validated against schema and version. ML failure falls back to the baseline. Models cannot set categories or expose contacts.
Planned PDF flow: limit size, page count, and upload rate; validate file type and owner; save a source version; create a job in the same transaction; extract text in an isolated resource-limited environment; mask contacts; request a structured result; validate its size and versions; show proposed fields for candidate approval. A scan without a text layer reports that state and offers manual entry; OCR is a separate extension. Never log full resume text or traces.
@@ -979,7 +1000,7 @@ The changed version, complete claim set, period confirmations, and private histo
Tables:
- `candidate_profiles`: `user_id` (the primary key and a foreign key to `users` with `ON DELETE CASCADE`), `version` (positive; the first save creates version 1, and the contract's version 0 is the absence of a row), and times. The profile is personal data of the account and goes with it; retention rules are an open legal question.
- `candidate_profile_claims`: one row per stored claim - a single field (`full_name`, `contact_email`, `contact_phone`, `contact_telegram`, `terms_location`, `terms_relocation`, `terms_salary_minimum` at `ordinal` 0) or a list item (`stack` up to 30, `role` up to 9, `experience` up to 20, `soft_skill` up to 10, by position). Columns: `value` jsonb, `status` (`confirmed` or `extracted`), `origin` (`manual`, `extracted_from_resume`, `imported`), `trust_level`, `quote`, `extraction_version`, and `confirmed_at`. A field without a value has no row, so the contract's `unknown` is the absence of a row. The foreign key points at `candidate_profiles` with `ON DELETE CASCADE`.
- `candidate_profile_claims`: one row per stored claim - a single field (`full_name`, `contact_email`, `contact_phone`, `contact_telegram`, `terms_location`, `terms_relocation`, `terms_salary_minimum` at `ordinal` 0) or a list item (`stack` up to 30, `role` up to 9, `experience` up to 20, `soft_skill` up to 10, `project` up to 10, by position; projects are described in [Candidate projects and GitHub repositories](#candidate-projects-and-github-repositories)). Columns: `value` jsonb, `status` (`confirmed` or `extracted`), `origin` (`manual`, `extracted_from_resume`, `imported`), `trust_level`, `quote`, `extraction_version`, and `confirmed_at`. A field without a value has no row, so the contract's `unknown` is the absence of a row. The foreign key points at `candidate_profiles` with `ON DELETE CASCADE`.
Decisions:
+40 -4
View File
@@ -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: the core and demo stands do not start ML and do not call it. Search uses the neutral semantic similarity 0.5 and marks it with the `ml_unavailable` flag. `make -C deploy ml-up` starts a separate service without a model: `/healthz` answers 200 and `/readyz` 503. The core needs no GPU or external inference key and reads none.
- 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.
- 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
@@ -474,6 +474,7 @@ make -C backend policy-publish ARGS='matching --actor operator:<handle>'
- It needs only `DATABASE_URL`, reads no dotenv file, validates its arguments first, and prints the version number only. The author of the version is the `operator:<handle>` label, an audit label and not authentication: local database access is the operator boundary.
- 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.
## Isolated demo stand
@@ -508,16 +509,51 @@ What the seed creates (all names carry a synthetic marker; addresses are on `@de
## Separate ML Compose project
ML uses a separate Compose file and project; it does not require or start Redis or SeaweedFS in the current scaffold. Its default host bind is 127.0.0.1:8000. Set ML_BIND_ADDRESS only after choosing a private address and preparing firewall rules. Prometheus does not scrape remote ML while ML_METRICS_TARGET is empty.
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 ML image uses `python:alpine` and upgrades system packages during the build. Dependencies are installed with uv only in the build stage; the final runtime contains the prepared virtual environment without pip or ensurepip. Current dependencies support musl. Check Alpine compatibility before adding inference or GPU libraries; glibc-dependent libraries will require a different validated runtime.
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.
| 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_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.
make -C deploy ml-config
make -C deploy ml-build
make -C deploy ml-up
make -C deploy ml-logs
make -C deploy ml-down
GET /healthz checks the process. GET /readyz checks inference readiness and returns 503 while a model is unavailable. The current scaffold has no working model. Readiness does not measure model quality or inference behavior.
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.
## 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`).
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.
| Backend variable | Default | Purpose |
| --- | --- | --- |
| `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_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` |
| `GITHUB_TOKEN` | empty | optional token for reading public data only; raises the GitHub limit from 60 to 5000 requests an hour; a secret |
| `GITHUB_TIMEOUT` | 10s | timeout of a GitHub request |
| `REPOSITORY_CHECK_INTERVAL` | 10m | how often a candidate may ask for a new check |
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.
## Separate monitoring Compose project
+7
View File
@@ -42,6 +42,13 @@ Eight Gitleaks exceptions cover exact public API examples, test fixtures, a rele
For any further exception, scope it to the specific finding and affected input, record the reason, owner, and expiry, and have the change reviewed. The current integration does not enforce expiry uniformly across every tool, so review expiry explicitly where needed. Do not disable an entire scanner or globally suppress unfixed vulnerabilities to obtain a passing result.
## Outbound requests and ML
- 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.
## CI and limits
CI runs `make -C security test check` for source checks and `make -C security images` for images, and includes both jobs in its required aggregate result. Reports are uploaded as artifacts with a 14-day retention period, including when checks fail. Gitleaks redacts secret values, but reports can still reveal repository paths and dependency details; restrict artifact access accordingly.
+8
View File
@@ -626,6 +626,14 @@ On the runner host the suite runs from a bundle: `make -C runner a16-bundle` (`A
What the tests do not prove: isolation in the production VM until the suite has passed there; protection against kernel, nsjail, or cgroup vulnerabilities; the absence of side channels (timing, CPU caches); or behavior under load.
## 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.
- 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).
- 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
Go unit tests should exercise domain/usecase rules with explicit inputs, results, and errors. Integration tests should use a real PostgreSQL at the same major version, apply goose migrations, and exercise sqlc, constraints, transactions, rollback, and concurrent transitions. The HTTP path should use chi, middleware, usecases, and the database; replace external ML with a controlled HTTP fake and email with a test adapter.
+27 -6
View File
@@ -767,7 +767,7 @@ Checker задается для группы: `exact`, `tokens`, `numbers` (чи
## Подбор и объяснение
Реализован как детерминированный поиск без ML: `POST /api/v1/organizations/{org_id}/matches` (`SearchOrganizationMatches`, [api/README.md](../../api/README.md#подбор)). Код: usecase `backend/internal/usecase/matching/` (`search.go` - порядок работы, `filter.go` - фильтры, `score.go` - целочисленный расчет, `explain.go` - объяснение), список карточек `candidateview.Service.ListVisibleCards`, раздел политики `domain.MatchingPolicy` (`policy_matching.go`), связи навыков `domain.RelateEvidenceSkill` (`evidence_relation.go`), обработчик `adapter/primary/http/v1/matches.go` и сборка `bootstrap/matches.go`. Новых таблиц, миграций и файлов запросов нет: поиск использует барьерные запросы, которыми уже пользуются карточка и доказательства, поэтому правило видимости существует в одном экземпляре.
Реализован как детерминированный поиск, который не вызывает ML, а читает заранее вычисленные векторы (см. [Семантический слой и объяснения](#семантический-слой-и-объяснения)): `POST /api/v1/organizations/{org_id}/matches` (`SearchOrganizationMatches`, [api/README.md](../../api/README.md#подбор)). Код: usecase `backend/internal/usecase/matching/` (`search.go` - порядок работы, `filter.go` - фильтры, `score.go` - целочисленный расчет, `explain.go` - объяснение), список карточек `candidateview.Service.ListVisibleCards`, раздел политики `domain.MatchingPolicy` (`policy_matching.go`), связи навыков `domain.RelateEvidenceSkill` (`evidence_relation.go`), обработчик `adapter/primary/http/v1/matches.go` и сборка `bootstrap/matches.go`. Видимость не получила новых запросов: поиск использует барьерные запросы, которыми уже пользуются карточка и доказательства, поэтому правило видимости существует в одном экземпляре.
- Доступ до ранжирования. Поиск выполняется в одной транзакции. Роль владельца проверяется под блокировкой членства до чтения любых карточек. Затем `ListVisibleCards` проводит проверки чтения карточки: подтвержденный работодатель, затем `ListVisibleCandidateViewSources`, который выбирает из `candidate_effective_publications` (опубликовано и подкреплено неотозванным C2) и исключает кандидатов, скрывших читающую организацию, через `NOT EXISTS` по `candidate_hidden_organizations`; затем блокировки аккаунта, C2 и публикации и анонимная проекция с минимальной когортой из пяти. Поэтому список - это ровно те handle, которые в этот момент открывает `GetOrganizationCandidateCard`: карточка, скрытая правилами когорты, не ищется, отзыв C2, закрытая публикация или скрытая организация действуют со следующего запроса, ничего не кешируется и не хранится. Разрешенные доказательства читаются только организационно безопасным пакетным запросом `ListOrganizationVisibleEvidenceBatch` (один запрос на весь набор кандидатов с барьерами одиночного чтения: представление действующих публикаций, `NOT EXISTS` по скрытию, поле `categories`, видимые измерения) и только если запрос называет навыки. Блокировки - те же, что у чтения карточки, ничего больше не блокируется; записи поиска ограничены кандидатами, которых он возвращает.
- Только владелец. Для MVP ищет действующий владелец организации. HTTP-граница отклоняет любую другую роль (`ownerCompanyOperations`), а usecase повторяет проверку роли под блокировкой членства, поэтому само членство ничего не дает. Полная матрица ролей и назначений - более поздняя работа и не должна расширять права по одному членству.
@@ -777,7 +777,7 @@ Checker задается для группы: `exact`, `tokens`, `numbers` (чи
- Фильтры, все до расчета. `confirmed_grade`, `confirmed_category` и `confirmation_status: confirmed` оставляют только подтвержденные записи; заявленный грейд их не удовлетворяет. `declared_grade` - отдельное заявление. `stack` требует каждый названный тег в карточке и одновременно считается обязательным навыком запроса. `conditions.work_formats` требует один общий формат, `conditions.salary_compatibility` - то же значение; неизвестное значение карточки условие не удовлетворяет. Одна неподтвержденная категория ничего не скрывает: без подтвержденного фильтра заявленные специализации выводятся.
- Запрошенные навыки. Навыки для Cov берутся из подтвержденных обязательных (вес 2) и желательных (вес 1) навыков снимка потребности, теги фильтра `stack` считаются обязательными. Код считается один раз, сколько бы раз он ни повторялся. Навык без таксономического кода не имеет проверенного соответствия, ничему не соответствует и остается пробелом. Пустой запрос использует нейтральное Cov 0.5 вместо деления на ноль. Потребность читается по `requirements_version` (`GetVersion`); общая версия, изменившая только название, не является снимком требований и дает 404, а снимок прежней версии требований остается доступным и неизменным.
- Доказательство навыка. Для каждого запрошенного навыка берется лучшее произведение коэффициентов доверия, атрибуции и связи среди разрешенных доказательств, а не их сумма. Доказательства - заявленные теги стека карточки (доверие 0, заявление) и для подтвержденной записи единственный факт оценки, подтверждающий ее категорию (доверие 1, личный). Связь точная для того же кода, широкая для специализации над технологией и узкая в обратную сторону, по `skill_taxonomy` версии политики (демо: `backend` над `docker`, `go`, `kafka`, `postgresql`; `devops_sre` над `docker`); версия без таксономии связывает только равные коды, так что версия политики полностью определяет результат. Таксономия - демонстрационное соответствие, а не измеренное. Онлайн-результат Backend стоит 0.6 * 1.0 * 0.4 = 0.24 для запрошенного Go, заявленный тег Go - 0.25; порог близости 0.25, поэтому кандидат, у которого единственное доказательство обязательной технологии - оценка Backend, для нее всегда в `near`, а одного заявленного тега достаточно для `main`. Это следствие значений PRD - вопрос владельцу продукта. Повтор тега или навыка ничего не добавляет.
- Компоненты и группы. `Cov` - взвешенное среднее вкладов; `Dom = 0.5` (анонимная карточка не несет домен) и `Sem = 0.5` для каждой записи (ML нет), оба названы в `unknown_flags`; `T = 0.5` с null-перцентилем и признаком `cohort_below_30`, который поиск доказывает, а не декларирует: он считает кандидатов, имеющих каждую возвращаемую категорию из источника, отличного от синтетической демонстрации (`CountRealComparableCategories`, только числа), и сравнивает число с `percentile_min_cohort`; сегодня оно равно 0, так как каждая сохраненная категория - синтетическая демонстрация, которая никогда не смешивается с реальными результатами. Реальной когорте на уровне минимума понадобилась бы theta ее участников, которой нет в организационно безопасной проекции, поэтому поиск из-за этого никогда не падает: T остается нейтральным 0.5, перцентиль остается null, причина становится `percentile_not_computed` вместо `cohort_below_30`, и поиск пишет одно предупреждение на каждую такую категорию. Считаются только категории записей, прошедших фильтры; `V = 0`, так как данных о соревнованиях нет, - это ни штраф, ни неизвестность; `Fr = Rsp = 0.5` с признаками `no_freshness_history` и `no_response_history`. Подтвержденная запись с обязательным навыком ниже порога близости (0.25) попадает в `near`, иначе в `main`; неподтвержденная запись попадает в `unconfirmed` только с Fit и Coverage, считается отдельным путем и никогда не вычисляет theta, T, P, перцентиль или S. Отсутствие ФСП нигде не оценивается.
- Компоненты и группы. `Cov` - взвешенное среднее вкладов; `Dom = 0.5` (анонимная карточка не несет домен) и `Sem = 0.5` для записи без сохраненных векторов, оба названы в `unknown_flags`; `T = 0.5` с null-перцентилем и признаком `cohort_below_30`, который поиск доказывает, а не декларирует: он считает кандидатов, имеющих каждую возвращаемую категорию из источника, отличного от синтетической демонстрации (`CountRealComparableCategories`, только числа), и сравнивает число с `percentile_min_cohort`; сегодня оно равно 0, так как каждая сохраненная категория - синтетическая демонстрация, которая никогда не смешивается с реальными результатами. Реальной когорте на уровне минимума понадобилась бы theta ее участников, которой нет в организационно безопасной проекции, поэтому поиск из-за этого никогда не падает: T остается нейтральным 0.5, перцентиль остается null, причина становится `percentile_not_computed` вместо `cohort_below_30`, и поиск пишет одно предупреждение на каждую такую категорию. Считаются только категории записей, прошедших фильтры; `V = 0`, так как данных о соревнованиях нет, - это ни штраф, ни неизвестность; `Fr = Rsp = 0.5` с признаками `no_freshness_history` и `no_response_history`. Подтвержденная запись с обязательным навыком ниже порога близости (0.25) попадает в `near`, иначе в `main`; неподтвержденная запись попадает в `unconfirmed` только с Fit и Coverage, считается отдельным путем и никогда не вычисляет theta, T, P, перцентиль или S. Отсутствие ФСП нигде не оценивается.
- Порядок и округление. Баллы - целые числа в микроединицах (шесть знаков), доли - базисные пункты, произведения точные целые, поэтому одни и те же данные и политика дают один порядок на любой платформе. `main` и `near` сортируются по S, затем Cov (оба по убыванию), затем по внутреннему идентификатору кандидата по возрастанию (затем по коду специализации, который лишь разделяет две записи одного кандидата); `unconfirmed` - по Fit, затем Cov, затем по идентификатору. Идентификатор не покидает сервер, группы не объединяются общей шкалой.
- Объяснение. Сводка и признаки строятся из тех же рассчитанных вкладов: для каждой группы навыков `supports` (каждый навык подкреплен измерением не ниже порога), `declared_only` (только заявленные теги), `partial` (смесь или измерения ниже порога) или `gap` (ничего), а также подтвержденная категория, заявленный грейд, совпадение форматов работы с потребностью или фильтром и совместимость зарплаты. Только ограниченные коды, никогда свободный текст, контакт, локация кандидата, значение или минимум зарплаты, проваленная попытка или причина скрытых данных. Неизвестный компонент виден только в `unknown_flags`.
- Политика. Поиск читает действующую политику `product` на время приложения и ее раздел `matching`. Политика без раздела дает закрытый отказ с внутренней ошибкой (в перечислении ProblemCode нет кода для временно недоступной зависимости, и новый не добавляется); в логе ошибка говорит, что в действующей политике нет раздела подбора, и называет команду оператора `policy-publish`, при старте backend пишет предупреждение, пока раздела нет, а [DEPLOY.md](DEPLOY.md#политика-подбора-на-стенде) описывает команду. Ответ не называет версию политики, поиск не сохраняется.
@@ -785,15 +785,36 @@ Checker задается для группы: `exact`, `tokens`, `numbers` (чи
- Принятые остаточные риски. `truncated` - один бит о размере видимого банка (он говорит, что существует больше, чем предел или лимит), а время ответа растет с банком, поэтому оба раскрывают владельцу грубый размер. Бит ограничен пределом группы, число не возвращается; риск принят для демонстрации и внесен в вопросы владельцу.
- Проверки. Модульные тесты `internal/usecase/matching` (формулы с рассчитанными вручную значениями, равенства и порядок, фильтры, объяснение, обрезка и оплата вывода), `internal/domain/policy_matching_test.go` (круговой проход документа, строгость, проверка значений), `v1/matches_test.go` (отображение и ошибки) и интеграционный тест `TestMatchSearchOverHTTP` на PostgreSQL: скрытые кандидаты и две организации, потребность и ее измененные требования, повторные одинаковые ответы, Backend подтвержден и сети не подтверждены для одного handle, профиль без грейда, опубликованный настоящими операциями профиля, согласия и публикации и убранный отзывом C2, кандидат один в своей когорте, отсутствие контактов и идентификаторов в теле, оплата и история доступа за поиск, организация с лимитом меньше ее банка, предел группы, пакетное чтение доказательств, два одновременных поиска под одним лимитом, демонстрационный предел группы, таксономия политики, отказы доступа и политика без раздела.
Не реализовано: перцентиль и настоящий T (нужны theta сопоставимой реальной когорты не менее 30 человек); соревновательное значение V и данные ФСП; домен кандидата; истории свежести и своевременности; семантическая близость и признак недоступности ML сверх нейтрального значения; сохраняемые снимки `search_run`, уточнение, сравнение и шортлист; продолжение выдачи сверх предела группы; использование грейда потребности как фильтра. Отправка приглашения из результата поиска тоже не реализована, поэтому отзыв C2 после приглашения здесь не проверяется; черновик приглашения разрешает handle из результата поиска через тот же барьер видимости (см. [Черновики приглашений](#черновики-приглашений)).
Не реализовано: перцентиль и настоящий T (нужны theta сопоставимой реальной когорты не менее 30 человек); соревновательное значение V и данные ФСП; домен кандидата; истории свежести и своевременности; сохраняемые снимки `search_run`, уточнение, сравнение и шортлист; продолжение выдачи сверх предела группы; использование грейда потребности как фильтра. Отправка приглашения из результата поиска тоже не реализована, поэтому отзыв C2 после приглашения здесь не проверяется; черновик приглашения разрешает handle из результата поиска через тот же барьер видимости (см. [Черновики приглашений](#черновики-приглашений)).
До ранжирования Go применяет жесткие фильтры: опубликованный профиль, специализация, подтвержденный грейд, обязательные навыки и другие выбранные требования. Хорошее резюме или достижение не компенсирует отсутствующий обязательный критерий. Отсутствие подтверждения навыка нужно отличать от подтвержденного отсутствия. Это первая модель, а не оптимальное или измеренное ранжирование: планируется сравнить ключевые слова, baseline подтвержденных навыков и ML-вариант, семантический сигнал добавлять только после эксперимента и не считать его балл вероятностью успешного найма.
До ранжирования Go применяет жесткие фильтры: опубликованный профиль, специализация, подтвержденный грейд, обязательные навыки и другие выбранные требования. Хорошее резюме или достижение не компенсирует отсутствующий обязательный критерий. Отсутствие подтверждения навыка нужно отличать от подтвержденного отсутствия. Это первая модель, а не оптимальное или измеренное ранжирование: планируется сравнить ключевые слова, baseline подтвержденных навыков и ML-вариант, семантический сигнал добавлен после исследования (см. [Семантический слой и объяснения](#семантический-слой-и-объяснения)) и не считать его балл вероятностью успешного найма.
Каждая подборка сохраняется как search_run с компанией, исходной потребностью, фильтрами, версией ранжирования и родительской версией. Уточнение создает новый снимок. search_items фиксирует позиции, score и версии профилей без контактов. Старый снимок не сохраняет доступ: скрытые/удаленные профили из него исключаются, устаревший расчет помечается, срок хранения ограничен. Это запланировано; реализованный поиск ничего не сохраняет.
### Семантический слой и объяснения
Реализовано: эмбеддинги потребностей и опубликованных карточек, `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), отсортированных по длине с позицией запроса как тай-брейком, поэтому одни и те же тексты на одном образе и числе потоков дают одни и те же векторы.
- Какие поля ранжируют. Только то, что показывает анонимная карточка этого кандидата до когортного обобщения: роли из `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 при этом не пересчитываются (дайджесты те же), а векторы прежних моделей остаются и позволяют откатиться на прошлую версию политики без пересчета.
- Объяснение. Для поиска по потребности каждое подтвержденное требование (обязательный и желательный навык, задача) сопоставляется с ближайшим элементом карточки по косинусу. Пороги из 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
- Профиль. Раздел `projects` (до 10): название до 100 символов, описание до 500, до 10 тегов стека, необязательный адрес репозитория. Принимается только `https://github.com/<owner>/<repo>` (слеш в конце и `.git` удаляются, другие хосты, порты, учетные данные, пути, запросы и фрагменты отклоняются), один репозиторий не более одного раза. Проекты - заявления уровня 0 в `candidate_profile_claims` (вид `project`, миграция `00048`), версионируются вместе с профилем через `expected_version`. Тело без `projects` сохраняет проекты, поэтому старый клиент их не стирает.
- Карточка. Новое поле публикации `projects`: карточка показывает название, описание, теги и `repository_verified`, но никогда адрес или владельца репозитория. Название - текст кандидата и может его идентифицировать, поэтому поле включается только отдельным выбором, не участвует в когортном обобщении, а интерфейс должен предупреждать об этом (открытый вопрос владельца).
- Проверка. Новый или измененный адрес ставит задание `profile.repository_check`; `POST /api/v1/me/profile/repository-checks` повторяет проверки всех репозиториев не чаще `REPOSITORY_CHECK_INTERVAL` (по умолчанию 10 минут, иначе 429). Ключ и payload задания содержат только дайджест репозитория. Обработчик читает `api.github.com` (метаданные, языки, начало README), сохраняет состояние `pending`, `verified`, `not_found` или `unavailable` в `candidate_project_repositories`, ETag для условных запросов, а метаданные - только пока репозиторий публичный. README превращается в простой текст (без кода, HTML, ссылок и URL), до 4000 символов хранится и до 600 входит в текст карточки для ранжирования; ни одно из этих полей не возвращается API и не показывается. Лимит GitHub (403/429) сохраняет `unavailable` и переносит проверку на время сброса (от 1 минуты до 1 часа); сбои сети и сервера повторяет worker. "Проверен" значит только "репозиторий существует и публичен": авторство не доказывается, сверки владельца с аккаунтом кандидата нет.
- Контакты после C4. Адрес репозитория не добавлен в раскрытие C4: согласие C4 в журнале фиксирует закрытый набор полей (`full_name`, `email`, `phone`, `telegram`, CHECK в `00009` и `00030`), а расширение требует новой версии текста согласия и миграции журнала. До решения владельца организация не получает адрес ни до, ни после C4.
## ML, документы и фоновые задания
Целевые ML операции: анализ резюме, разбор потребности, а после baseline - embeddings и ограниченный rerank. Go передает только разрешенные данные и короткий shortlist. Ответы ограничены известными ID, проверяются по схеме и версии. Неудача ML включает baseline. Модель не назначает категории и не раскрывает контакты.
Реализованы embeddings для подбора (см. [Семантический слой и объяснения](#семантический-слой-и-объяснения)). Целевые ML операции дальше: анализ резюме, разбор потребности и ограниченный rerank. Go передает только разрешенные данные и короткий shortlist. Ответы ограничены известными ID, проверяются по схеме и версии. Неудача ML включает baseline. Модель не назначает категории и не раскрывает контакты.
План импорта PDF: ограничить размер, число страниц и частоту; проверить тип и владельца; сохранить версию исходника; в одной транзакции создать job; извлечь текст в изолированной среде с лимитами; замаскировать контакты; запросить структурированный результат; проверить его размер и версии; показать кандидату предложенные поля на подтверждение. Скан без текстового слоя сообщает об ошибке/ручном вводе; OCR - отдельное расширение. Полный текст не пишется в логи или traces.
@@ -979,7 +1000,7 @@ Middleware `backend/internal/adapter/primary/http/company_context.go` прове
Таблицы:
- `candidate_profiles`: `user_id` (первичный ключ и внешний ключ `ON DELETE CASCADE` на `users`), `version` (больше нуля; первое сохранение создает версию 1, а версия 0 контракта - отсутствие строки) и времена. Профиль - ПДн аккаунта и уходит вместе с ним; правила хранения - открытый юридический вопрос.
- `candidate_profile_claims`: по строке на сохраненное заявление - одиночное поле (`full_name`, `contact_email`, `contact_phone`, `contact_telegram`, `terms_location`, `terms_relocation`, `terms_salary_minimum` при `ordinal` 0) или элемент списка (`stack` до 30, `role` до 9, `experience` до 20, `soft_skill` до 10 по позиции). Столбцы: `value` jsonb, `status` (`confirmed` или `extracted`), `origin` (`manual`, `extracted_from_resume`, `imported`), `trust_level`, `quote`, `extraction_version` и `confirmed_at`. Поле без значения строки не имеет, поэтому `unknown` контракта - это отсутствие строки. Внешний ключ ведет на `candidate_profiles` с `ON DELETE CASCADE`.
- `candidate_profile_claims`: по строке на сохраненное заявление - одиночное поле (`full_name`, `contact_email`, `contact_phone`, `contact_telegram`, `terms_location`, `terms_relocation`, `terms_salary_minimum` при `ordinal` 0) или элемент списка (`stack` до 30, `role` до 9, `experience` до 20, `soft_skill` до 10, `project` до 10 по позиции; проекты описаны в разделе [Проекты кандидата и репозитории GitHub](#проекты-кандидата-и-репозитории-github)). Столбцы: `value` jsonb, `status` (`confirmed` или `extracted`), `origin` (`manual`, `extracted_from_resume`, `imported`), `trust_level`, `quote`, `extraction_version` и `confirmed_at`. Поле без значения строки не имеет, поэтому `unknown` контракта - это отсутствие строки. Внешний ключ ведет на `candidate_profiles` с `ON DELETE CASCADE`.
Решения:
+40 -4
View File
@@ -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`. `make -C deploy ml-up` запускает отдельный сервис без модели: `/healthz` отвечает 200, `/readyz` - 503. GPU и ключи внешнего inference ядру не нужны и не читаются.
- ML: основной и демонстрационный стенды по умолчанию не запускают ML и не обращаются к нему; поиск подставляет нейтральную смысловую близость 0.5 с флагом `ml_unavailable`. Семантический подбор включается отдельно: ML-проект с моделью Giga-Embeddings-instruct-480M на CPU, `SEMANTIC_MATCHING_ENABLED`, семантическая политика и backfill (см. [Семантический подбор](#семантический-подбор)). GPU и ключи внешнего inference не нужны и не читаются.
- Данные: демонстрационный стенд содержит только синтетические данные. Адреса на зарезервированном домене `@demo.lincodex.test` никогда не получают почту, названия помечены как синтетические, категории имеют источник `synthetic_demo` и не откалиброваны, а семейства заданий синтетические и не прошли предметную проверку. Не регистрируйте на этом стенде реальных людей. Синтетические категории (`ASSESSMENT_DEMO_CATEGORIES_ENABLED=true`) включают только демонстрационный overlay и overlay изолированного браузерного набора регистрации (см. [TESTING.md](TESTING.md#минимальный-путь-от-регистрации-до-раскрытых-контактов)); в `.env.example` значение `false`.
### 6. Проверки
@@ -476,6 +476,7 @@ make -C backend policy-publish ARGS='matching --actor operator:<handle>'
- Нужен только `DATABASE_URL`, dotenv-файл не читается, аргументы проверяются до подключения, печатается только номер версии. Автор версии - метка `operator:<handle>`: это метка аудита, а не аутентификация, границей оператора служит локальный доступ к базе.
- Новая версия действует для новых поисков сразу и не меняет сохраненных результатов. Это также новая версия всей политики product, поэтому открытие категории, привязанное к прежней версии, нужно открыть заново (и аттестовать заново на демонстрационном стенде, см. выше), прежде чем создавать новые попытки оценки. Публикуйте ее до начала попыток кандидатов либо повторите открытие и аттестацию после.
- Демонстрационные значения (коэффициенты PRD, предел 10 записей на группу и небольшая таксономия «специализация - технология») описаны в [архитектуре](ARCHITECTURE.md#версии-продуктовой-политики); они не калиброваны. Изолированный браузерный стенд публикует тот же раздел сам.
- `policy-publish semantic` публикует следующую версию, в которой раздел подбора заменен семантическим (`DemoSemanticMatchingPolicy`: веса Fit 0.4167 / 0.0833 / 0.5, модель, калибровка и пороги объяснений, см. [Семантический подбор](#семантический-подбор)); если у последней версии семантический раздел уже есть, ничего не меняется. Версия с точкой PRD остается предыдущей.
## Изолированный демонстрационный стенд
@@ -510,16 +511,51 @@ make -C deploy demo-down DEMO_MODE=isolated
## Отдельный ML Compose
ML имеет отдельный Compose-файл и проект; Redis и SeaweedFS ему пока не требуются и здесь не запускаются. По умолчанию он слушает на 127.0.0.1:8000. Настройте ML_BIND_ADDRESS только если выбранный приватный адрес и firewall уже подготовлены. Метрики удаленного ML target не собираются, пока ML_METRICS_TARGET пуст.
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 пуст.
Образ ML использует `python:alpine` с обновлением системных пакетов при сборке. Зависимости устанавливаются через uv только на этапе сборки; итоговый runtime содержит готовое виртуальное окружение без pip и ensurepip. Текущие зависимости поддерживают musl. Перед добавлением библиотек inference или GPU проверьте их совместимость с Alpine; glibc-зависимым библиотекам потребуется другой проверенный runtime.
Образ основан на `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); на этой машине образ не собирался из-за свободного места на диске.
| Переменная | По умолчанию | Назначение |
| --- | --- | --- |
| `ML_EMBEDDER` | `giga` в образе и Compose, `none` вне образа | `giga` - модель из образа, `fake` - детерминированный хеш-кодировщик для стендов без модели (его model id не совпадает с политикой, векторы не используются), `none` - сервис не готов |
| `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 только после загрузки и прогрева.
make -C deploy ml-config
make -C deploy ml-build
make -C deploy ml-up
make -C deploy ml-logs
make -C deploy ml-down
GET /healthz проверяет процесс. GET /readyz проверяет готовность к inference и возвращает 503, пока модель не доступна. В текущем scaffold рабочей модели нет. Не принимайте readiness за качество или работоспособность ML inference.
Для разработки без 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 с. Это один ноутбук с другими нагрузками, а не замер стенда.
## Семантический подбор
Поиск не вызывает 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`).
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.
| Переменная backend | По умолчанию | Назначение |
| --- | --- | --- |
| `SEMANTIC_MATCHING_ENABLED` | false | ставить и выполнять задания векторов |
| `ML_SERVICE_URL` | `http://ml:8000` в Compose | origin ML без пути и учетных данных |
| `ML_REQUEST_TIMEOUT` | 30s | таймаут одного запроса к ML |
| `ML_CIRCUIT_FAILURES`, `ML_CIRCUIT_OPEN` | 3, 30s | после стольких подряд неудач клиент не вызывает ML указанное время |
| `GITHUB_REPOSITORY_CHECKS_ENABLED` | false | выполнять проверки репозиториев проектов на `api.github.com` |
| `GITHUB_TOKEN` | пусто | необязательный токен только для чтения публичных данных; повышает лимит GitHub с 60 до 5000 запросов в час; секрет |
| `GITHUB_TIMEOUT` | 10s | таймаут запроса к GitHub |
| `REPOSITORY_CHECK_INTERVAL` | 10m | как часто кандидат может запросить повторную проверку |
Без 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#семантический-слой-и-объяснения). Векторы модели, которую политика больше не называет, поиск не читает; они остаются для отката на прошлую версию политики.
## Отдельный monitoring Compose
+7
View File
@@ -42,6 +42,13 @@ Gitleaks требует полный Git checkout. Отсутствие репо
Любое следующее исключение ограничивайте конкретной находкой и входными данными, указывайте причину, ответственного и срок действия, затем отдавайте изменение на ревью. Текущая интеграция не обеспечивает автоматический контроль срока одинаково для всех инструментов; там, где его нет, проверяйте срок вручную. Не отключайте сканер целиком и не скрывайте все уязвимости без исправлений ради успешной проверки.
## Исходящие запросы и ML
- 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 не загружается, сервис работает офлайн.
## CI и границы проверок
CI запускает `make -C security test check` для исходников и `make -C security images` для образов и включает обе проверки в обязательный общий результат. Отчеты загружаются как artifacts со сроком хранения 14 дней, в том числе при ошибке проверки. Gitleaks скрывает значения секретов, но отчеты могут раскрывать пути репозитория и сведения о зависимостях; доступ к artifacts должен это учитывать.
+8
View File
@@ -626,6 +626,14 @@ Vitest работает в Node без DOM, поэтому ограничени
Что тесты не доказывают: изоляцию в production VM, пока набор там не прошел; защиту от уязвимостей ядра, nsjail или cgroup; отсутствие побочных каналов (время, кеш процессора) и устойчивость под нагрузкой.
## Тесты семантического подбора
- 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) и повторное кодирование (тот же вектор). Это проверка воспроизводимости рецепта, а не оценка качества.
- 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).
- Не проверено: качество ранжирования и точность объяснений на реальных данных, задержка на рабочем сервере, сборка образа ML на этой машине и запуск стенда с моделью. Внешний GitHub в тестах не вызывается.
## Будущая программная валидация
Для Go unit tests нужны правила domain/usecase с конкретными входами, результатами и ошибками. Интеграционные тесты используют настоящую PostgreSQL той же major версии, применяют goose migrations и проверяют sqlc, ограничения, транзакции, rollback и конкурентные переходы. Для HTTP путь собирается через chi, middleware, usecase и БД; внешний ML заменяется контролируемым HTTP fake, почта - тестовым адаптером.