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

+1 -1
View File
@@ -1,6 +1,6 @@
# ML service standard
The ML service is a separate Python HTTP service. Its current role is an operational scaffold with health and readiness routes; there is no model-backed product endpoint yet.
The ML service is a separate Python HTTP service. It serves health and readiness routes and one model-backed endpoint, `POST /v1/embeddings`, with a pinned embedding model baked into its image. Ordinary tests use the deterministic fake encoder; the real model runs only in the marked slow test.
Keep the service contract in api/ml/. The Go client uses backend/codegen/ogen-ml.yml and is consumed under backend/internal/adapter/secondary/ml/api/. Python model generation belongs to ml/codegen/pyproject.toml: datamodel-code-generator produces Pydantic v2 models from api/ml/openapi.bundle.yml in ml/src/lincodex_ml/api/models.py. Keep generator dependencies in ml/pyproject.toml and uv.lock; the codegen pyproject contains tool settings only. Health/readiness handlers import generated models instead of maintaining duplicate transport schemas.
+6 -2
View File
@@ -99,7 +99,7 @@ Timestamps use the `Timestamp` schema: `string`, `format: date-time`, UTC with t
### ML service errors
The ML service answers its errors with the same `Problem` schema. Its `ProblemCode` enum keeps the public identity codes so both contracts share one shape, but the service never returns them. FastAPI request validation answers 400 `validation_failed`. An HTTP exception raised inside the service maps by status: 400, 401, 403, 404, 405, 409 (`state_conflict`), 412, 413, 415, 428, 429, and 501 to their codes, 422 to 400 `validation_failed`, any other 4xx to 400 `validation_failed`, and any other 5xx to 500 `internal`. An unhandled exception answers 500 `internal` inside the application, so Starlette does not re-raise it to uvicorn; only its type is logged. The service also routes the uvicorn loggers through its JSON log format, which keeps only the exception type of a record and never its text or traceback.
The ML service answers its errors with the same `Problem` schema. Its `ProblemCode` enum keeps the public identity codes so both contracts share one shape, but the service never returns them. FastAPI request validation answers 400 `validation_failed`. An HTTP exception raised inside the service maps by status: 400, 401, 403, 404, 405, 409 (`state_conflict`), 412, 413, 415, 428, 429, 501, and 503 (`service_unavailable`, while the model is not ready) to their codes, 422 to 400 `validation_failed`, any other 4xx to 400 `validation_failed`, and any other 5xx to 500 `internal`. An unhandled exception answers 500 `internal` inside the application, so Starlette does not re-raise it to uvicorn; only its type is logged. The service also routes the uvicorn loggers through its JSON log format, which keeps only the exception type of a record and never its text or traceback.
### Code runner contract
@@ -201,6 +201,7 @@ The `candidate` tag includes implemented `GetMyProfile` and `SaveMyProfile` oper
| --- | --- | --- | --- | --- |
| `GET /api/v1/me/profile` | `GetMyProfile` | session | 200 `CandidateProfile`, `Cache-Control: no-store` | 401 `unauthenticated`, 403 `forbidden` |
| `PUT /api/v1/me/profile` | `SaveMyProfile` | session and CSRF | 200 `CandidateProfile`, `Cache-Control: no-store` | 400 `validation_failed`, 401, 403 `csrf_check_failed` or `forbidden`, 412 `version_conflict` |
| `POST /api/v1/me/profile/repository-checks` | `RequestMyRepositoryChecks` | session and CSRF | 202 `ProfileRepositoryCheckRequest`, `Cache-Control: no-store` | 401, 403 `csrf_check_failed` or `forbidden`, 429 `rate_limited` with Retry-After |
Each operation also declares the default problem response. No new problem code is added: the contract uses `validation_failed`, `unauthenticated`, `forbidden`, `csrf_check_failed`, and `version_conflict`.
@@ -253,6 +254,8 @@ Open questions for the product owner and legal:
`TestCandidateProfileOperationsFollowTheConventions`, `TestCandidateProfileSeparatesSelfAssessedGradeFromConfirmedCategory`, `TestCandidateProfileClaimsCarrySourceAndTrustLevelZero`, `TestPrivateProfileSchemasAreNotMixedWithOrganizationVisibleDTOs`, `TestGeneratedProfileDTOsCarryNoConfirmedGradeInRequests`, `TestProfileSchemaValidationPrecedesImplementation`, and `TestProfileAccessBeforeImplementation` pin the generated server and the bundle, and `frontend/src/shared/api/profile-contract.test.ts` pins the generated Zod rules, the request types without a confirmed grade, and the absence of profile fields from the organization, invitation, and need schemas.
Projects: the optional `projects` list of the `SaveMyProfile` body (up to 10; an absent list keeps the projects, an empty array removes them) with a title, description, tags, and an address `https://github.com/<owner>/<repo>`; other addresses answer 400 with the pointer `/projects/<n>/repository_url`. The `CandidateProfile` response carries `projects[].repository_check` (`pending`, `verified`, `not_found`, `unavailable`). `RequestMyRepositoryChecks` repeats the checks on `api.github.com` at most once per stand interval. Publishing projects on the card is the separate `projects` value of `CardField` (see [architecture](../docs/en/ARCHITECTURE.md#candidate-projects-and-github-repositories)).
### Assessment
The `assessment` tag covers the assessment attempts of the current candidate (PRD FR04 and FR05): availability, start and resume, answers including the code practice, finalization, and the result. The operations are in the contract, but their business logic is not implemented: a guest answers 401 `unauthenticated`, and a request with a verified session reaches 501 `not_implemented` after request validation. Unsafe protected operations also require the session-bound CSRF token and exact Origin.
@@ -750,9 +753,10 @@ The operation changes nothing and needs no Idempotency-Key; `POST` carries the b
- Basis. `MatchSearchByNeed` searches the immutable `requirements_version` snapshot (not the general `version`), and its optional `filters` narrow it; `MatchSearchByBank` searches all organization-visible entries with explicit filters. The response `source` repeats the basis: the need reference, or the bank filters with every key present and null for a filter that was not sent (the stack is sorted).
- Entries. Every entry is one candidate specialization under the organization-scoped `candidate_handle`. `main` and `near` hold confirmed categories (`near` when a required skill of the request earns less than 0.25), `unconfirmed` holds the declared specializations, sorted by Fit, then Coverage, then an internal identifier that is never returned. An unconfirmed entry has `category: null`, `strength: null`, and only `fit` and `coverage`. The groups are not one scale, and one handle can be confirmed in one specialization and unconfirmed in another.
- Category basis. Each confirmed category of an entry carries `basis` (`synthetic_demo` for a demonstration category). The organization sees a demonstration as such, not as a standard confirmation; the field is required in `MatchCategory`.
- Neutral and unknown values. The semantics component is 0.5 for every entry with `ml_unavailable`; `percentile` is null with `cohort_below_30` and T is 0.5 (no comparable real cohort exists, and demonstration results never form one); domain, freshness, and responsiveness are 0.5 with their flags; competition is 0 and is neither a penalty nor an unknown; a card value that is not published is `null` in `public_context` with `not_in_public_card`.
- Neutral and unknown values. The semantics component is the calibrated cosine of the stored vectors of the need and the card, and 0.5 with `ml_unavailable` without them; `percentile` is null with `cohort_below_30` and T is 0.5 (no comparable real cohort exists, and demonstration results never form one); domain, freshness, and responsiveness are 0.5 with their flags; competition is 0 and is neither a penalty nor an unknown; a card value that is not published is `null` in `public_context` with `not_in_public_card`.
- A search is charged like card reads, because an entry carries card content. The whole visible bank is ranked, and each group returns at most `max_results_per_group` entries of the policy version (demo 10, so at most 30 reveals for one search, below the 50 views per day of tier E0); no total is returned. In the order `main`, `near`, `unconfirmed`, each newly revealed candidate counts as one distinct card view of the organization (the same reservation as `GetOrganizationCandidateCard`, so a candidate already viewed inside the window costs nothing again, and repeating the search or opening the card afterwards does not charge twice) and gets one `card_viewed` entry in the access history per search with the fields actually returned. When the allowance ends, the entries already paid for are returned with `truncated: true`, nothing is written for the rest, and no error and no new problem code is returned. `truncated` is also true when a group exceeded its limit and never carries a count. The response `truncated` is required.
- No contact, candidate location, salary amount or minimum, raw answer, failed attempt, or reason for withheld data is in any entry; the explanation uses the bounded `MatchEvidenceCode` and `MatchEvidenceState` values only. A deployment whose effective policy has no `matching` section answers an internal error and never ranks with defaults.
- `semantic_evidence` (up to 12, 6 by default) explains a need search: a requirement of the need, the closest item of the published card (`project`, `stack`, `roles`), the band `high` or `medium`, and `repository_verified`. A project is named only by its published title (the card field `projects`), never by the repository address or owner; no model text enters the explanation ([architecture](../docs/en/ARCHITECTURE.md#semantic-layer-and-explanations)).
Accepted residual risks: `truncated` is one bit about the size of the visible bank, and the response time grows with it; both are bounded by the group limit and carry no count. When the real comparable cohort of a category reaches the policy minimum, the percentile is still null with the reason `percentile_not_computed` and the search does not fail. A change of the visible cohort during a search repeats it up to three times; two simultaneous searches of one organization are serialized by its quota lock.
+7 -3
View File
@@ -99,7 +99,7 @@
### Ошибки ML-сервиса
ML-сервис отвечает на ошибки той же схемой `Problem`. Его перечисление `ProblemCode` сохраняет публичные коды identity, чтобы оба контракта имели одну форму, но сервис их никогда не возвращает. Валидация запроса FastAPI дает 400 `validation_failed`. HTTP-исключение внутри сервиса преобразуется по статусу: 400, 401, 403, 404, 405, 409 (`state_conflict`), 412, 413, 415, 428, 429 и 501 - в свои коды, 422 - в 400 `validation_failed`, любой другой 4xx - в 400 `validation_failed`, любой другой 5xx - в 500 `internal`. Необработанное исключение дает 500 `internal` внутри приложения, поэтому Starlette не пробрасывает его в uvicorn; в лог попадает только тип. Сервис также направляет логгеры uvicorn через свой JSON-формат, который сохраняет только тип исключения записи, но не текст и не traceback.
ML-сервис отвечает на ошибки той же схемой `Problem`. Его перечисление `ProblemCode` сохраняет публичные коды identity, чтобы оба контракта имели одну форму, но сервис их никогда не возвращает. Валидация запроса FastAPI дает 400 `validation_failed`. HTTP-исключение внутри сервиса преобразуется по статусу: 400, 401, 403, 404, 405, 409 (`state_conflict`), 412, 413, 415, 428, 429, 501 и 503 (`service_unavailable`, пока модель не готова) - в свои коды, 422 - в 400 `validation_failed`, любой другой 4xx - в 400 `validation_failed`, любой другой 5xx - в 500 `internal`. Необработанное исключение дает 500 `internal` внутри приложения, поэтому Starlette не пробрасывает его в uvicorn; в лог попадает только тип. Сервис также направляет логгеры uvicorn через свой JSON-формат, который сохраняет только тип исключения записи, но не текст и не traceback.
### Контракт исполнителя кода
@@ -201,6 +201,7 @@ ML-сервис отвечает на ошибки той же схемой `Pro
| --- | --- | --- | --- | --- |
| `GET /api/v1/me/profile` | `GetMyProfile` | сессия | 200 `CandidateProfile`, `Cache-Control: no-store` | 401 `unauthenticated`, 403 `forbidden` |
| `PUT /api/v1/me/profile` | `SaveMyProfile` | сессия и CSRF | 200 `CandidateProfile`, `Cache-Control: no-store` | 400 `validation_failed`, 401, 403 `csrf_check_failed` или `forbidden`, 412 `version_conflict` |
| `POST /api/v1/me/profile/repository-checks` | `RequestMyRepositoryChecks` | сессия и CSRF | 202 `ProfileRepositoryCheckRequest`, `Cache-Control: no-store` | 401, 403 `csrf_check_failed` или `forbidden`, 429 `rate_limited` с Retry-After |
Каждая операция также объявляет problem-ответ `default`. Новый код problem не добавляется: контракт использует `validation_failed`, `unauthenticated`, `forbidden`, `csrf_check_failed` и `version_conflict`.
@@ -253,6 +254,8 @@ ML-сервис отвечает на ошибки той же схемой `Pro
`TestCandidateProfileOperationsFollowTheConventions`, `TestCandidateProfileSeparatesSelfAssessedGradeFromConfirmedCategory`, `TestCandidateProfileClaimsCarrySourceAndTrustLevelZero`, `TestPrivateProfileSchemasAreNotMixedWithOrganizationVisibleDTOs`, `TestGeneratedProfileDTOsCarryNoConfirmedGradeInRequests`, `TestProfileSchemaValidationPrecedesImplementation` и `TestProfileAccessBeforeImplementation` закрепляют сгенерированный сервер и бандл, а `frontend/src/shared/api/profile-contract.test.ts` - сгенерированные правила Zod, типы запросов без подтвержденного грейда и отсутствие полей профиля в схемах организации, приглашения и потребности.
Проекты: необязательный в теле `SaveMyProfile` список `projects` (до 10; отсутствие сохраняет проекты, пустой массив удаляет) с названием, описанием, тегами и адресом `https://github.com/<owner>/<repo>`; другие адреса дают 400 с указателем `/projects/<n>/repository_url`. Ответ `CandidateProfile` несет `projects[].repository_check` (`pending`, `verified`, `not_found`, `unavailable`). `RequestMyRepositoryChecks` повторяет проверки на `api.github.com` не чаще интервала стенда. Публикация проектов в карточке - отдельное поле `projects` в `CardField` (см. [архитектуру](../docs/ru/ARCHITECTURE.md#проекты-кандидата-и-репозитории-github)).
### Оценка
Тег `assessment` описывает попытки оценки текущего кандидата (FR04 и FR05 в PRD): доступность, старт и возобновление, ответы вместе с кодовой практикой, завершение и результат. Операции есть в контракте, но их бизнес-логика еще не реализована: гость получает 401 `unauthenticated`, а запрос с подтвержденной сессией достигает 501 `not_implemented` после проверки запроса. Небезопасные защищенные операции также требуют session-bound CSRF-токен и точный Origin.
@@ -750,9 +753,10 @@ ML-сервис отвечает на ошибки той же схемой `Pro
- Основание. `MatchSearchByNeed` ищет по неизменяемому снимку `requirements_version` (не по общей `version`), необязательные `filters` сужают его; `MatchSearchByBank` ищет по всем записям, видимым организации, с явными фильтрами. `source` в ответе повторяет основание: ссылку на потребность либо фильтры банка, где присутствует каждый ключ, а неотправленный фильтр равен null (стек отсортирован).
- Записи. Каждая запись - одна специализация кандидата под организационным `candidate_handle`. В `main` и `near` лежат подтвержденные категории (`near`, если обязательный навык запроса дает меньше 0.25), в `unconfirmed` - заявленные специализации, отсортированные по Fit, затем Coverage, затем по внутреннему идентификатору, который не возвращается. У неподтвержденной записи `category: null`, `strength: null` и только `fit` и `coverage`. Группы - не одна шкала, и один handle может быть подтвержден по одной специализации и не подтвержден по другой.
- Основание категории. Каждая подтвержденная категория записи несет `basis` (`synthetic_demo` для демонстрационной категории). Организация видит демонстрацию как таковую, а не как стандартное подтверждение; поле обязательно в `MatchCategory`.
- Нейтральные и неизвестные значения. Семантика равна 0.5 для каждой записи с `ml_unavailable`; `percentile` равен null с `cohort_below_30`, а T равен 0.5 (сопоставимой реальной когорты нет, демонстрационные результаты ее не образуют); домен, свежесть и своевременность равны 0.5 со своими признаками; соревновательный вклад равен 0 и не является ни штрафом, ни неизвестностью; неопубликованное значение карточки - `null` в `public_context` с `not_in_public_card`.
- Нейтральные и неизвестные значения. Семантика - калиброванный косинус сохраненных векторов потребности и карточки, а без них 0.5 с `ml_unavailable`; `percentile` равен null с `cohort_below_30`, а T равен 0.5 (сопоставимой реальной когорты нет, демонстрационные результаты ее не образуют); домен, свежесть и своевременность равны 0.5 со своими признаками; соревновательный вклад равен 0 и не является ни штрафом, ни неизвестностью; неопубликованное значение карточки - `null` в `public_context` с `not_in_public_card`.
- Поиск оплачивается как чтение карточек, потому что запись несет содержимое карточки. Ранжируется весь видимый банк, а каждая группа возвращает не более `max_results_per_group` записей версии политики (демо 10, то есть не более 30 показов за один поиск, меньше 50 просмотров в сутки для уровня E0); итог не возвращается. В порядке `main`, `near`, `unconfirmed` каждый впервые показанный кандидат считается одним уникальным просмотром карточки организации (то же резервирование, что у `GetOrganizationCandidateCard`: кандидат, уже просмотренный в окне, второй раз ничего не стоит, и повтор поиска или последующее открытие карточки не списывает дважды) и получает по одной записи `card_viewed` в истории доступа за поиск с фактически возвращенными полями. Когда лимит заканчивается, возвращаются уже оплаченные записи с `truncated: true`, для остальных ничего не пишется, ошибка и новый код проблемы не возвращаются. `truncated` также истинно, когда группа превысила предел, и никогда не несет число. В ответе `truncated` обязателен.
- Ни в одной записи нет контакта, локации кандидата, суммы или минимума зарплаты, сырого ответа, проваленной попытки и причины скрытых данных; объяснение использует только ограниченные значения `MatchEvidenceCode` и `MatchEvidenceState`. Развертывание, действующая политика которого не содержит раздела `matching`, отвечает внутренней ошибкой и не ранжирует по умолчаниям.
- Ни в одной записи нет контакта, локации кандидата, суммы или минимума зарплаты, сырого ответа, проваленной попытки и причины скрытых данных; объяснение использует только ограниченные значения `MatchEvidenceCode` и `MatchEvidenceState`.
- `semantic_evidence` (до 12, по умолчанию 6) объясняет поиск по потребности: требование потребности, ближайший элемент опубликованной карточки (`project`, `stack`, `roles`), полоса `high` или `medium` и `repository_verified`. Проект назван только опубликованным названием (поле карточки `projects`), без адреса и владельца репозитория; текст модели в объяснение не входит ([архитектура](../docs/ru/ARCHITECTURE.md#семантический-слой-и-объяснения)). Развертывание, действующая политика которого не содержит раздела `matching`, отвечает внутренней ошибкой и не ранжирует по умолчаниям.
Принятые остаточные риски: `truncated` - один бит о размере видимого банка, и время ответа растет вместе с ним; оба ограничены пределом группы и не несут числа. Когда реальная сопоставимая когорта категории достигает минимума политики, перцентиль все равно null с причиной `percentile_not_computed`, и поиск не падает. Изменение видимой когорты во время поиска повторяет его до трех раз; два одновременных поиска одной организации сериализуются ее блокировкой квоты.
+22
View File
@@ -4020,6 +4020,7 @@ NewCandidateProfile:
experience: []
experience_overlaps: []
soft_skills: []
projects: []
terms:
location:
status: unknown
@@ -4129,6 +4130,25 @@ BackendCandidateProfile:
quote: null
extraction_version: null
confirmed_at: "2026-10-05T09:30:00Z"
projects:
- title: Payment webhook deduplication service
description: >-
Idempotent receiver for acquirer callbacks with a unique operation
key and an outbox for retries.
stack:
- Go
- PostgreSQL
repository_url: https://github.com/example-org/payments-ledger
repository_check:
state: verified
checked_at: "2026-10-05T09:31:00Z"
status: confirmed
source:
origin: manual
trust_level: 0
quote: null
extraction_version: null
confirmed_at: "2026-10-05T09:30:00Z"
terms:
location:
status: confirmed
@@ -4412,6 +4432,7 @@ PublishedCardPreview:
experience_band: "1_3"
work_formats: null
salary_compatibility: null
projects: null
evidence:
items:
- skill: backend
@@ -4438,6 +4459,7 @@ OrganizationAnonymousCandidateCard:
experience_band: "1_3"
work_formats: null
salary_compatibility: null
projects: null
ClosedCardPreview:
summary: The preview of a closed profile
value:
+81
View File
@@ -69,6 +69,7 @@ ThreeGroups:
state: supports
- code: work_conditions_match
state: supports
semantic_evidence: []
components:
fit: 0.78
coverage: 0.72
@@ -102,6 +103,7 @@ ThreeGroups:
state: supports
- code: required_skill_evidence
state: gap
semantic_evidence: []
components:
fit: 0.48
coverage: 0.18
@@ -135,6 +137,7 @@ ThreeGroups:
state: declared_only
- code: required_skill_evidence
state: partial
semantic_evidence: []
components:
fit: 0.51
coverage: 0.38
@@ -197,6 +200,7 @@ MLUnavailable:
evidence_summary:
- code: confirmed_category
state: supports
semantic_evidence: []
components:
fit: 0.7
coverage: 0.6
@@ -249,6 +253,7 @@ CohortBelow30:
evidence_summary:
- code: confirmed_category
state: supports
semantic_evidence: []
components:
fit: 0.62
coverage: 0.55
@@ -301,6 +306,7 @@ Truncated:
evidence_summary:
- code: confirmed_category
state: supports
semantic_evidence: []
components:
fit: 0.5
coverage: 0.5
@@ -319,3 +325,78 @@ Truncated:
near: []
unconfirmed: []
truncated: true
SemanticEvidence:
summary: A need search explains an entry with semantic evidence from published card items.
description: >-
Synthetic example. `semantics` is the calibrated cosine of the stored
vectors; each evidence item pairs one confirmed requirement of the need
with the closest published card item. The project is named only by the
title that the candidate published; the repository address never appears.
value:
source:
kind: need
need_id: 4d3a4a1b-4f60-44c1-9dc2-6c8e6c9d4c11
requirements_version: 3
groups:
main:
- candidate_handle: cv1_FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
specialization: backend
confirmation_status: confirmed
declared_grade: middle
category:
specialization: backend
grade: middle
basis: synthetic_demo
strength: standard
public_context:
stack:
- kafka
- postgresql
experience_band: "3_6"
work_formats: null
salary_compatibility: null
evidence_summary:
- code: confirmed_category
state: supports
- code: required_skill_evidence
state: declared_only
semantic_evidence:
- requirement_kind: task
requirement_text: Make payment callbacks idempotent
item_kind: project
project_title: Payment webhook deduplication service
repository_verified: true
similarity: high
- requirement_kind: required_skill
requirement_text: Kafka
item_kind: stack
project_title: null
repository_verified: false
similarity: medium
components:
fit: 0.69
coverage: 0.25
domain: 0.5
semantics: 0.92
percentile: null
competition: 0.0
freshness: 0.5
responsiveness: 0.5
rank_score: 0.59
unknown_flags:
- component: percentile
reason: cohort_below_30
- component: freshness
reason: no_freshness_history
- component: responsiveness
reason: no_response_history
- component: work_formats
reason: not_in_public_card
- component: salary_compatibility
reason: not_in_public_card
- component: domain
reason: not_in_public_card
near: []
unconfirmed: []
truncated: false
+268 -5
View File
@@ -2267,6 +2267,112 @@ ProfileExperienceItem:
$ref: '#/ProfileItemStatus'
source:
$ref: '#/ProfileClaimSource'
ProfileProjectTitle:
type: string
minLength: 1
maxLength: 100
pattern: ^\S(?:.*\S)?$
description: Name of a project as the candidate wants an organization to read it. It has no leading or trailing whitespace and no line breaks. When the candidate publishes the `projects` card field, the title reaches the anonymous card and match explanations, so it must not contain a name, a contact, or a repository address. Plain text; clients show it as text, never as HTML.
ProfileProjectDescription:
type: string
minLength: 1
maxLength: 500
description: What the project does and what the candidate did in it. It may contain line breaks. When the `projects` card field is published it reaches the anonymous card. Plain text; clients show it as text, never as HTML.
ProfileRepositoryUrl:
type: string
minLength: 22
maxLength: 160
pattern: ^https://github\.com/[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})/[A-Za-z0-9._-]{1,100}/?$
description: Address of a public GitHub repository of the project in the form https://github.com/<owner>/<repository>. The server accepts only this host and form, removes a trailing slash and a `.git` suffix, and stores the canonical address. Organizations never receive the address before an accepted invitation, because the owner name can identify the candidate.
examples:
- https://github.com/example-org/payments-ledger
ProfileRepositoryCheckState:
type: string
description: 'Result of the latest server check of a project repository on the public GitHub API. The server only reads public metadata; a check never proves that the candidate wrote the code.
- pending: the check is scheduled and has not finished yet.
- verified: the repository exists and is public. Match explanations may then say that the project is backed by a public repository.
- not_found: GitHub reports no such public repository; it may be private, renamed to another owner, or deleted.
- unavailable: GitHub could not be asked, for example because of its rate limit; the server retries later.'
enum:
- pending
- verified
- not_found
- unavailable
ProfileRepositoryCheck:
type: object
description: State of the server check of a project repository. Read-only; no request writes it. The fetched metadata itself (description, topics, languages, and a plain-text README excerpt) is used only for ranking and is never returned or shown.
additionalProperties: false
required:
- state
- checked_at
properties:
state:
$ref: '#/ProfileRepositoryCheckState'
checked_at:
description: Time of the last finished check, or null before the first one.
oneOf:
- $ref: '#/Timestamp'
- type: 'null'
ProfileProjectStack:
type: array
maxItems: 10
description: Technology tags of the project, each tag at most once without regard to letter case.
items:
$ref: '#/StackTag'
ProfileRepositoryCheckRequest:
type: object
description: Result of a request to check the linked repositories again.
additionalProperties: false
required:
- scheduled
properties:
scheduled:
type: integer
format: int32
minimum: 0
maximum: 10
description: Number of repository checks that the request scheduled.
ProfileProjectItem:
type: object
description: One project of the candidate with its confirmation state and provenance. A project is a claim of trust level 0 that the candidate types; a linked repository adds a separate server check (`repository_check`), never a higher trust level. The project reaches organizations only when the candidate publishes the `projects` card field, and then without the repository address.
additionalProperties: false
required:
- title
- description
- stack
- repository_url
- repository_check
- status
- source
properties:
title:
$ref: '#/ProfileProjectTitle'
description:
description: What the project is about, or null when the candidate gives nothing.
oneOf:
- $ref: '#/ProfileProjectDescription'
- type: 'null'
stack:
$ref: '#/ProfileProjectStack'
repository_url:
description: Canonical repository address, or null when the project links none.
oneOf:
- $ref: '#/ProfileRepositoryUrl'
- type: 'null'
repository_check:
description: The server check of the linked repository, or null when the project links none.
oneOf:
- $ref: '#/ProfileRepositoryCheck'
- type: 'null'
status:
$ref: '#/ProfileItemStatus'
source:
$ref: '#/ProfileClaimSource'
ProfileExperienceOverlapStatus:
type: string
description: Whether the candidate confirmed that two overlapping periods are genuine parallel work.
@@ -2354,7 +2460,7 @@ ProfileConfirmedCategory:
description: Assessment attempt whose result confirmed the grade. The attempt belongs to the candidate.
CandidateProfile:
type: object
description: 'The private profile of the current candidate: full name and contacts, stack, roles, work experience, soft skills, and desired terms, each value with its confirmation state and provenance. It is personal data that only the candidate reads. It is never an organization-visible schema: an organization sees a candidate only through the anonymous card and, after an accepted invitation, through the contact grant, and no organization schema refers to this one.
description: 'The private profile of the current candidate: full name and contacts, stack, roles, work experience, soft skills, projects, and desired terms, each value with its confirmation state and provenance. It is personal data that only the candidate reads. It is never an organization-visible schema: an organization sees a candidate only through the anonymous card and, after an accepted invitation, through the contact grant, and no organization schema refers to this one.
Every value is a claim of trust level 0. The `self_assessed_grade` of a role is what the candidate says; the `confirmed_categories` list is what assessment results established, and the two are never mixed. A candidate who has not saved the profile gets version 0, every single field `unknown`, empty lists, and null `updated_at`.
@@ -2369,6 +2475,7 @@ CandidateProfile:
- experience
- experience_overlaps
- soft_skills
- projects
- terms
- confirmed_categories
- updated_at
@@ -2409,6 +2516,12 @@ CandidateProfile:
description: Soft skills in the order the candidate gave them, each skill at most once without regard to letter case.
items:
$ref: '#/ProfileSoftSkillItem'
projects:
type: array
maxItems: 10
description: Projects in the order the candidate gave them, each repository address at most once.
items:
$ref: '#/ProfileProjectItem'
terms:
$ref: '#/ProfileTerms'
confirmed_categories:
@@ -2620,9 +2733,34 @@ ProfileExperienceItemInput:
- type: 'null'
status:
$ref: '#/ProfileItemStatus'
ProfileProjectItemInput:
type: object
description: Decision about one project in a request; see CandidateProfileUpdate for the rules of `status`. The server answers 400 with the pointer of the field for a repository address that is not a GitHub repository address, a repeated repository, or a repeated stack tag.
additionalProperties: false
required:
- title
- description
- stack
- repository_url
- status
properties:
title:
$ref: '#/ProfileProjectTitle'
description:
oneOf:
- $ref: '#/ProfileProjectDescription'
- type: 'null'
stack:
$ref: '#/ProfileProjectStack'
repository_url:
oneOf:
- $ref: '#/ProfileRepositoryUrl'
- type: 'null'
status:
$ref: '#/ProfileItemStatus'
CandidateProfileUpdate:
type: object
description: 'Complete new state of the candidate profile. It replaces every stored value as a whole: a single field sent as null is unknown and is removed, and a list replaces the stored list. The body is personal data.
description: 'Complete new state of the candidate profile. It replaces every stored value as a whole: a single field sent as null is unknown and is removed, and a list replaces the stored list; only `projects` may be omitted, which keeps the stored projects. The body is personal data.
Each value carries a decision `status`. `confirmed` sets a manual value or confirms a stored suggestion; confirming a suggestion with exactly its stored value keeps its origin and quote, and any other value makes the claim manual. `extracted` keeps a stored suggestion unconfirmed and is accepted only with exactly the stored value; any other use answers 400 with the pointer of that status, for example `/stack/1/status`. The provenance, the trust level, and the confirmed categories are not part of the request, and unknown fields are rejected, so a request can neither mark a claim as verified nor write a confirmed grade or a category.'
additionalProperties: false
@@ -2674,6 +2812,12 @@ CandidateProfileUpdate:
description: Soft skills. The server answers 400 with the pointer of a skill that repeats an earlier one without regard to letter case.
items:
$ref: '#/ProfileSoftSkillItemInput'
projects:
type: array
maxItems: 10
description: 'Projects. Unlike the other lists this one is optional: a body without `projects` keeps the stored projects unchanged, so a client that does not know the section never deletes it, and an array, including an empty one, replaces the stored list. A new or changed repository address schedules a server check on the public GitHub API after the save commits; the save itself never waits for GitHub.'
items:
$ref: '#/ProfileProjectItemInput'
terms:
$ref: '#/ProfileTermsInput'
DirectionCode:
@@ -4946,6 +5090,72 @@ MatchEvidenceSummary:
maxItems: 12
items:
$ref: '#/MatchEvidenceSummaryItem'
MatchRequirementKind:
type: string
description: Kind of the need requirement that an explanation item answers.
enum:
- required_skill
- desired_skill
- task
MatchSemanticItemKind:
type: string
description: 'Kind of the published card item that matched a requirement.
- project: one published project; `project_title` names it.
- stack: the recognized technology codes of the card.
- roles: the specializations and grades that the card shows.'
enum:
- project
- stack
- roles
MatchSimilarityBand:
type: string
description: Coarse band of the cosine similarity between the requirement and the matched item under the versioned policy thresholds. `high` and `medium` are the only values; a weaker similarity produces no item. The band is a computed similarity of two texts, not a judgement of the candidate.
enum:
- high
- medium
MatchSemanticEvidence:
type: object
description: 'Why the entry is in the result: one confirmed requirement of the need and the published card item with the highest semantic similarity to it. The server computes it from stored vectors and the versioned thresholds; no model writes text into it. `requirement_text` is the confirmed text of the organization''s own need. `project_title` is the title the candidate published with the `projects` card field and is null for other kinds. No repository address, owner, or fetched repository text is ever part of it.'
additionalProperties: false
required:
- requirement_kind
- requirement_text
- item_kind
- project_title
- repository_verified
- similarity
properties:
requirement_kind:
$ref: '#/MatchRequirementKind'
requirement_text:
type: string
minLength: 1
maxLength: 300
description: Confirmed skill name or task text of the need. Plain text; show it as text, never as HTML.
item_kind:
$ref: '#/MatchSemanticItemKind'
project_title:
description: Published project title for `project`, otherwise null. Plain text; show it as text, never as HTML.
oneOf:
- type: string
minLength: 1
maxLength: 100
- type: 'null'
repository_verified:
type: boolean
description: True only for a project whose linked repository the latest server check found public on GitHub ("backed by a public repository"). It does not prove authorship.
similarity:
$ref: '#/MatchSimilarityBand'
MatchSemanticEvidenceList:
type: array
description: 'Semantic explanation items in a stable order: `high` before `medium`, then by similarity, then by the order of the requirements in the need. At most the versioned per-entry limit is returned. It is empty for a bank search, while vectors are not ready, when ML is unavailable, and when no requirement reaches a band; `unknown_flags` names `ml_unavailable` when the semantic component itself is unknown.'
maxItems: 12
items:
$ref: '#/MatchSemanticEvidence'
MatchPublicStack:
type: array
maxItems: 4
@@ -5048,6 +5258,7 @@ MatchConfirmedCandidate:
- strength
- public_context
- evidence_summary
- semantic_evidence
- components
- unknown_flags
properties:
@@ -5072,6 +5283,8 @@ MatchConfirmedCandidate:
$ref: '#/MatchPublicContext'
evidence_summary:
$ref: '#/MatchEvidenceSummary'
semantic_evidence:
$ref: '#/MatchSemanticEvidenceList'
components:
$ref: '#/MatchConfirmedComponents'
unknown_flags:
@@ -5089,6 +5302,7 @@ MatchUnconfirmedCandidate:
- strength
- public_context
- evidence_summary
- semantic_evidence
- components
- unknown_flags
properties:
@@ -5115,6 +5329,8 @@ MatchUnconfirmedCandidate:
$ref: '#/MatchPublicContext'
evidence_summary:
$ref: '#/MatchEvidenceSummary'
semantic_evidence:
$ref: '#/MatchSemanticEvidenceList'
components:
$ref: '#/MatchUnconfirmedComponents'
unknown_flags:
@@ -6600,6 +6816,8 @@ CardField:
- salary_compatibility: a nullable compatibility outcome with no salary amounts or bounds.
- projects: the projects of the profile with their title, description, stack tags, and whether a linked repository is a public GitHub repository. The titles and descriptions are text that the candidate writes and may identify them; the repository address and its owner never reach an organization through the card. Published projects are also the text that semantic ranking reads and that match explanations name.
- soft_skills, location, and relocation: retained only for compatibility in existing saved sets; they are not returned by the anonymous card.
@@ -6617,10 +6835,11 @@ CardField:
- location
- relocation
- work_formats
- projects
CardFieldSet:
type: array
minItems: 0
maxItems: 9
maxItems: 10
uniqueItems: true
description: Distinct card fields. The server stores them in ascending order of the codes and answers them in that order, whatever order the client sent, so equal sets are equal arrays.
items:
@@ -6880,9 +7099,41 @@ CandidateSalaryCompatibility:
enum:
- compatible
- not_compatible
CardProject:
type: object
description: One published project as the card shows it. It never carries the repository address, the repository owner, or any text fetched from the repository.
additionalProperties: false
required:
- title
- description
- stack
- repository_verified
properties:
title:
type: string
minLength: 1
maxLength: 100
description: Project title as the candidate published it. Plain text; show it as text, never as HTML.
description:
description: Published project description, or null. Plain text; show it as text, never as HTML.
oneOf:
- type: string
minLength: 1
maxLength: 500
- type: 'null'
stack:
type: array
maxItems: 10
description: Published technology tags of the project.
items:
$ref: '#/StackTag'
repository_verified:
type: boolean
description: True when the latest server check found the linked repository on GitHub and it is public. It does not prove that the candidate wrote the code.
AnonymousCardContent:
type: object
description: The anonymous candidate card as an organization reads it. Only explicitly published values reach it; unconfirmed stack suggestions and unknown values never do. Stack output uses a closed taxonomy. It carries no name, contact, resume text, employer, salary figure, account or profile identifier, and no schema of the private profile or of a contact disclosure is reachable from it; a contact reaches an organization only through the contact grant of an accepted invitation. Each property is null when its field is not published or the candidate has no value for it, so the card does not tell the two apart. The set of properties is closed, and an organization-visible card must never gain a property that identifies the candidate. The search ranking and the full card of an organization's search result are defined by the search contract, which reuses this content.
description: 'The anonymous candidate card as an organization reads it. Only explicitly published values reach it; unconfirmed stack suggestions and unknown values never do. Stack output uses a closed taxonomy. It carries no name, contact, resume text, employer, salary figure, account or profile identifier, and no schema of the private profile or of a contact disclosure is reachable from it; a contact reaches an organization only through the contact grant of an accepted invitation. Each property is null when its field is not published or the candidate has no value for it, so the card does not tell the two apart. The set of properties is closed, and an organization-visible card must never gain a property that identifies the candidate. The one free-text exception is `projects`: the candidate writes it and publishes it by a separate explicit choice, the card never adds the repository address or owner to it, and the client warns that a project title can identify its author. The search ranking
and the full card of an organization''s search result are defined by the search contract, which reuses this content.'
additionalProperties: false
required:
- pseudonym
@@ -6892,6 +7143,7 @@ AnonymousCardContent:
- experience_band
- work_formats
- salary_compatibility
- projects
properties:
pseudonym:
type: string
@@ -6946,6 +7198,14 @@ AnonymousCardContent:
- $ref: '#/CandidateSalaryCompatibility'
- type: 'null'
description: Nullable compatibility result with no salary values.
projects:
type:
- array
- 'null'
maxItems: 10
description: 'Published projects in the candidate''s order, or null. Cohort generalization never changes them: they are text the candidate chose to publish, so publishing them can make the card unique.'
items:
$ref: '#/CardProject'
CardPreview:
type: object
description: A private candidate preview computed from the current profile, publication, and consent ledger. Its pseudonym uses a separate preview context and is not an organization's alias. Organization-specific visibility filters and cohort checks can further generalize or suppress the organization-facing card. This read creates no view or history record and never reaches an organization. `card` is null while the profile is closed. `evidence` is what an organization would read in the evidence section of the card, one supporting assessment fact for each category of the card, and is null exactly when `card` is null; the organization-facing section can still be generalized or suppressed.
@@ -7190,7 +7450,9 @@ ProblemCode:
- internal (500): unexpected server error.
- not_implemented (501): the operation is in the contract but not implemented yet.'
- not_implemented (501): the operation is in the contract but not implemented yet.
- service_unavailable (503): the service cannot serve the request now, for example while a model loads; retry later.'
enum:
- validation_failed
- verification_token_invalid
@@ -7212,6 +7474,7 @@ ProblemCode:
- rate_limited
- internal
- not_implemented
- service_unavailable
ProblemFieldError:
type: object
description: One reason why a request field or parameter is invalid.
@@ -515,6 +515,138 @@ schemas:
$ref: "#/schemas/ProfileItemStatus"
source:
$ref: "#/schemas/ProfileClaimSource"
ProfileProjectTitle:
type: string
minLength: 1
maxLength: 100
pattern: '^\S(?:.*\S)?$'
description: >-
Name of a project as the candidate wants an organization to read it. It
has no leading or trailing whitespace and no line breaks. When the
candidate publishes the `projects` card field, the title reaches the
anonymous card and match explanations, so it must not contain a name,
a contact, or a repository address. Plain text; clients show it as
text, never as HTML.
ProfileProjectDescription:
type: string
minLength: 1
maxLength: 500
description: >-
What the project does and what the candidate did in it. It may contain
line breaks. When the `projects` card field is published it reaches the
anonymous card. Plain text; clients show it as text, never as HTML.
ProfileRepositoryUrl:
type: string
minLength: 22
maxLength: 160
pattern: '^https://github\.com/[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})/[A-Za-z0-9._-]{1,100}/?$'
description: >-
Address of a public GitHub repository of the project in the form
https://github.com/<owner>/<repository>. The server accepts only this
host and form, removes a trailing slash and a `.git` suffix, and stores
the canonical address. Organizations never receive the address before
an accepted invitation, because the owner name can identify the
candidate.
examples:
- https://github.com/example-org/payments-ledger
ProfileRepositoryCheckState:
type: string
description: |-
Result of the latest server check of a project repository on the public GitHub API. The server only reads public metadata; a check never proves that the candidate wrote the code.
- pending: the check is scheduled and has not finished yet.
- verified: the repository exists and is public. Match explanations may then say that the project is backed by a public repository.
- not_found: GitHub reports no such public repository; it may be private, renamed to another owner, or deleted.
- unavailable: GitHub could not be asked, for example because of its rate limit; the server retries later.
enum:
- pending
- verified
- not_found
- unavailable
ProfileRepositoryCheck:
type: object
description: >-
State of the server check of a project repository. Read-only; no
request writes it. The fetched metadata itself (description, topics,
languages, and a plain-text README excerpt) is used only for ranking
and is never returned or shown.
additionalProperties: false
required:
- state
- checked_at
properties:
state:
$ref: "#/schemas/ProfileRepositoryCheckState"
checked_at:
description: Time of the last finished check, or null before the first one.
oneOf:
- $ref: "./common_schemas.yml#/schemas/Timestamp"
- type: "null"
ProfileProjectStack:
type: array
maxItems: 10
description: >-
Technology tags of the project, each tag at most once without regard to
letter case.
items:
$ref: "./questionnaire_schemas.yml#/schemas/StackTag"
ProfileRepositoryCheckRequest:
type: object
description: Result of a request to check the linked repositories again.
additionalProperties: false
required:
- scheduled
properties:
scheduled:
type: integer
format: int32
minimum: 0
maximum: 10
description: Number of repository checks that the request scheduled.
ProfileProjectItem:
type: object
description: >-
One project of the candidate with its confirmation state and provenance.
A project is a claim of trust level 0 that the candidate types; a
linked repository adds a separate server check (`repository_check`),
never a higher trust level. The project reaches organizations only when
the candidate publishes the `projects` card field, and then without the
repository address.
additionalProperties: false
required:
- title
- description
- stack
- repository_url
- repository_check
- status
- source
properties:
title:
$ref: "#/schemas/ProfileProjectTitle"
description:
description: What the project is about, or null when the candidate gives nothing.
oneOf:
- $ref: "#/schemas/ProfileProjectDescription"
- type: "null"
stack:
$ref: "#/schemas/ProfileProjectStack"
repository_url:
description: Canonical repository address, or null when the project links none.
oneOf:
- $ref: "#/schemas/ProfileRepositoryUrl"
- type: "null"
repository_check:
description: >-
The server check of the linked repository, or null when the project
links none.
oneOf:
- $ref: "#/schemas/ProfileRepositoryCheck"
- type: "null"
status:
$ref: "#/schemas/ProfileItemStatus"
source:
$ref: "#/schemas/ProfileClaimSource"
ProfileExperienceOverlapStatus:
type: string
description: Whether the candidate confirmed that two overlapping periods are genuine parallel work.
@@ -622,8 +754,8 @@ schemas:
type: object
description: >-
The private profile of the current candidate: full name and contacts,
stack, roles, work experience, soft skills, and desired terms, each
value with its confirmation state and provenance. It is personal data
stack, roles, work experience, soft skills, projects, and desired
terms, each value with its confirmation state and provenance. It is personal data
that only the candidate reads. It is never an organization-visible
schema: an organization sees a candidate only through the anonymous
card and, after an accepted invitation, through the contact grant, and
@@ -650,6 +782,7 @@ schemas:
- experience
- experience_overlaps
- soft_skills
- projects
- terms
- confirmed_categories
- updated_at
@@ -698,6 +831,14 @@ schemas:
most once without regard to letter case.
items:
$ref: "#/schemas/ProfileSoftSkillItem"
projects:
type: array
maxItems: 10
description: >-
Projects in the order the candidate gave them, each repository
address at most once.
items:
$ref: "#/schemas/ProfileProjectItem"
terms:
$ref: "#/schemas/ProfileTerms"
confirmed_categories:
@@ -945,12 +1086,42 @@ schemas:
- type: "null"
status:
$ref: "#/schemas/ProfileItemStatus"
ProfileProjectItemInput:
type: object
description: >-
Decision about one project in a request; see CandidateProfileUpdate for
the rules of `status`. The server answers 400 with the pointer of the
field for a repository address that is not a GitHub repository address,
a repeated repository, or a repeated stack tag.
additionalProperties: false
required:
- title
- description
- stack
- repository_url
- status
properties:
title:
$ref: "#/schemas/ProfileProjectTitle"
description:
oneOf:
- $ref: "#/schemas/ProfileProjectDescription"
- type: "null"
stack:
$ref: "#/schemas/ProfileProjectStack"
repository_url:
oneOf:
- $ref: "#/schemas/ProfileRepositoryUrl"
- type: "null"
status:
$ref: "#/schemas/ProfileItemStatus"
CandidateProfileUpdate:
type: object
description: >-
Complete new state of the candidate profile. It replaces every stored
value as a whole: a single field sent as null is unknown and is removed,
and a list replaces the stored list. The body is personal data.
and a list replaces the stored list; only `projects` may be omitted,
which keeps the stored projects. The body is personal data.
Each value carries a decision `status`. `confirmed` sets a manual value
or confirms a stored suggestion; confirming a suggestion with exactly
@@ -1025,5 +1196,17 @@ schemas:
that repeats an earlier one without regard to letter case.
items:
$ref: "#/schemas/ProfileSoftSkillItemInput"
projects:
type: array
maxItems: 10
description: >-
Projects. Unlike the other lists this one is optional: a body
without `projects` keeps the stored projects unchanged, so a client
that does not know the section never deletes it, and an array,
including an empty one, replaces the stored list. A new or changed
repository address schedules a server check on the public GitHub
API after the save commits; the save itself never waits for GitHub.
items:
$ref: "#/schemas/ProfileProjectItemInput"
terms:
$ref: "#/schemas/ProfileTermsInput"
@@ -353,6 +353,91 @@ schemas:
maxItems: 12
items:
$ref: "#/schemas/MatchEvidenceSummaryItem"
MatchRequirementKind:
type: string
description: Kind of the need requirement that an explanation item answers.
enum:
- required_skill
- desired_skill
- task
MatchSemanticItemKind:
type: string
description: |-
Kind of the published card item that matched a requirement.
- project: one published project; `project_title` names it.
- stack: the recognized technology codes of the card.
- roles: the specializations and grades that the card shows.
enum:
- project
- stack
- roles
MatchSimilarityBand:
type: string
description: >-
Coarse band of the cosine similarity between the requirement and the
matched item under the versioned policy thresholds. `high` and `medium`
are the only values; a weaker similarity produces no item. The band is
a computed similarity of two texts, not a judgement of the candidate.
enum:
- high
- medium
MatchSemanticEvidence:
type: object
description: >-
Why the entry is in the result: one confirmed requirement of the need
and the published card item with the highest semantic similarity to it.
The server computes it from stored vectors and the versioned
thresholds; no model writes text into it. `requirement_text` is the
confirmed text of the organization's own need. `project_title` is the
title the candidate published with the `projects` card field and is
null for other kinds. No repository address, owner, or fetched
repository text is ever part of it.
additionalProperties: false
required:
- requirement_kind
- requirement_text
- item_kind
- project_title
- repository_verified
- similarity
properties:
requirement_kind:
$ref: "#/schemas/MatchRequirementKind"
requirement_text:
type: string
minLength: 1
maxLength: 300
description: Confirmed skill name or task text of the need. Plain text; show it as text, never as HTML.
item_kind:
$ref: "#/schemas/MatchSemanticItemKind"
project_title:
description: Published project title for `project`, otherwise null. Plain text; show it as text, never as HTML.
oneOf:
- type: string
minLength: 1
maxLength: 100
- type: "null"
repository_verified:
type: boolean
description: >-
True only for a project whose linked repository the latest server
check found public on GitHub ("backed by a public repository"). It
does not prove authorship.
similarity:
$ref: "#/schemas/MatchSimilarityBand"
MatchSemanticEvidenceList:
type: array
description: >-
Semantic explanation items in a stable order: `high` before `medium`,
then by similarity, then by the order of the requirements in the need.
At most the versioned per-entry limit is returned. It is empty for a
bank search, while vectors are not ready, when ML is unavailable, and
when no requirement reaches a band; `unknown_flags` names
`ml_unavailable` when the semantic component itself is unknown.
maxItems: 12
items:
$ref: "#/schemas/MatchSemanticEvidence"
MatchPublicStack:
type: array
maxItems: 4
@@ -469,6 +554,7 @@ schemas:
- strength
- public_context
- evidence_summary
- semantic_evidence
- components
- unknown_flags
properties:
@@ -493,6 +579,8 @@ schemas:
$ref: "#/schemas/MatchPublicContext"
evidence_summary:
$ref: "#/schemas/MatchEvidenceSummary"
semantic_evidence:
$ref: "#/schemas/MatchSemanticEvidenceList"
components:
$ref: "#/schemas/MatchConfirmedComponents"
unknown_flags:
@@ -514,6 +602,7 @@ schemas:
- strength
- public_context
- evidence_summary
- semantic_evidence
- components
- unknown_flags
properties:
@@ -540,6 +629,8 @@ schemas:
$ref: "#/schemas/MatchPublicContext"
evidence_summary:
$ref: "#/schemas/MatchEvidenceSummary"
semantic_evidence:
$ref: "#/schemas/MatchSemanticEvidenceList"
components:
$ref: "#/schemas/MatchUnconfirmedComponents"
unknown_flags:
@@ -34,6 +34,7 @@ schemas:
- experience: a coarse total-experience band, without employers, periods, or descriptions.
- work_formats: explicitly selected work formats from the private questionnaire.
- salary_compatibility: a nullable compatibility outcome with no salary amounts or bounds.
- projects: the projects of the profile with their title, description, stack tags, and whether a linked repository is a public GitHub repository. The titles and descriptions are text that the candidate writes and may identify them; the repository address and its owner never reach an organization through the card. Published projects are also the text that semantic ranking reads and that match explanations name.
- soft_skills, location, and relocation: retained only for compatibility in existing saved sets; they are not returned by the anonymous card.
Only values that the candidate confirmed ever reach the card: an unconfirmed suggestion (status `extracted`) and an unknown value never do, whatever the field set says.
@@ -49,10 +50,11 @@ schemas:
- location
- relocation
- work_formats
- projects
CardFieldSet:
type: array
minItems: 0
maxItems: 9
maxItems: 10
uniqueItems: true
description: >-
Distinct card fields. The server stores them in ascending order of
@@ -383,6 +385,47 @@ schemas:
enum:
- compatible
- not_compatible
CardProject:
type: object
description: >-
One published project as the card shows it. It never carries the
repository address, the repository owner, or any text fetched from the
repository.
additionalProperties: false
required:
- title
- description
- stack
- repository_verified
properties:
title:
type: string
minLength: 1
maxLength: 100
description: >-
Project title as the candidate published it. Plain text; show it as
text, never as HTML.
description:
description: >-
Published project description, or null. Plain text; show it as text,
never as HTML.
oneOf:
- type: string
minLength: 1
maxLength: 500
- type: "null"
stack:
type: array
maxItems: 10
description: Published technology tags of the project.
items:
$ref: "./questionnaire_schemas.yml#/schemas/StackTag"
repository_verified:
type: boolean
description: >-
True when the latest server check found the linked repository on
GitHub and it is public. It does not prove that the candidate wrote
the code.
AnonymousCardContent:
type: object
description: >-
@@ -396,8 +439,11 @@ schemas:
invitation. Each property is null when its field is not published or
the candidate has no value for it, so the card does not tell the two
apart. The set of properties is closed, and an organization-visible
card must never gain a property that identifies the candidate. The
search ranking and the full card of an organization's search result
card must never gain a property that identifies the candidate. The one
free-text exception is `projects`: the candidate writes it and
publishes it by a separate explicit choice, the card never adds the
repository address or owner to it, and the client warns that a project
title can identify its author. The search ranking and the full card of an organization's search result
are defined by the search contract, which reuses this
content.
additionalProperties: false
@@ -409,6 +455,7 @@ schemas:
- experience_band
- work_formats
- salary_compatibility
- projects
properties:
pseudonym:
type: string
@@ -465,6 +512,17 @@ schemas:
- $ref: "#/schemas/CandidateSalaryCompatibility"
- type: "null"
description: Nullable compatibility result with no salary values.
projects:
type:
- array
- "null"
maxItems: 10
description: >-
Published projects in the candidate's order, or null. Cohort
generalization never changes them: they are text the candidate
chose to publish, so publishing them can make the card unique.
items:
$ref: "#/schemas/CardProject"
CardPreview:
type: object
description: >-
@@ -89,6 +89,7 @@ schemas:
- rate_limited (429): too many requests; see Retry-After.
- internal (500): unexpected server error.
- not_implemented (501): the operation is in the contract but not implemented yet.
- service_unavailable (503): the service cannot serve the request now, for example while a model loads; retry later.
enum:
- validation_failed
- verification_token_invalid
@@ -110,6 +111,7 @@ schemas:
- rate_limited
- internal
- not_implemented
- service_unavailable
ProblemFieldError:
type: object
description: One reason why a request field or parameter is invalid.
+393 -5
View File
@@ -699,6 +699,39 @@ paths:
$ref: '#/components/responses/ProfileVersionConflict'
default:
$ref: '#/components/responses/Problem'
/api/v1/me/profile/repository-checks:
post:
operationId: RequestMyRepositoryChecks
summary: Ask the server to check the linked project repositories again.
description: |-
Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, and an allowed Origin. The request has no body. It schedules a new check of every repository that the current profile links, for example after the candidate made a repository public, and answers 202 with the number of scheduled checks; the checks run in the background and `GetMyProfile` shows their state in `projects[].repository_check`. A profile without linked repositories answers 202 with 0.
A check reads only public metadata from the public GitHub API (`api.github.com`): whether the repository exists and is public, its description, topics, languages, and the beginning of its README as plain text. The server never fetches any other host, never follows a redirect to another host, and never shows the fetched text; it uses it only for semantic ranking. A verified repository does not prove that the candidate wrote the code.
The operation is limited per candidate: a second request inside the versioned window answers 429 rate_limited with Retry-After and schedules nothing. A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account answers 403 forbidden.
security:
- sessionCookie: []
sessionCsrf: []
tags:
- candidate
responses:
'202':
description: The checks are scheduled.
headers:
Cache-Control:
$ref: '#/components/headers/CacheControlNoStore'
content:
application/json:
schema:
$ref: '#/components/schemas/ProfileRepositoryCheckRequest'
'401':
$ref: '#/components/responses/Unauthenticated'
'403':
$ref: '#/components/responses/CsrfCheckFailedOrForbidden'
'429':
$ref: '#/components/responses/TooManyRequests'
default:
$ref: '#/components/responses/Problem'
/api/v1/me/assessment-availability:
get:
operationId: GetMyAssessmentAvailability
@@ -1712,7 +1745,9 @@ paths:
Every entry is one candidate specialization. A confirmed result in Backend never confirms Networks for the same candidate. The `main`, `near`, and `unconfirmed` arrays are separate groups. A confirmed category with required-skill coverage below 0.25 belongs to `near`; other confirmed entries belong to `main` (FR09). Entries in `unconfirmed` are ordered by Fit, then coverage, then a stable internal tie-breaker that is never returned. Their category and strength remain null, and they have no theta, T, P, or test percentile. The search result uses the organization-scoped opaque `candidate_handle` as its display pseudonym and invitation reference, never a candidate account or profile identifier.
The card context is limited to safe public fields: recognized stack tags, coarse experience, accepted work formats, and coarse salary compatibility. It contains no contact, candidate location, salary amount or minimum, raw answer, arbitrary profile text, or reason for withheld FSP data. Evidence explanations use bounded codes, not free text. When ML is unavailable, semantic similarity uses the neutral 0.5 specified by FR09 and `unknown_flags` names `ml_unavailable`. For fewer than 30 comparable real candidates, the search uses neutral T = 0.5, returns no percentile value, and names `cohort_below_30`. When the comparable real cohort of a category reaches the minimum, the percentile is still not computed (the organization-safe projection carries no theta), T stays the neutral 0.5, the percentile stays null, and `unknown_flags` names `percentile_not_computed`; the search does not fail.
The card context is limited to safe public fields: recognized stack tags, coarse experience, accepted work formats, and coarse salary compatibility. It contains no contact, candidate location, salary amount or minimum, raw answer, arbitrary profile text, or reason for withheld FSP data. Evidence explanations use bounded codes, not free text.
Semantic similarity `Sem` is the calibrated cosine between the stored vector of the need's confirmed requirements snapshot and the stored vector of the candidate's published card text (roles, recognized stack, and published projects with the public metadata of their verified repositories). The search never calls the ML service: vectors are computed in the background after a change, and an entry whose vectors are missing, stale for the current model, or not computed because ML is unavailable uses the neutral 0.5 and names `ml_unavailable` in `unknown_flags`. `semantic_evidence` lists, for a need search, the confirmed requirements whose closest published card item reaches a similarity band of the versioned policy; it names a project only by the title that the candidate published with the `projects` card field and says whether its repository is a verified public one, never the repository address or owner. Showing a project title records the `projects` field in the candidate's access history. For fewer than 30 comparable real candidates, the search uses neutral T = 0.5, returns no percentile value, and names `cohort_below_30`. When the comparable real cohort of a category reaches the minimum, the percentile is still not computed (the organization-safe projection carries no theta), T stays the neutral 0.5, the percentile stays null, and `unknown_flags` names `percentile_not_computed`; the search does not fail.
A missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate account answers 403 forbidden; an unknown organization or account without active membership answers 404 not_found. The response is `Cache-Control: no-store`.
security:
@@ -1754,6 +1789,8 @@ paths:
$ref: '#/components/examples/CohortBelow30'
truncated:
$ref: '#/components/examples/Truncated'
semantic_evidence:
$ref: '#/components/examples/SemanticEvidence'
'400':
$ref: '#/components/responses/ValidationFailed'
'401':
@@ -3643,6 +3680,7 @@ components:
- rate_limited (429): too many requests; see Retry-After.
- internal (500): unexpected server error.
- not_implemented (501): the operation is in the contract but not implemented yet.
- service_unavailable (503): the service cannot serve the request now, for example while a model loads; retry later.
enum:
- validation_failed
- verification_token_invalid
@@ -3664,6 +3702,7 @@ components:
- rate_limited
- internal
- not_implemented
- service_unavailable
ProblemFieldError:
type: object
description: One reason why a request field or parameter is invalid.
@@ -4755,7 +4794,7 @@ components:
CandidateProfile:
type: object
description: |-
The private profile of the current candidate: full name and contacts, stack, roles, work experience, soft skills, and desired terms, each value with its confirmation state and provenance. It is personal data that only the candidate reads. It is never an organization-visible schema: an organization sees a candidate only through the anonymous card and, after an accepted invitation, through the contact grant, and no organization schema refers to this one.
The private profile of the current candidate: full name and contacts, stack, roles, work experience, soft skills, projects, and desired terms, each value with its confirmation state and provenance. It is personal data that only the candidate reads. It is never an organization-visible schema: an organization sees a candidate only through the anonymous card and, after an accepted invitation, through the contact grant, and no organization schema refers to this one.
Every value is a claim of trust level 0. The `self_assessed_grade` of a role is what the candidate says; the `confirmed_categories` list is what assessment results established, and the two are never mixed. A candidate who has not saved the profile gets version 0, every single field `unknown`, empty lists, and null `updated_at`.
The profile is manual by nature and complete without a file: no field requires a resume, the ML service, or an FSP account, and a candidate with none of them has the same fields. Work formats live in the questionnaire; a candidate's assessment starts from the questionnaire, not from this profile.
additionalProperties: false
@@ -4768,6 +4807,7 @@ components:
- experience
- experience_overlaps
- soft_skills
- projects
- terms
- confirmed_categories
- updated_at
@@ -4808,6 +4848,12 @@ components:
description: Soft skills in the order the candidate gave them, each skill at most once without regard to letter case.
items:
$ref: '#/components/schemas/ProfileSoftSkillItem'
projects:
type: array
maxItems: 10
description: Projects in the order the candidate gave them, each repository address at most once.
items:
$ref: '#/components/schemas/ProfileProjectItem'
terms:
$ref: '#/components/schemas/ProfileTerms'
confirmed_categories:
@@ -5022,7 +5068,7 @@ components:
CandidateProfileUpdate:
type: object
description: |-
Complete new state of the candidate profile. It replaces every stored value as a whole: a single field sent as null is unknown and is removed, and a list replaces the stored list. The body is personal data.
Complete new state of the candidate profile. It replaces every stored value as a whole: a single field sent as null is unknown and is removed, and a list replaces the stored list; only `projects` may be omitted, which keeps the stored projects. The body is personal data.
Each value carries a decision `status`. `confirmed` sets a manual value or confirms a stored suggestion; confirming a suggestion with exactly its stored value keeps its origin and quote, and any other value makes the claim manual. `extracted` keeps a stored suggestion unconfirmed and is accepted only with exactly the stored value; any other use answers 400 with the pointer of that status, for example `/stack/1/status`. The provenance, the trust level, and the confirmed categories are not part of the request, and unknown fields are rejected, so a request can neither mark a claim as verified nor write a confirmed grade or a category.
additionalProperties: false
required:
@@ -5073,6 +5119,12 @@ components:
description: Soft skills. The server answers 400 with the pointer of a skill that repeats an earlier one without regard to letter case.
items:
$ref: '#/components/schemas/ProfileSoftSkillItemInput'
projects:
type: array
maxItems: 10
description: 'Projects. Unlike the other lists this one is optional: a body without `projects` keeps the stored projects unchanged, so a client that does not know the section never deletes it, and an array, including an empty one, replaces the stored list. A new or changed repository address schedules a server check on the public GitHub API after the save commits; the save itself never waits for GitHub.'
items:
$ref: '#/components/schemas/ProfileProjectItemInput'
terms:
$ref: '#/components/schemas/ProfileTermsInput'
AssessmentMode:
@@ -9291,6 +9343,7 @@ components:
- experience: a coarse total-experience band, without employers, periods, or descriptions.
- work_formats: explicitly selected work formats from the private questionnaire.
- salary_compatibility: a nullable compatibility outcome with no salary amounts or bounds.
- projects: the projects of the profile with their title, description, stack tags, and whether a linked repository is a public GitHub repository. The titles and descriptions are text that the candidate writes and may identify them; the repository address and its owner never reach an organization through the card. Published projects are also the text that semantic ranking reads and that match explanations name.
- soft_skills, location, and relocation: retained only for compatibility in existing saved sets; they are not returned by the anonymous card.
Only values that the candidate confirmed ever reach the card: an unconfirmed suggestion (status `extracted`) and an unknown value never do, whatever the field set says.
@@ -9306,10 +9359,11 @@ components:
- location
- relocation
- work_formats
- projects
CardFieldSet:
type: array
minItems: 0
maxItems: 9
maxItems: 10
uniqueItems: true
description: Distinct card fields. The server stores them in ascending order of the codes and answers them in that order, whatever order the client sent, so equal sets are equal arrays.
items:
@@ -9526,7 +9580,7 @@ components:
$ref: '#/components/schemas/EvidenceBasis'
AnonymousCardContent:
type: object
description: The anonymous candidate card as an organization reads it. Only explicitly published values reach it; unconfirmed stack suggestions and unknown values never do. Stack output uses a closed taxonomy. It carries no name, contact, resume text, employer, salary figure, account or profile identifier, and no schema of the private profile or of a contact disclosure is reachable from it; a contact reaches an organization only through the contact grant of an accepted invitation. Each property is null when its field is not published or the candidate has no value for it, so the card does not tell the two apart. The set of properties is closed, and an organization-visible card must never gain a property that identifies the candidate. The search ranking and the full card of an organization's search result are defined by the search contract, which reuses this content.
description: 'The anonymous candidate card as an organization reads it. Only explicitly published values reach it; unconfirmed stack suggestions and unknown values never do. Stack output uses a closed taxonomy. It carries no name, contact, resume text, employer, salary figure, account or profile identifier, and no schema of the private profile or of a contact disclosure is reachable from it; a contact reaches an organization only through the contact grant of an accepted invitation. Each property is null when its field is not published or the candidate has no value for it, so the card does not tell the two apart. The set of properties is closed, and an organization-visible card must never gain a property that identifies the candidate. The one free-text exception is `projects`: the candidate writes it and publishes it by a separate explicit choice, the card never adds the repository address or owner to it, and the client warns that a project title can identify its author. The search ranking and the full card of an organization''s search result are defined by the search contract, which reuses this content.'
additionalProperties: false
required:
- pseudonym
@@ -9536,6 +9590,7 @@ components:
- experience_band
- work_formats
- salary_compatibility
- projects
properties:
pseudonym:
type: string
@@ -9590,6 +9645,14 @@ components:
- $ref: '#/components/schemas/CandidateSalaryCompatibility'
- type: 'null'
description: Nullable compatibility result with no salary values.
projects:
type:
- array
- 'null'
maxItems: 10
description: 'Published projects in the candidate''s order, or null. Cohort generalization never changes them: they are text the candidate chose to publish, so publishing them can make the card unique.'
items:
$ref: '#/components/schemas/CardProject'
CardPreview:
type: object
description: A private candidate preview computed from the current profile, publication, and consent ledger. Its pseudonym uses a separate preview context and is not an organization's alias. Organization-specific visibility filters and cohort checks can further generalize or suppress the organization-facing card. This read creates no view or history record and never reaches an organization. `card` is null while the profile is closed. `evidence` is what an organization would read in the evidence section of the card, one supporting assessment fact for each category of the card, and is null exactly when `card` is null; the organization-facing section can still be generalized or suppressed.
@@ -10102,6 +10165,134 @@ components:
minLength: 1
maxLength: 128
description: Password chosen for the registration that issued the code. The server applies NFKC normalization and the login length bounds, without reapplying the current new-registration blocklist.
ProfileProjectTitle:
type: string
minLength: 1
maxLength: 100
pattern: ^\S(?:.*\S)?$
description: Name of a project as the candidate wants an organization to read it. It has no leading or trailing whitespace and no line breaks. When the candidate publishes the `projects` card field, the title reaches the anonymous card and match explanations, so it must not contain a name, a contact, or a repository address. Plain text; clients show it as text, never as HTML.
ProfileProjectDescription:
type: string
minLength: 1
maxLength: 500
description: What the project does and what the candidate did in it. It may contain line breaks. When the `projects` card field is published it reaches the anonymous card. Plain text; clients show it as text, never as HTML.
ProfileProjectStack:
type: array
maxItems: 10
description: Technology tags of the project, each tag at most once without regard to letter case.
items:
$ref: '#/components/schemas/StackTag'
ProfileRepositoryUrl:
type: string
minLength: 22
maxLength: 160
pattern: ^https://github\.com/[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})/[A-Za-z0-9._-]{1,100}/?$
description: Address of a public GitHub repository of the project in the form https://github.com/<owner>/<repository>. The server accepts only this host and form, removes a trailing slash and a `.git` suffix, and stores the canonical address. Organizations never receive the address before an accepted invitation, because the owner name can identify the candidate.
examples:
- https://github.com/example-org/payments-ledger
ProfileRepositoryCheckState:
type: string
description: |-
Result of the latest server check of a project repository on the public GitHub API. The server only reads public metadata; a check never proves that the candidate wrote the code.
- pending: the check is scheduled and has not finished yet.
- verified: the repository exists and is public. Match explanations may then say that the project is backed by a public repository.
- not_found: GitHub reports no such public repository; it may be private, renamed to another owner, or deleted.
- unavailable: GitHub could not be asked, for example because of its rate limit; the server retries later.
enum:
- pending
- verified
- not_found
- unavailable
ProfileRepositoryCheck:
type: object
description: State of the server check of a project repository. Read-only; no request writes it. The fetched metadata itself (description, topics, languages, and a plain-text README excerpt) is used only for ranking and is never returned or shown.
additionalProperties: false
required:
- state
- checked_at
properties:
state:
$ref: '#/components/schemas/ProfileRepositoryCheckState'
checked_at:
description: Time of the last finished check, or null before the first one.
oneOf:
- $ref: '#/components/schemas/Timestamp'
- type: 'null'
ProfileProjectItem:
type: object
description: One project of the candidate with its confirmation state and provenance. A project is a claim of trust level 0 that the candidate types; a linked repository adds a separate server check (`repository_check`), never a higher trust level. The project reaches organizations only when the candidate publishes the `projects` card field, and then without the repository address.
additionalProperties: false
required:
- title
- description
- stack
- repository_url
- repository_check
- status
- source
properties:
title:
$ref: '#/components/schemas/ProfileProjectTitle'
description:
description: What the project is about, or null when the candidate gives nothing.
oneOf:
- $ref: '#/components/schemas/ProfileProjectDescription'
- type: 'null'
stack:
$ref: '#/components/schemas/ProfileProjectStack'
repository_url:
description: Canonical repository address, or null when the project links none.
oneOf:
- $ref: '#/components/schemas/ProfileRepositoryUrl'
- type: 'null'
repository_check:
description: The server check of the linked repository, or null when the project links none.
oneOf:
- $ref: '#/components/schemas/ProfileRepositoryCheck'
- type: 'null'
status:
$ref: '#/components/schemas/ProfileItemStatus'
source:
$ref: '#/components/schemas/ProfileClaimSource'
ProfileProjectItemInput:
type: object
description: Decision about one project in a request; see CandidateProfileUpdate for the rules of `status`. The server answers 400 with the pointer of the field for a repository address that is not a GitHub repository address, a repeated repository, or a repeated stack tag.
additionalProperties: false
required:
- title
- description
- stack
- repository_url
- status
properties:
title:
$ref: '#/components/schemas/ProfileProjectTitle'
description:
oneOf:
- $ref: '#/components/schemas/ProfileProjectDescription'
- type: 'null'
stack:
$ref: '#/components/schemas/ProfileProjectStack'
repository_url:
oneOf:
- $ref: '#/components/schemas/ProfileRepositoryUrl'
- type: 'null'
status:
$ref: '#/components/schemas/ProfileItemStatus'
ProfileRepositoryCheckRequest:
type: object
description: Result of a request to check the linked repositories again.
additionalProperties: false
required:
- scheduled
properties:
scheduled:
type: integer
format: int32
minimum: 0
maximum: 10
description: Number of repository checks that the request scheduled.
AssessmentRealMode:
type: string
description: Server-selected mode available to a real category assessment.
@@ -11031,6 +11222,70 @@ components:
maxItems: 12
items:
$ref: '#/components/schemas/MatchEvidenceSummaryItem'
MatchRequirementKind:
type: string
description: Kind of the need requirement that an explanation item answers.
enum:
- required_skill
- desired_skill
- task
MatchSemanticItemKind:
type: string
description: |-
Kind of the published card item that matched a requirement.
- project: one published project; `project_title` names it.
- stack: the recognized technology codes of the card.
- roles: the specializations and grades that the card shows.
enum:
- project
- stack
- roles
MatchSimilarityBand:
type: string
description: Coarse band of the cosine similarity between the requirement and the matched item under the versioned policy thresholds. `high` and `medium` are the only values; a weaker similarity produces no item. The band is a computed similarity of two texts, not a judgement of the candidate.
enum:
- high
- medium
MatchSemanticEvidence:
type: object
description: 'Why the entry is in the result: one confirmed requirement of the need and the published card item with the highest semantic similarity to it. The server computes it from stored vectors and the versioned thresholds; no model writes text into it. `requirement_text` is the confirmed text of the organization''s own need. `project_title` is the title the candidate published with the `projects` card field and is null for other kinds. No repository address, owner, or fetched repository text is ever part of it.'
additionalProperties: false
required:
- requirement_kind
- requirement_text
- item_kind
- project_title
- repository_verified
- similarity
properties:
requirement_kind:
$ref: '#/components/schemas/MatchRequirementKind'
requirement_text:
type: string
minLength: 1
maxLength: 300
description: Confirmed skill name or task text of the need. Plain text; show it as text, never as HTML.
item_kind:
$ref: '#/components/schemas/MatchSemanticItemKind'
project_title:
description: Published project title for `project`, otherwise null. Plain text; show it as text, never as HTML.
oneOf:
- type: string
minLength: 1
maxLength: 100
- type: 'null'
repository_verified:
type: boolean
description: True only for a project whose linked repository the latest server check found public on GitHub ("backed by a public repository"). It does not prove authorship.
similarity:
$ref: '#/components/schemas/MatchSimilarityBand'
MatchSemanticEvidenceList:
type: array
description: 'Semantic explanation items in a stable order: `high` before `medium`, then by similarity, then by the order of the requirements in the need. At most the versioned per-entry limit is returned. It is empty for a bank search, while vectors are not ready, when ML is unavailable, and when no requirement reaches a band; `unknown_flags` names `ml_unavailable` when the semantic component itself is unknown.'
maxItems: 12
items:
$ref: '#/components/schemas/MatchSemanticEvidence'
MatchScore:
type: number
format: double
@@ -11133,6 +11388,7 @@ components:
- strength
- public_context
- evidence_summary
- semantic_evidence
- components
- unknown_flags
properties:
@@ -11157,6 +11413,8 @@ components:
$ref: '#/components/schemas/MatchPublicContext'
evidence_summary:
$ref: '#/components/schemas/MatchEvidenceSummary'
semantic_evidence:
$ref: '#/components/schemas/MatchSemanticEvidenceList'
components:
$ref: '#/components/schemas/MatchConfirmedComponents'
unknown_flags:
@@ -11194,6 +11452,7 @@ components:
- strength
- public_context
- evidence_summary
- semantic_evidence
- components
- unknown_flags
properties:
@@ -11220,6 +11479,8 @@ components:
$ref: '#/components/schemas/MatchPublicContext'
evidence_summary:
$ref: '#/components/schemas/MatchEvidenceSummary'
semantic_evidence:
$ref: '#/components/schemas/MatchSemanticEvidenceList'
components:
$ref: '#/components/schemas/MatchUnconfirmedComponents'
unknown_flags:
@@ -11286,6 +11547,37 @@ components:
- remote
- office
- hybrid
CardProject:
type: object
description: One published project as the card shows it. It never carries the repository address, the repository owner, or any text fetched from the repository.
additionalProperties: false
required:
- title
- description
- stack
- repository_verified
properties:
title:
type: string
minLength: 1
maxLength: 100
description: Project title as the candidate published it. Plain text; show it as text, never as HTML.
description:
description: Published project description, or null. Plain text; show it as text, never as HTML.
oneOf:
- type: string
minLength: 1
maxLength: 500
- type: 'null'
stack:
type: array
maxItems: 10
description: Published technology tags of the project.
items:
$ref: '#/components/schemas/StackTag'
repository_verified:
type: boolean
description: True when the latest server check found the linked repository on GitHub and it is public. It does not prove that the candidate wrote the code.
parameters:
IdempotencyKey:
name: Idempotency-Key
@@ -12436,6 +12728,7 @@ components:
experience: []
experience_overlaps: []
soft_skills: []
projects: []
terms:
location:
status: unknown
@@ -12538,6 +12831,23 @@ components:
quote: null
extraction_version: null
confirmed_at: '2026-10-05T09:30:00Z'
projects:
- title: Payment webhook deduplication service
description: Idempotent receiver for acquirer callbacks with a unique operation key and an outbox for retries.
stack:
- Go
- PostgreSQL
repository_url: https://github.com/example-org/payments-ledger
repository_check:
state: verified
checked_at: '2026-10-05T09:31:00Z'
status: confirmed
source:
origin: manual
trust_level: 0
quote: null
extraction_version: null
confirmed_at: '2026-10-05T09:30:00Z'
terms:
location:
status: confirmed
@@ -14704,6 +15014,7 @@ components:
state: supports
- code: work_conditions_match
state: supports
semantic_evidence: []
components:
fit: 0.78
coverage: 0.72
@@ -14737,6 +15048,7 @@ components:
state: supports
- code: required_skill_evidence
state: gap
semantic_evidence: []
components:
fit: 0.48
coverage: 0.18
@@ -14770,6 +15082,7 @@ components:
state: declared_only
- code: required_skill_evidence
state: partial
semantic_evidence: []
components:
fit: 0.51
coverage: 0.38
@@ -14830,6 +15143,7 @@ components:
evidence_summary:
- code: confirmed_category
state: supports
semantic_evidence: []
components:
fit: 0.7
coverage: 0.6
@@ -14881,6 +15195,7 @@ components:
evidence_summary:
- code: confirmed_category
state: supports
semantic_evidence: []
components:
fit: 0.62
coverage: 0.55
@@ -14930,6 +15245,7 @@ components:
evidence_summary:
- code: confirmed_category
state: supports
semantic_evidence: []
components:
fit: 0.5
coverage: 0.5
@@ -14948,6 +15264,76 @@ components:
near: []
unconfirmed: []
truncated: true
SemanticEvidence:
summary: A need search explains an entry with semantic evidence from published card items.
description: Synthetic example. `semantics` is the calibrated cosine of the stored vectors; each evidence item pairs one confirmed requirement of the need with the closest published card item. The project is named only by the title that the candidate published; the repository address never appears.
value:
source:
kind: need
need_id: 4d3a4a1b-4f60-44c1-9dc2-6c8e6c9d4c11
requirements_version: 3
groups:
main:
- candidate_handle: cv1_FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
specialization: backend
confirmation_status: confirmed
declared_grade: middle
category:
specialization: backend
grade: middle
basis: synthetic_demo
strength: standard
public_context:
stack:
- kafka
- postgresql
experience_band: '3_6'
work_formats: null
salary_compatibility: null
evidence_summary:
- code: confirmed_category
state: supports
- code: required_skill_evidence
state: declared_only
semantic_evidence:
- requirement_kind: task
requirement_text: Make payment callbacks idempotent
item_kind: project
project_title: Payment webhook deduplication service
repository_verified: true
similarity: high
- requirement_kind: required_skill
requirement_text: Kafka
item_kind: stack
project_title: null
repository_verified: false
similarity: medium
components:
fit: 0.69
coverage: 0.25
domain: 0.5
semantics: 0.92
percentile: null
competition: 0
freshness: 0.5
responsiveness: 0.5
rank_score: 0.59
unknown_flags:
- component: percentile
reason: cohort_below_30
- component: freshness
reason: no_freshness_history
- component: responsiveness
reason: no_response_history
- component: work_formats
reason: not_in_public_card
- component: salary_compatibility
reason: not_in_public_card
- component: domain
reason: not_in_public_card
near: []
unconfirmed: []
truncated: false
OrganizationAnonymousCandidateCard:
summary: An anonymous card currently visible to one organization
description: The alias is scoped to the reading organization; no contact values are included.
@@ -14965,6 +15351,7 @@ components:
experience_band: '1_3'
work_formats: null
salary_compatibility: null
projects: null
OrganizationCandidateEvidence:
summary: The one supporting assessment fact of the category on the card
value:
@@ -16414,6 +16801,7 @@ components:
experience_band: '1_3'
work_formats: null
salary_compatibility: null
projects: null
evidence:
items:
- skill: backend
+2
View File
@@ -119,6 +119,8 @@ paths:
$ref: ./routes/candidate_questionnaire.yml
/api/v1/me/profile:
$ref: ./routes/candidate_profile.yml
/api/v1/me/profile/repository-checks:
$ref: ./routes/candidate_profile_repository_checks.yml
/api/v1/me/assessment-availability:
$ref: ./routes/candidate_assessment_availability.yml
/api/v1/me/assessment-results:
@@ -0,0 +1,32 @@
post:
operationId: RequestMyRepositoryChecks
summary: Ask the server to check the linked project repositories again.
description: |-
Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, and an allowed Origin. The request has no body. It schedules a new check of every repository that the current profile links, for example after the candidate made a repository public, and answers 202 with the number of scheduled checks; the checks run in the background and `GetMyProfile` shows their state in `projects[].repository_check`. A profile without linked repositories answers 202 with 0.
A check reads only public metadata from the public GitHub API (`api.github.com`): whether the repository exists and is public, its description, topics, languages, and the beginning of its README as plain text. The server never fetches any other host, never follows a redirect to another host, and never shows the fetched text; it uses it only for semantic ranking. A verified repository does not prove that the candidate wrote the code.
The operation is limited per candidate: a second request inside the versioned window answers 429 rate_limited with Retry-After and schedules nothing. A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account answers 403 forbidden.
security:
- sessionCookie: []
sessionCsrf: []
tags:
- candidate
responses:
"202":
description: The checks are scheduled.
headers:
Cache-Control:
$ref: ../components/headers.yml#/CacheControlNoStore
content:
application/json:
schema:
$ref: ../components/schemas.yml#/ProfileRepositoryCheckRequest
"401":
$ref: ../components/responses.yml#/Unauthenticated
"403":
$ref: ../components/responses.yml#/CsrfCheckFailedOrForbidden
"429":
$ref: ../components/responses.yml#/TooManyRequests
default:
$ref: ../components/responses.yml#/Problem
+5 -1
View File
@@ -10,7 +10,9 @@ post:
Every entry is one candidate specialization. A confirmed result in Backend never confirms Networks for the same candidate. The `main`, `near`, and `unconfirmed` arrays are separate groups. A confirmed category with required-skill coverage below 0.25 belongs to `near`; other confirmed entries belong to `main` (FR09). Entries in `unconfirmed` are ordered by Fit, then coverage, then a stable internal tie-breaker that is never returned. Their category and strength remain null, and they have no theta, T, P, or test percentile. The search result uses the organization-scoped opaque `candidate_handle` as its display pseudonym and invitation reference, never a candidate account or profile identifier.
The card context is limited to safe public fields: recognized stack tags, coarse experience, accepted work formats, and coarse salary compatibility. It contains no contact, candidate location, salary amount or minimum, raw answer, arbitrary profile text, or reason for withheld FSP data. Evidence explanations use bounded codes, not free text. When ML is unavailable, semantic similarity uses the neutral 0.5 specified by FR09 and `unknown_flags` names `ml_unavailable`. For fewer than 30 comparable real candidates, the search uses neutral T = 0.5, returns no percentile value, and names `cohort_below_30`. When the comparable real cohort of a category reaches the minimum, the percentile is still not computed (the organization-safe projection carries no theta), T stays the neutral 0.5, the percentile stays null, and `unknown_flags` names `percentile_not_computed`; the search does not fail.
The card context is limited to safe public fields: recognized stack tags, coarse experience, accepted work formats, and coarse salary compatibility. It contains no contact, candidate location, salary amount or minimum, raw answer, arbitrary profile text, or reason for withheld FSP data. Evidence explanations use bounded codes, not free text.
Semantic similarity `Sem` is the calibrated cosine between the stored vector of the need's confirmed requirements snapshot and the stored vector of the candidate's published card text (roles, recognized stack, and published projects with the public metadata of their verified repositories). The search never calls the ML service: vectors are computed in the background after a change, and an entry whose vectors are missing, stale for the current model, or not computed because ML is unavailable uses the neutral 0.5 and names `ml_unavailable` in `unknown_flags`. `semantic_evidence` lists, for a need search, the confirmed requirements whose closest published card item reaches a similarity band of the versioned policy; it names a project only by the title that the candidate published with the `projects` card field and says whether its repository is a verified public one, never the repository address or owner. Showing a project title records the `projects` field in the candidate's access history. For fewer than 30 comparable real candidates, the search uses neutral T = 0.5, returns no percentile value, and names `cohort_below_30`. When the comparable real cohort of a category reaches the minimum, the percentile is still not computed (the organization-safe projection carries no theta), T stays the neutral 0.5, the percentile stays null, and `unknown_flags` names `percentile_not_computed`; the search does not fail.
A missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate account answers 403 forbidden; an unknown organization or account without active membership answers 404 not_found. The response is `Cache-Control: no-store`.
security:
@@ -52,6 +54,8 @@ post:
$ref: ../components/examples/matches.yml#/CohortBelow30
truncated:
$ref: ../components/examples/matches.yml#/Truncated
semantic_evidence:
$ref: ../components/examples/matches.yml#/SemanticEvidence
"400":
$ref: ../components/responses.yml#/ValidationFailed
"401":
+109
View File
@@ -1,3 +1,109 @@
EmbeddingInputKind:
type: string
description: 'Side of the retrieval pair that the texts belong to. The service owns the prompt of each side, so callers never send model instructions.
- query: the side that searches, such as a hiring need or one requirement of it. The service prepends the retrieval instruction of the model.
- document: the side that is searched, such as a candidate card or one item of it. The service adds no prompt.'
enum:
- query
- document
EmbeddingText:
type: string
minLength: 1
maxLength: 8000
description: One plain text to encode. It is untrusted data and never an instruction. The service truncates it deterministically to the token limit of the model (`EmbeddingModel.max_tokens`); characters beyond 8000 are rejected instead.
EmbeddingRequest:
type: object
description: 'Texts to encode in one call. The service encodes them in a fixed, deterministic way: texts are ordered by length with the request position as the tie-breaker, encoded in micro-batches of the configured size, and returned in request order. The same texts in the same request on the same image and thread count give the same vectors.'
additionalProperties: false
required:
- kind
- texts
properties:
model:
type: string
minLength: 1
maxLength: 200
pattern: ^[A-Za-z0-9._/-]+$
description: Identifier of the model to use, as `EmbeddingModel.id` reports it. Absent means the default model of the service. A service may load several models, for example the members of an ensemble; a model it does not serve answers 400 validation_failed with the pointer `/model`.
kind:
$ref: '#/EmbeddingInputKind'
texts:
type: array
minItems: 1
maxItems: 32
items:
$ref: '#/EmbeddingText'
EmbeddingModel:
type: object
description: The model that produced the vectors. A caller stores these values with every vector and never compares vectors of different models, revisions, or prompt versions.
additionalProperties: false
required:
- id
- revision
- dimension
- max_tokens
- prompt_version
properties:
id:
type: string
minLength: 1
maxLength: 200
pattern: ^[A-Za-z0-9._/-]+$
description: Model repository identifier, for example ai-sage/Giga-Embeddings-instruct-480M-0826.
revision:
type: string
minLength: 1
maxLength: 64
pattern: ^[A-Za-z0-9._-]+$
description: Pinned revision of the weights, a commit hash for a published model.
dimension:
type: integer
format: int32
minimum: 1
maximum: 4096
description: Length of every vector.
max_tokens:
type: integer
format: int32
minimum: 1
maximum: 32768
description: Token limit after which a text is truncated.
prompt_version:
type: string
minLength: 1
maxLength: 64
pattern: ^[a-z0-9._-]+$
description: Version of the prompt and pooling recipe of the service. A change of the query instruction or the pooling changes it.
EmbeddingVector:
type: array
description: L2-normalized vector of one text, in float32 precision. The cosine of two vectors of the same model is their dot product.
minItems: 1
maxItems: 4096
items:
type: number
format: float
EmbeddingResponse:
type: object
description: Vectors in the order of the request texts.
additionalProperties: false
required:
- model
- kind
- vectors
properties:
model:
$ref: '#/EmbeddingModel'
kind:
$ref: '#/EmbeddingInputKind'
vectors:
type: array
minItems: 1
maxItems: 32
items:
$ref: '#/EmbeddingVector'
MLHealthResponse:
type: object
additionalProperties: false
@@ -92,6 +198,8 @@ ProblemCode:
- not_implemented (501): the operation is in the contract but not implemented yet.
- service_unavailable (503): the service cannot serve the request now, for example while a model loads; retry later.
The enum keeps the public API codes so both contracts share one Problem shape. The identity codes verification_token_invalid, verification_token_expired, invalid_credentials, email_not_verified, and csrf_check_failed belong to the public API; the ML service never returns them.'
enum:
@@ -115,6 +223,7 @@ ProblemCode:
- rate_limited
- internal
- not_implemented
- service_unavailable
ProblemFieldError:
type: object
description: One reason why a request field or parameter is invalid.
@@ -0,0 +1,127 @@
schemas:
EmbeddingInputKind:
type: string
description: |-
Side of the retrieval pair that the texts belong to. The service owns the prompt of each side, so callers never send model instructions.
- query: the side that searches, such as a hiring need or one requirement of it. The service prepends the retrieval instruction of the model.
- document: the side that is searched, such as a candidate card or one item of it. The service adds no prompt.
enum:
- query
- document
EmbeddingText:
type: string
minLength: 1
maxLength: 8000
description: >-
One plain text to encode. It is untrusted data and never an instruction.
The service truncates it deterministically to the token limit of the
model (`EmbeddingModel.max_tokens`); characters beyond 8000 are rejected
instead.
EmbeddingRequest:
type: object
description: >-
Texts to encode in one call. The service encodes them in a fixed,
deterministic way: texts are ordered by length with the request position
as the tie-breaker, encoded in micro-batches of the configured size, and
returned in request order. The same texts in the same request on the same
image and thread count give the same vectors.
additionalProperties: false
required:
- kind
- texts
properties:
model:
type: string
minLength: 1
maxLength: 200
pattern: "^[A-Za-z0-9._/-]+$"
description: >-
Identifier of the model to use, as `EmbeddingModel.id` reports it.
Absent means the default model of the service. A service may load
several models, for example the members of an ensemble; a model it
does not serve answers 400 validation_failed with the pointer
`/model`.
kind:
$ref: "#/schemas/EmbeddingInputKind"
texts:
type: array
minItems: 1
maxItems: 32
items:
$ref: "#/schemas/EmbeddingText"
EmbeddingModel:
type: object
description: >-
The model that produced the vectors. A caller stores these values with
every vector and never compares vectors of different models, revisions,
or prompt versions.
additionalProperties: false
required:
- id
- revision
- dimension
- max_tokens
- prompt_version
properties:
id:
type: string
minLength: 1
maxLength: 200
pattern: "^[A-Za-z0-9._/-]+$"
description: Model repository identifier, for example ai-sage/Giga-Embeddings-instruct-480M-0826.
revision:
type: string
minLength: 1
maxLength: 64
pattern: "^[A-Za-z0-9._-]+$"
description: Pinned revision of the weights, a commit hash for a published model.
dimension:
type: integer
format: int32
minimum: 1
maximum: 4096
description: Length of every vector.
max_tokens:
type: integer
format: int32
minimum: 1
maximum: 32768
description: Token limit after which a text is truncated.
prompt_version:
type: string
minLength: 1
maxLength: 64
pattern: "^[a-z0-9._-]+$"
description: >-
Version of the prompt and pooling recipe of the service. A change of
the query instruction or the pooling changes it.
EmbeddingVector:
type: array
description: >-
L2-normalized vector of one text, in float32 precision. The cosine of two
vectors of the same model is their dot product.
minItems: 1
maxItems: 4096
items:
type: number
format: float
EmbeddingResponse:
type: object
description: Vectors in the order of the request texts.
additionalProperties: false
required:
- model
- kind
- vectors
properties:
model:
$ref: "#/schemas/EmbeddingModel"
kind:
$ref: "#/schemas/EmbeddingInputKind"
vectors:
type: array
minItems: 1
maxItems: 32
items:
$ref: "#/schemas/EmbeddingVector"
@@ -86,6 +86,7 @@ schemas:
- rate_limited (429): too many requests; see Retry-After.
- internal (500): unexpected server error.
- not_implemented (501): the operation is in the contract but not implemented yet.
- service_unavailable (503): the service cannot serve the request now, for example while a model loads; retry later.
The enum keeps the public API codes so both contracts share one Problem shape. The identity codes verification_token_invalid, verification_token_expired, invalid_credentials, email_not_verified, and csrf_check_failed belong to the public API; the ML service never returns them.
enum:
@@ -109,6 +110,7 @@ schemas:
- rate_limited
- internal
- not_implemented
- service_unavailable
ProblemFieldError:
type: object
description: One reason why a request field or parameter is invalid.
+139
View File
@@ -43,6 +43,38 @@ paths:
$ref: '#/components/schemas/MLReadinessResponse'
default:
$ref: '#/components/responses/Problem'
/v1/embeddings:
post:
operationId: CreateMLEmbeddings
summary: Encode texts into normalized vectors with the pinned embedding model.
description: |-
Internal operation for the Go backend; it is not reachable from browsers and needs no credentials on the private network. The request carries only text that the caller is allowed to process, and the service never logs it.
The service answers 503 service_unavailable until the model is loaded from the image and a warm-up encode has finished; `/readyz` reports the same state. A request above the body limit answers 413, and a request that breaks the schema, such as too many texts or a text over 8000 characters, or names a model that the service does not serve, answers 400.
security: []
tags:
- inference
requestBody:
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/EmbeddingRequest'
responses:
'200':
description: One vector for each text, in request order.
content:
application/json:
schema:
$ref: '#/components/schemas/EmbeddingResponse'
'400':
$ref: '#/components/responses/Problem'
'413':
$ref: '#/components/responses/Problem'
'503':
$ref: '#/components/responses/Problem'
default:
$ref: '#/components/responses/Problem'
components:
responses:
Problem:
@@ -94,6 +126,7 @@ components:
- rate_limited (429): too many requests; see Retry-After.
- internal (500): unexpected server error.
- not_implemented (501): the operation is in the contract but not implemented yet.
- service_unavailable (503): the service cannot serve the request now, for example while a model loads; retry later.
The enum keeps the public API codes so both contracts share one Problem shape. The identity codes verification_token_invalid, verification_token_expired, invalid_credentials, email_not_verified, and csrf_check_failed belong to the public API; the ML service never returns them.
enum:
@@ -117,6 +150,7 @@ components:
- rate_limited
- internal
- not_implemented
- service_unavailable
ProblemFieldLocation:
type: string
description: Part of the request that contains the invalid field.
@@ -224,3 +258,108 @@ components:
enum:
- ready
- not_ready
EmbeddingInputKind:
type: string
description: |-
Side of the retrieval pair that the texts belong to. The service owns the prompt of each side, so callers never send model instructions.
- query: the side that searches, such as a hiring need or one requirement of it. The service prepends the retrieval instruction of the model.
- document: the side that is searched, such as a candidate card or one item of it. The service adds no prompt.
enum:
- query
- document
EmbeddingText:
type: string
minLength: 1
maxLength: 8000
description: One plain text to encode. It is untrusted data and never an instruction. The service truncates it deterministically to the token limit of the model (`EmbeddingModel.max_tokens`); characters beyond 8000 are rejected instead.
EmbeddingRequest:
type: object
description: 'Texts to encode in one call. The service encodes them in a fixed, deterministic way: texts are ordered by length with the request position as the tie-breaker, encoded in micro-batches of the configured size, and returned in request order. The same texts in the same request on the same image and thread count give the same vectors.'
additionalProperties: false
required:
- kind
- texts
properties:
model:
type: string
minLength: 1
maxLength: 200
pattern: ^[A-Za-z0-9._/-]+$
description: Identifier of the model to use, as `EmbeddingModel.id` reports it. Absent means the default model of the service. A service may load several models, for example the members of an ensemble; a model it does not serve answers 400 validation_failed with the pointer `/model`.
kind:
$ref: '#/components/schemas/EmbeddingInputKind'
texts:
type: array
minItems: 1
maxItems: 32
items:
$ref: '#/components/schemas/EmbeddingText'
EmbeddingModel:
type: object
description: The model that produced the vectors. A caller stores these values with every vector and never compares vectors of different models, revisions, or prompt versions.
additionalProperties: false
required:
- id
- revision
- dimension
- max_tokens
- prompt_version
properties:
id:
type: string
minLength: 1
maxLength: 200
pattern: ^[A-Za-z0-9._/-]+$
description: Model repository identifier, for example ai-sage/Giga-Embeddings-instruct-480M-0826.
revision:
type: string
minLength: 1
maxLength: 64
pattern: ^[A-Za-z0-9._-]+$
description: Pinned revision of the weights, a commit hash for a published model.
dimension:
type: integer
format: int32
minimum: 1
maximum: 4096
description: Length of every vector.
max_tokens:
type: integer
format: int32
minimum: 1
maximum: 32768
description: Token limit after which a text is truncated.
prompt_version:
type: string
minLength: 1
maxLength: 64
pattern: ^[a-z0-9._-]+$
description: Version of the prompt and pooling recipe of the service. A change of the query instruction or the pooling changes it.
EmbeddingVector:
type: array
description: L2-normalized vector of one text, in float32 precision. The cosine of two vectors of the same model is their dot product.
minItems: 1
maxItems: 4096
items:
type: number
format: float
EmbeddingResponse:
type: object
description: Vectors in the order of the request texts.
additionalProperties: false
required:
- model
- kind
- vectors
properties:
model:
$ref: '#/components/schemas/EmbeddingModel'
kind:
$ref: '#/components/schemas/EmbeddingInputKind'
vectors:
type: array
minItems: 1
maxItems: 32
items:
$ref: '#/components/schemas/EmbeddingVector'
+2
View File
@@ -9,6 +9,8 @@ paths:
$ref: ./routes/healthz.yml
/readyz:
$ref: ./routes/readyz.yml
/v1/embeddings:
$ref: ./routes/embeddings.yml
components:
responses:
Problem:
+31
View File
@@ -0,0 +1,31 @@
post:
operationId: CreateMLEmbeddings
summary: Encode texts into normalized vectors with the pinned embedding model.
description: |-
Internal operation for the Go backend; it is not reachable from browsers and needs no credentials on the private network. The request carries only text that the caller is allowed to process, and the service never logs it.
The service answers 503 service_unavailable until the model is loaded from the image and a warm-up encode has finished; `/readyz` reports the same state. A request above the body limit answers 413, and a request that breaks the schema, such as too many texts or a text over 8000 characters, or names a model that the service does not serve, answers 400.
security: []
tags:
- inference
requestBody:
required: true
content:
application/json:
schema:
$ref: ../components/schemas.yml#/EmbeddingRequest
responses:
"200":
description: One vector for each text, in request order.
content:
application/json:
schema:
$ref: ../components/schemas.yml#/EmbeddingResponse
"400":
$ref: ../components/responses.yml#/Problem
"413":
$ref: ../components/responses.yml#/Problem
"503":
$ref: ../components/responses.yml#/Problem
default:
$ref: ../components/responses.yml#/Problem
+2
View File
@@ -252,6 +252,7 @@ components:
- rate_limited (429): too many requests; see Retry-After.
- internal (500): unexpected server error.
- not_implemented (501): the operation is in the contract but not implemented yet.
- service_unavailable (503): the service cannot serve the request now, for example while a model loads; retry later.
enum:
- validation_failed
- verification_token_invalid
@@ -273,6 +274,7 @@ components:
- rate_limited
- internal
- not_implemented
- service_unavailable
ProblemFieldError:
type: object
description: One reason why a request field or parameter is invalid.
+9 -1
View File
@@ -58,13 +58,21 @@ assessment-category-attest-build: ## Build the local category attestation operat
$(GO) build -buildvcs=false -trimpath -o bin/assessment-category-attest ./cmd/assessment-category-attest
.PHONY: policy-publish policy-publish-build
policy-publish: ## Add the demo matching section to the product policy (set ARGS)
policy-publish: ## Add the demo matching or semantic matching section to the product policy (set ARGS)
$(GO) run ./cmd/policy-publish $(ARGS)
policy-publish-build: ## Build the local policy publication operator command
@mkdir -p bin
$(GO) build -buildvcs=false -trimpath -o bin/policy-publish ./cmd/policy-publish
.PHONY: semantic-backfill semantic-backfill-build
semantic-backfill: ## Schedule vector jobs for existing candidates and needs (set ARGS)
$(GO) run ./cmd/semantic-backfill $(ARGS)
semantic-backfill-build: ## Build the local semantic backfill operator command
@mkdir -p bin
$(GO) build -buildvcs=false -trimpath -o bin/semantic-backfill ./cmd/semantic-backfill
.PHONY: demo-seed demo-seed-build
demo-seed: ## Seed, check, or count the isolated demo stand; needs DEMO_MODE=isolated (set ARGS)
$(GO) run ./cmd/demo-seed $(ARGS)
+1 -1
View File
@@ -143,7 +143,7 @@ The candidate reads the facts at `GET /api/v1/me/evidence` (`usecase/evidence/re
## Match search
`POST /api/v1/organizations/{org_id}/matches` ranks the organization-visible candidate bank without ML (`usecase/matching/`). It runs in one transaction: `candidateview.Service.ListVisibleCards` applies the checks of a card read (verified employer, locked active membership, `ListVisibleCandidateViewSources` over `candidate_effective_publications` with `NOT EXISTS` over the hidden organizations, the account, C2, and publication locks, and the anonymous projection with its minimum cohort of five), the need snapshot is read by `requirements_version`, and the permitted evidence comes only from `ListOrganizationFacts`. The usecase repeats the owner role check; the HTTP boundary lists the operation in `ownerCompanyOperations`. A search is charged like card reads: each group is cut to the policy limit, and each candidate returned is reserved through the company quota port and recorded in the access history with the returned fields (`candidateview.SearchViews`); when the allowance ends the response is cut and flagged `truncated`. The operator publishes the matching section with `make policy-publish ARGS='matching --actor operator:<handle>'` (`cmd/policy-publish`), see [DEPLOY](../docs/en/DEPLOY.md#match-search-policy-on-a-stand).
`POST /api/v1/organizations/{org_id}/matches` ranks the organization-visible candidate bank without ML (`usecase/matching/`). It runs in one transaction: `candidateview.Service.ListVisibleCards` applies the checks of a card read (verified employer, locked active membership, `ListVisibleCandidateViewSources` over `candidate_effective_publications` with `NOT EXISTS` over the hidden organizations, the account, C2, and publication locks, and the anonymous projection with its minimum cohort of five), the need snapshot is read by `requirements_version`, and the permitted evidence comes only from `ListOrganizationFacts`. The usecase repeats the owner role check; the HTTP boundary lists the operation in `ownerCompanyOperations`. A search is charged like card reads: each group is cut to the policy limit, and each candidate returned is reserved through the company quota port and recorded in the access history with the returned fields (`candidateview.SearchViews`); when the allowance ends the response is cut and flagged `truncated`. The operator publishes the matching section with `make policy-publish ARGS='matching --actor operator:<handle>'` (`cmd/policy-publish`), the semantic section with `ARGS='semantic --actor operator:<handle>'`, and schedules vectors for existing data with `make semantic-backfill ARGS='all --run <label>'` (`cmd/semantic-backfill`), see [DEPLOY](../docs/en/DEPLOY.md#match-search-policy-on-a-stand) and [semantic matching](../docs/en/DEPLOY.md#semantic-matching). The search itself never calls ML: it reads the vectors that the `semantic.candidate` and `semantic.need` jobs compute (`usecase/semantic/`).
Each entry is one candidate specialization. Scores use the `matching` section of the effective product policy (`domain.MatchingPolicy`, demo version `DemoProductPolicyV4`); a policy without the section makes the search fail closed. The arithmetic is integer (micro units for components, basis points for shares), so the order is reproducible: confirmed groups sort by S, then coverage, then the internal candidate identifier; the unconfirmed group by Fit, then coverage, then the identifier, and it never computes theta, T, P, a percentile, or S. The explanation and the unknown flags are built from the same computed contributions. The model, the neutral values, and what is not implemented are described in [architecture](../docs/en/ARCHITECTURE.md#matching-and-explanations).
+1 -1
View File
@@ -142,7 +142,7 @@
## Подбор
`POST /api/v1/organizations/{org_id}/matches` ранжирует банк кандидатов, видимый организации, без ML (`usecase/matching/`). Он выполняется в одной транзакции: `candidateview.Service.ListVisibleCards` применяет проверки чтения карточки (подтвержденный работодатель, заблокированное действующее членство, `ListVisibleCandidateViewSources` по `candidate_effective_publications` с `NOT EXISTS` по скрытым организациям, блокировки аккаунта, C2 и публикации и анонимная проекция с минимальной когортой из пяти), снимок потребности читается по `requirements_version`, а разрешенные доказательства приходят только из `ListOrganizationFacts`. Usecase повторяет проверку роли владельца; HTTP-граница перечисляет операцию в `ownerCompanyOperations`. Поиск оплачивается как чтение карточек: каждая группа обрезается до предела политики, а каждый возвращенный кандидат резервируется через порт квоты компании и записывается в историю доступа с возвращенными полями (`candidateview.SearchViews`); когда лимит заканчивается, ответ обрезается и получает флаг `truncated`. Раздел подбора оператор публикует командой `make policy-publish ARGS='matching --actor operator:<handle>'` (`cmd/policy-publish`), см. [DEPLOY](../docs/ru/DEPLOY.md#политика-подбора-на-стенде).
`POST /api/v1/organizations/{org_id}/matches` ранжирует банк кандидатов, видимый организации, без ML (`usecase/matching/`). Он выполняется в одной транзакции: `candidateview.Service.ListVisibleCards` применяет проверки чтения карточки (подтвержденный работодатель, заблокированное действующее членство, `ListVisibleCandidateViewSources` по `candidate_effective_publications` с `NOT EXISTS` по скрытым организациям, блокировки аккаунта, C2 и публикации и анонимная проекция с минимальной когортой из пяти), снимок потребности читается по `requirements_version`, а разрешенные доказательства приходят только из `ListOrganizationFacts`. Usecase повторяет проверку роли владельца; HTTP-граница перечисляет операцию в `ownerCompanyOperations`. Поиск оплачивается как чтение карточек: каждая группа обрезается до предела политики, а каждый возвращенный кандидат резервируется через порт квоты компании и записывается в историю доступа с возвращенными полями (`candidateview.SearchViews`); когда лимит заканчивается, ответ обрезается и получает флаг `truncated`. Раздел подбора оператор публикует командой `make policy-publish ARGS='matching --actor operator:<handle>'` (`cmd/policy-publish`), семантический раздел - `ARGS='semantic --actor operator:<handle>'`, а векторы существующих данных ставит `make semantic-backfill ARGS='all --run <метка>'` (`cmd/semantic-backfill`), см. [DEPLOY](../docs/ru/DEPLOY.md#политика-подбора-на-стенде) и [семантический подбор](../docs/ru/DEPLOY.md#семантический-подбор). Поиск сам ML не вызывает: он читает векторы, которые считают задания `semantic.candidate` и `semantic.need` (`usecase/semantic/`).
Каждая запись - одна специализация кандидата. Баллы используют раздел `matching` действующей политики `product` (`domain.MatchingPolicy`, демонстрационная версия `DemoProductPolicyV4`); политика без раздела приводит к закрытому отказу. Арифметика целочисленная (микроединицы для компонентов, базисные пункты для долей), поэтому порядок воспроизводим: подтвержденные группы сортируются по S, затем по покрытию, затем по внутреннему идентификатору кандидата; неподтвержденная - по Fit, затем по покрытию, затем по идентификатору, и она никогда не вычисляет theta, T, P, перцентиль или S. Объяснение и признаки неизвестности строятся из тех же рассчитанных вкладов. Модель, нейтральные значения и нереализованное описаны в [архитектуре](../docs/ru/ARCHITECTURE.md#подбор-и-объяснение).
+2 -2
View File
@@ -1,5 +1,5 @@
// Command policy-publish adds the demo matching section to the product
// policy of a stand. It publishes a new immutable version and changes nothing
// Command policy-publish adds the demo matching section or the semantic
// matching section to the product policy of a stand. It publishes a new immutable version and changes nothing
// else.
package main
+28
View File
@@ -0,0 +1,28 @@
// Command semantic-backfill schedules vector jobs for the existing published
// candidates and needs of a stand. It changes no product data.
package main
import (
"context"
"fmt"
"os"
"os/signal"
"syscall"
"time"
"lincodex/backend/internal/adapter/primary/cli/semanticbackfill"
)
func main() {
os.Exit(run())
}
func run() int {
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
if err := semanticbackfill.Run(ctx, os.Args[1:], os.LookupEnv, os.Stdout, time.Now); err != nil {
_, _ = fmt.Fprintf(os.Stderr, "semantic-backfill: %v\n", err)
return 2
}
return 0
}
+8
View File
@@ -156,6 +156,9 @@ type Config struct {
// assignment. Reviewed source provenance is required separately.
AssessmentDemoCategoriesEnabled bool
// Semantic configures semantic matching and repository checks.
Semantic SemanticSettings
// CodeRunner configures the client of the own code runner. It is disabled
// unless CODE_RUNNER_URL is set.
CodeRunner CodeRunnerSettings
@@ -254,6 +257,11 @@ func (config *Config) loadIdentityAndProxySettings(lookup LookupEnv) error {
if err := config.loadAssessment(lookup); err != nil {
return err
}
semantic, err := LoadSemanticSettings(lookup)
if err != nil {
return err
}
config.Semantic = semantic
codeRunner, err := LoadCodeRunnerSettings(lookup)
if err != nil {
return err
+126
View File
@@ -0,0 +1,126 @@
package config
import (
"errors"
"net/url"
"strings"
"time"
)
const (
// Semantic matching is off by default: a stand without the ML service
// ranks with the neutral Sem, as before.
defaultSemanticMatchingEnabled = false
// defaultMLRequestTimeout bounds one embedding request. A whole card is at
// most a dozen texts; on four CPU threads each takes well under a second.
defaultMLRequestTimeout = 30 * time.Second
maxMLRequestTimeout = 5 * time.Minute
// After this many consecutive failures the client stops calling the ML
// service for the open duration, so a dead service costs no timeouts.
defaultMLCircuitFailures = 3
maxMLCircuitFailures = 100
defaultMLCircuitOpen = 30 * time.Second
maxMLCircuitOpen = time.Hour
// Repository checks call api.github.com; they are off unless enabled.
defaultGitHubChecksEnabled = false
defaultGitHubTimeout = 10 * time.Second
maxGitHubTimeout = time.Minute
// defaultRepositoryCheckInterval is the shortest time between two check
// requests of one candidate through the refresh operation.
defaultRepositoryCheckInterval = 10 * time.Minute
maxRepositoryCheckInterval = 24 * time.Hour
)
// SemanticSettings configure semantic matching and repository checks.
type SemanticSettings struct {
// SemanticMatchingEnabled schedules vector jobs on changes and runs them
// against MLServiceURL. The search reads stored vectors either way.
SemanticMatchingEnabled bool
MLServiceURL string
MLRequestTimeout time.Duration
MLCircuitFailures int
MLCircuitOpen time.Duration
// GitHubChecksEnabled schedules and runs repository checks against the
// public GitHub API.
GitHubChecksEnabled bool
// GitHubToken is an optional read-only token that raises the GitHub rate
// limit. It is a secret: never log it.
GitHubToken string
GitHubTimeout time.Duration
RepositoryCheckInterval time.Duration
}
// LoadSemanticSettings reads the semantic settings; the operator commands
// that need only them use it directly.
func LoadSemanticSettings(lookup LookupEnv) (SemanticSettings, error) {
settings := SemanticSettings{
MLServiceURL: strings.TrimSpace(valueOrDefault(lookup, "ML_SERVICE_URL", "")),
GitHubToken: strings.TrimSpace(valueOrDefault(lookup, "GITHUB_TOKEN", "")),
}
var err error
if settings.SemanticMatchingEnabled, err = boolOrDefault(lookup, "SEMANTIC_MATCHING_ENABLED", defaultSemanticMatchingEnabled); err != nil {
return SemanticSettings{}, err
}
if settings.MLRequestTimeout, err = durationOrDefault(lookup, "ML_REQUEST_TIMEOUT", defaultMLRequestTimeout); err != nil {
return SemanticSettings{}, err
}
if settings.MLCircuitFailures, err = intOrDefault(lookup, "ML_CIRCUIT_FAILURES", defaultMLCircuitFailures); err != nil {
return SemanticSettings{}, err
}
if settings.MLCircuitOpen, err = durationOrDefault(lookup, "ML_CIRCUIT_OPEN", defaultMLCircuitOpen); err != nil {
return SemanticSettings{}, err
}
if settings.GitHubChecksEnabled, err = boolOrDefault(lookup, "GITHUB_REPOSITORY_CHECKS_ENABLED", defaultGitHubChecksEnabled); err != nil {
return SemanticSettings{}, err
}
if settings.GitHubTimeout, err = durationOrDefault(lookup, "GITHUB_TIMEOUT", defaultGitHubTimeout); err != nil {
return SemanticSettings{}, err
}
if settings.RepositoryCheckInterval, err = durationOrDefault(lookup, "REPOSITORY_CHECK_INTERVAL", defaultRepositoryCheckInterval); err != nil {
return SemanticSettings{}, err
}
return settings, settings.Validate()
}
// Validate checks the values even while the features are off, so enabling
// them later cannot surface an old mistake.
func (settings SemanticSettings) Validate() error {
if err := settings.validateMLService(); err != nil {
return err
}
return settings.validateLimits()
}
func (settings SemanticSettings) validateMLService() error {
const location = "SemanticSettings.Validate"
if settings.SemanticMatchingEnabled && settings.MLServiceURL == "" {
return errors.New(location + " - ML_SERVICE_URL is required when SEMANTIC_MATCHING_ENABLED is true")
}
if settings.MLServiceURL != "" {
parsed, err := url.Parse(settings.MLServiceURL)
if err != nil || (parsed.Scheme != "http" && parsed.Scheme != "https") || parsed.Host == "" ||
parsed.User != nil || parsed.RawQuery != "" || parsed.Fragment != "" || strings.Trim(parsed.Path, "/") != "" {
return errors.New(location + " - ML_SERVICE_URL must be an http or https origin without credentials or path")
}
}
return nil
}
func (settings SemanticSettings) validateLimits() error {
const location = "SemanticSettings.Validate"
switch {
case settings.MLRequestTimeout <= 0 || settings.MLRequestTimeout > maxMLRequestTimeout:
return errors.New(location + " - ML_REQUEST_TIMEOUT must be positive and at most 5m")
case settings.MLCircuitFailures < 1 || settings.MLCircuitFailures > maxMLCircuitFailures:
return errors.New(location + " - ML_CIRCUIT_FAILURES must be between 1 and 100")
case settings.MLCircuitOpen <= 0 || settings.MLCircuitOpen > maxMLCircuitOpen:
return errors.New(location + " - ML_CIRCUIT_OPEN must be positive and at most 1h")
case settings.GitHubTimeout <= 0 || settings.GitHubTimeout > maxGitHubTimeout:
return errors.New(location + " - GITHUB_TIMEOUT must be positive and at most 1m")
case settings.RepositoryCheckInterval <= 0 || settings.RepositoryCheckInterval > maxRepositoryCheckInterval:
return errors.New(location + " - REPOSITORY_CHECK_INTERVAL must be positive and at most 24h")
case strings.ContainsAny(settings.GitHubToken, " \t\r\n"):
return errors.New(location + " - GITHUB_TOKEN must not contain white space")
}
return nil
}
+47
View File
@@ -0,0 +1,47 @@
package config
import (
"strings"
"testing"
"time"
)
func lookupOf(values map[string]string) LookupEnv {
return func(key string) (string, bool) {
value, ok := values[key]
return value, ok
}
}
func TestSemanticSettingsDefaultOffAndValidateTheMLOrigin(t *testing.T) {
settings, err := LoadSemanticSettings(lookupOf(nil))
if err != nil || settings.SemanticMatchingEnabled || settings.GitHubChecksEnabled ||
settings.MLRequestTimeout != 30*time.Second || settings.RepositoryCheckInterval != 10*time.Minute {
t.Fatalf("defaults = %+v, %v", settings, err)
}
enabled, err := LoadSemanticSettings(lookupOf(map[string]string{
"SEMANTIC_MATCHING_ENABLED": "true", "ML_SERVICE_URL": "http://ml:8000", "GITHUB_TOKEN": "token-value",
}))
if err != nil || !enabled.SemanticMatchingEnabled || enabled.GitHubToken != "token-value" {
t.Fatalf("enabled = %+v, %v", enabled, err)
}
for name, values := range map[string]map[string]string{
"missing URL": {"SEMANTIC_MATCHING_ENABLED": "true"},
"credentials": {"ML_SERVICE_URL": "http://user:secret@ml:8000"},
"path": {"ML_SERVICE_URL": "http://ml:8000/v1"},
"scheme": {"ML_SERVICE_URL": "file:///tmp/ml"},
"timeout": {"ML_REQUEST_TIMEOUT": "0s"},
"circuit": {"ML_CIRCUIT_FAILURES": "0"},
"interval": {"REPOSITORY_CHECK_INTERVAL": "48h"},
"token whitespace": {"GITHUB_TOKEN": "a b"},
} {
_, err := LoadSemanticSettings(lookupOf(values))
if err == nil {
t.Errorf("%s: invalid settings were accepted", name)
continue
}
if strings.Contains(err.Error(), "secret") || strings.Contains(err.Error(), "a b") {
t.Errorf("%s: the error quotes the value: %v", name, err)
}
}
}
@@ -0,0 +1,265 @@
-- +goose Up
-- Candidate projects: a new list kind of profile claims, a publishable card
-- field `projects`, and the stored server check of each linked GitHub
-- repository. A project is a claim of trust level 0 like every other; the
-- repository check is separate evidence and never changes the claim.
ALTER TABLE candidate_profile_claims
DROP CONSTRAINT candidate_profile_claims_kind_ordinal,
ADD CONSTRAINT candidate_profile_claims_kind_ordinal CHECK (
(
kind IN (
'full_name',
'contact_email',
'contact_phone',
'contact_telegram',
'terms_location',
'terms_relocation',
'terms_salary_minimum'
)
AND ordinal = 0
)
OR (kind = 'stack' AND ordinal BETWEEN 0 AND 29)
OR (kind = 'role' AND ordinal BETWEEN 0 AND 8)
OR (kind = 'experience' AND ordinal BETWEEN 0 AND 19)
OR (kind = 'soft_skill' AND ordinal BETWEEN 0 AND 9)
OR (kind = 'project' AND ordinal BETWEEN 0 AND 9)
),
-- The bounds repeat ProfileProjectItem of the public contract. The address
-- is the canonical https://github.com/<owner>/<name> that the domain stores.
ADD CONSTRAINT candidate_profile_claims_project_value CHECK (
kind <> 'project' OR (
jsonb_typeof(value) = 'object'
AND value ?& ARRAY['title', 'description', 'stack', 'repository_url']
AND value - 'title' - 'description' - 'stack' - 'repository_url' = '{}'::jsonb
AND jsonb_typeof(value -> 'title') = 'string'
AND char_length(value ->> 'title') BETWEEN 1 AND 100
AND value ->> 'title' !~ '^\s|\s$'
AND value ->> 'title' !~ '[[:cntrl:]]'
AND (
jsonb_typeof(value -> 'description') = 'null'
OR (
jsonb_typeof(value -> 'description') = 'string'
AND char_length(value ->> 'description') BETWEEN 1 AND 500
AND value ->> 'description' !~ '^\s|\s$'
AND translate(value ->> 'description', E'\n', '') !~ '[[:cntrl:]]'
)
)
AND jsonb_typeof(value -> 'stack') = 'array'
AND jsonb_array_length(value -> 'stack') <= 10
AND (
jsonb_typeof(value -> 'repository_url') = 'null'
OR (
jsonb_typeof(value -> 'repository_url') = 'string'
AND value ->> 'repository_url'
~ '^https://github\.com/[A-Za-z0-9][A-Za-z0-9-]{0,38}/[A-Za-z0-9._-]{1,100}$'
)
)
)
);
-- The publishable card fields gain `projects`; saved sets stay valid.
-- +goose StatementBegin
CREATE OR REPLACE FUNCTION candidate_card_fields_are_canonical(fields text []) RETURNS boolean
LANGUAGE sql IMMUTABLE STRICT PARALLEL SAFE AS $$
SELECT
(cardinality(fields) = 0 OR array_ndims(fields) = 1)
AND cardinality(fields) BETWEEN 0 AND 10
AND array_position(fields, NULL) IS NULL
AND fields <@ ARRAY[
'categories', 'experience', 'location', 'projects', 'relocation',
'salary_compatibility', 'self_assessment', 'soft_skills',
'stack', 'work_formats'
]::text []
AND fields = ARRAY(
SELECT DISTINCT field COLLATE "C"
FROM unnest(fields) AS field
ORDER BY field COLLATE "C"
);
$$;
-- +goose StatementEnd
-- A card view can now return the published projects.
-- +goose StatementBegin
CREATE OR REPLACE FUNCTION candidate_card_access_fields_are_valid(kind text, field_codes text []) RETURNS boolean
LANGUAGE sql IMMUTABLE STRICT PARALLEL SAFE AS $$
SELECT
cardinality(field_codes) BETWEEN 0 AND 7
AND array_position(field_codes, NULL) IS NULL
AND field_codes = ARRAY(
SELECT DISTINCT code COLLATE "C"
FROM unnest(field_codes) AS code
ORDER BY code COLLATE "C"
)
AND (
(
kind = 'card_viewed'
AND field_codes <@ ARRAY[
'categories', 'experience', 'projects', 'salary_compatibility',
'self_assessment', 'stack', 'work_formats'
]::text []
)
OR (
kind = 'contact_read'
AND cardinality(field_codes) BETWEEN 1 AND 4
AND field_codes <@ ARRAY['email', 'full_name', 'phone', 'telegram']::text []
)
);
$$;
-- +goose StatementEnd
-- The latest server check of each repository that a candidate's projects
-- link. The key is "<owner>/<name>" in lower case. Fetched metadata is kept
-- only while the repository is verified public and is used for ranking only;
-- the API never returns it. No token, header, or response body other than the
-- bounded fields below is stored.
CREATE TABLE candidate_project_repositories (
candidate_id uuid NOT NULL,
repository_key text NOT NULL,
state text NOT NULL,
github_id bigint,
description text,
topics text [] NOT NULL DEFAULT '{}',
languages text [] NOT NULL DEFAULT '{}',
readme_excerpt text,
repository_etag text,
readme_etag text,
failure_class text,
checked_at timestamptz,
requested_at timestamptz NOT NULL,
created_at timestamptz NOT NULL,
updated_at timestamptz NOT NULL,
CONSTRAINT candidate_project_repositories_pkey PRIMARY KEY (candidate_id, repository_key),
CONSTRAINT candidate_project_repositories_candidate_fkey FOREIGN KEY (candidate_id)
REFERENCES users (id) ON DELETE CASCADE,
CONSTRAINT candidate_project_repositories_key_format CHECK (
repository_key ~ '^[a-z0-9][a-z0-9-]{0,38}/[a-z0-9._-]{1,100}$'
),
CONSTRAINT candidate_project_repositories_state_known CHECK (
state IN ('pending', 'verified', 'not_found', 'unavailable')
),
CONSTRAINT candidate_project_repositories_failure_known CHECK (
failure_class IS NULL OR failure_class IN (
'rate_limited', 'server_error', 'network', 'invalid_response'
)
),
CONSTRAINT candidate_project_repositories_failure_state CHECK (
(state = 'unavailable') = (failure_class IS NOT NULL)
),
CONSTRAINT candidate_project_repositories_checked CHECK (
state = 'pending' OR checked_at IS NOT NULL
),
-- Metadata exists only for a verified public repository.
CONSTRAINT candidate_project_repositories_evidence_verified CHECK (
state = 'verified' OR (
github_id IS NULL
AND description IS NULL
AND readme_excerpt IS NULL
AND cardinality(topics) = 0
AND cardinality(languages) = 0
)
),
CONSTRAINT candidate_project_repositories_github_id CHECK (
github_id IS NULL OR github_id > 0
),
CONSTRAINT candidate_project_repositories_bounds CHECK (
(description IS NULL OR char_length(description) <= 1000)
AND (readme_excerpt IS NULL OR char_length(readme_excerpt) <= 4000)
AND cardinality(topics) <= 20
AND cardinality(languages) <= 10
AND (repository_etag IS NULL OR char_length(repository_etag) <= 200)
AND (readme_etag IS NULL OR char_length(readme_etag) <= 200)
),
CONSTRAINT candidate_project_repositories_times CHECK (
updated_at >= created_at
)
);
-- +goose Down
-- Refuse to strand stored projects or published project fields outside the
-- older contract; remove them through the product first.
-- +goose StatementBegin
DO $$
BEGIN
IF EXISTS (SELECT 1 FROM candidate_profile_claims WHERE kind = 'project')
OR EXISTS (SELECT 1 FROM candidate_publications WHERE 'projects' = ANY (fields))
OR EXISTS (SELECT 1 FROM candidate_privacy_events WHERE 'projects' = ANY (fields))
OR EXISTS (SELECT 1 FROM candidate_card_access_events WHERE 'projects' = ANY (field_codes))
THEN
RAISE EXCEPTION 'candidate projects are still stored or published';
END IF;
END;
$$;
-- +goose StatementEnd
DROP TABLE candidate_project_repositories;
-- +goose StatementBegin
CREATE OR REPLACE FUNCTION candidate_card_access_fields_are_valid(kind text, field_codes text []) RETURNS boolean
LANGUAGE sql IMMUTABLE STRICT PARALLEL SAFE AS $$
SELECT
cardinality(field_codes) BETWEEN 0 AND 6
AND array_position(field_codes, NULL) IS NULL
AND field_codes = ARRAY(
SELECT DISTINCT code COLLATE "C"
FROM unnest(field_codes) AS code
ORDER BY code COLLATE "C"
)
AND (
(
kind = 'card_viewed'
AND field_codes <@ ARRAY[
'categories', 'experience', 'salary_compatibility',
'self_assessment', 'stack', 'work_formats'
]::text []
)
OR (
kind = 'contact_read'
AND cardinality(field_codes) BETWEEN 1 AND 4
AND field_codes <@ ARRAY['email', 'full_name', 'phone', 'telegram']::text []
)
);
$$;
-- +goose StatementEnd
-- +goose StatementBegin
CREATE OR REPLACE FUNCTION candidate_card_fields_are_canonical(fields text []) RETURNS boolean
LANGUAGE sql IMMUTABLE STRICT PARALLEL SAFE AS $$
SELECT
(cardinality(fields) = 0 OR array_ndims(fields) = 1)
AND cardinality(fields) BETWEEN 0 AND 9
AND array_position(fields, NULL) IS NULL
AND fields <@ ARRAY[
'categories', 'experience', 'location', 'relocation',
'salary_compatibility', 'self_assessment', 'soft_skills',
'stack', 'work_formats'
]::text []
AND fields = ARRAY(
SELECT DISTINCT field COLLATE "C"
FROM unnest(fields) AS field
ORDER BY field COLLATE "C"
);
$$;
-- +goose StatementEnd
ALTER TABLE candidate_profile_claims
DROP CONSTRAINT candidate_profile_claims_project_value,
DROP CONSTRAINT candidate_profile_claims_kind_ordinal,
ADD CONSTRAINT candidate_profile_claims_kind_ordinal CHECK (
(
kind IN (
'full_name',
'contact_email',
'contact_phone',
'contact_telegram',
'terms_location',
'terms_relocation',
'terms_salary_minimum'
)
AND ordinal = 0
)
OR (kind = 'stack' AND ordinal BETWEEN 0 AND 29)
OR (kind = 'role' AND ordinal BETWEEN 0 AND 8)
OR (kind = 'experience' AND ordinal BETWEEN 0 AND 19)
OR (kind = 'soft_skill' AND ordinal BETWEEN 0 AND 9)
);
@@ -0,0 +1,64 @@
-- +goose Up
-- Stored embedding vectors of candidate cards and need snapshots. A row is
-- one text of a subject (the whole view or one item) encoded by one model,
-- revision, and prompt recipe; content_sha256 is the digest of the rendered
-- text, so a stale row is never mistaken for the current one. The vector is
-- little-endian float32: exact, platform independent, 4 KiB for 1024
-- dimensions. Derived data follows its subject: an account or a need that
-- is deleted takes its vectors with it.
CREATE TABLE semantic_vectors (
subject_kind text NOT NULL,
subject_id uuid NOT NULL,
candidate_id uuid,
need_id uuid,
model_id text NOT NULL,
model_revision text NOT NULL,
prompt_version text NOT NULL,
item_key text NOT NULL,
content_sha256 bytea NOT NULL,
label_sha256 bytea,
dimension integer NOT NULL,
vector bytea NOT NULL,
computed_at timestamptz NOT NULL,
CONSTRAINT semantic_vectors_pkey PRIMARY KEY (
subject_kind, subject_id, model_id, model_revision, prompt_version, item_key, content_sha256
),
CONSTRAINT semantic_vectors_candidate_fkey FOREIGN KEY (candidate_id)
REFERENCES users (id) ON DELETE CASCADE,
CONSTRAINT semantic_vectors_need_fkey FOREIGN KEY (need_id)
REFERENCES organization_needs (id) ON DELETE CASCADE,
CONSTRAINT semantic_vectors_subject CHECK (
(subject_kind = 'candidate' AND candidate_id = subject_id AND need_id IS NULL)
OR (subject_kind = 'need' AND need_id = subject_id AND candidate_id IS NULL)
),
CONSTRAINT semantic_vectors_model_format CHECK (
model_id ~ '^[A-Za-z0-9._/-]{1,200}$'
AND model_revision ~ '^[A-Za-z0-9._/-]{1,200}$'
AND prompt_version ~ '^[A-Za-z0-9._/-]{1,200}$'
),
CONSTRAINT semantic_vectors_item_key_format CHECK (
item_key ~ '^[a-z_]{1,32}(:[0-9]{1,3})?$'
),
CONSTRAINT semantic_vectors_digests CHECK (
octet_length(content_sha256) = 32
AND (label_sha256 IS NULL OR octet_length(label_sha256) = 32)
),
CONSTRAINT semantic_vectors_dimension CHECK (
dimension BETWEEN 1 AND 4096 AND octet_length(vector) = 4 * dimension
)
);
-- The search reads the whole-view vector of many candidates for one model.
CREATE INDEX semantic_vectors_candidate_whole_idx
ON semantic_vectors (model_id, model_revision, prompt_version, candidate_id)
WHERE subject_kind = 'candidate' AND item_key = 'whole';
-- Account and need deletion find the rows of their subject through these.
CREATE INDEX semantic_vectors_candidate_idx ON semantic_vectors (candidate_id)
WHERE candidate_id IS NOT NULL;
CREATE INDEX semantic_vectors_need_idx ON semantic_vectors (need_id)
WHERE need_id IS NOT NULL;
-- +goose Down
-- The vectors are derived data: the backfill command computes them again.
DROP TABLE semantic_vectors;
+1 -1
View File
@@ -125,7 +125,7 @@ func TestOnlyTheSettingsQueriesReadThePublicationTableDirectly(t *testing.T) {
for _, required := range []string{
"from candidate_effective_publications as effective",
"where effective.user_id = sqlc.arg(candidate_id)",
"claim.kind in ('stack', 'role', 'experience')",
"claim.kind in ('stack', 'role', 'experience', 'project')",
"coalesce(questionnaire.work_formats, '{}'::text[])",
} {
if !strings.Contains(previewQuery, required) {
+29 -7
View File
@@ -2,9 +2,11 @@
-- usecase has already authorized the active organization membership. This
-- single statement snapshot filters both revoked/unpublished C2 states and
-- candidates hidden from this organization before any profile value is read.
-- The projection reads only stack, declared role, and experience dates. It
-- deliberately excludes names, contacts, salary, location, soft skills,
-- employer names, summaries, and imported excerpts. The only assessment data
-- The projection reads only stack, declared role, experience dates, and
-- projects with the keys of their verified repositories. It deliberately
-- excludes names, contacts, salary, location, soft skills, employer names,
-- summaries, and imported excerpts; the repository address of a project stays
-- in the private input and never reaches the card. The only assessment data
-- is the current category (specialization and grade) of the separate current
-- category table; it carries no attempt, score, review, policy, or history.
-- name: ListVisibleCandidateViewSources :many
@@ -64,11 +66,21 @@ SELECT
WHERE category.candidate_id = effective.user_id
),
'[]'::text
) AS confirmed_categories
) AS confirmed_categories,
COALESCE(
(
SELECT array_agg(repository.repository_key ORDER BY repository.repository_key)
FROM candidate_project_repositories AS repository
WHERE
repository.candidate_id = effective.user_id
AND repository.state = 'verified'
),
'{}'::text []
)::text [] AS verified_repositories
FROM candidate_effective_publications AS effective
LEFT JOIN candidate_profile_claims AS claim
ON claim.user_id = effective.user_id
AND claim.kind IN ('stack', 'role', 'experience')
AND claim.kind IN ('stack', 'role', 'experience', 'project')
LEFT JOIN candidate_questionnaires AS questionnaire
ON questionnaire.user_id = effective.user_id
WHERE NOT EXISTS (
@@ -202,11 +214,21 @@ SELECT
WHERE category.candidate_id = effective.user_id
),
'[]'::text
) AS confirmed_categories
) AS confirmed_categories,
COALESCE(
(
SELECT array_agg(repository.repository_key ORDER BY repository.repository_key)
FROM candidate_project_repositories AS repository
WHERE
repository.candidate_id = effective.user_id
AND repository.state = 'verified'
),
'{}'::text []
)::text [] AS verified_repositories
FROM candidate_effective_publications AS effective
LEFT JOIN candidate_profile_claims AS claim
ON claim.user_id = effective.user_id
AND claim.kind IN ('stack', 'role', 'experience')
AND claim.kind IN ('stack', 'role', 'experience', 'project')
LEFT JOIN candidate_questionnaires AS questionnaire
ON questionnaire.user_id = effective.user_id
WHERE effective.user_id = sqlc.arg(candidate_id)
@@ -0,0 +1,62 @@
-- Server checks of the GitHub repositories that candidate projects link.
-- Every statement is scoped by the candidate.
-- name: ListCandidateProjectRepositories :many
SELECT
candidate_id, repository_key, state, github_id, description, topics,
languages, readme_excerpt, repository_etag, readme_etag, failure_class,
checked_at, requested_at, created_at, updated_at
FROM candidate_project_repositories
WHERE candidate_id = sqlc.arg(candidate_id)
ORDER BY repository_key;
-- name: GetCandidateProjectRepositoryForUpdate :one
SELECT
candidate_id, repository_key, state, github_id, description, topics,
languages, readme_excerpt, repository_etag, readme_etag, failure_class,
checked_at, requested_at, created_at, updated_at
FROM candidate_project_repositories
WHERE candidate_id = sqlc.arg(candidate_id) AND repository_key = sqlc.arg(repository_key)
FOR UPDATE;
-- A new repository starts pending; a known one only records the request.
-- name: RequestCandidateProjectRepositoryCheck :exec
INSERT INTO candidate_project_repositories (
candidate_id, repository_key, state, requested_at, created_at, updated_at
) VALUES (
sqlc.arg(candidate_id), sqlc.arg(repository_key), 'pending', sqlc.arg(requested_at),
sqlc.arg(requested_at), sqlc.arg(requested_at)
)
ON CONFLICT (candidate_id, repository_key) DO UPDATE
SET
requested_at = excluded.requested_at,
updated_at = GREATEST(candidate_project_repositories.updated_at, excluded.updated_at);
-- name: SaveCandidateProjectRepositoryCheck :exec
UPDATE candidate_project_repositories
SET
state = sqlc.arg(state),
github_id = sqlc.narg(github_id),
description = sqlc.narg(description),
topics = sqlc.arg(topics),
languages = sqlc.arg(languages),
readme_excerpt = sqlc.narg(readme_excerpt),
repository_etag = sqlc.narg(repository_etag),
readme_etag = sqlc.narg(readme_etag),
failure_class = sqlc.narg(failure_class),
checked_at = sqlc.arg(checked_at),
updated_at = GREATEST(updated_at, sqlc.arg(checked_at))
WHERE candidate_id = sqlc.arg(candidate_id) AND repository_key = sqlc.arg(repository_key);
-- Removes the checks of repositories that no project links any more.
-- name: DeleteUnlinkedCandidateProjectRepositories :exec
DELETE FROM candidate_project_repositories
WHERE
candidate_id = sqlc.arg(candidate_id)
AND NOT (repository_key = ANY(sqlc.arg(linked_keys)::text []));
-- The latest check request of a candidate, for the per-candidate limit.
-- name: GetLatestRepositoryCheckRequest :one
SELECT MAX(requested_at)::timestamptz AS requested_at
FROM candidate_project_repositories
WHERE candidate_id = sqlc.arg(candidate_id);
+110
View File
@@ -0,0 +1,110 @@
-- Stored embedding vectors. A candidate keeps one set of rows for a model:
-- the job deletes every other row of the candidate and model before it
-- inserts the new set, in one transaction. A need keeps the rows of its
-- latest computed requirements snapshot the same way.
-- name: DeleteSemanticVectorsOfModel :exec
DELETE FROM semantic_vectors
WHERE
subject_kind = sqlc.arg(subject_kind)
AND subject_id = sqlc.arg(subject_id)
AND model_id = sqlc.arg(model_id)
AND model_revision = sqlc.arg(model_revision)
AND prompt_version = sqlc.arg(prompt_version);
-- Removes every vector of a subject, of any model: a closed card or a need
-- without requirements keeps no derived data.
-- name: DeleteSemanticVectorsOfSubject :exec
DELETE FROM semantic_vectors
WHERE subject_kind = sqlc.arg(subject_kind) AND subject_id = sqlc.arg(subject_id);
-- name: InsertSemanticVector :exec
INSERT INTO semantic_vectors (
subject_kind, subject_id, candidate_id, need_id, model_id, model_revision,
prompt_version, item_key, content_sha256, label_sha256, dimension, vector,
computed_at
) VALUES (
sqlc.arg(subject_kind), sqlc.arg(subject_id), sqlc.narg(candidate_id),
sqlc.narg(need_id), sqlc.arg(model_id), sqlc.arg(model_revision),
sqlc.arg(prompt_version), sqlc.arg(item_key), sqlc.arg(content_sha256),
sqlc.narg(label_sha256), sqlc.arg(dimension), sqlc.arg(vector),
sqlc.arg(computed_at)
);
-- The digests of the stored rows of a subject and model, for the job that
-- decides whether anything changed.
-- name: ListSemanticVectorDigests :many
SELECT item_key, content_sha256
FROM semantic_vectors
WHERE
subject_kind = sqlc.arg(subject_kind)
AND subject_id = sqlc.arg(subject_id)
AND model_id = sqlc.arg(model_id)
AND model_revision = sqlc.arg(model_revision)
AND prompt_version = sqlc.arg(prompt_version)
ORDER BY item_key, content_sha256;
-- The whole-view vectors of the candidates of one search.
-- name: ListCandidateWholeVectors :many
SELECT candidate_id, dimension, vector
FROM semantic_vectors
WHERE
subject_kind = 'candidate'
AND item_key = 'whole'
AND model_id = sqlc.arg(model_id)
AND model_revision = sqlc.arg(model_revision)
AND prompt_version = sqlc.arg(prompt_version)
AND candidate_id = ANY(sqlc.arg(candidate_ids)::uuid [])
ORDER BY candidate_id;
-- The item vectors of the candidates that a search returns, at most a few
-- dozen candidates.
-- name: ListCandidateItemVectors :many
SELECT candidate_id, item_key, label_sha256, dimension, vector
FROM semantic_vectors
WHERE
subject_kind = 'candidate'
AND item_key <> 'whole'
AND model_id = sqlc.arg(model_id)
AND model_revision = sqlc.arg(model_revision)
AND prompt_version = sqlc.arg(prompt_version)
AND candidate_id = ANY(sqlc.arg(candidate_ids)::uuid [])
ORDER BY candidate_id, item_key;
-- The vectors of a need whose texts match the given digests of the
-- requirements snapshot that the search renders.
-- name: ListNeedVectors :many
SELECT item_key, content_sha256, dimension, vector
FROM semantic_vectors
WHERE
subject_kind = 'need'
AND need_id = sqlc.arg(need_id)
AND model_id = sqlc.arg(model_id)
AND model_revision = sqlc.arg(model_revision)
AND prompt_version = sqlc.arg(prompt_version)
AND content_sha256 = ANY(sqlc.arg(content_digests)::bytea [])
ORDER BY item_key;
-- Candidates with a saved profile for the backfill, in identifier order
-- after a cursor. The job of a candidate who is not published removes the
-- stored vectors, so a backfill also cleans up after a closed card.
-- name: ListProfileCandidatesAfter :many
SELECT profiles.user_id
FROM candidate_profiles AS profiles
WHERE profiles.user_id > sqlc.arg(after_id)
ORDER BY profiles.user_id
LIMIT sqlc.arg(page_size);
-- Needs and their current requirements snapshot for the backfill.
-- name: ListNeedsAfter :many
SELECT id, organization_id, requirements_version
FROM organization_needs
WHERE id > sqlc.arg(after_id)
ORDER BY id
LIMIT sqlc.arg(page_size);
-- Serializes the vector jobs of one subject: a job takes this lock before it
-- reads the subject, so the job that runs last also read last and its vectors
-- describe the latest committed state. User requests never take it.
-- name: LockSemanticSubject :exec
SELECT pg_advisory_xact_lock(sqlc.arg(lock_key)::bigint);
@@ -36,6 +36,8 @@ var (
// candidateProfileTables reference users, so a TRUNCATE of users names
// them through usersDependentTables.
candidateProfileTables = []pgx.Identifier{
// Repository checks of the projects of a profile.
{"candidate_project_repositories"},
{"candidate_profile_overlap_confirmations"},
{"candidate_profile_history"},
candidateProfileClaimsTable,
@@ -37,6 +37,7 @@ import (
"lincodex/backend/internal/usecase/organization"
"lincodex/backend/internal/usecase/policy"
profileusecase "lincodex/backend/internal/usecase/profile"
"lincodex/backend/internal/usecase/semantic"
)
const matchSearchHTTPTimeout = 15 * time.Minute
@@ -50,6 +51,13 @@ type matchSearchHarness struct {
}
func newMatchSearchHarness(ctx context.Context, t *testing.T, env *testEnvironment) *matchSearchHarness {
t.Helper()
return newMatchSearchHarnessWithSemantic(ctx, t, env, nil)
}
// newMatchSearchHarnessWithSemantic wires the semantic trigger into the
// profile, publication, and need operations; nil schedules nothing.
func newMatchSearchHarnessWithSemantic(ctx context.Context, t *testing.T, env *testEnvironment, trigger *semantic.Trigger) *matchSearchHarness {
t.Helper()
var key domain.CandidateViewPseudonymKey
var organizationHandler *v1.OrganizationHandler
@@ -71,7 +79,15 @@ func newMatchSearchHarness(ctx context.Context, t *testing.T, env *testEnvironme
if err != nil {
t.Fatalf("candidateview.NewService() error = %v", err)
}
settings, err := candidateprivacy.NewService(candidateprivacy.Dependencies{Transactor: parts.transactor, Clock: parts.clock.Now})
privacyDependencies := candidateprivacy.Dependencies{Transactor: parts.transactor, Clock: parts.clock.Now}
needDependencies := needusecase.Dependencies{Transactor: parts.transactor, Keyring: parts.keyring, Clock: parts.clock.Now}
profileService := profileusecase.NewService(parts.transactor, parts.clock.Now)
if trigger != nil {
privacyDependencies.Semantic = trigger
needDependencies.Semantic = trigger
profileService = profileService.WithSemantic(trigger, semanticCheckInterval)
}
settings, err := candidateprivacy.NewService(privacyDependencies)
if err != nil {
t.Fatalf("candidateprivacy.NewService() error = %v", err)
}
@@ -81,9 +97,7 @@ func newMatchSearchHarness(ctx context.Context, t *testing.T, env *testEnvironme
if err != nil {
t.Fatalf("organization.NewService() error = %v", err)
}
needService, err := needusecase.NewService(needusecase.Dependencies{
Transactor: parts.transactor, Keyring: parts.keyring, Clock: parts.clock.Now,
})
needService, err := needusecase.NewService(needDependencies)
if err != nil {
t.Fatalf("need.NewService() error = %v", err)
}
@@ -110,7 +124,7 @@ func newMatchSearchHarness(ctx context.Context, t *testing.T, env *testEnvironme
return []v1.HandlerOption{
v1.WithEvidence(v1.NewEvidenceHandler(evidenceService)),
v1.WithPrivacy(v1.NewPrivacyHandler(views, settings, env.Config.AppPublicURL)),
v1.WithProfile(v1.NewProfileHandler(profileusecase.NewService(parts.transactor, parts.clock.Now))),
v1.WithProfile(v1.NewProfileHandler(profileService)),
v1.WithOrganization(organizationHandler),
v1.WithNeed(v1.NewNeedHandler(needService)),
v1.WithMatches(v1.NewMatchHandler(search)),
@@ -33,10 +33,17 @@ func TestNotificationSubjectMigrations(t *testing.T) {
if _, err := migrator.Up(ctx); err != nil {
t.Fatalf("Up() error = %v", err)
}
// Migration 00046 (verification codes) is newer than the subject migration
// under test. Roll it back first, so the rollback checks below act on 00045.
if result, err := migrator.DownOne(ctx); err != nil || result.Version != 46 {
t.Fatalf("roll back the newest migration: result %+v, error = %v; want migration 46", result, err)
// Migration 00046 (verification codes) and every later one are newer than
// the subject migration under test. Roll them back first, newest first, so
// the rollback checks below act on 00045.
for {
result, err := migrator.DownOne(ctx)
if err != nil || result.Version < 46 {
t.Fatalf("roll back the newer migrations: result %+v, error = %v; want every migration down to 46", result, err)
}
if result.Version == 46 {
break
}
}
now := time.Date(2026, 10, 9, 12, 0, 0, 0, time.UTC)
@@ -42,6 +42,8 @@ var (
{"candidate_card_access_events"},
{"invitation_creation_results"}, {"invitation_send_results"}, {"invitation_decline_results"}, {"invitation_declines"},
{"invitation_events"}, {"invitation_terms_versions"}, {"invitation_accept_results"}, {"contact_grants"}, {"invitations"},
// Stored vectors reference both needs and candidate accounts.
{"semantic_vectors"},
{"organization_need_versions"}, {"organization_needs"},
{"organization_need_creation_results"},
{"company_invitation_quota_usage"}, {"company_card_view_quota_usage"},
@@ -0,0 +1,478 @@
//go:build integration
package integration_test
import (
"context"
"encoding/json"
"fmt"
"log/slog"
"math"
"net/http"
"net/http/httptest"
"slices"
"strings"
"sync"
"testing"
"time"
"github.com/google/uuid"
mladapter "lincodex/backend/internal/adapter/secondary/ml"
postgresadapter "lincodex/backend/internal/adapter/secondary/postgres"
"lincodex/backend/internal/adapter/secondary/prometheus"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/inbound"
"lincodex/backend/internal/port/outbound"
"lincodex/backend/internal/usecase/semantic"
"lincodex/backend/internal/worker/jobrunner"
"lincodex/backend/internal/worker/retry"
)
const (
semanticHTTPTimeout = 10 * time.Minute
semanticCheckInterval = 10 * time.Minute
// semanticRepository is the address a project links; its owner must
// never reach an organization.
semanticRepository = "https://github.com/Private-Owner-Marker/payments-ledger"
semanticRepositoryOwner = "Private-Owner-Marker"
)
// fakeMLService answers the ML embedding contract with a bag-of-topics
// encoder: each topic word lights one dimension, so texts about the same
// topic are close and others are not. It reports the policy model, so the
// vectors pass the model check, and counts the texts it encoded.
type fakeMLService struct {
mutex sync.Mutex
texts int
down bool
}
var fakeTopics = [][]string{
{"payment", "idempot", "webhook", "callback", "ledger"},
{"kafka", "stream", "event"},
{"react", "frontend", "css"},
{"kubernetes", "terraform", "infra"},
}
func fakeTopicVector(text string) []float32 {
lower := strings.ToLower(text)
vector := make([]float32, len(fakeTopics)+1)
vector[len(fakeTopics)] = 0.2
for index, words := range fakeTopics {
for _, word := range words {
if strings.Contains(lower, word) {
vector[index]++
}
}
}
var norm float64
for _, value := range vector {
norm += float64(value) * float64(value)
}
for index := range vector {
vector[index] = float32(float64(vector[index]) / math.Sqrt(norm))
}
return vector
}
func (service *fakeMLService) ServeHTTP(writer http.ResponseWriter, request *http.Request) {
service.mutex.Lock()
down := service.down
service.mutex.Unlock()
if down {
writer.Header().Set("Content-Type", "application/problem+json")
writer.WriteHeader(http.StatusServiceUnavailable)
_, _ = writer.Write([]byte(`{"type":"urn:lincodex:problem:service_unavailable","title":"Service unavailable","status":503,"code":"service_unavailable"}`))
return
}
var body struct {
Model string `json:"model"`
Kind string `json:"kind"`
Texts []string `json:"texts"`
}
// The service serves one model; a request for another one is refused
// as the real service refuses it.
if request.URL.Path != "/v1/embeddings" || json.NewDecoder(request.Body).Decode(&body) != nil ||
body.Model != domain.GigaEmbeddingsModelID {
writer.WriteHeader(http.StatusBadRequest)
return
}
service.mutex.Lock()
service.texts += len(body.Texts)
service.mutex.Unlock()
vectors := make([][]float32, 0, len(body.Texts))
for _, text := range body.Texts {
vectors = append(vectors, fakeTopicVector(text))
}
writer.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(writer).Encode(map[string]any{
"model": map[string]any{
"id": domain.GigaEmbeddingsModelID, "revision": domain.GigaEmbeddingsModelRevision,
"dimension": len(fakeTopics) + 1, "max_tokens": 1024, "prompt_version": domain.GigaEmbeddingsPromptVersion,
},
"kind": body.Kind, "vectors": vectors,
})
}
func (service *fakeMLService) encodedTexts() int {
service.mutex.Lock()
defer service.mutex.Unlock()
return service.texts
}
func (service *fakeMLService) setDown(down bool) {
service.mutex.Lock()
defer service.mutex.Unlock()
service.down = down
}
// fakeRepositoryFetcher stands in for the public GitHub API; tests never
// call GitHub.
type fakeRepositoryFetcher struct {
mutex sync.Mutex
calls int
}
func (fetcher *fakeRepositoryFetcher) Fetch(_ context.Context, repository domain.GitHubRepository, _ outbound.RepositoryCheck) (outbound.RepositoryFetch, error) {
fetcher.mutex.Lock()
defer fetcher.mutex.Unlock()
fetcher.calls++
if repository.Owner() != semanticRepositoryOwner {
return outbound.RepositoryFetch{Found: false}, nil
}
return outbound.RepositoryFetch{
Found: true, GitHubID: 42, RepositoryETag: `"etag-1"`,
Evidence: domain.RepositoryEvidence{
Description: "Ledger with idempotent payment webhooks", Topics: []string{"payments"},
Languages: []string{"Go"}, ReadmeExcerpt: "Deduplicates acquirer callbacks by operation key.",
},
}, nil
}
type semanticEntryBody struct {
matchEntryBody
SemanticEvidence []struct {
RequirementKind string `json:"requirement_kind"`
RequirementText string `json:"requirement_text"`
ItemKind string `json:"item_kind"`
ProjectTitle *string `json:"project_title"`
RepositoryVerified bool `json:"repository_verified"`
Similarity string `json:"similarity"`
} `json:"semantic_evidence"`
}
type semanticSearchBody struct {
Groups struct {
Unconfirmed []semanticEntryBody `json:"unconfirmed"`
} `json:"groups"`
}
func TestSemanticMatchingOverHTTP(t *testing.T) {
env := bootstrap(t, postgresService, redisService)
ctx, cancel := context.WithTimeout(t.Context(), semanticHTTPTimeout)
defer cancel()
databaseURL := env.createIsolatedDatabase(ctx, t)
applyMigrations(ctx, t, databaseURL)
isolatedEnv := *env
isolatedEnv.Config.DatabaseURL = databaseURL
trigger := semantic.NewTrigger(true, true)
harness := newMatchSearchHarnessWithSemantic(ctx, t, &isolatedEnv, trigger)
client := &categoryHTTPClient{harness: harness.assessmentAttemptHTTPHarness, ctx: ctx}
transactor := postgresadapter.NewTransactor(harness.pool)
product := domain.DemoProductPolicyV5()
product.Matching.MaxResultsPerGroup = 100
// The questionnaire of a candidate needs the assessment bank; the bank
// seed publishes the semantic policy V5 with it.
seedAssessmentCategoryHTTPBank(ctx, t, harness.pool, product, true)
ml := &fakeMLService{}
mlServer := httptest.NewServer(ml)
defer mlServer.Close()
embedder, err := mladapter.NewEmbedder(mladapter.Settings{
BaseURL: mlServer.URL, Timeout: 5 * time.Second, FailureThreshold: 100, OpenDuration: time.Second,
}, time.Now)
if err != nil {
t.Fatalf("NewEmbedder() error = %v", err)
}
vectorJobs, err := semantic.NewVectorJobs(embedder, time.Now, nil)
if err != nil {
t.Fatalf("NewVectorJobs() error = %v", err)
}
fetcher := &fakeRepositoryFetcher{}
repositoryJob, err := semantic.NewRepositoryCheckJob(fetcher, trigger, time.Now, nil)
if err != nil {
t.Fatalf("NewRepositoryCheckJob() error = %v", err)
}
jobPool := isolatedEnv.newPool(ctx, t)
worker, err := jobrunner.New(
[]inbound.JobHandler{vectorJobs.CandidateHandler(), vectorJobs.NeedHandler(), repositoryJob},
postgresadapter.NewScheduledJobStore(jobPool, time.Minute), prometheus.New(), slog.New(slog.DiscardHandler),
jobrunner.Settings{
BatchSize: 50, PollInterval: 10 * time.Millisecond, Lease: time.Minute, MaxAttempts: 3,
Backoff: retry.Backoff{Initial: time.Millisecond, Max: time.Millisecond},
ShutdownGrace: time.Second, StoreTimeout: 5 * time.Second, BacklogInterval: time.Second,
}, func() time.Time { return time.Now().Add(time.Hour) })
if err != nil {
t.Fatalf("jobrunner.New() error = %v", err)
}
// drain runs passes until no job is due; follow-up jobs that a job
// schedules run in the next pass.
drain := func() {
t.Helper()
for range 10 {
result, err := worker.RunDue(ctx)
if err != nil {
t.Fatalf("RunDue() error = %v", err)
}
if result.Claimed == 0 {
return
}
}
t.Fatal("jobs kept falling due")
}
countRows := func(query string, args ...any) int {
t.Helper()
var count int
if err := harness.pool.QueryRow(ctx, query, args...).Scan(&count); err != nil {
t.Fatalf("count rows: %v", err)
}
return count
}
mustCall := func(who categoryHTTPCandidate, method, path, body string, want int) []byte {
t.Helper()
status, response := client.call(t, who, method, path, body, "")
if status != want {
t.Fatalf("%s %s = %d %s, want %d", method, path, status, response, want)
}
return response
}
profileBody := func(version int, projects string) string {
return fmt.Sprintf(`{"expected_version":%d,"full_name":null,"contacts":{"email":null,"phone":null,"telegram":null},
"stack":[{"tag":"go","status":"confirmed"}],"roles":[{"specialization":"backend","self_assessed_grade":"junior","status":"confirmed"}],
"experience":[],"confirmed_parallel_periods":[],"soft_skills":[],"projects":%s,
"terms":{"location":null,"relocation":null,"salary_minimum":null}}`, version, projects)
}
publishFields := func(who categoryHTTPCandidate, version int, fields string) {
t.Helper()
mustCall(who, http.MethodPut, "/api/v1/me/privacy/publication",
fmt.Sprintf(`{"expected_version":%d,"state":"published","fields":%s}`, version, fields), http.StatusOK)
}
payments := `[{"title":"Payment webhook deduplication","description":"Idempotent callback receiver","stack":["Go","PostgreSQL"],"repository_url":"` + semanticRepository + `/","status":"confirmed"}]`
frontendProject := `[{"title":"Landing page","description":"React and CSS components","stack":["React"],"repository_url":null,"status":"confirmed"}]`
candidates := make([]categoryHTTPCandidate, 0, 6)
for index := range 6 {
member := client.candidate(t, fmt.Sprintf("semantic-%d@example.test", index))
projects := frontendProject
if index == 0 {
projects = payments
}
mustCall(member, http.MethodPut, "/api/v1/me/profile", profileBody(0, projects), http.StatusOK)
mustCall(member, http.MethodPut, "/api/v1/me/consents/c2", fmt.Sprintf(`{"text_version":%q,"accepted":true}`, privacyC2Version), http.StatusOK)
publishFields(member, 0, `["projects","self_assessment","stack"]`)
candidates = append(candidates, member)
}
paymentsCandidate := candidates[0]
t.Run("a profile save schedules jobs whose keys and payloads name no repository", func(t *testing.T) {
if got := countRows(`SELECT count(*) FROM scheduled_jobs WHERE kind = $1`, semantic.CandidateJobKind); got < 6 {
t.Fatalf("candidate jobs = %d, want one per save and publication", got)
}
if got := countRows(`SELECT count(*) FROM scheduled_jobs WHERE kind = $1`, semantic.RepositoryCheckJobKind); got != 1 {
t.Fatalf("repository jobs = %d, want 1", got)
}
if got := countRows(`SELECT count(*) FROM scheduled_jobs WHERE dedup_key ILIKE '%owner-marker%' OR payload::text ILIKE '%owner-marker%'`); got != 0 {
t.Fatalf("%d jobs name the repository owner", got)
}
profile := mustCall(paymentsCandidate, http.MethodGet, "/api/v1/me/profile", "", http.StatusOK)
if !strings.Contains(string(profile), `"repository_url":"`+semanticRepository+`"`) || !strings.Contains(string(profile), `"state":"pending"`) {
t.Fatalf("profile = %s, want the canonical address and a pending check", profile)
}
})
t.Run("the jobs verify the repository and store the card vectors", func(t *testing.T) {
drain()
if fetcher.calls != 1 {
t.Fatalf("repository fetches = %d, want 1", fetcher.calls)
}
profile := mustCall(paymentsCandidate, http.MethodGet, "/api/v1/me/profile", "", http.StatusOK)
if !strings.Contains(string(profile), `"state":"verified"`) {
t.Fatalf("profile = %s, want a verified check", profile)
}
if got := countRows(`SELECT count(DISTINCT candidate_id) FROM semantic_vectors WHERE subject_kind = 'candidate' AND item_key = 'whole'`); got != 6 {
t.Fatalf("candidates with a whole vector = %d, want 6", got)
}
if got := countRows(`SELECT count(*) FROM semantic_vectors WHERE candidate_id = $1`, paymentsCandidate.id); got != 4 {
t.Fatalf("vectors of the payments candidate = %d, want whole, roles, stack, and one project", got)
}
})
employer := client.employer(t, "semantic-employer@example.test")
organizations := organizationFixture{ctx: ctx, pool: harness.pool, identity: identityFixture{ctx: ctx, pool: harness.pool, store: harness.store, now: time.Now().UTC()}, transactor: transactor, now: time.Now().UTC()}
org := organizations.create(t, domain.User{ID: employer.id}, organizations.completeProfile(t, "Semantic organization"), time.Now().UTC())
harness.clock.Set(time.Now().UTC().Add(time.Minute).Truncate(time.Microsecond))
status, created := client.call(t, employer, http.MethodPost, fmt.Sprintf("/api/v1/organizations/%s/needs", org.ID()),
`{"title":"Payments backend","specialization":{"value":"backend","status":"confirmed"},"required_skills":[{"name":"Kafka","status":"confirmed"}],"tasks":[{"text":"Make payment callbacks idempotent","status":"confirmed"}]}`,
"semantic-need-1")
var need struct {
ID uuid.UUID `json:"id"`
RequirementsVersion int64 `json:"requirements_version"`
}
if status != http.StatusCreated || json.Unmarshal(created, &need) != nil {
t.Fatalf("create need = %d %s", status, created)
}
searchBody := fmt.Sprintf(`{"need_id":%q,"requirements_version":%d}`, need.ID, need.RequirementsVersion)
search := func() (semanticSearchBody, []byte) {
t.Helper()
response := mustCall(employer, http.MethodPost, fmt.Sprintf("/api/v1/organizations/%s/matches", org.ID()), searchBody, http.StatusOK)
var decoded semanticSearchBody
if err := json.Unmarshal(response, &decoded); err != nil {
t.Fatalf("decode search: %v", err)
}
return decoded, response
}
paymentsHandle, err := harness.key.ForOrganization(org.ID(), paymentsCandidate.id)
if err != nil {
t.Fatalf("ForOrganization() error = %v", err)
}
t.Run("before the need vectors exist every entry keeps the neutral Sem and the ML flag", func(t *testing.T) {
result, _ := search()
if len(result.Groups.Unconfirmed) != 6 {
t.Fatalf("unconfirmed entries = %d, want 6", len(result.Groups.Unconfirmed))
}
for _, entry := range result.Groups.Unconfirmed {
if !slices.Contains(entry.flags(), "semantics:ml_unavailable") || len(entry.SemanticEvidence) != 0 {
t.Fatalf("entry flags %v evidence %v, want the ML flag and no evidence", entry.flags(), entry.SemanticEvidence)
}
}
})
t.Run("with vectors the related project ranks first and explains the match without the repository", func(t *testing.T) {
drain()
first, raw := search()
second, rawAgain := search()
if string(raw) != string(rawAgain) || len(first.Groups.Unconfirmed) != len(second.Groups.Unconfirmed) {
t.Fatal("two searches over the same vectors differ")
}
top := first.Groups.Unconfirmed[0]
if top.CandidateHandle != paymentsHandle {
t.Fatalf("first entry = %s, want the payments candidate", top.CandidateHandle)
}
if slices.Contains(top.flags(), "semantics:ml_unavailable") {
t.Fatalf("flags = %v, want Sem known", top.flags())
}
if top.component("fit") <= first.Groups.Unconfirmed[1].component("fit") {
t.Fatalf("fit %v is not above the next entry %v", top.component("fit"), first.Groups.Unconfirmed[1].component("fit"))
}
var project bool
for _, item := range top.SemanticEvidence {
if item.ItemKind == "project" && item.ProjectTitle != nil && *item.ProjectTitle == "Payment webhook deduplication" && item.RepositoryVerified &&
item.RequirementKind == "task" && item.RequirementText == "Make payment callbacks idempotent" {
project = true
}
}
if !project {
t.Fatalf("evidence = %+v, want the task matched to the verified project", top.SemanticEvidence)
}
for _, forbidden := range []string{"github.com", semanticRepositoryOwner, "owner-marker", "payments-ledger", "acquirer"} {
if strings.Contains(strings.ToLower(string(raw)), strings.ToLower(forbidden)) {
t.Fatalf("the search result contains %q", forbidden)
}
}
var fields []string
if err := harness.pool.QueryRow(ctx, `SELECT field_codes FROM candidate_card_access_events
WHERE candidate_id = $1 AND organization_id = $2 ORDER BY occurred_at DESC, id DESC LIMIT 1`,
paymentsCandidate.id, org.ID()).Scan(&fields); err != nil {
t.Fatalf("read access history: %v", err)
}
if !slices.Contains(fields, "projects") {
t.Fatalf("access history fields = %v, want projects", fields)
}
})
t.Run("the card shows the published project but never the repository address", func(t *testing.T) {
card := mustCall(employer, http.MethodGet, fmt.Sprintf("/api/v1/organizations/%s/candidate-cards/%s", org.ID(), paymentsHandle), "", http.StatusOK)
if !strings.Contains(string(card), `"title":"Payment webhook deduplication"`) || !strings.Contains(string(card), `"repository_verified":true`) {
t.Fatalf("card = %s, want the published project", card)
}
if strings.Contains(string(card), "github.com") || strings.Contains(string(card), semanticRepositoryOwner) {
t.Fatalf("card = %s, leaks the repository", card)
}
})
t.Run("an unchanged card costs no ML call and a repeated backfill schedules nothing twice", func(t *testing.T) {
backfill, err := semantic.NewBackfill(transactor, time.Now)
if err != nil {
t.Fatalf("NewBackfill() error = %v", err)
}
for range 2 {
if err := backfill.Run(ctx, semantic.BackfillCandidates, "it-1", uuid.Nil, nil); err != nil {
t.Fatalf("Backfill.Run() error = %v", err)
}
if err := backfill.Run(ctx, semantic.BackfillNeeds, "it-1", uuid.Nil, nil); err != nil {
t.Fatalf("Backfill.Run(needs) error = %v", err)
}
}
if got := countRows(`SELECT count(*) FROM scheduled_jobs WHERE dedup_key LIKE '%:backfill-it-1'`); got != 6+1 {
t.Fatalf("backfill jobs = %d, want one per published candidate and need", got)
}
before := ml.encodedTexts()
drain()
if after := ml.encodedTexts(); after != before {
t.Fatalf("the backfill encoded %d texts, want none for unchanged cards", after-before)
}
})
t.Run("unpublishing projects removes them from the vectors and the explanation", func(t *testing.T) {
publishFields(paymentsCandidate, 1, `["self_assessment","stack"]`)
drain()
if got := countRows(`SELECT count(*) FROM semantic_vectors WHERE candidate_id = $1 AND item_key LIKE 'project:%'`, paymentsCandidate.id); got != 0 {
t.Fatalf("project vectors = %d, want 0 after unpublishing", got)
}
result, _ := search()
for _, entry := range result.Groups.Unconfirmed {
for _, item := range entry.SemanticEvidence {
if item.ProjectTitle != nil && entry.CandidateHandle == paymentsHandle {
t.Fatalf("evidence still names a project: %+v", item)
}
}
}
})
t.Run("an ML outage keeps the job pending and the search answering", func(t *testing.T) {
ml.setDown(true)
defer ml.setDown(false)
mustCall(candidates[1], http.MethodPut, "/api/v1/me/profile", profileBody(1, `[{"title":"Kafka event pipeline","description":null,"stack":["Kafka"],"repository_url":null,"status":"confirmed"}]`), http.StatusOK)
if _, err := worker.RunDue(ctx); err != nil {
t.Fatalf("RunDue() error = %v", err)
}
if got := countRows(`SELECT count(*) FROM scheduled_jobs WHERE kind = $1 AND status = 'failed'`, semantic.CandidateJobKind); got == 0 {
t.Fatal("the vector job did not record a failed attempt while ML was down")
}
search()
})
t.Run("the refresh of repository checks is limited per candidate", func(t *testing.T) {
harness.clock.Set(time.Now().UTC().Add(time.Hour).Truncate(time.Microsecond))
for _, member := range []categoryHTTPCandidate{candidates[2]} {
mustCall(member, http.MethodPut, "/api/v1/me/profile", profileBody(1, `[{"title":"Infra","description":null,"stack":[],"repository_url":"https://github.com/someone/infra","status":"confirmed"}]`), http.StatusOK)
status, body := client.call(t, member, http.MethodPost, "/api/v1/me/profile/repository-checks", "", "")
if status != http.StatusTooManyRequests {
t.Fatalf("refresh right after the save = %d %s, want 429", status, body)
}
harness.clock.Set(time.Now().UTC().Add(2 * time.Hour).Truncate(time.Microsecond))
status, body = client.call(t, member, http.MethodPost, "/api/v1/me/profile/repository-checks", "", "")
if status != http.StatusAccepted || !strings.Contains(string(body), `"scheduled":1`) {
t.Fatalf("refresh after the interval = %d %s, want 202 with one check", status, body)
}
}
status, body := client.call(t, candidates[3], http.MethodPost, "/api/v1/me/profile/repository-checks", "", "")
if status != http.StatusAccepted || !strings.Contains(string(body), `"scheduled":0`) {
t.Fatalf("refresh without repositories = %d %s, want 202 with nothing", status, body)
}
})
}
@@ -1,5 +1,6 @@
// Package policypublish implements the local operator command that adds the
// demo matching section to the product policy. Until an administrative policy
// demo matching section, or the semantic matching section, to the product
// policy. Until an administrative policy
// editor exists, this is how a stand gets the coefficients that the match
// search needs: startup seeds only the first demo version.
package policypublish
@@ -20,24 +21,38 @@ import (
"lincodex/backend/internal/usecase/policy"
)
const usage = "usage: policy-publish matching --actor operator:<handle>"
const usage = "usage: policy-publish matching|semantic --actor operator:<handle>"
// Track names which section a command publishes.
type Track string
const (
// TrackMatching adds the PRD matching section (Sem weight 0.10).
TrackMatching Track = "matching"
// TrackSemantic adds the semantic matching section (Sem weight 0.5, the
// encoder identity, the calibration, and the explanation thresholds).
TrackSemantic Track = "semantic"
)
// Command is a parsed, validated request.
type Command struct {
Track Track
Author domain.PolicyAuthor
}
// Extender publishes the demo matching section.
type Extender interface {
EnsureDemoMatchingSection(ctx context.Context, author domain.PolicyAuthor) (policy.MatchingResult, error)
EnsureDemoSemanticMatchingSection(ctx context.Context, author domain.PolicyAuthor) (policy.MatchingResult, error)
}
// Parse validates every argument before Run reads configuration or connects.
func Parse(args []string) (Command, error) {
if len(args) == 0 || args[0] != "matching" {
if len(args) == 0 || (args[0] != string(TrackMatching) && args[0] != string(TrackSemantic)) {
return Command{}, errors.New(usage)
}
flags := flag.NewFlagSet("policy-publish matching", flag.ContinueOnError)
track := Track(args[0])
flags := flag.NewFlagSet("policy-publish "+args[0], flag.ContinueOnError)
flags.SetOutput(io.Discard)
actor := flags.String("actor", "", "operator handle")
if err := flags.Parse(args[1:]); err != nil || flags.NArg() != 0 {
@@ -48,7 +63,7 @@ func Parse(args []string) (Command, error) {
if err != nil || !strings.HasPrefix(value, "operator:") {
return Command{}, errors.New("actor must be operator:<handle>")
}
return Command{Author: author}, nil
return Command{Track: track, Author: author}, nil
}
// Run parses the command, loads only DATABASE_URL from the supplied
@@ -81,7 +96,14 @@ func Execute(ctx context.Context, command Command, extender Extender, output io.
if extender == nil || output == nil {
return errors.New("policy publication command dependencies are required")
}
result, err := extender.EnsureDemoMatchingSection(ctx, command.Author)
publish, section, note := extender.EnsureDemoMatchingSection, "the demo matching section",
"note: demonstration values, not calibrated; they apply to new searches at once and change no stored result\n"
if command.Track == TrackSemantic {
publish, section, note = extender.EnsureDemoSemanticMatchingSection, "the semantic matching section",
"note: research-calibrated values (LincodexMatch DEV split), not product measurements; searches use them at once,\n"+
"and Sem stays neutral for subjects without vectors until the semantic-backfill command has run\n"
}
result, err := publish(ctx, command.Author)
if err != nil {
return safeOperationError(err)
}
@@ -89,11 +111,7 @@ func Execute(ctx context.Context, command Command, extender Extender, output io.
if result.Created {
status = "published"
}
if _, err := fmt.Fprintf(output,
"%s: product policy version %d carries the demo matching section\n"+
"note: demonstration values, not calibrated; they apply to new searches at once and change no stored result\n",
status, result.Version.Version(),
); err != nil {
if _, err := fmt.Fprintf(output, "%s: product policy version %d carries %s\n%s", status, result.Version.Version(), section, note); err != nil {
return errors.New("could not write the result")
}
return nil
@@ -13,9 +13,10 @@ import (
)
type extenderFake struct {
result policy.MatchingResult
err error
author domain.PolicyAuthor
result policy.MatchingResult
err error
author domain.PolicyAuthor
semantic bool
}
func (extender *extenderFake) EnsureDemoMatchingSection(_ context.Context, author domain.PolicyAuthor) (policy.MatchingResult, error) {
@@ -23,11 +24,21 @@ func (extender *extenderFake) EnsureDemoMatchingSection(_ context.Context, autho
return extender.result, extender.err
}
func (extender *extenderFake) EnsureDemoSemanticMatchingSection(_ context.Context, author domain.PolicyAuthor) (policy.MatchingResult, error) {
extender.author = author
extender.semantic = true
return extender.result, extender.err
}
func TestParseRequiresTheMatchingTrackAndAnOperatorHandle(t *testing.T) {
command, err := Parse([]string{"matching", "--actor", "operator:night"})
if err != nil || command.Author != "operator:night" {
if err != nil || command.Author != "operator:night" || command.Track != TrackMatching {
t.Fatalf("Parse(valid) = %+v, %v", command, err)
}
semantic, err := Parse([]string{"semantic", "--actor", "operator:night"})
if err != nil || semantic.Track != TrackSemantic {
t.Fatalf("Parse(semantic) = %+v, %v", semantic, err)
}
for _, args := range [][]string{
nil, {"list"}, {"matching"}, {"matching", "--actor", "alice"}, {"matching", "--actor", "system:demo-seed"},
{"matching", "--actor", "operator:night", "extra"},
@@ -62,3 +73,14 @@ func TestExecutePrintsOnlyTheVersionAndMapsFailuresToSafeMessages(t *testing.T)
}
}
}
func TestExecuteSemanticTrackPublishesTheSemanticSection(t *testing.T) {
var output bytes.Buffer
extender := &extenderFake{}
if err := Execute(context.Background(), Command{Track: TrackSemantic, Author: "operator:night"}, extender, &output); err != nil {
t.Fatalf("Execute() error = %v", err)
}
if !extender.semantic || !strings.Contains(output.String(), "the semantic matching section") {
t.Fatalf("output = %q, semantic called %v", output.String(), extender.semantic)
}
}
@@ -0,0 +1,120 @@
// Package semanticbackfill implements the operator command that schedules
// vector jobs for existing published candidates and needs, for example after
// semantic matching is enabled, the semantic policy is published, or the ML
// model changes. The jobs run in the backend worker; the command only
// schedules them and prints the resume cursor of every page.
package semanticbackfill
import (
"context"
"errors"
"flag"
"fmt"
"io"
"time"
"github.com/google/uuid"
"lincodex/backend/config"
"lincodex/backend/internal/adapter/secondary/postgres"
"lincodex/backend/internal/usecase/semantic"
)
const usage = "usage: semantic-backfill candidates|needs|all --run <label> [--after <uuid>]"
// Command is a parsed, validated request.
type Command struct {
Scopes []semantic.BackfillScope
Run string
After uuid.UUID
}
// Runner schedules the jobs of one scope.
type Runner interface {
Run(ctx context.Context, scope semantic.BackfillScope, run string, after uuid.UUID, report func(semantic.BackfillProgress) error) error
}
// Parse validates every argument before Run reads configuration or connects.
func Parse(args []string) (Command, error) {
if len(args) == 0 {
return Command{}, errors.New(usage)
}
var scopes []semantic.BackfillScope
switch args[0] {
case string(semantic.BackfillCandidates):
scopes = []semantic.BackfillScope{semantic.BackfillCandidates}
case string(semantic.BackfillNeeds):
scopes = []semantic.BackfillScope{semantic.BackfillNeeds}
case "all":
scopes = []semantic.BackfillScope{semantic.BackfillCandidates, semantic.BackfillNeeds}
default:
return Command{}, errors.New(usage)
}
flags := flag.NewFlagSet("semantic-backfill", flag.ContinueOnError)
flags.SetOutput(io.Discard)
run := flags.String("run", "", "run label; a new label recomputes again")
after := flags.String("after", "", "resume after this identifier")
if err := flags.Parse(args[1:]); err != nil || flags.NArg() != 0 || *run == "" {
return Command{}, errors.New(usage)
}
command := Command{Scopes: scopes, Run: *run}
if *after != "" {
if len(scopes) != 1 {
return Command{}, errors.New("--after needs a single scope")
}
parsed, err := uuid.Parse(*after)
if err != nil {
return Command{}, errors.New("--after must be a UUID")
}
command.After = parsed
}
return command, nil
}
// Run parses the command, loads only DATABASE_URL, and schedules.
func Run(ctx context.Context, args []string, lookup config.LookupEnv, output io.Writer, clock func() time.Time) error {
command, err := Parse(args)
if err != nil {
return err
}
if lookup == nil || output == nil || clock == nil {
return errors.New("semantic backfill command dependencies are required")
}
databaseURL := config.DatabaseURLFromEnv(lookup)
if databaseURL == "" {
return errors.New("DATABASE_URL is not set")
}
pool, err := postgres.NewPool(ctx, databaseURL)
if err != nil {
return errors.New("database configuration is invalid")
}
defer pool.Close()
if err := pool.Ping(ctx); err != nil {
return errors.New("database is unavailable")
}
backfill, err := semantic.NewBackfill(postgres.NewTransactor(pool), clock)
if err != nil {
return err
}
return Execute(ctx, command, backfill, output)
}
// Execute runs every scope and prints one line per page.
func Execute(ctx context.Context, command Command, runner Runner, output io.Writer) error {
for _, scope := range command.Scopes {
total := 0
err := runner.Run(ctx, scope, command.Run, command.After, func(progress semantic.BackfillProgress) error {
total += progress.Scheduled
_, err := fmt.Fprintf(output, "%s: scheduled %d (total %d), resume with --after %s\n",
progress.Scope, progress.Scheduled, total, progress.After)
return err
})
if err != nil {
return errors.New("the backfill stopped; run it again with --after of the last printed line")
}
if _, err := fmt.Fprintf(output, "%s: done, %d jobs scheduled; the backend worker computes them\n", scope, total); err != nil {
return errors.New("could not write the result")
}
}
return nil
}
@@ -0,0 +1,63 @@
package semanticbackfill
import (
"bytes"
"context"
"errors"
"strings"
"testing"
"github.com/google/uuid"
"lincodex/backend/internal/usecase/semantic"
)
type runnerFake struct {
scopes []semantic.BackfillScope
err error
}
func (runner *runnerFake) Run(_ context.Context, scope semantic.BackfillScope, _ string, after uuid.UUID, report func(semantic.BackfillProgress) error) error {
runner.scopes = append(runner.scopes, scope)
if runner.err != nil {
return runner.err
}
return report(semantic.BackfillProgress{Scope: scope, Scheduled: 2, After: after, Done: true})
}
func TestParseRequiresAScopeAndARunLabel(t *testing.T) {
command, err := Parse([]string{"all", "--run", "2026-10-11"})
if err != nil || len(command.Scopes) != 2 || command.Run != "2026-10-11" {
t.Fatalf("Parse(all) = %+v, %v", command, err)
}
after := uuid.New()
command, err = Parse([]string{"needs", "--run", "r1", "--after", after.String()})
if err != nil || command.After != after {
t.Fatalf("Parse(needs --after) = %+v, %v", command, err)
}
for _, args := range [][]string{
nil, {"vectors"}, {"candidates"}, {"all", "--run", "r1", "--after", after.String()},
{"needs", "--run", "r1", "--after", "x"}, {"needs", "--run", "r1", "extra"},
} {
if _, err := Parse(args); err == nil {
t.Errorf("Parse(%v) accepted invalid arguments", args)
}
}
}
func TestExecuteReportsEveryScopeAndHidesStorageErrors(t *testing.T) {
var output bytes.Buffer
runner := &runnerFake{}
command := Command{Scopes: []semantic.BackfillScope{semantic.BackfillCandidates, semantic.BackfillNeeds}, Run: "r1"}
if err := Execute(context.Background(), command, runner, &output); err != nil {
t.Fatalf("Execute() error = %v", err)
}
if len(runner.scopes) != 2 || !strings.Contains(output.String(), "needs: done, 2 jobs scheduled") {
t.Fatalf("output = %q", output.String())
}
failing := &runnerFake{err: errors.New("pq: password authentication failed for user x")}
err := Execute(context.Background(), command, failing, &bytes.Buffer{})
if err == nil || strings.Contains(err.Error(), "password") {
t.Fatalf("Execute(failing) error = %v, want a safe message", err)
}
}
@@ -37,6 +37,7 @@ var regexMap = map[string]ogenregex.Regexp{
"^__Host-lincodex_session=": ogenregex.MustCompile("^__Host-lincodex_session="),
"^cv1_[A-Za-z0-9_-]{43}$": ogenregex.MustCompile("^cv1_[A-Za-z0-9_-]{43}$"),
"^https://[^\\s/?#@]+(?:[/?#][^\\s]*)?$": ogenregex.MustCompile("^https://[^\\s/?#@]+(?:[/?#][^\\s]*)?$"),
"^https://github\\.com/[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})/[A-Za-z0-9._-]{1,100}/?$": ogenregex.MustCompile("^https://github\\.com/[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})/[A-Za-z0-9._-]{1,100}/?$"),
}
var (
// Allocate option closure once.
@@ -12806,6 +12806,223 @@ func (s *Server) handleRequestMyAccountDeletionRequest(args [0]string, argsEscap
}
}
// handleRequestMyRepositoryChecksRequest handles RequestMyRepositoryChecks operation.
//
// Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token,
// and an allowed Origin. The request has no body. It schedules a new check of every repository that
// the current profile links, for example after the candidate made a repository public, and answers 202
// with the number of scheduled checks; the checks run in the background and `GetMyProfile` shows their
// state in `projects[].repository_check`. A profile without linked repositories answers 202 with 0.
//
// A check reads only public metadata from the public GitHub API (`api.github.com`): whether the
// repository exists and is public, its description, topics, languages, and the beginning of its README
// as plain text. The server never fetches any other host, never follows a redirect to another host,
// and never shows the fetched text; it uses it only for semantic ranking. A verified repository does
// not prove that the candidate wrote the code.
//
// The operation is limited per candidate: a second request inside the versioned window answers 429
// rate_limited with Retry-After and schedules nothing. A missing, unknown, expired, or revoked session
// answers 401 unauthenticated; an employer account answers 403 forbidden.
//
// POST /api/v1/me/profile/repository-checks
func (s *Server) handleRequestMyRepositoryChecksRequest(args [0]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) {
statusWriter := &codeRecorder{ResponseWriter: w}
w = statusWriter
otelAttrs := []attribute.KeyValue{
otelogen.OperationID("RequestMyRepositoryChecks"),
semconv.HTTPRequestMethodKey.String("POST"),
semconv.HTTPRouteKey.String("/api/v1/me/profile/repository-checks"),
}
// Add attributes from config.
otelAttrs = append(otelAttrs, s.cfg.Attributes...)
// Start a span for this request.
ctx, span := s.cfg.Tracer.Start(r.Context(), RequestMyRepositoryChecksOperation,
trace.WithAttributes(otelAttrs...),
serverSpanKind,
)
defer span.End()
// Add Labeler to context.
labeler := &Labeler{attrs: otelAttrs}
ctx = contextWithLabeler(ctx, labeler)
// Run stopwatch.
startTime := time.Now()
defer func() {
elapsedDuration := time.Since(startTime)
attrSet := labeler.AttributeSet()
attrs := attrSet.ToSlice()
code := statusWriter.status
if code != 0 {
codeAttr := semconv.HTTPResponseStatusCode(code)
attrs = append(attrs, codeAttr)
span.SetAttributes(attrs...)
}
attrOpt := metric.WithAttributes(attrs...)
// Increment request counter.
s.requests.Add(ctx, 1, attrOpt)
// Use floating point division here for higher precision (instead of Millisecond method).
s.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), attrOpt)
}()
var (
recordError = func(stage string, err error) {
span.RecordError(err)
// https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status
// Span Status MUST be left unset if HTTP status code was in the 1xx, 2xx or 3xx ranges,
// unless there was another error (e.g., network error receiving the response body; or 3xx codes with
// max redirects exceeded), in which case status MUST be set to Error.
code := statusWriter.status
if code < 100 || code >= 500 {
span.SetStatus(codes.Error, stage)
}
attrSet := labeler.AttributeSet()
attrs := attrSet.ToSlice()
if code != 0 {
attrs = append(attrs, semconv.HTTPResponseStatusCode(code))
}
s.errors.Add(ctx, 1, metric.WithAttributes(attrs...))
}
err error
opErrContext = ogenerrors.OperationContext{
Name: RequestMyRepositoryChecksOperation,
ID: "RequestMyRepositoryChecks",
}
)
{
type bitset = [1]uint8
var satisfied bitset
{
sctx, ok, err := s.securitySessionCookie(ctx, RequestMyRepositoryChecksOperation, r)
if err != nil {
err = &ogenerrors.SecurityError{
OperationContext: opErrContext,
Security: "SessionCookie",
Err: err,
}
if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil {
defer recordError("Security:SessionCookie", err)
}
return
}
if ok {
satisfied[0] |= 1 << 0
ctx = sctx
}
}
{
sctx, ok, err := s.securitySessionCsrf(ctx, RequestMyRepositoryChecksOperation, r)
if err != nil {
err = &ogenerrors.SecurityError{
OperationContext: opErrContext,
Security: "SessionCsrf",
Err: err,
}
if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil {
defer recordError("Security:SessionCsrf", err)
}
return
}
if ok {
satisfied[0] |= 1 << 1
ctx = sctx
}
}
if ok := func() bool {
nextRequirement:
for _, requirement := range []bitset{
{0b00000011},
} {
for i, mask := range requirement {
if satisfied[i]&mask != mask {
continue nextRequirement
}
}
return true
}
return false
}(); !ok {
err = &ogenerrors.SecurityError{
OperationContext: opErrContext,
Err: ogenerrors.ErrSecurityRequirementIsNotSatisfied,
}
if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil {
defer recordError("Security", err)
}
return
}
}
var rawBody []byte
var response RequestMyRepositoryChecksRes
if m := s.cfg.Middleware; m != nil {
mreq := middleware.Request{
Context: ctx,
OperationName: RequestMyRepositoryChecksOperation,
OperationSummary: "Ask the server to check the linked project repositories again.",
OperationID: "RequestMyRepositoryChecks",
Body: nil,
RawBody: rawBody,
Params: middleware.Parameters{},
Raw: r,
}
type (
Request = struct{}
Params = struct{}
Response = RequestMyRepositoryChecksRes
)
response, err = middleware.HookMiddleware[
Request,
Params,
Response,
](
m,
mreq,
nil,
func(ctx context.Context, request Request, params Params) (response Response, err error) {
response, err = s.h.RequestMyRepositoryChecks(ctx)
return response, err
},
)
} else {
response, err = s.h.RequestMyRepositoryChecks(ctx)
}
if err != nil {
if errRes, ok := errors.Into[*ProblemStatusCode](err); ok {
if err := encodeErrorResponse(errRes, w, span); err != nil {
defer recordError("Internal", err)
}
return
}
if errors.Is(err, ht.ErrNotImplemented) {
s.cfg.ErrorHandler(ctx, w, r, err)
return
}
if err := encodeErrorResponse(s.h.NewError(ctx, err), w, span); err != nil {
defer recordError("Internal", err)
}
return
}
if err := encodeRequestMyRepositoryChecksResponse(response, w, span); err != nil {
defer recordError("EncodeResponse", err)
if !errors.Is(err, ht.ErrInternalServerErrorResponse) {
s.cfg.ErrorHandler(ctx, w, r, err)
}
return
}
}
// handleResendEmailVerificationRequest handles ResendEmailVerification operation.
//
// Public operation without a session. The answer is the same 202 for an unknown email, a verified
@@ -13976,13 +14193,23 @@ func (s *Server) handleSaveMyQuestionnaireRequest(args [0]string, argsEscaped bo
// The card context is limited to safe public fields: recognized stack tags, coarse experience,
// accepted work formats, and coarse salary compatibility. It contains no contact, candidate location,
// salary amount or minimum, raw answer, arbitrary profile text, or reason for withheld FSP data.
// Evidence explanations use bounded codes, not free text. When ML is unavailable, semantic similarity
// uses the neutral 0.5 specified by FR09 and `unknown_flags` names `ml_unavailable`. For fewer than 30
// comparable real candidates, the search uses neutral T = 0.5, returns no percentile value, and names
// `cohort_below_30`. When the comparable real cohort of a category reaches the minimum, the percentile
// is still not computed (the organization-safe projection carries no theta), T stays the neutral 0.5,
// the percentile stays null, and `unknown_flags` names `percentile_not_computed`; the search does not
// fail.
// Evidence explanations use bounded codes, not free text.
//
// Semantic similarity `Sem` is the calibrated cosine between the stored vector of the need's confirmed
// requirements snapshot and the stored vector of the candidate's published card text (roles,
// recognized stack, and published projects with the public metadata of their verified repositories).
// The search never calls the ML service: vectors are computed in the background after a change, and an
// entry whose vectors are missing, stale for the current model, or not computed because ML is
// unavailable uses the neutral 0.5 and names `ml_unavailable` in `unknown_flags`. `semantic_evidence`
// lists, for a need search, the confirmed requirements whose closest published card item reaches a
// similarity band of the versioned policy; it names a project only by the title that the candidate
// published with the `projects` card field and says whether its repository is a verified public one,
// never the repository address or owner. Showing a project title records the `projects` field in the
// candidate's access history. For fewer than 30 comparable real candidates, the search uses neutral T
// = 0.5, returns no percentile value, and names `cohort_below_30`. When the comparable real cohort of
// a category reaches the minimum, the percentile is still not computed (the organization-safe
// projection carries no theta), T stays the neutral 0.5, the percentile stays null, and
// `unknown_flags` names `percentile_not_computed`; the search does not fail.
//
// A missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate account
// answers 403 forbidden; an unknown organization or account without active membership answers 404
@@ -221,6 +221,10 @@ type RequestMyAccountDeletionRes interface {
requestMyAccountDeletionRes()
}
type RequestMyRepositoryChecksRes interface {
requestMyRepositoryChecksRes()
}
type ResendEmailVerificationRes interface {
resendEmailVerificationRes()
}
File diff suppressed because it is too large. Load diff
@@ -63,6 +63,7 @@ const (
RecordMyAssessmentAttemptSignalsOperation OperationName = "RecordMyAssessmentAttemptSignals"
RegisterAccountOperation OperationName = "RegisterAccount"
RequestMyAccountDeletionOperation OperationName = "RequestMyAccountDeletion"
RequestMyRepositoryChecksOperation OperationName = "RequestMyRepositoryChecks"
ResendEmailVerificationOperation OperationName = "ResendEmailVerification"
RevokeMyConsentOperation OperationName = "RevokeMyConsent"
RevokeMyOrganizationContactConsentOperation OperationName = "RevokeMyOrganizationContactConsent"
@@ -4933,6 +4933,97 @@ func encodeRequestMyAccountDeletionResponse(response RequestMyAccountDeletionRes
}
}
func encodeRequestMyRepositoryChecksResponse(response RequestMyRepositoryChecksRes, w http.ResponseWriter, span trace.Span) error {
switch response := response.(type) {
case *ProfileRepositoryCheckRequestHeaders:
w.Header().Set("Content-Type", "application/json; charset=utf-8")
// Encoding response headers.
{
h := uri.NewHeaderEncoder(w.Header())
// Encode "Cache-Control" header.
{
cfg := uri.HeaderParameterEncodingConfig{
Name: "Cache-Control",
Explode: false,
}
if err := h.EncodeParam(cfg, func(e uri.Encoder) error {
return e.EncodeValue(conv.StringToString(string(response.CacheControl)))
}); err != nil {
return errors.Wrap(err, "encode Cache-Control header")
}
}
}
w.WriteHeader(202)
e := new(jx.Encoder)
response.Response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *RequestMyRepositoryChecksUnauthorized:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(401)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *RequestMyRepositoryChecksForbidden:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(403)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *TooManyRequestsHeaders:
w.Header().Set("Content-Type", "application/problem+json")
w.Header().Set("Access-Control-Expose-Headers", "Retry-After")
// Encoding response headers.
{
h := uri.NewHeaderEncoder(w.Header())
// Encode "Retry-After" header.
{
cfg := uri.HeaderParameterEncodingConfig{
Name: "Retry-After",
Explode: false,
}
if err := h.EncodeParam(cfg, func(e uri.Encoder) error {
if val, ok := response.RetryAfter.Get(); ok {
return e.EncodeValue(conv.Int32ToString(val))
}
return nil
}); err != nil {
return errors.Wrap(err, "encode Retry-After header")
}
}
}
w.WriteHeader(429)
e := new(jx.Encoder)
response.Response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
default:
return errors.Errorf("unexpected response type: %T", response)
}
}
func encodeResendEmailVerificationResponse(response ResendEmailVerificationRes, w http.ResponseWriter, span trace.Span) error {
switch response := response.(type) {
case *IdentityRequestAccepted:
@@ -11,7 +11,7 @@ import (
)
var (
rn84AllowedHeaders = map[string]string{
rn85AllowedHeaders = map[string]string{
"POST": "Content-Type",
}
rn9AllowedHeaders = map[string]string{
@@ -35,13 +35,13 @@ var (
rn12AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
rn95AllowedHeaders = map[string]string{
rn96AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
rn23AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
rn94AllowedHeaders = map[string]string{
rn95AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
rn79AllowedHeaders = map[string]string{
@@ -50,7 +50,7 @@ var (
rn5AllowedHeaders = map[string]string{
"PUT": "Content-Type,X-Csrf-Token",
}
rn86AllowedHeaders = map[string]string{
rn87AllowedHeaders = map[string]string{
"DELETE": "X-Csrf-Token",
}
rn54AllowedHeaders = map[string]string{
@@ -66,7 +66,7 @@ var (
rn20AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
rn96AllowedHeaders = map[string]string{
rn97AllowedHeaders = map[string]string{
"POST": "X-Csrf-Token",
}
rn73AllowedHeaders = map[string]string{
@@ -76,15 +76,18 @@ var (
"DELETE": "X-Csrf-Token",
"PUT": "X-Csrf-Token",
}
rn91AllowedHeaders = map[string]string{
rn92AllowedHeaders = map[string]string{
"PUT": "Content-Type,X-Csrf-Token",
}
rn92AllowedHeaders = map[string]string{
rn93AllowedHeaders = map[string]string{
"PUT": "Content-Type,X-Csrf-Token",
}
rn39AllowedHeaders = map[string]string{
"PUT": "Content-Type,X-Csrf-Token",
}
rn83AllowedHeaders = map[string]string{
"POST": "X-Csrf-Token",
}
rn40AllowedHeaders = map[string]string{
"PUT": "Content-Type,X-Csrf-Token",
}
@@ -106,13 +109,13 @@ var (
rn78AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
rn89AllowedHeaders = map[string]string{
rn90AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
rn97AllowedHeaders = map[string]string{
rn98AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
rn87AllowedHeaders = map[string]string{
rn88AllowedHeaders = map[string]string{
"POST": "Content-Type,X-Csrf-Token",
}
rn19AllowedHeaders = map[string]string{
@@ -278,7 +281,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn84AllowedHeaders,
allowedHeaders: rn85AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
@@ -607,7 +610,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn95AllowedHeaders,
allowedHeaders: rn96AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
@@ -700,7 +703,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn94AllowedHeaders,
allowedHeaders: rn95AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
@@ -938,7 +941,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "DELETE",
allowedHeaders: rn86AllowedHeaders,
allowedHeaders: rn87AllowedHeaders,
acceptPost: "",
acceptPatch: "",
})
@@ -1180,7 +1183,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn96AllowedHeaders,
allowedHeaders: rn97AllowedHeaders,
acceptPost: "",
acceptPatch: "",
})
@@ -1527,7 +1530,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "PUT",
allowedHeaders: rn91AllowedHeaders,
allowedHeaders: rn92AllowedHeaders,
acceptPost: "",
acceptPatch: "",
})
@@ -1554,7 +1557,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "PUT",
allowedHeaders: rn92AllowedHeaders,
allowedHeaders: rn93AllowedHeaders,
acceptPost: "",
acceptPatch: "",
})
@@ -1576,7 +1579,6 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
}
if len(elem) == 0 {
// Leaf node.
switch r.Method {
case "GET":
s.handleGetMyProfileRequest([0]string{}, elemIsEscaped, w, r)
@@ -1593,6 +1595,33 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
return
}
switch elem[0] {
case '/': // Prefix: "/repository-checks"
if l := len("/repository-checks"); len(elem) >= l && elem[0:l] == "/repository-checks" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
// Leaf node.
switch r.Method {
case "POST":
s.handleRequestMyRepositoryChecksRequest([0]string{}, elemIsEscaped, w, r)
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn83AllowedHeaders,
acceptPost: "",
acceptPatch: "",
})
}
return
}
}
}
@@ -2000,7 +2029,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn89AllowedHeaders,
allowedHeaders: rn90AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
@@ -2030,7 +2059,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn97AllowedHeaders,
allowedHeaders: rn98AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
@@ -2063,7 +2092,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn87AllowedHeaders,
allowedHeaders: rn88AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
@@ -3759,7 +3788,6 @@ func (s *Server) FindPath(method string, u *url.URL) (r Route, _ bool) {
}
if len(elem) == 0 {
// Leaf node.
switch method {
case "GET":
r.name = GetMyProfileOperation
@@ -3783,6 +3811,33 @@ func (s *Server) FindPath(method string, u *url.URL) (r Route, _ bool) {
return
}
}
switch elem[0] {
case '/': // Prefix: "/repository-checks"
if l := len("/repository-checks"); len(elem) >= l && elem[0:l] == "/repository-checks" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
// Leaf node.
switch method {
case "POST":
r.name = RequestMyRepositoryChecksOperation
r.summary = "Ask the server to check the linked project repositories again."
r.operationID = "RequestMyRepositoryChecks"
r.operationGroup = ""
r.pathPattern = "/api/v1/me/profile/repository-checks"
r.args = args
r.count = 0
return r, true
default:
return
}
}
}
}
File diff suppressed because it is too large. Load diff
@@ -106,6 +106,7 @@ var operationRolesSessionCookie = map[string][]string{
RaiseOrganizationInvitationSalaryOperation: []string{},
RecordMyAssessmentAttemptSignalsOperation: []string{},
RequestMyAccountDeletionOperation: []string{},
RequestMyRepositoryChecksOperation: []string{},
RevokeMyConsentOperation: []string{},
RevokeMyOrganizationContactConsentOperation: []string{},
SaveMyProfileOperation: []string{},
@@ -165,6 +166,7 @@ var operationRolesSessionCsrf = map[string][]string{
RaiseOrganizationInvitationSalaryOperation: []string{},
RecordMyAssessmentAttemptSignalsOperation: []string{},
RequestMyAccountDeletionOperation: []string{},
RequestMyRepositoryChecksOperation: []string{},
RevokeMyConsentOperation: []string{},
RevokeMyOrganizationContactConsentOperation: []string{},
SaveMyProfileOperation: []string{},
@@ -1556,6 +1556,26 @@ type Handler interface {
//
// POST /api/v1/me/account-deletion-requests
RequestMyAccountDeletion(ctx context.Context) (RequestMyAccountDeletionRes, error)
// RequestMyRepositoryChecks implements RequestMyRepositoryChecks operation.
//
// Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token,
// and an allowed Origin. The request has no body. It schedules a new check of every repository that
// the current profile links, for example after the candidate made a repository public, and answers 202
// with the number of scheduled checks; the checks run in the background and `GetMyProfile` shows their
// state in `projects[].repository_check`. A profile without linked repositories answers 202 with 0.
//
// A check reads only public metadata from the public GitHub API (`api.github.com`): whether the
// repository exists and is public, its description, topics, languages, and the beginning of its README
// as plain text. The server never fetches any other host, never follows a redirect to another host,
// and never shows the fetched text; it uses it only for semantic ranking. A verified repository does
// not prove that the candidate wrote the code.
//
// The operation is limited per candidate: a second request inside the versioned window answers 429
// rate_limited with Retry-After and schedules nothing. A missing, unknown, expired, or revoked session
// answers 401 unauthenticated; an employer account answers 403 forbidden.
//
// POST /api/v1/me/profile/repository-checks
RequestMyRepositoryChecks(ctx context.Context) (RequestMyRepositoryChecksRes, error)
// ResendEmailVerification implements ResendEmailVerification operation.
//
// Public operation without a session. The answer is the same 202 for an unknown email, a verified
@@ -1730,13 +1750,23 @@ type Handler interface {
// The card context is limited to safe public fields: recognized stack tags, coarse experience,
// accepted work formats, and coarse salary compatibility. It contains no contact, candidate location,
// salary amount or minimum, raw answer, arbitrary profile text, or reason for withheld FSP data.
// Evidence explanations use bounded codes, not free text. When ML is unavailable, semantic similarity
// uses the neutral 0.5 specified by FR09 and `unknown_flags` names `ml_unavailable`. For fewer than 30
// comparable real candidates, the search uses neutral T = 0.5, returns no percentile value, and names
// `cohort_below_30`. When the comparable real cohort of a category reaches the minimum, the percentile
// is still not computed (the organization-safe projection carries no theta), T stays the neutral 0.5,
// the percentile stays null, and `unknown_flags` names `percentile_not_computed`; the search does not
// fail.
// Evidence explanations use bounded codes, not free text.
//
// Semantic similarity `Sem` is the calibrated cosine between the stored vector of the need's confirmed
// requirements snapshot and the stored vector of the candidate's published card text (roles,
// recognized stack, and published projects with the public metadata of their verified repositories).
// The search never calls the ML service: vectors are computed in the background after a change, and an
// entry whose vectors are missing, stale for the current model, or not computed because ML is
// unavailable uses the neutral 0.5 and names `ml_unavailable` in `unknown_flags`. `semantic_evidence`
// lists, for a need search, the confirmed requirements whose closest published card item reaches a
// similarity band of the versioned policy; it names a project only by the title that the candidate
// published with the `projects` card field and says whether its repository is a verified public one,
// never the repository address or owner. Showing a project title records the `projects` field in the
// candidate's access history. For fewer than 30 comparable real candidates, the search uses neutral T
// = 0.5, returns no percentile value, and names `cohort_below_30`. When the comparable real cohort of
// a category reaches the minimum, the percentile is still not computed (the organization-safe
// projection carries no theta), T stays the neutral 0.5, the percentile stays null, and
// `unknown_flags` names `percentile_not_computed`; the search does not fail.
//
// A missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate account
// answers 403 forbidden; an unknown organization or account without active membership answers 404
@@ -1732,6 +1732,29 @@ func (UnimplementedHandler) RequestMyAccountDeletion(ctx context.Context) (r Req
return r, ht.ErrNotImplemented
}
// RequestMyRepositoryChecks implements RequestMyRepositoryChecks operation.
//
// Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token,
// and an allowed Origin. The request has no body. It schedules a new check of every repository that
// the current profile links, for example after the candidate made a repository public, and answers 202
// with the number of scheduled checks; the checks run in the background and `GetMyProfile` shows their
// state in `projects[].repository_check`. A profile without linked repositories answers 202 with 0.
//
// A check reads only public metadata from the public GitHub API (`api.github.com`): whether the
// repository exists and is public, its description, topics, languages, and the beginning of its README
// as plain text. The server never fetches any other host, never follows a redirect to another host,
// and never shows the fetched text; it uses it only for semantic ranking. A verified repository does
// not prove that the candidate wrote the code.
//
// The operation is limited per candidate: a second request inside the versioned window answers 429
// rate_limited with Retry-After and schedules nothing. A missing, unknown, expired, or revoked session
// answers 401 unauthenticated; an employer account answers 403 forbidden.
//
// POST /api/v1/me/profile/repository-checks
func (UnimplementedHandler) RequestMyRepositoryChecks(ctx context.Context) (r RequestMyRepositoryChecksRes, _ error) {
return r, ht.ErrNotImplemented
}
// ResendEmailVerification implements ResendEmailVerification operation.
//
// Public operation without a session. The answer is the same 202 for an unknown email, a verified
@@ -1921,13 +1944,23 @@ func (UnimplementedHandler) SaveMyQuestionnaire(ctx context.Context, req *Candid
// The card context is limited to safe public fields: recognized stack tags, coarse experience,
// accepted work formats, and coarse salary compatibility. It contains no contact, candidate location,
// salary amount or minimum, raw answer, arbitrary profile text, or reason for withheld FSP data.
// Evidence explanations use bounded codes, not free text. When ML is unavailable, semantic similarity
// uses the neutral 0.5 specified by FR09 and `unknown_flags` names `ml_unavailable`. For fewer than 30
// comparable real candidates, the search uses neutral T = 0.5, returns no percentile value, and names
// `cohort_below_30`. When the comparable real cohort of a category reaches the minimum, the percentile
// is still not computed (the organization-safe projection carries no theta), T stays the neutral 0.5,
// the percentile stays null, and `unknown_flags` names `percentile_not_computed`; the search does not
// fail.
// Evidence explanations use bounded codes, not free text.
//
// Semantic similarity `Sem` is the calibrated cosine between the stored vector of the need's confirmed
// requirements snapshot and the stored vector of the candidate's published card text (roles,
// recognized stack, and published projects with the public metadata of their verified repositories).
// The search never calls the ML service: vectors are computed in the background after a change, and an
// entry whose vectors are missing, stale for the current model, or not computed because ML is
// unavailable uses the neutral 0.5 and names `ml_unavailable` in `unknown_flags`. `semantic_evidence`
// lists, for a need search, the confirmed requirements whose closest published card item reaches a
// similarity band of the versioned policy; it names a project only by the title that the candidate
// published with the `projects` card field and says whether its repository is a verified public one,
// never the repository address or owner. Showing a project title records the `projects` field in the
// candidate's access history. For fewer than 30 comparable real candidates, the search uses neutral T
// = 0.5, returns no percentile value, and names `cohort_below_30`. When the comparable real cohort of
// a category reaches the minimum, the percentile is still not computed (the organization-safe
// projection carries no theta), T stays the neutral 0.5, the percentile stays null, and
// `unknown_flags` names `percentile_not_computed`; the search does not fail.
//
// A missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate account
// answers 403 forbidden; an unknown organization or account without active membership answers 404
@@ -396,6 +396,42 @@ func (s *AnonymousCardContent) Validate() error {
Error: err,
})
}
if err := func() error {
if s.Projects == nil {
return nil // null
}
if err := (validate.Array{
MinLength: 0,
MinLengthSet: false,
MaxLength: 10,
MaxLengthSet: true,
}).ValidateLength(len(s.Projects)); err != nil {
return errors.Wrap(err, "array")
}
var failures []validate.FieldError
for i, elem := range s.Projects {
if err := func() error {
if err := elem.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: fmt.Sprintf("[%d]", i),
Error: err,
})
}
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "projects",
Error: err,
})
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
}
@@ -5687,6 +5723,42 @@ func (s *CandidateProfile) Validate() error {
Error: err,
})
}
if err := func() error {
if s.Projects == nil {
return errors.New("nil is invalid value")
}
if err := (validate.Array{
MinLength: 0,
MinLengthSet: false,
MaxLength: 10,
MaxLengthSet: true,
}).ValidateLength(len(s.Projects)); err != nil {
return errors.Wrap(err, "array")
}
var failures []validate.FieldError
for i, elem := range s.Projects {
if err := func() error {
if err := elem.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: fmt.Sprintf("[%d]", i),
Error: err,
})
}
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "projects",
Error: err,
})
}
if err := func() error {
if err := s.Terms.Validate(); err != nil {
return err
@@ -6000,6 +6072,42 @@ func (s *CandidateProfileUpdate) Validate() error {
Error: err,
})
}
if err := func() error {
if s.Projects == nil {
return nil // optional
}
if err := (validate.Array{
MinLength: 0,
MinLengthSet: false,
MaxLength: 10,
MaxLengthSet: true,
}).ValidateLength(len(s.Projects)); err != nil {
return errors.Wrap(err, "array")
}
var failures []validate.FieldError
for i, elem := range s.Projects {
if err := func() error {
if err := elem.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: fmt.Sprintf("[%d]", i),
Error: err,
})
}
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "projects",
Error: err,
})
}
if err := func() error {
if err := s.Terms.Validate(); err != nil {
return err
@@ -6454,6 +6562,8 @@ func (s CardField) Validate() error {
return nil
case "work_formats":
return nil
case "projects":
return nil
default:
return errors.Errorf("invalid value: %v", s)
}
@@ -6467,7 +6577,7 @@ func (s CardFieldSet) Validate() error {
if err := (validate.Array{
MinLength: 0,
MinLengthSet: true,
MaxLength: 9,
MaxLength: 10,
MaxLengthSet: true,
}).ValidateLength(len(alias)); err != nil {
return errors.Wrap(err, "array")
@@ -6599,6 +6709,107 @@ func (s *CardPreviewHeaders) Validate() error {
return nil
}
func (s *CardProject) Validate() error {
if s == nil {
return validate.ErrNilPointer
}
var failures []validate.FieldError
if err := func() error {
if err := (validate.String{
MinLength: 1,
MinLengthSet: true,
MaxLength: 100,
MaxLengthSet: true,
Email: false,
Hostname: false,
Regex: nil,
MinNumeric: 0,
MinNumericSet: false,
MaxNumeric: 0,
MaxNumericSet: false,
}).Validate(string(s.Title)); err != nil {
return errors.Wrap(err, "string")
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "title",
Error: err,
})
}
if err := func() error {
if value, ok := s.Description.Get(); ok {
if err := func() error {
if err := (validate.String{
MinLength: 1,
MinLengthSet: true,
MaxLength: 500,
MaxLengthSet: true,
Email: false,
Hostname: false,
Regex: nil,
MinNumeric: 0,
MinNumericSet: false,
MaxNumeric: 0,
MaxNumericSet: false,
}).Validate(string(value)); err != nil {
return errors.Wrap(err, "string")
}
return nil
}(); err != nil {
return err
}
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "description",
Error: err,
})
}
if err := func() error {
if s.Stack == nil {
return errors.New("nil is invalid value")
}
if err := (validate.Array{
MinLength: 0,
MinLengthSet: false,
MaxLength: 10,
MaxLengthSet: true,
}).ValidateLength(len(s.Stack)); err != nil {
return errors.Wrap(err, "array")
}
var failures []validate.FieldError
for i, elem := range s.Stack {
if err := func() error {
if err := elem.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: fmt.Sprintf("[%d]", i),
Error: err,
})
}
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "stack",
Error: err,
})
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
}
return nil
}
func (s *CardSelfAssessment) Validate() error {
if s == nil {
return validate.ErrNilPointer
@@ -12275,6 +12486,17 @@ func (s *MatchConfirmedCandidate) Validate() error {
Error: err,
})
}
if err := func() error {
if err := s.SemanticEvidence.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "semantic_evidence",
Error: err,
})
}
if err := func() error {
if err := s.Components.Validate(); err != nil {
return err
@@ -12713,6 +12935,19 @@ func (s MatchPublicStack) Validate() error {
return nil
}
func (s MatchRequirementKind) Validate() error {
switch s {
case "required_skill":
return nil
case "desired_skill":
return nil
case "task":
return nil
default:
return errors.Errorf("invalid value: %v", s)
}
}
func (s MatchScore) Validate() error {
alias := (float64)(s)
if err := (validate.Float{
@@ -13322,6 +13557,161 @@ func (s MatchSearchStackTag) Validate() error {
}
}
func (s *MatchSemanticEvidence) Validate() error {
if s == nil {
return validate.ErrNilPointer
}
var failures []validate.FieldError
if err := func() error {
if err := s.RequirementKind.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "requirement_kind",
Error: err,
})
}
if err := func() error {
if err := (validate.String{
MinLength: 1,
MinLengthSet: true,
MaxLength: 300,
MaxLengthSet: true,
Email: false,
Hostname: false,
Regex: nil,
MinNumeric: 0,
MinNumericSet: false,
MaxNumeric: 0,
MaxNumericSet: false,
}).Validate(string(s.RequirementText)); err != nil {
return errors.Wrap(err, "string")
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "requirement_text",
Error: err,
})
}
if err := func() error {
if err := s.ItemKind.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "item_kind",
Error: err,
})
}
if err := func() error {
if value, ok := s.ProjectTitle.Get(); ok {
if err := func() error {
if err := (validate.String{
MinLength: 1,
MinLengthSet: true,
MaxLength: 100,
MaxLengthSet: true,
Email: false,
Hostname: false,
Regex: nil,
MinNumeric: 0,
MinNumericSet: false,
MaxNumeric: 0,
MaxNumericSet: false,
}).Validate(string(value)); err != nil {
return errors.Wrap(err, "string")
}
return nil
}(); err != nil {
return err
}
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "project_title",
Error: err,
})
}
if err := func() error {
if err := s.Similarity.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "similarity",
Error: err,
})
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
}
return nil
}
func (s MatchSemanticEvidenceList) Validate() error {
alias := ([]MatchSemanticEvidence)(s)
if alias == nil {
return errors.New("nil is invalid value")
}
if err := (validate.Array{
MinLength: 0,
MinLengthSet: false,
MaxLength: 12,
MaxLengthSet: true,
}).ValidateLength(len(alias)); err != nil {
return errors.Wrap(err, "array")
}
var failures []validate.FieldError
for i, elem := range alias {
if err := func() error {
if err := elem.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: fmt.Sprintf("[%d]", i),
Error: err,
})
}
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
}
return nil
}
func (s MatchSemanticItemKind) Validate() error {
switch s {
case "project":
return nil
case "stack":
return nil
case "roles":
return nil
default:
return errors.Errorf("invalid value: %v", s)
}
}
func (s MatchSimilarityBand) Validate() error {
switch s {
case "high":
return nil
case "medium":
return nil
default:
return errors.Errorf("invalid value: %v", s)
}
}
func (s MatchStrength) Validate() error {
switch s {
case "standard":
@@ -13412,6 +13802,17 @@ func (s *MatchUnconfirmedCandidate) Validate() error {
Error: err,
})
}
if err := func() error {
if err := s.SemanticEvidence.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "semantic_evidence",
Error: err,
})
}
if err := func() error {
if err := s.Components.Validate(); err != nil {
return err
@@ -19485,6 +19886,8 @@ func (s ProblemCode) Validate() error {
return nil
case "not_implemented":
return nil
case "service_unavailable":
return nil
default:
return errors.Errorf("invalid value: %v", s)
}
@@ -20803,6 +21206,270 @@ func (s *ProfilePhoneInput) Validate() error {
return nil
}
func (s ProfileProjectDescription) Validate() error {
alias := (string)(s)
if err := (validate.String{
MinLength: 1,
MinLengthSet: true,
MaxLength: 500,
MaxLengthSet: true,
Email: false,
Hostname: false,
Regex: nil,
MinNumeric: 0,
MinNumericSet: false,
MaxNumeric: 0,
MaxNumericSet: false,
}).Validate(string(alias)); err != nil {
return errors.Wrap(err, "string")
}
return nil
}
func (s *ProfileProjectItem) Validate() error {
if s == nil {
return validate.ErrNilPointer
}
var failures []validate.FieldError
if err := func() error {
if err := s.Title.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "title",
Error: err,
})
}
if err := func() error {
if value, ok := s.Description.Get(); ok {
if err := func() error {
if err := value.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
return err
}
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "description",
Error: err,
})
}
if err := func() error {
if err := s.Stack.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "stack",
Error: err,
})
}
if err := func() error {
if value, ok := s.RepositoryURL.Get(); ok {
if err := func() error {
if err := value.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
return err
}
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "repository_url",
Error: err,
})
}
if err := func() error {
if value, ok := s.RepositoryCheck.Get(); ok {
if err := func() error {
if err := value.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
return err
}
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "repository_check",
Error: err,
})
}
if err := func() error {
if err := s.Status.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "status",
Error: err,
})
}
if err := func() error {
if err := s.Source.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "source",
Error: err,
})
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
}
return nil
}
func (s *ProfileProjectItemInput) Validate() error {
if s == nil {
return validate.ErrNilPointer
}
var failures []validate.FieldError
if err := func() error {
if err := s.Title.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "title",
Error: err,
})
}
if err := func() error {
if value, ok := s.Description.Get(); ok {
if err := func() error {
if err := value.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
return err
}
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "description",
Error: err,
})
}
if err := func() error {
if err := s.Stack.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "stack",
Error: err,
})
}
if err := func() error {
if value, ok := s.RepositoryURL.Get(); ok {
if err := func() error {
if err := value.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
return err
}
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "repository_url",
Error: err,
})
}
if err := func() error {
if err := s.Status.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "status",
Error: err,
})
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
}
return nil
}
func (s ProfileProjectStack) Validate() error {
alias := ([]StackTag)(s)
if alias == nil {
return errors.New("nil is invalid value")
}
if err := (validate.Array{
MinLength: 0,
MinLengthSet: false,
MaxLength: 10,
MaxLengthSet: true,
}).ValidateLength(len(alias)); err != nil {
return errors.Wrap(err, "array")
}
var failures []validate.FieldError
for i, elem := range alias {
if err := func() error {
if err := elem.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: fmt.Sprintf("[%d]", i),
Error: err,
})
}
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
}
return nil
}
func (s ProfileProjectTitle) Validate() error {
alias := (string)(s)
if err := (validate.String{
MinLength: 1,
MinLengthSet: true,
MaxLength: 100,
MaxLengthSet: true,
Email: false,
Hostname: false,
Regex: regexMap["^\\S(?:.*\\S)?$"],
MinNumeric: 0,
MinNumericSet: false,
MaxNumeric: 0,
MaxNumericSet: false,
}).Validate(string(alias)); err != nil {
return errors.Wrap(err, "string")
}
return nil
}
func (s *ProfileRelocationClaim) Validate() error {
if s == nil {
return validate.ErrNilPointer
@@ -20867,6 +21534,131 @@ func (s *ProfileRelocationInput) Validate() error {
return nil
}
func (s *ProfileRepositoryCheck) Validate() error {
if s == nil {
return validate.ErrNilPointer
}
var failures []validate.FieldError
if err := func() error {
if err := s.State.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "state",
Error: err,
})
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
}
return nil
}
func (s *ProfileRepositoryCheckRequest) Validate() error {
if s == nil {
return validate.ErrNilPointer
}
var failures []validate.FieldError
if err := func() error {
if err := (validate.Int{
MinSet: true,
Min: 0,
MaxSet: true,
Max: 10,
MinExclusive: false,
MaxExclusive: false,
MultipleOfSet: false,
MultipleOf: 0,
Pattern: nil,
}).Validate(int64(s.Scheduled)); err != nil {
return errors.Wrap(err, "int")
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "scheduled",
Error: err,
})
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
}
return nil
}
func (s *ProfileRepositoryCheckRequestHeaders) Validate() error {
if s == nil {
return validate.ErrNilPointer
}
var failures []validate.FieldError
if err := func() error {
if err := s.CacheControl.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "CacheControl",
Error: err,
})
}
if err := func() error {
if err := s.Response.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "Response",
Error: err,
})
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
}
return nil
}
func (s ProfileRepositoryCheckState) Validate() error {
switch s {
case "pending":
return nil
case "verified":
return nil
case "not_found":
return nil
case "unavailable":
return nil
default:
return errors.Errorf("invalid value: %v", s)
}
}
func (s ProfileRepositoryUrl) Validate() error {
alias := (string)(s)
if err := (validate.String{
MinLength: 22,
MinLengthSet: true,
MaxLength: 160,
MaxLengthSet: true,
Email: false,
Hostname: false,
Regex: regexMap["^https://github\\.com/[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})/[A-Za-z0-9._-]{1,100}/?$"],
MinNumeric: 0,
MinNumericSet: false,
MaxNumeric: 0,
MaxNumericSet: false,
}).Validate(string(alias)); err != nil {
return errors.Wrap(err, "string")
}
return nil
}
func (s *ProfileRoleItem) Validate() error {
if s == nil {
return validate.ErrNilPointer
@@ -22099,6 +22891,22 @@ func (s *RequestMyAccountDeletionUnauthorized) Validate() error {
return nil
}
func (s *RequestMyRepositoryChecksForbidden) Validate() error {
alias := (*Problem)(s)
if err := alias.Validate(); err != nil {
return err
}
return nil
}
func (s *RequestMyRepositoryChecksUnauthorized) Validate() error {
alias := (*Problem)(s)
if err := alias.Validate(); err != nil {
return err
}
return nil
}
func (s *ResendEmailVerificationBadRequest) Validate() error {
alias := (*Problem)(s)
if err := alias.Validate(); err != nil {
@@ -33,7 +33,7 @@ var (
hiddenSchemas = []string{"HiddenOrganization", "HiddenOrganizationList", "PrivacyOrganization"}
privacyOnlySchemas = []string{
"PrivacySettings", "CardPreview", "AnonymousCardContent", "CardCategory", "CardCategoryStrength", "CardSelfAssessment",
"CardSelfAssessmentConfirmationStatus",
"CardSelfAssessmentConfirmationStatus", "CardProject",
"CandidateExperienceBand", "CandidateWorkFormat", "CandidateSalaryCompatibility",
"PrivacyEvent", "PrivacyEventKind", "PrivacyEventList", "CardAccess", "CardAccessKind", "CardAccessList",
}
@@ -218,14 +218,14 @@ func TestPublicationAndSearchStatusAreNotConsents(t *testing.T) {
fields := enumValues(t, resolveSchema(t, spec, &ogen.Schema{Ref: "#/components/schemas/CardField"}))
want := []string{
"categories", "stack", "experience", "soft_skills", "location", "relocation",
"self_assessment", "work_formats", "salary_compatibility",
"self_assessment", "work_formats", "salary_compatibility", "projects",
}
slices.Sort(fields)
slices.Sort(want)
if !slices.Equal(fields, want) {
t.Errorf("CardField = %v, want %v", fields, want)
}
if update := spec.Components.Schemas["CardFieldSet"]; update.UniqueItems != true || update.MaxItems == nil || *update.MaxItems != 9 {
if update := spec.Components.Schemas["CardFieldSet"]; update.UniqueItems != true || update.MaxItems == nil || *update.MaxItems != 10 {
t.Error("CardFieldSet must hold distinct items and at most one per field")
}
status := enumValues(t, resolveSchema(t, spec, &ogen.Schema{Ref: "#/components/schemas/SearchStatusValue"}))
@@ -246,7 +246,7 @@ func TestAnonymousCardReachesNoProfileOrContactSchema(t *testing.T) {
t.Fatal("the contract has no AnonymousCardContent")
}
if got, want := propertyNames(card), []string{
"categories", "experience_band", "pseudonym", "salary_compatibility", "self_assessment", "stack", "work_formats",
"categories", "experience_band", "projects", "pseudonym", "salary_compatibility", "self_assessment", "stack", "work_formats",
}; !slices.Equal(got, want) {
t.Errorf("AnonymousCardContent properties = %v, want %v", got, want)
}
@@ -269,7 +269,7 @@ func TestAnonymousCardReachesNoProfileOrContactSchema(t *testing.T) {
allowed := slices.Concat([]string{
"AnonymousCardContent", "CardCategory", "CardCategoryStrength", "CardSelfAssessment", "CardSelfAssessmentConfirmationStatus", "CandidateExperienceBand", "CandidateWorkFormat",
"CandidateSalaryCompatibility", "CardField", "CardFieldSet", "PublicationState", "SpecializationCode",
"GradeCode", "StackTag", "Timestamp", "CardPreview",
"GradeCode", "StackTag", "Timestamp", "CardPreview", "CardProject",
}, previewEvidenceSchemas)
for _, name := range []string{"AnonymousCardContent", "CardPreview"} {
for reached := range reachableSchemas(index, mustJSONValue(t, spec.Components.Schemas[name])) {
@@ -323,7 +323,7 @@ func TestAnonymousCardReachesNoProfileOrContactSchema(t *testing.T) {
slices.Contains([]string{
"AnonymousCardContent", "CardCategory", "CardCategoryStrength", "CardSelfAssessment",
"CardSelfAssessmentConfirmationStatus", "CandidateExperienceBand", "CandidateWorkFormat",
"CandidateSalaryCompatibility",
"CandidateSalaryCompatibility", "CardProject",
}, reached) {
continue
}
@@ -106,7 +106,7 @@ func TestCandidateProfileSeparatesSelfAssessedGradeFromConfirmedCategory(t *test
t.Error("the profile does not state confirmed categories apart from the claims")
}
update := resolveSchema(t, spec, &ogen.Schema{Ref: "#/components/schemas/CandidateProfileUpdate"})
wantUpdate := []string{"confirmed_parallel_periods", "contacts", "expected_version", "experience", "full_name", "roles", "soft_skills", "stack", "terms"}
wantUpdate := []string{"confirmed_parallel_periods", "contacts", "expected_version", "experience", "full_name", "projects", "roles", "soft_skills", "stack", "terms"}
if got := propertyNames(update); !slices.Equal(got, wantUpdate) {
t.Errorf("CandidateProfileUpdate properties = %v, want %v", got, wantUpdate)
}
@@ -128,6 +128,11 @@ var definitions = map[api.ProblemCode]definition{
title: "Operation not implemented",
detail: "This operation is not available yet.",
},
api.ProblemCodeServiceUnavailable: {
status: http.StatusServiceUnavailable,
title: "Service unavailable",
detail: "The service cannot serve the request now. Retry later.",
},
}
// New returns the problem response for code with its fixed status, title,
@@ -219,6 +219,7 @@ func matchConfirmedCandidate(entry matching.Entry) api.MatchConfirmedCandidate {
ConfirmationStatus: api.MatchConfirmedCandidateConfirmationStatusConfirmed,
PublicContext: matchPublicContext(entry.PublicContext),
EvidenceSummary: matchEvidenceSummary(entry.EvidenceSummary),
SemanticEvidence: matchSemanticEvidence(entry.SemanticEvidence),
UnknownFlags: matchUnknownFlags(entry.UnknownFlags),
}
candidate.DeclaredGrade = matchDeclaredGrade(entry.DeclaredGrade)
@@ -251,6 +252,7 @@ func matchUnconfirmedCandidate(entry matching.Entry) api.MatchUnconfirmedCandida
DeclaredGrade: matchDeclaredGrade(entry.DeclaredGrade),
PublicContext: matchPublicContext(entry.PublicContext),
EvidenceSummary: matchEvidenceSummary(entry.EvidenceSummary),
SemanticEvidence: matchSemanticEvidence(entry.SemanticEvidence),
Components: api.MatchUnconfirmedComponents{Fit: entry.Components.Fit, Coverage: entry.Components.Coverage},
UnknownFlags: matchUnknownFlags(entry.UnknownFlags),
}
@@ -300,6 +302,24 @@ func matchEvidenceSummary(items []matching.EvidenceItem) api.MatchEvidenceSummar
return summary
}
// matchSemanticEvidence maps the computed explanation. The list is never
// null, so a client tells "nothing to explain" from a missing field.
func matchSemanticEvidence(items []matching.SemanticEvidence) api.MatchSemanticEvidenceList {
evidence := make(api.MatchSemanticEvidenceList, 0, len(items))
for _, item := range items {
title := api.NilString{Null: true}
if item.ProjectTitle != nil {
title = api.NewNilString(*item.ProjectTitle)
}
evidence = append(evidence, api.MatchSemanticEvidence{
RequirementKind: api.MatchRequirementKind(item.RequirementKind), RequirementText: item.RequirementText,
ItemKind: api.MatchSemanticItemKind(item.ItemKind), ProjectTitle: title,
RepositoryVerified: item.RepositoryVerified, Similarity: api.MatchSimilarityBand(item.Similarity),
})
}
return evidence
}
func matchUnknownFlags(flags []matching.UnknownFlag) api.MatchUnknownFlags {
response := make(api.MatchUnknownFlags, 0, len(flags))
for _, flag := range flags {
@@ -112,7 +112,7 @@ func TestSearchOrganizationMatchesMapsANeedRequestAndKeepsUnconfirmedEntriesStri
}
want := `[{"candidate_handle":"` + handle + `","specialization":"network_engineer","confirmation_status":"unconfirmed","declared_grade":"junior",` +
`"category":null,"strength":null,"public_context":{"stack":null,"experience_band":null,"work_formats":null,"salary_compatibility":null},` +
`"evidence_summary":[{"code":"declared_grade","state":"declared_only"}],"components":{"fit":0.3125,"coverage":0.25},` +
`"evidence_summary":[{"code":"declared_grade","state":"declared_only"}],"semantic_evidence":[],"components":{"fit":0.3125,"coverage":0.25},` +
`"unknown_flags":[{"component":"assessment","reason":"no_confirmation_for_specialization"}]}]`
if string(encoded) != want {
t.Fatalf("unconfirmed entries = %s\nwant %s", encoded, want)
@@ -565,6 +565,19 @@ func anonymousCardResponse(view domain.AnonymousCandidateViewDTO) api.AnonymousC
if view.SalaryCompatibility != nil {
content.SalaryCompatibility.SetTo(api.CandidateSalaryCompatibility(*view.SalaryCompatibility))
}
for _, project := range view.Projects {
description := api.NilString{Null: true}
if project.Description != nil {
description.SetTo(*project.Description)
}
stack := make([]api.StackTag, 0, len(project.Stack))
for _, tag := range project.Stack {
stack = append(stack, api.StackTag(tag))
}
content.Projects = append(content.Projects, api.CardProject{
Title: project.Title, Description: description, Stack: stack, RepositoryVerified: project.RepositoryVerified,
})
}
return content
}
@@ -3,6 +3,7 @@ package v1
import (
"context"
"errors"
"math"
"github.com/google/uuid"
@@ -18,6 +19,7 @@ import (
type ProfileOperations interface {
GetMyProfile(ctx context.Context, userID uuid.UUID) (profile.View, error)
SaveMyProfile(ctx context.Context, userID uuid.UUID, expectedVersion int64, input domain.CandidateProfileInput) (profile.View, error)
RequestRepositoryChecks(ctx context.Context, userID uuid.UUID) (int, error)
}
// ProfileHandler serves the candidate's own profile operations.
@@ -46,6 +48,39 @@ func (handler *Handler) SaveMyProfile(ctx context.Context, request *api.Candidat
return handler.profile.SaveMyProfile(ctx, request)
}
func (handler *Handler) RequestMyRepositoryChecks(ctx context.Context) (api.RequestMyRepositoryChecksRes, error) {
if handler.profile == nil {
return handler.UnimplementedHandler.RequestMyRepositoryChecks(ctx)
}
return handler.profile.RequestMyRepositoryChecks(ctx)
}
// RequestMyRepositoryChecks schedules new checks of the linked repositories.
func (handler *ProfileHandler) RequestMyRepositoryChecks(ctx context.Context) (api.RequestMyRepositoryChecksRes, error) {
principal, ok := PrincipalFromContext(ctx)
if !ok {
return (*api.RequestMyRepositoryChecksUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
}
scheduled, err := handler.operations.RequestRepositoryChecks(ctx, principal.UserID)
if err != nil {
if limit, ok := errors.AsType[*profile.RepositoryCheckLimitError](err); ok {
return problem.RateLimited(ctx, int32(math.Ceil(limit.RetryAfter.Seconds()))), nil
}
switch {
case errors.Is(err, profile.ErrForbidden), errors.Is(err, profile.ErrEmailNotVerified):
return (*api.RequestMyRepositoryChecksForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
case errors.Is(err, outbound.ErrUserNotFound):
return (*api.RequestMyRepositoryChecksUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
default:
return nil, err
}
}
return &api.ProfileRepositoryCheckRequestHeaders{
CacheControl: api.CacheControlNoStoreNoStore,
Response: api.ProfileRepositoryCheckRequest{Scheduled: int32(scheduled)}, //nolint:gosec // at most ten projects
}, nil
}
func (handler *ProfileHandler) GetMyProfile(ctx context.Context) (api.GetMyProfileRes, error) {
principal, ok := PrincipalFromContext(ctx)
if !ok {
@@ -167,6 +202,7 @@ func candidateProfileInput(request *api.CandidateProfileUpdate) domain.Candidate
for _, item := range request.SoftSkills {
input.SoftSkills = append(input.SoftSkills, domain.ProfileClaimInput[string]{Value: string(item.Skill), Status: domain.ProfileClaimStatus(item.Status)})
}
input.Projects = projectInputs(request.Projects)
if value, ok := request.Terms.Location.Get(); ok {
input.Location = profileStringInput(string(value.Value), value.Status)
}
@@ -277,6 +313,7 @@ func candidateProfileResponse(view profile.View) api.CandidateProfile {
Skill: api.ProfileSoftSkill(item.Value()), Status: api.ProfileItemStatus(item.Status()), Source: profileClaimSourceResponse(item.Source()),
})
}
response.Projects = projectResponses(content, view.RepositoryChecks)
response.Terms = candidateProfileTerms(content)
updatedAt := api.NilTimestamp{}
if saved.UpdatedAt().IsZero() {
@@ -289,6 +326,75 @@ func candidateProfileResponse(view profile.View) api.CandidateProfile {
return response
}
// projectInputs maps the request projects. An absent list keeps the stored
// projects and maps to nil; an empty one clears them.
func projectInputs(items []api.ProfileProjectItemInput) *[]domain.ProfileClaimInput[domain.ProfileProject] {
if items == nil {
return nil
}
projects := make([]domain.ProfileClaimInput[domain.ProfileProject], 0, len(items))
for _, item := range items {
description := ""
if value, ok := item.Description.Get(); ok {
description = string(value)
}
repository := ""
if value, ok := item.RepositoryURL.Get(); ok {
repository = string(value)
}
stack := make([]string, 0, len(item.Stack))
for _, tag := range item.Stack {
stack = append(stack, string(tag))
}
projects = append(projects, domain.ProfileClaimInput[domain.ProfileProject]{
Value: domain.NewProfileProject(string(item.Title), description, stack, repository),
Status: domain.ProfileClaimStatus(item.Status),
})
}
return &projects
}
func projectResponses(content domain.CandidateProfileContent, checks map[string]outbound.RepositoryCheck) []api.ProfileProjectItem {
projects := make([]api.ProfileProjectItem, 0, len(content.Projects()))
for _, item := range content.Projects() {
projects = append(projects, profileProjectResponse(item, checks))
}
return projects
}
// profileProjectResponse maps one project with the state of its repository
// check. A linked repository without a stored check is pending.
func profileProjectResponse(item domain.ProfileClaim[domain.ProfileProject], checks map[string]outbound.RepositoryCheck) api.ProfileProjectItem {
value := item.Value()
description := api.NilProfileProjectDescription{Null: true}
if value.Description != "" {
description.SetTo(api.ProfileProjectDescription(value.Description))
}
stack := make(api.ProfileProjectStack, 0, len(value.StackTags()))
for _, tag := range value.StackTags() {
stack = append(stack, api.StackTag(tag))
}
project := api.ProfileProjectItem{
Title: api.ProfileProjectTitle(value.Title), Description: description, Stack: stack,
RepositoryURL: api.NilProfileRepositoryUrl{Null: true}, RepositoryCheck: api.NilProfileRepositoryCheck{Null: true},
Status: api.ProfileItemStatus(item.Status()), Source: profileClaimSourceResponse(item.Source()),
}
repository, linked := value.Repository()
if !linked {
return project
}
project.RepositoryURL.SetTo(api.ProfileRepositoryUrl(repository.URL()))
check := api.ProfileRepositoryCheck{State: api.ProfileRepositoryCheckStatePending, CheckedAt: api.NilTimestamp{Null: true}}
if stored, ok := checks[repository.Key()]; ok {
check.State = api.ProfileRepositoryCheckState(stored.State)
if !stored.CheckedAt.IsZero() {
check.CheckedAt.SetTo(api.Timestamp(stored.CheckedAt))
}
}
project.RepositoryCheck.SetTo(check)
return project
}
// confirmedCategoriesResponse maps the categories in their stored order. The
// result is never nil, so a profile without categories encodes as an empty list.
func confirmedCategoriesResponse(categories []domain.CandidateAssessmentCategory) []api.ProfileConfirmedCategory {
@@ -0,0 +1,360 @@
// Package github reads public repository metadata from the public GitHub
// REST API. It is SSRF-safe by construction: the only origin it contacts is
// https://api.github.com, a repository coordinate is validated by the domain
// before it becomes a path, and a redirect to any other origin is refused.
package github
import (
"cmp"
"context"
"crypto/tls"
"encoding/json"
"errors"
"fmt"
"io"
"net"
"net/http"
"net/url"
"regexp"
"slices"
"strconv"
"strings"
"time"
"unicode/utf8"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
const (
// apiOrigin is the only origin the fetcher ever contacts.
apiOrigin = "https://api.github.com"
apiVersion = "2022-11-28"
userAgent = "lincodex-repository-check"
// Response caps: a repository document is a few KiB, the language map
// smaller; a README is read only up to its excerpt budget.
maxMetadataBytes = 1 << 20
maxReadmeBytes = 64 << 10
// maxRedirects bounds same-origin redirects, such as a renamed repository.
maxRedirects = 3
// The stored bounds of candidate_project_repositories.
maxDescriptionRunes = 1000
maxReadmeRunes = 4000
maxTopics = 20
// maxLanguages keeps the main languages by size.
maxLanguages = 3
// Rate limit waits are clamped, so a wrong header cannot stall a check
// for days or make it spin.
minRateLimitWait = time.Minute
maxRateLimitWait = time.Hour
)
// Fetcher implements outbound.RepositoryMetadataFetcher.
type Fetcher struct {
client *http.Client
origin string
token string
clock func() time.Time
}
var _ outbound.RepositoryMetadataFetcher = (*Fetcher)(nil)
// NewFetcher builds a fetcher for api.github.com. token is optional; it is
// sent only to that origin and never logged.
func NewFetcher(timeout time.Duration, token string, clock func() time.Time) (*Fetcher, error) {
return newFetcher(apiOrigin, timeout, token, clock, &http.Transport{
// No proxy from the environment: the request goes to GitHub directly.
Proxy: nil,
DialContext: (&net.Dialer{Timeout: timeout}).DialContext,
TLSClientConfig: &tls.Config{MinVersion: tls.VersionTLS12},
TLSHandshakeTimeout: timeout,
ResponseHeaderTimeout: timeout,
MaxIdleConns: 4,
IdleConnTimeout: time.Minute,
ForceAttemptHTTP2: true,
})
}
// newFetcher lets tests point the fetcher at an httptest server; production
// code reaches it only through NewFetcher with the fixed origin.
func newFetcher(origin string, timeout time.Duration, token string, clock func() time.Time, transport http.RoundTripper) (*Fetcher, error) {
if timeout <= 0 || clock == nil || transport == nil {
return nil, errors.New("github.newFetcher - timeout, clock, and transport must be set")
}
parsed, err := url.Parse(origin)
if err != nil || parsed.Host == "" || parsed.Path != "" {
return nil, errors.New("github.newFetcher - origin is invalid")
}
return &Fetcher{
client: &http.Client{
Timeout: timeout,
Transport: transport,
CheckRedirect: func(request *http.Request, via []*http.Request) error {
if len(via) >= maxRedirects {
return errors.New("too many redirects")
}
if request.URL.Scheme != parsed.Scheme || request.URL.Host != parsed.Host {
return errors.New("redirect to another origin")
}
return nil
},
},
origin: parsed.Scheme + "://" + parsed.Host,
token: token,
clock: clock,
}, nil
}
type repositoryDocument struct {
ID int64 `json:"id"`
Private bool `json:"private"`
Visibility string `json:"visibility"`
Description *string `json:"description"`
Topics []string `json:"topics"`
}
// Fetch reads the repository, its languages, and its README. A repository
// that does not exist or is not public is Found=false with no metadata.
func (fetcher *Fetcher) Fetch(
ctx context.Context, repository domain.GitHubRepository, previous outbound.RepositoryCheck,
) (outbound.RepositoryFetch, error) {
if repository.IsZero() {
return outbound.RepositoryFetch{}, fmt.Errorf("github.Fetcher.Fetch - repository is not set: %w", domain.ErrInvalidGitHubRepository)
}
base := "/repos/" + url.PathEscape(repository.Owner()) + "/" + url.PathEscape(repository.Name())
repositoryETag := ""
if previous.State == outbound.RepositoryCheckVerified {
repositoryETag = previous.RepositoryETag
}
response, err := fetcher.get(ctx, base, "application/vnd.github+json", repositoryETag, maxMetadataBytes)
if err != nil {
return outbound.RepositoryFetch{}, err
}
switch {
case response.status == http.StatusNotModified && repositoryETag != "":
return outbound.RepositoryFetch{
Found: true, NotModified: true, GitHubID: previous.GitHubID, Evidence: previous.Evidence,
RepositoryETag: previous.RepositoryETag, ReadmeETag: previous.ReadmeETag,
}, nil
case response.status == http.StatusNotFound || response.status == http.StatusGone ||
response.status == http.StatusUnavailableForLegalReasons:
return outbound.RepositoryFetch{Found: false}, nil
case response.status != http.StatusOK:
return outbound.RepositoryFetch{}, fetcher.statusError(response)
}
return fetcher.publicRepository(ctx, base, response)
}
// publicRepository reads the metadata of a repository document that GitHub
// returned: a private or internal one is not found, a public one gets its
// languages and README.
func (fetcher *Fetcher) publicRepository(ctx context.Context, base string, response fetched) (outbound.RepositoryFetch, error) {
var document repositoryDocument
if err := json.Unmarshal(response.body, &document); err != nil || document.ID <= 0 {
return outbound.RepositoryFetch{}, &outbound.RepositoryFetchError{Class: outbound.RepositoryFailureInvalidResponse}
}
if document.Private || (document.Visibility != "" && document.Visibility != "public") {
return outbound.RepositoryFetch{Found: false}, nil
}
languages, err := fetcher.languages(ctx, base)
if err != nil {
return outbound.RepositoryFetch{}, err
}
readme, readmeETag, err := fetcher.readme(ctx, base)
if err != nil {
return outbound.RepositoryFetch{}, err
}
description := ""
if document.Description != nil {
description = truncate(plainLine(*document.Description), maxDescriptionRunes)
}
return outbound.RepositoryFetch{
Found: true, GitHubID: document.ID, RepositoryETag: boundedETag(response.etag), ReadmeETag: readmeETag,
Evidence: domain.RepositoryEvidence{
Description: description, Topics: cleanTopics(document.Topics), Languages: languages, ReadmeExcerpt: readme,
},
}, nil
}
func (fetcher *Fetcher) languages(ctx context.Context, base string) ([]string, error) {
response, err := fetcher.get(ctx, base+"/languages", "application/vnd.github+json", "", maxMetadataBytes)
if err != nil {
return nil, err
}
if response.status == http.StatusNotFound {
return []string{}, nil
}
if response.status != http.StatusOK {
return nil, fetcher.statusError(response)
}
var sizes map[string]int64
if err := json.Unmarshal(response.body, &sizes); err != nil {
return nil, &outbound.RepositoryFetchError{Class: outbound.RepositoryFailureInvalidResponse}
}
type language struct {
name string
bytes int64
}
var ordered []language
for name, size := range sizes {
if clean := plainLine(name); clean != "" && utf8.RuneCountInString(clean) <= 50 {
ordered = append(ordered, language{name: clean, bytes: size})
}
}
slices.SortFunc(ordered, func(left, right language) int {
return cmp.Or(cmp.Compare(right.bytes, left.bytes), strings.Compare(left.name, right.name))
})
names := make([]string, 0, maxLanguages)
for _, item := range ordered[:min(len(ordered), maxLanguages)] {
names = append(names, item.name)
}
return names, nil
}
func (fetcher *Fetcher) readme(ctx context.Context, base string) (string, string, error) {
response, err := fetcher.get(ctx, base+"/readme", "application/vnd.github.raw+json", "", maxReadmeBytes)
if err != nil {
return "", "", err
}
if response.status == http.StatusNotFound {
return "", "", nil
}
if response.status != http.StatusOK {
return "", "", fetcher.statusError(response)
}
// A cut body may end inside a multi-byte character; invalid bytes are
// dropped instead of failing the check.
text := strings.ToValidUTF8(string(response.body), "")
return truncate(MarkdownToText(text), maxReadmeRunes), boundedETag(response.etag), nil
}
type fetched struct {
status int
etag string
body []byte
headers http.Header
}
func (fetcher *Fetcher) get(ctx context.Context, path, accept, etag string, limit int64) (fetched, error) {
request, err := http.NewRequestWithContext(ctx, http.MethodGet, fetcher.origin+path, nil)
if err != nil {
return fetched{}, &outbound.RepositoryFetchError{Class: outbound.RepositoryFailureNetwork}
}
request.Header.Set("Accept", accept)
request.Header.Set("User-Agent", userAgent)
request.Header.Set("X-GitHub-Api-Version", apiVersion)
if etag != "" {
request.Header.Set("If-None-Match", etag)
}
if fetcher.token != "" {
request.Header.Set("Authorization", "Bearer "+fetcher.token)
}
response, err := fetcher.client.Do(request)
if err != nil {
// The error can carry the URL; only the class leaves this function.
return fetched{}, &outbound.RepositoryFetchError{Class: outbound.RepositoryFailureNetwork}
}
defer func() { _ = response.Body.Close() }()
body, err := io.ReadAll(io.LimitReader(response.Body, limit))
if err != nil {
return fetched{}, &outbound.RepositoryFetchError{Class: outbound.RepositoryFailureNetwork}
}
return fetched{status: response.StatusCode, etag: response.Header.Get("ETag"), body: body, headers: response.Header}, nil
}
// statusError classifies an unexpected status. GitHub reports an exhausted
// rate limit as 403 or 429 with x-ratelimit-remaining 0 or Retry-After.
func (fetcher *Fetcher) statusError(response fetched) error {
limited := response.status == http.StatusTooManyRequests ||
(response.status == http.StatusForbidden &&
(response.headers.Get("X-RateLimit-Remaining") == "0" || response.headers.Get("Retry-After") != ""))
switch {
case limited:
return &outbound.RepositoryFetchError{Class: outbound.RepositoryFailureRateLimited, RetryAfter: fetcher.rateLimitWait(response.headers)}
case response.status >= http.StatusInternalServerError:
return &outbound.RepositoryFetchError{Class: outbound.RepositoryFailureServerError}
default:
return &outbound.RepositoryFetchError{Class: outbound.RepositoryFailureInvalidResponse}
}
}
func (fetcher *Fetcher) rateLimitWait(headers http.Header) time.Duration {
wait := minRateLimitWait
if seconds, err := strconv.ParseInt(headers.Get("Retry-After"), 10, 64); err == nil && seconds > 0 {
wait = time.Duration(seconds) * time.Second
} else if reset, err := strconv.ParseInt(headers.Get("X-RateLimit-Reset"), 10, 64); err == nil {
wait = time.Unix(reset, 0).Sub(fetcher.clock())
}
return min(max(wait, minRateLimitWait), maxRateLimitWait)
}
func boundedETag(etag string) string {
if etag == "" || len(etag) > 200 || strings.ContainsFunc(etag, func(character rune) bool { return character < 0x20 || character > 0x7e }) {
return ""
}
return etag
}
func cleanTopics(topics []string) []string {
cleaned := make([]string, 0, min(len(topics), maxTopics))
for _, topic := range topics {
if len(cleaned) == maxTopics {
break
}
if clean := plainLine(topic); clean != "" && utf8.RuneCountInString(clean) <= 50 {
cleaned = append(cleaned, clean)
}
}
return cleaned
}
// plainLine keeps printable text on one line.
func plainLine(value string) string {
value = strings.Map(func(character rune) rune {
if character < 0x20 || character == 0x7f || character == '
' || character == '
' {
return ' '
}
return character
}, value)
return strings.Join(strings.Fields(value), " ")
}
func truncate(value string, limit int) string {
if utf8.RuneCountInString(value) <= limit {
return value
}
return strings.TrimSpace(string([]rune(value)[:limit]))
}
var (
fencedCodePattern = regexp.MustCompile("(?s)```.*?(```|$)|~~~.*?(~~~|$)")
htmlCommentPatter = regexp.MustCompile(`(?s)<!--.*?-->`)
htmlTagPattern = regexp.MustCompile(`(?s)<[^>]{0,500}>`)
imagePattern = regexp.MustCompile(`!\[[^\]]*\]\([^)]*\)`)
linkPattern = regexp.MustCompile(`\[([^\]]*)\]\([^)]*\)`)
referencePattern = regexp.MustCompile(`(?m)^\s*\[[^\]]+\]:\s*\S+.*$`)
urlPattern = regexp.MustCompile(`https?://\S+`)
headingPattern = regexp.MustCompile(`(?m)^\s{0,3}#{1,6}\s*`)
listPattern = regexp.MustCompile(`(?m)^\s*(?:[-*+]|\d+[.)])\s+`)
quotePattern = regexp.MustCompile(`(?m)^\s*>\s?`)
emphasisPattern = regexp.MustCompile("[*_`~|]+")
rulePattern = regexp.MustCompile(`(?m)^\s*[-=*_]{3,}\s*$`)
)
// MarkdownToText turns a README into plain text for ranking: code blocks,
// HTML, images, link targets, and bare URLs are removed and the markup
// characters are dropped. The result is never rendered.
func MarkdownToText(markdown string) string {
text := strings.ReplaceAll(markdown, "\r\n", "\n")
for _, step := range []struct {
pattern *regexp.Regexp
replacement string
}{
{fencedCodePattern, " "}, {htmlCommentPatter, " "}, {imagePattern, " "}, {linkPattern, "$1"},
{referencePattern, " "}, {htmlTagPattern, " "}, {urlPattern, " "}, {rulePattern, " "},
{headingPattern, ""}, {listPattern, ""}, {quotePattern, ""}, {emphasisPattern, " "},
} {
text = step.pattern.ReplaceAllString(text, step.replacement)
}
return plainLine(text)
}
@@ -0,0 +1,234 @@
package github
import (
"context"
"errors"
"net/http"
"net/http/httptest"
"strconv"
"strings"
"sync"
"testing"
"time"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
var testNow = time.Date(2026, 10, 11, 12, 0, 0, 0, time.UTC)
type recordedRequest struct {
path, authorization, accept, ifNoneMatch string
}
type fakeGitHub struct {
mutex sync.Mutex
requests []recordedRequest
handler func(writer http.ResponseWriter, request *http.Request)
}
func (fake *fakeGitHub) ServeHTTP(writer http.ResponseWriter, request *http.Request) {
fake.mutex.Lock()
fake.requests = append(fake.requests, recordedRequest{
path: request.URL.EscapedPath(), authorization: request.Header.Get("Authorization"),
accept: request.Header.Get("Accept"), ifNoneMatch: request.Header.Get("If-None-Match"),
})
fake.mutex.Unlock()
fake.handler(writer, request)
}
func publicRepository(writer http.ResponseWriter, request *http.Request) {
switch request.URL.Path {
case "/repos/Example/ledger":
writer.Header().Set("ETag", `"repo-1"`)
_, _ = writer.Write([]byte(`{"id":7,"private":false,"visibility":"public","description":"Payments\nledger","topics":["payments","go"],"language":"Go"}`))
case "/repos/Example/ledger/languages":
_, _ = writer.Write([]byte(`{"Shell":10,"Go":5000,"Python":900,"Makefile":5}`))
case "/repos/Example/ledger/readme":
writer.Header().Set("ETag", `"readme-1"`)
_, _ = writer.Write([]byte("# Ledger\n\nIdempotent [callbacks](https://example.test/x) with `outbox`.\n\n```sh\nmake run\n```\n<img src=x onerror=alert(1)>"))
default:
http.NotFound(writer, request)
}
}
func newTestFetcher(t *testing.T, fake *fakeGitHub, token string) *Fetcher {
t.Helper()
server := httptest.NewTLSServer(fake)
t.Cleanup(server.Close)
fetcher, err := newFetcher(server.URL, time.Second, token, func() time.Time { return testNow }, server.Client().Transport)
if err != nil {
t.Fatalf("newFetcher() error = %v", err)
}
return fetcher
}
func repository(t *testing.T, raw string) domain.GitHubRepository {
t.Helper()
parsed, err := domain.ParseGitHubRepositoryURL(raw)
if err != nil {
t.Fatalf("ParseGitHubRepositoryURL() error = %v", err)
}
return parsed
}
func TestFetchReadsPublicMetadataAsPlainText(t *testing.T) {
fake := &fakeGitHub{handler: publicRepository}
fetcher := newTestFetcher(t, fake, "")
result, err := fetcher.Fetch(context.Background(), repository(t, "https://github.com/Example/ledger"), outbound.RepositoryCheck{})
if err != nil {
t.Fatalf("Fetch() error = %v", err)
}
if !result.Found || result.GitHubID != 7 || result.RepositoryETag != `"repo-1"` || result.ReadmeETag != `"readme-1"` {
t.Fatalf("result = %+v", result)
}
evidence := result.Evidence
if evidence.Description != "Payments ledger" || strings.Join(evidence.Topics, ",") != "payments,go" ||
strings.Join(evidence.Languages, ",") != "Go,Python,Shell" {
t.Fatalf("evidence = %+v", evidence)
}
if evidence.ReadmeExcerpt != "Ledger Idempotent callbacks with outbox ." {
t.Fatalf("readme = %q, want plain text without markup, links, code, or HTML", evidence.ReadmeExcerpt)
}
for _, request := range fake.requests {
if request.authorization != "" {
t.Fatalf("a request without a token sent Authorization %q", request.authorization)
}
}
}
func TestFetchSendsTheTokenAndTheStoredETag(t *testing.T) {
fake := &fakeGitHub{handler: func(writer http.ResponseWriter, request *http.Request) {
if request.Header.Get("If-None-Match") == `"repo-1"` {
writer.WriteHeader(http.StatusNotModified)
return
}
publicRepository(writer, request)
}}
fetcher := newTestFetcher(t, fake, "secret-token")
previous := outbound.RepositoryCheck{
State: outbound.RepositoryCheckVerified, RepositoryETag: `"repo-1"`, GitHubID: 7,
Evidence: domain.RepositoryEvidence{Description: "kept"},
}
result, err := fetcher.Fetch(context.Background(), repository(t, "https://github.com/Example/ledger"), previous)
if err != nil || !result.NotModified || result.Evidence.Description != "kept" {
t.Fatalf("Fetch(not modified) = %+v, %v", result, err)
}
if len(fake.requests) != 1 || fake.requests[0].authorization != "Bearer secret-token" || fake.requests[0].ifNoneMatch != `"repo-1"` {
t.Fatalf("requests = %+v", fake.requests)
}
}
func TestFetchTreatsMissingAndPrivateRepositoriesAsNotFound(t *testing.T) {
for name, handler := range map[string]http.HandlerFunc{
"missing": http.NotFound,
"private": func(writer http.ResponseWriter, _ *http.Request) {
_, _ = writer.Write([]byte(`{"id":7,"private":true,"visibility":"private","description":"secret"}`))
},
"internal": func(writer http.ResponseWriter, _ *http.Request) {
_, _ = writer.Write([]byte(`{"id":7,"private":false,"visibility":"internal"}`))
},
} {
fetcher := newTestFetcher(t, &fakeGitHub{handler: handler}, "")
result, err := fetcher.Fetch(context.Background(), repository(t, "https://github.com/Example/ledger"), outbound.RepositoryCheck{})
if err != nil || result.Found || result.Evidence.Description != "" {
t.Errorf("%s: result = %+v, %v; want not found without metadata", name, result, err)
}
}
}
func TestFetchClassifiesRateLimitsAndFailures(t *testing.T) {
reset := strconv.FormatInt(testNow.Add(20*time.Minute).Unix(), 10)
for _, test := range []struct {
name string
write func(http.ResponseWriter)
class outbound.RepositoryFailureClass
wait time.Duration
}{
{"primary limit", func(writer http.ResponseWriter) {
writer.Header().Set("X-RateLimit-Remaining", "0")
writer.Header().Set("X-RateLimit-Reset", reset)
writer.WriteHeader(http.StatusForbidden)
}, outbound.RepositoryFailureRateLimited, 20 * time.Minute},
{"secondary limit", func(writer http.ResponseWriter) {
writer.Header().Set("Retry-After", "5")
writer.WriteHeader(http.StatusTooManyRequests)
}, outbound.RepositoryFailureRateLimited, minRateLimitWait},
{"server error", func(writer http.ResponseWriter) { writer.WriteHeader(http.StatusBadGateway) }, outbound.RepositoryFailureServerError, 0},
{"bad token", func(writer http.ResponseWriter) { writer.WriteHeader(http.StatusUnauthorized) }, outbound.RepositoryFailureInvalidResponse, 0},
{"broken body", func(writer http.ResponseWriter) { _, _ = writer.Write([]byte(`{"id":`)) }, outbound.RepositoryFailureInvalidResponse, 0},
} {
fetcher := newTestFetcher(t, &fakeGitHub{handler: func(writer http.ResponseWriter, _ *http.Request) { test.write(writer) }}, "")
_, err := fetcher.Fetch(context.Background(), repository(t, "https://github.com/Example/ledger"), outbound.RepositoryCheck{})
var fetchError *outbound.RepositoryFetchError
if !errors.As(err, &fetchError) || fetchError.Class != test.class || fetchError.RetryAfter != test.wait {
t.Errorf("%s: error = %v, want class %s wait %s", test.name, err, test.class, test.wait)
}
if !errors.Is(err, outbound.ErrRepositoryFetchUnavailable) {
t.Errorf("%s: error does not match ErrRepositoryFetchUnavailable", test.name)
}
}
}
func TestFetchFollowsOnlySameOriginRedirects(t *testing.T) {
other := httptest.NewTLSServer(http.HandlerFunc(func(writer http.ResponseWriter, _ *http.Request) {
t.Error("the fetcher followed a redirect to another origin")
_, _ = writer.Write([]byte(`{"id":1}`))
}))
defer other.Close()
fake := &fakeGitHub{}
fake.handler = func(writer http.ResponseWriter, request *http.Request) {
switch request.URL.Path {
case "/repos/Example/renamed":
http.Redirect(writer, request, "/repos/Example/ledger", http.StatusMovedPermanently)
case "/repos/Example/escape":
http.Redirect(writer, request, other.URL+"/repos/Example/ledger", http.StatusMovedPermanently)
default:
publicRepository(writer, request)
}
}
fetcher := newTestFetcher(t, fake, "secret-token")
if result, err := fetcher.Fetch(context.Background(), repository(t, "https://github.com/Example/renamed"), outbound.RepositoryCheck{}); err != nil || !result.Found {
t.Fatalf("same-origin redirect = %+v, %v", result, err)
}
_, err := fetcher.Fetch(context.Background(), repository(t, "https://github.com/Example/escape"), outbound.RepositoryCheck{})
var fetchError *outbound.RepositoryFetchError
if !errors.As(err, &fetchError) || fetchError.Class != outbound.RepositoryFailureNetwork {
t.Fatalf("cross-origin redirect error = %v, want a refused request", err)
}
}
func TestFetchCapsTheBodiesItReads(t *testing.T) {
huge := strings.Repeat("word ", maxReadmeBytes)
fake := &fakeGitHub{handler: func(writer http.ResponseWriter, request *http.Request) {
if request.URL.Path == "/repos/Example/ledger/readme" {
_, _ = writer.Write([]byte(huge))
return
}
publicRepository(writer, request)
}}
fetcher := newTestFetcher(t, fake, "")
result, err := fetcher.Fetch(context.Background(), repository(t, "https://github.com/Example/ledger"), outbound.RepositoryCheck{})
if err != nil {
t.Fatalf("Fetch() error = %v", err)
}
if runes := len([]rune(result.Evidence.ReadmeExcerpt)); runes == 0 || runes > maxReadmeRunes {
t.Fatalf("readme excerpt has %d runes, want at most %d", runes, maxReadmeRunes)
}
oversized := &fakeGitHub{handler: func(writer http.ResponseWriter, _ *http.Request) {
_, _ = writer.Write([]byte(`{"id":7,"description":"` + strings.Repeat("x", maxMetadataBytes) + `"}`))
}}
if _, err := newTestFetcher(t, oversized, "").Fetch(context.Background(), repository(t, "https://github.com/Example/ledger"), outbound.RepositoryCheck{}); err == nil {
t.Fatal("a repository document over the cap was accepted")
}
}
func TestNewFetcherUsesOnlyTheGitHubOrigin(t *testing.T) {
fetcher, err := NewFetcher(time.Second, "", time.Now)
if err != nil || fetcher.origin != "https://api.github.com" {
t.Fatalf("NewFetcher() origin = %q, %v", fetcher.origin, err)
}
if _, err := fetcher.Fetch(context.Background(), domain.GitHubRepository{}, outbound.RepositoryCheck{}); !errors.Is(err, domain.ErrInvalidGitHubRepository) {
t.Fatalf("Fetch(zero repository) error = %v", err)
}
}
@@ -17,6 +17,8 @@ import (
var regexMap = map[string]ogenregex.Regexp{
"^(/([^~/]|~[01])*)*$": ogenregex.MustCompile("^(/([^~/]|~[01])*)*$"),
"^[A-Za-z0-9._-]+$": ogenregex.MustCompile("^[A-Za-z0-9._-]+$"),
"^[A-Za-z0-9._/-]+$": ogenregex.MustCompile("^[A-Za-z0-9._/-]+$"),
"^[a-z0-9._-]+$": ogenregex.MustCompile("^[a-z0-9._-]+$"),
"^[a-z][a-z0-9_]*$": ogenregex.MustCompile("^[a-z][a-z0-9_]*$"),
}
var (
@@ -27,6 +27,19 @@ func trimTrailingSlashes(u *url.URL) {
// Invoker invokes operations described by OpenAPI v3 specification.
type Invoker interface {
// CreateMLEmbeddings invokes CreateMLEmbeddings operation.
//
// Internal operation for the Go backend; it is not reachable from browsers and needs no credentials on
// the private network. The request carries only text that the caller is allowed to process, and the
// service never logs it.
//
// The service answers 503 service_unavailable until the model is loaded from the image and a warm-up
// encode has finished; `/readyz` reports the same state. A request above the body limit answers 413,
// and a request that breaks the schema, such as too many texts or a text over 8000 characters, or
// names a model that the service does not serve, answers 400.
//
// POST /v1/embeddings
CreateMLEmbeddings(ctx context.Context, request *EmbeddingRequest) (CreateMLEmbeddingsRes, error)
// GetMLHealthz invokes GetMLHealthz operation.
//
// Check whether the ML process is responding.
@@ -80,6 +93,96 @@ func (c *Client) requestURL(ctx context.Context) *url.URL {
return u
}
// CreateMLEmbeddings invokes CreateMLEmbeddings operation.
//
// Internal operation for the Go backend; it is not reachable from browsers and needs no credentials on
// the private network. The request carries only text that the caller is allowed to process, and the
// service never logs it.
//
// The service answers 503 service_unavailable until the model is loaded from the image and a warm-up
// encode has finished; `/readyz` reports the same state. A request above the body limit answers 413,
// and a request that breaks the schema, such as too many texts or a text over 8000 characters, or
// names a model that the service does not serve, answers 400.
//
// POST /v1/embeddings
func (c *Client) CreateMLEmbeddings(ctx context.Context, request *EmbeddingRequest) (CreateMLEmbeddingsRes, error) {
res, err := c.sendCreateMLEmbeddings(ctx, request)
return res, err
}
func (c *Client) sendCreateMLEmbeddings(ctx context.Context, request *EmbeddingRequest) (res CreateMLEmbeddingsRes, err error) {
otelAttrs := []attribute.KeyValue{
otelogen.OperationID("CreateMLEmbeddings"),
semconv.HTTPRequestMethodKey.String("POST"),
semconv.URLTemplateKey.String("/v1/embeddings"),
}
otelAttrs = append(otelAttrs, c.cfg.Attributes...)
// Run stopwatch.
startTime := time.Now()
defer func() {
// Use floating point division here for higher precision (instead of Millisecond method).
elapsedDuration := time.Since(startTime)
c.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), metric.WithAttributes(otelAttrs...))
}()
// Increment request counter.
c.requests.Add(ctx, 1, metric.WithAttributes(otelAttrs...))
// Start a span for this request.
ctx, span := c.cfg.Tracer.Start(ctx, CreateMLEmbeddingsOperation,
trace.WithAttributes(otelAttrs...),
clientSpanKind,
)
// Track stage for error reporting.
var stage string
defer func() {
if err != nil {
span.RecordError(err)
span.SetStatus(codes.Error, stage)
c.errors.Add(ctx, 1, metric.WithAttributes(otelAttrs...))
}
span.End()
}()
stage = "BuildURL"
u := uri.Clone(c.requestURL(ctx))
var pathParts [1]string
pathParts[0] = "/v1/embeddings"
uri.AddPathParts(u, pathParts[:]...)
stage = "EncodeRequest"
r, err := ht.NewRequest(ctx, "POST", u)
if err != nil {
return res, errors.Wrap(err, "create request")
}
if err := encodeCreateMLEmbeddingsRequest(request, r); err != nil {
return res, errors.Wrap(err, "encode request")
}
stage = "SendRequest"
resp, err := c.cfg.Client.Do(r)
if err != nil {
return res, errors.Wrap(err, "do request")
}
body := resp.Body
defer func() {
// Drain the body to EOF before closing, so the underlying
// connection can be reused by the Transport regardless of the
// response status code. See https://github.com/ogen-go/ogen/issues/1670.
_, _ = io.Copy(io.Discard, body)
_ = body.Close()
}()
stage = "DecodeResponse"
result, err := decodeCreateMLEmbeddingsResponse(resp)
if err != nil {
return res, errors.Wrap(err, "decode response")
}
return result, nil
}
// GetMLHealthz invokes GetMLHealthz operation.
//
// Check whether the ML process is responding.
@@ -1,6 +1,10 @@
// Code generated by ogen, DO NOT EDIT.
package api
type CreateMLEmbeddingsRes interface {
createMLEmbeddingsRes()
}
type GetMLReadyzRes interface {
getMLReadyzRes()
}
@@ -11,6 +11,576 @@ import (
"github.com/ogen-go/ogen/validate"
)
// Encode encodes EmbeddingInputKind as json.
func (s EmbeddingInputKind) Encode(e *jx.Encoder) {
e.Str(string(s))
}
// Decode decodes EmbeddingInputKind from json.
func (s *EmbeddingInputKind) Decode(d *jx.Decoder) error {
if s == nil {
return errors.New("invalid: unable to decode EmbeddingInputKind to nil")
}
v, err := d.StrBytes()
if err != nil {
return err
}
// Try to use constant string.
switch EmbeddingInputKind(v) {
case EmbeddingInputKindQuery:
*s = EmbeddingInputKindQuery
case EmbeddingInputKindDocument:
*s = EmbeddingInputKindDocument
default:
*s = EmbeddingInputKind(v)
}
return nil
}
// MarshalJSON implements stdjson.Marshaler.
func (s EmbeddingInputKind) MarshalJSON() ([]byte, error) {
e := jx.Encoder{}
s.Encode(&e)
return e.Bytes(), nil
}
// UnmarshalJSON implements stdjson.Unmarshaler.
func (s *EmbeddingInputKind) UnmarshalJSON(data []byte) error {
d := jx.DecodeBytes(data)
return s.Decode(d)
}
// Encode implements json.Marshaler.
func (s *EmbeddingModel) Encode(e *jx.Encoder) {
e.ObjStart()
s.encodeFields(e)
e.ObjEnd()
}
// encodeFields encodes fields.
func (s *EmbeddingModel) encodeFields(e *jx.Encoder) {
{
e.FieldStart("id")
e.Str(s.ID)
}
{
e.FieldStart("revision")
e.Str(s.Revision)
}
{
e.FieldStart("dimension")
e.Int32(s.Dimension)
}
{
e.FieldStart("max_tokens")
e.Int32(s.MaxTokens)
}
{
e.FieldStart("prompt_version")
e.Str(s.PromptVersion)
}
}
var jsonFieldsNameOfEmbeddingModel = [5]string{
0: "id",
1: "revision",
2: "dimension",
3: "max_tokens",
4: "prompt_version",
}
// Decode decodes EmbeddingModel from json.
func (s *EmbeddingModel) Decode(d *jx.Decoder) error {
if s == nil {
return errors.New("invalid: unable to decode EmbeddingModel to nil")
}
var requiredBitSet [1]uint8
if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error {
switch string(k) {
case "id":
requiredBitSet[0] |= 1 << 0
if err := func() error {
v, err := d.Str()
s.ID = string(v)
if err != nil {
return err
}
return nil
}(); err != nil {
return errors.Wrap(err, "decode field \"id\"")
}
case "revision":
requiredBitSet[0] |= 1 << 1
if err := func() error {
v, err := d.Str()
s.Revision = string(v)
if err != nil {
return err
}
return nil
}(); err != nil {
return errors.Wrap(err, "decode field \"revision\"")
}
case "dimension":
requiredBitSet[0] |= 1 << 2
if err := func() error {
v, err := d.Int32()
s.Dimension = int32(v)
if err != nil {
return err
}
return nil
}(); err != nil {
return errors.Wrap(err, "decode field \"dimension\"")
}
case "max_tokens":
requiredBitSet[0] |= 1 << 3
if err := func() error {
v, err := d.Int32()
s.MaxTokens = int32(v)
if err != nil {
return err
}
return nil
}(); err != nil {
return errors.Wrap(err, "decode field \"max_tokens\"")
}
case "prompt_version":
requiredBitSet[0] |= 1 << 4
if err := func() error {
v, err := d.Str()
s.PromptVersion = string(v)
if err != nil {
return err
}
return nil
}(); err != nil {
return errors.Wrap(err, "decode field \"prompt_version\"")
}
default:
return errors.Errorf("unexpected field %q", k)
}
return nil
}); err != nil {
return errors.Wrap(err, "decode EmbeddingModel")
}
// Validate required fields.
var failures []validate.FieldError
for i, mask := range [1]uint8{
0b00011111,
} {
if result := (requiredBitSet[i] & mask) ^ mask; result != 0 {
// Mask only required fields and check equality to mask using XOR.
//
// If XOR result is not zero, result is not equal to expected, so some fields are missed.
// Bits of fields which would be set are actually bits of missed fields.
missed := bits.OnesCount8(result)
for bitN := 0; bitN < missed; bitN++ {
bitIdx := bits.TrailingZeros8(result)
fieldIdx := i*8 + bitIdx
var name string
if fieldIdx < len(jsonFieldsNameOfEmbeddingModel) {
name = jsonFieldsNameOfEmbeddingModel[fieldIdx]
} else {
name = strconv.Itoa(fieldIdx)
}
failures = append(failures, validate.FieldError{
Name: name,
Error: validate.ErrFieldRequired,
})
// Reset bit.
result &^= 1 << bitIdx
}
}
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
}
return nil
}
// MarshalJSON implements stdjson.Marshaler.
func (s *EmbeddingModel) MarshalJSON() ([]byte, error) {
e := jx.Encoder{}
s.Encode(&e)
return e.Bytes(), nil
}
// UnmarshalJSON implements stdjson.Unmarshaler.
func (s *EmbeddingModel) UnmarshalJSON(data []byte) error {
d := jx.DecodeBytes(data)
return s.Decode(d)
}
// Encode implements json.Marshaler.
func (s *EmbeddingRequest) Encode(e *jx.Encoder) {
e.ObjStart()
s.encodeFields(e)
e.ObjEnd()
}
// encodeFields encodes fields.
func (s *EmbeddingRequest) encodeFields(e *jx.Encoder) {
{
if s.Model.Set {
e.FieldStart("model")
s.Model.Encode(e)
}
}
{
e.FieldStart("kind")
s.Kind.Encode(e)
}
{
e.FieldStart("texts")
e.ArrStart()
for _, elem := range s.Texts {
elem.Encode(e)
}
e.ArrEnd()
}
}
var jsonFieldsNameOfEmbeddingRequest = [3]string{
0: "model",
1: "kind",
2: "texts",
}
// Decode decodes EmbeddingRequest from json.
func (s *EmbeddingRequest) Decode(d *jx.Decoder) error {
if s == nil {
return errors.New("invalid: unable to decode EmbeddingRequest to nil")
}
var requiredBitSet [1]uint8
if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error {
switch string(k) {
case "model":
if err := func() error {
s.Model.Reset()
if err := s.Model.Decode(d); err != nil {
return err
}
return nil
}(); err != nil {
return errors.Wrap(err, "decode field \"model\"")
}
case "kind":
requiredBitSet[0] |= 1 << 1
if err := func() error {
if err := s.Kind.Decode(d); err != nil {
return err
}
return nil
}(); err != nil {
return errors.Wrap(err, "decode field \"kind\"")
}
case "texts":
requiredBitSet[0] |= 1 << 2
if err := func() error {
s.Texts = make([]EmbeddingText, 0)
if err := d.Arr(func(d *jx.Decoder) error {
var elem EmbeddingText
if err := elem.Decode(d); err != nil {
return err
}
s.Texts = append(s.Texts, elem)
return nil
}); err != nil {
return err
}
return nil
}(); err != nil {
return errors.Wrap(err, "decode field \"texts\"")
}
default:
return errors.Errorf("unexpected field %q", k)
}
return nil
}); err != nil {
return errors.Wrap(err, "decode EmbeddingRequest")
}
// Validate required fields.
var failures []validate.FieldError
for i, mask := range [1]uint8{
0b00000110,
} {
if result := (requiredBitSet[i] & mask) ^ mask; result != 0 {
// Mask only required fields and check equality to mask using XOR.
//
// If XOR result is not zero, result is not equal to expected, so some fields are missed.
// Bits of fields which would be set are actually bits of missed fields.
missed := bits.OnesCount8(result)
for bitN := 0; bitN < missed; bitN++ {
bitIdx := bits.TrailingZeros8(result)
fieldIdx := i*8 + bitIdx
var name string
if fieldIdx < len(jsonFieldsNameOfEmbeddingRequest) {
name = jsonFieldsNameOfEmbeddingRequest[fieldIdx]
} else {
name = strconv.Itoa(fieldIdx)
}
failures = append(failures, validate.FieldError{
Name: name,
Error: validate.ErrFieldRequired,
})
// Reset bit.
result &^= 1 << bitIdx
}
}
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
}
return nil
}
// MarshalJSON implements stdjson.Marshaler.
func (s *EmbeddingRequest) MarshalJSON() ([]byte, error) {
e := jx.Encoder{}
s.Encode(&e)
return e.Bytes(), nil
}
// UnmarshalJSON implements stdjson.Unmarshaler.
func (s *EmbeddingRequest) UnmarshalJSON(data []byte) error {
d := jx.DecodeBytes(data)
return s.Decode(d)
}
// Encode implements json.Marshaler.
func (s *EmbeddingResponse) Encode(e *jx.Encoder) {
e.ObjStart()
s.encodeFields(e)
e.ObjEnd()
}
// encodeFields encodes fields.
func (s *EmbeddingResponse) encodeFields(e *jx.Encoder) {
{
e.FieldStart("model")
s.Model.Encode(e)
}
{
e.FieldStart("kind")
s.Kind.Encode(e)
}
{
e.FieldStart("vectors")
e.ArrStart()
for _, elem := range s.Vectors {
elem.Encode(e)
}
e.ArrEnd()
}
}
var jsonFieldsNameOfEmbeddingResponse = [3]string{
0: "model",
1: "kind",
2: "vectors",
}
// Decode decodes EmbeddingResponse from json.
func (s *EmbeddingResponse) Decode(d *jx.Decoder) error {
if s == nil {
return errors.New("invalid: unable to decode EmbeddingResponse to nil")
}
var requiredBitSet [1]uint8
if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error {
switch string(k) {
case "model":
requiredBitSet[0] |= 1 << 0
if err := func() error {
if err := s.Model.Decode(d); err != nil {
return err
}
return nil
}(); err != nil {
return errors.Wrap(err, "decode field \"model\"")
}
case "kind":
requiredBitSet[0] |= 1 << 1
if err := func() error {
if err := s.Kind.Decode(d); err != nil {
return err
}
return nil
}(); err != nil {
return errors.Wrap(err, "decode field \"kind\"")
}
case "vectors":
requiredBitSet[0] |= 1 << 2
if err := func() error {
s.Vectors = make([]EmbeddingVector, 0)
if err := d.Arr(func(d *jx.Decoder) error {
var elem EmbeddingVector
if err := elem.Decode(d); err != nil {
return err
}
s.Vectors = append(s.Vectors, elem)
return nil
}); err != nil {
return err
}
return nil
}(); err != nil {
return errors.Wrap(err, "decode field \"vectors\"")
}
default:
return errors.Errorf("unexpected field %q", k)
}
return nil
}); err != nil {
return errors.Wrap(err, "decode EmbeddingResponse")
}
// Validate required fields.
var failures []validate.FieldError
for i, mask := range [1]uint8{
0b00000111,
} {
if result := (requiredBitSet[i] & mask) ^ mask; result != 0 {
// Mask only required fields and check equality to mask using XOR.
//
// If XOR result is not zero, result is not equal to expected, so some fields are missed.
// Bits of fields which would be set are actually bits of missed fields.
missed := bits.OnesCount8(result)
for bitN := 0; bitN < missed; bitN++ {
bitIdx := bits.TrailingZeros8(result)
fieldIdx := i*8 + bitIdx
var name string
if fieldIdx < len(jsonFieldsNameOfEmbeddingResponse) {
name = jsonFieldsNameOfEmbeddingResponse[fieldIdx]
} else {
name = strconv.Itoa(fieldIdx)
}
failures = append(failures, validate.FieldError{
Name: name,
Error: validate.ErrFieldRequired,
})
// Reset bit.
result &^= 1 << bitIdx
}
}
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
}
return nil
}
// MarshalJSON implements stdjson.Marshaler.
func (s *EmbeddingResponse) MarshalJSON() ([]byte, error) {
e := jx.Encoder{}
s.Encode(&e)
return e.Bytes(), nil
}
// UnmarshalJSON implements stdjson.Unmarshaler.
func (s *EmbeddingResponse) UnmarshalJSON(data []byte) error {
d := jx.DecodeBytes(data)
return s.Decode(d)
}
// Encode encodes EmbeddingText as json.
func (s EmbeddingText) Encode(e *jx.Encoder) {
unwrapped := string(s)
e.Str(unwrapped)
}
// Decode decodes EmbeddingText from json.
func (s *EmbeddingText) Decode(d *jx.Decoder) error {
if s == nil {
return errors.New("invalid: unable to decode EmbeddingText to nil")
}
var unwrapped string
if err := func() error {
v, err := d.Str()
unwrapped = string(v)
if err != nil {
return err
}
return nil
}(); err != nil {
return errors.Wrap(err, "alias")
}
*s = EmbeddingText(unwrapped)
return nil
}
// MarshalJSON implements stdjson.Marshaler.
func (s EmbeddingText) MarshalJSON() ([]byte, error) {
e := jx.Encoder{}
s.Encode(&e)
return e.Bytes(), nil
}
// UnmarshalJSON implements stdjson.Unmarshaler.
func (s *EmbeddingText) UnmarshalJSON(data []byte) error {
d := jx.DecodeBytes(data)
return s.Decode(d)
}
// Encode encodes EmbeddingVector as json.
func (s EmbeddingVector) Encode(e *jx.Encoder) {
unwrapped := []float32(s)
e.ArrStart()
for _, elem := range unwrapped {
e.Float32(elem)
}
e.ArrEnd()
}
// Decode decodes EmbeddingVector from json.
func (s *EmbeddingVector) Decode(d *jx.Decoder) error {
if s == nil {
return errors.New("invalid: unable to decode EmbeddingVector to nil")
}
var unwrapped []float32
if err := func() error {
unwrapped = make([]float32, 0)
if err := d.Arr(func(d *jx.Decoder) error {
var elem float32
v, err := d.Float32()
elem = float32(v)
if err != nil {
return err
}
unwrapped = append(unwrapped, elem)
return nil
}); err != nil {
return err
}
return nil
}(); err != nil {
return errors.Wrap(err, "alias")
}
*s = EmbeddingVector(unwrapped)
return nil
}
// MarshalJSON implements stdjson.Marshaler.
func (s EmbeddingVector) MarshalJSON() ([]byte, error) {
e := jx.Encoder{}
s.Encode(&e)
return e.Bytes(), nil
}
// UnmarshalJSON implements stdjson.Unmarshaler.
func (s *EmbeddingVector) UnmarshalJSON(data []byte) error {
d := jx.DecodeBytes(data)
return s.Decode(d)
}
// Encode encodes GetMLReadyzOK as json.
func (s *GetMLReadyzOK) Encode(e *jx.Encoder) {
unwrapped := (*MLReadinessResponse)(s)
@@ -668,6 +1238,8 @@ func (s *ProblemCode) Decode(d *jx.Decoder) error {
*s = ProblemCodeInternal
case ProblemCodeNotImplemented:
*s = ProblemCodeNotImplemented
case ProblemCodeServiceUnavailable:
*s = ProblemCodeServiceUnavailable
default:
*s = ProblemCode(v)
}
@@ -6,6 +6,7 @@ package api
type OperationName = string
const (
GetMLHealthzOperation OperationName = "GetMLHealthz"
GetMLReadyzOperation OperationName = "GetMLReadyz"
CreateMLEmbeddingsOperation OperationName = "CreateMLEmbeddings"
GetMLHealthzOperation OperationName = "GetMLHealthz"
GetMLReadyzOperation OperationName = "GetMLReadyz"
)
@@ -1,3 +1,25 @@
// Code generated by ogen, DO NOT EDIT.
package api
import (
"bytes"
"net/http"
"github.com/go-faster/jx"
ht "github.com/ogen-go/ogen/http"
)
func encodeCreateMLEmbeddingsRequest(
req *EmbeddingRequest,
r *http.Request,
) error {
const contentType = "application/json"
e := new(jx.Encoder)
{
req.Encode(e)
}
encoded := e.Bytes()
ht.SetBody(r, bytes.NewReader(encoded), contentType)
return nil
}
@@ -13,6 +13,248 @@ import (
"github.com/ogen-go/ogen/validate"
)
func decodeCreateMLEmbeddingsResponse(resp *http.Response) (res CreateMLEmbeddingsRes, _ error) {
switch resp.StatusCode {
case 200:
// Code 200.
ct, _, err := mime.ParseMediaType(resp.Header.Get("Content-Type"))
if err != nil {
return res, errors.Wrap(err, "parse media type")
}
switch {
case ct == "application/json":
buf, err := io.ReadAll(resp.Body)
if err != nil {
return res, err
}
d := jx.DecodeBytes(buf)
var response EmbeddingResponse
if err := func() error {
if err := response.Decode(d); err != nil {
return err
}
if err := d.Skip(); err != io.EOF {
return errors.New("unexpected trailing data")
}
return nil
}(); err != nil {
err = &ogenerrors.DecodeBodyError{
ContentType: ct,
Body: buf,
Err: err,
}
return res, err
}
// Validate response.
if err := func() error {
if err := response.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
return res, errors.Wrap(err, "validate")
}
return &response, nil
default:
return res, validate.InvalidContentType(ct)
}
case 400:
// Code 400.
ct, _, err := mime.ParseMediaType(resp.Header.Get("Content-Type"))
if err != nil {
return res, errors.Wrap(err, "parse media type")
}
switch {
case ct == "application/problem+json":
buf, err := io.ReadAll(resp.Body)
if err != nil {
return res, err
}
d := jx.DecodeBytes(buf)
var response Problem
if err := func() error {
if err := response.Decode(d); err != nil {
return err
}
if err := d.Skip(); err != io.EOF {
return errors.New("unexpected trailing data")
}
return nil
}(); err != nil {
err = &ogenerrors.DecodeBodyError{
ContentType: ct,
Body: buf,
Err: err,
}
return res, err
}
// Validate response.
if err := func() error {
if err := response.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
return res, errors.Wrap(err, "validate")
}
return &CreateMLEmbeddingsBadRequest{
StatusCode: resp.StatusCode,
Response: response,
}, nil
default:
return res, validate.InvalidContentType(ct)
}
case 413:
// Code 413.
ct, _, err := mime.ParseMediaType(resp.Header.Get("Content-Type"))
if err != nil {
return res, errors.Wrap(err, "parse media type")
}
switch {
case ct == "application/problem+json":
buf, err := io.ReadAll(resp.Body)
if err != nil {
return res, err
}
d := jx.DecodeBytes(buf)
var response Problem
if err := func() error {
if err := response.Decode(d); err != nil {
return err
}
if err := d.Skip(); err != io.EOF {
return errors.New("unexpected trailing data")
}
return nil
}(); err != nil {
err = &ogenerrors.DecodeBodyError{
ContentType: ct,
Body: buf,
Err: err,
}
return res, err
}
// Validate response.
if err := func() error {
if err := response.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
return res, errors.Wrap(err, "validate")
}
return &CreateMLEmbeddingsRequestEntityTooLarge{
StatusCode: resp.StatusCode,
Response: response,
}, nil
default:
return res, validate.InvalidContentType(ct)
}
case 503:
// Code 503.
ct, _, err := mime.ParseMediaType(resp.Header.Get("Content-Type"))
if err != nil {
return res, errors.Wrap(err, "parse media type")
}
switch {
case ct == "application/problem+json":
buf, err := io.ReadAll(resp.Body)
if err != nil {
return res, err
}
d := jx.DecodeBytes(buf)
var response Problem
if err := func() error {
if err := response.Decode(d); err != nil {
return err
}
if err := d.Skip(); err != io.EOF {
return errors.New("unexpected trailing data")
}
return nil
}(); err != nil {
err = &ogenerrors.DecodeBodyError{
ContentType: ct,
Body: buf,
Err: err,
}
return res, err
}
// Validate response.
if err := func() error {
if err := response.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
return res, errors.Wrap(err, "validate")
}
return &CreateMLEmbeddingsServiceUnavailable{
StatusCode: resp.StatusCode,
Response: response,
}, nil
default:
return res, validate.InvalidContentType(ct)
}
}
// Convenient error response.
defRes, err := func() (res *ProblemStatusCode, err error) {
ct, _, err := mime.ParseMediaType(resp.Header.Get("Content-Type"))
if err != nil {
return res, errors.Wrap(err, "parse media type")
}
switch {
case ct == "application/problem+json":
buf, err := io.ReadAll(resp.Body)
if err != nil {
return res, err
}
d := jx.DecodeBytes(buf)
var response Problem
if err := func() error {
if err := response.Decode(d); err != nil {
return err
}
if err := d.Skip(); err != io.EOF {
return errors.New("unexpected trailing data")
}
return nil
}(); err != nil {
err = &ogenerrors.DecodeBodyError{
ContentType: ct,
Body: buf,
Err: err,
}
return res, err
}
// Validate response.
if err := func() error {
if err := response.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
return res, errors.Wrap(err, "validate")
}
return &ProblemStatusCode{
StatusCode: resp.StatusCode,
Response: response,
}, nil
default:
return res, validate.InvalidContentType(ct)
}
}()
if err != nil {
return res, errors.Wrapf(err, "default (code %d)", resp.StatusCode)
}
return res, errors.Wrap(defRes, "error")
}
func decodeGetMLHealthzResponse(resp *http.Response) (res *MLHealthResponse, _ error) {
switch resp.StatusCode {
case 200:
@@ -12,6 +12,223 @@ func (s *ProblemStatusCode) Error() string {
return fmt.Sprintf("code %d: %+v", s.StatusCode, s.Response)
}
type CreateMLEmbeddingsBadRequest ProblemStatusCode
func (*CreateMLEmbeddingsBadRequest) createMLEmbeddingsRes() {}
type CreateMLEmbeddingsRequestEntityTooLarge ProblemStatusCode
func (*CreateMLEmbeddingsRequestEntityTooLarge) createMLEmbeddingsRes() {}
type CreateMLEmbeddingsServiceUnavailable ProblemStatusCode
func (*CreateMLEmbeddingsServiceUnavailable) createMLEmbeddingsRes() {}
// Side of the retrieval pair that the texts belong to. The service owns the prompt of each side, so
// callers never send model instructions.
//
// - query: the side that searches, such as a hiring need or one requirement of it. The service
// prepends the retrieval instruction of the model.
// - document: the side that is searched, such as a candidate card or one item of it. The service adds
// no prompt.
//
// Ref: #/components/schemas/EmbeddingInputKind
type EmbeddingInputKind string
const (
EmbeddingInputKindQuery EmbeddingInputKind = "query"
EmbeddingInputKindDocument EmbeddingInputKind = "document"
)
// AllValues returns all EmbeddingInputKind values.
func (EmbeddingInputKind) AllValues() []EmbeddingInputKind {
return []EmbeddingInputKind{
EmbeddingInputKindQuery,
EmbeddingInputKindDocument,
}
}
// MarshalText implements encoding.TextMarshaler.
func (s EmbeddingInputKind) MarshalText() ([]byte, error) {
switch s {
case EmbeddingInputKindQuery:
return []byte(s), nil
case EmbeddingInputKindDocument:
return []byte(s), nil
default:
return nil, errors.Errorf("invalid value: %q", s)
}
}
// UnmarshalText implements encoding.TextUnmarshaler.
func (s *EmbeddingInputKind) UnmarshalText(data []byte) error {
switch EmbeddingInputKind(data) {
case EmbeddingInputKindQuery:
*s = EmbeddingInputKindQuery
return nil
case EmbeddingInputKindDocument:
*s = EmbeddingInputKindDocument
return nil
default:
return errors.Errorf("invalid value: %q", data)
}
}
// The model that produced the vectors. A caller stores these values with every vector and never
// compares vectors of different models, revisions, or prompt versions.
// Ref: #/components/schemas/EmbeddingModel
type EmbeddingModel struct {
// Model repository identifier, for example ai-sage/Giga-Embeddings-instruct-480M-0826.
ID string `json:"id"`
// Pinned revision of the weights, a commit hash for a published model.
Revision string `json:"revision"`
// Length of every vector.
Dimension int32 `json:"dimension"`
// Token limit after which a text is truncated.
MaxTokens int32 `json:"max_tokens"`
// Version of the prompt and pooling recipe of the service. A change of the query instruction or the
// pooling changes it.
PromptVersion string `json:"prompt_version"`
}
// GetID returns the value of ID.
func (s *EmbeddingModel) GetID() string {
return s.ID
}
// GetRevision returns the value of Revision.
func (s *EmbeddingModel) GetRevision() string {
return s.Revision
}
// GetDimension returns the value of Dimension.
func (s *EmbeddingModel) GetDimension() int32 {
return s.Dimension
}
// GetMaxTokens returns the value of MaxTokens.
func (s *EmbeddingModel) GetMaxTokens() int32 {
return s.MaxTokens
}
// GetPromptVersion returns the value of PromptVersion.
func (s *EmbeddingModel) GetPromptVersion() string {
return s.PromptVersion
}
// SetID sets the value of ID.
func (s *EmbeddingModel) SetID(val string) {
s.ID = val
}
// SetRevision sets the value of Revision.
func (s *EmbeddingModel) SetRevision(val string) {
s.Revision = val
}
// SetDimension sets the value of Dimension.
func (s *EmbeddingModel) SetDimension(val int32) {
s.Dimension = val
}
// SetMaxTokens sets the value of MaxTokens.
func (s *EmbeddingModel) SetMaxTokens(val int32) {
s.MaxTokens = val
}
// SetPromptVersion sets the value of PromptVersion.
func (s *EmbeddingModel) SetPromptVersion(val string) {
s.PromptVersion = val
}
// Texts to encode in one call. The service encodes them in a fixed, deterministic way: texts are
// ordered by length with the request position as the tie-breaker, encoded in micro-batches of the
// configured size, and returned in request order. The same texts in the same request on the same image
// and thread count give the same vectors.
// Ref: #/components/schemas/EmbeddingRequest
type EmbeddingRequest struct {
// Identifier of the model to use, as `EmbeddingModel.id` reports it. Absent means the default model of
// the service. A service may load several models, for example the members of an ensemble; a model it
// does not serve answers 400 validation_failed with the pointer `/model`.
Model OptString `json:"model"`
Kind EmbeddingInputKind `json:"kind"`
Texts []EmbeddingText `json:"texts"`
}
// GetModel returns the value of Model.
func (s *EmbeddingRequest) GetModel() OptString {
return s.Model
}
// GetKind returns the value of Kind.
func (s *EmbeddingRequest) GetKind() EmbeddingInputKind {
return s.Kind
}
// GetTexts returns the value of Texts.
func (s *EmbeddingRequest) GetTexts() []EmbeddingText {
return s.Texts
}
// SetModel sets the value of Model.
func (s *EmbeddingRequest) SetModel(val OptString) {
s.Model = val
}
// SetKind sets the value of Kind.
func (s *EmbeddingRequest) SetKind(val EmbeddingInputKind) {
s.Kind = val
}
// SetTexts sets the value of Texts.
func (s *EmbeddingRequest) SetTexts(val []EmbeddingText) {
s.Texts = val
}
// Vectors in the order of the request texts.
// Ref: #/components/schemas/EmbeddingResponse
type EmbeddingResponse struct {
Model EmbeddingModel `json:"model"`
Kind EmbeddingInputKind `json:"kind"`
Vectors []EmbeddingVector `json:"vectors"`
}
// GetModel returns the value of Model.
func (s *EmbeddingResponse) GetModel() EmbeddingModel {
return s.Model
}
// GetKind returns the value of Kind.
func (s *EmbeddingResponse) GetKind() EmbeddingInputKind {
return s.Kind
}
// GetVectors returns the value of Vectors.
func (s *EmbeddingResponse) GetVectors() []EmbeddingVector {
return s.Vectors
}
// SetModel sets the value of Model.
func (s *EmbeddingResponse) SetModel(val EmbeddingModel) {
s.Model = val
}
// SetKind sets the value of Kind.
func (s *EmbeddingResponse) SetKind(val EmbeddingInputKind) {
s.Kind = val
}
// SetVectors sets the value of Vectors.
func (s *EmbeddingResponse) SetVectors(val []EmbeddingVector) {
s.Vectors = val
}
func (*EmbeddingResponse) createMLEmbeddingsRes() {}
type EmbeddingText string
type EmbeddingVector []float32
type GetMLReadyzOK MLReadinessResponse
func (*GetMLReadyzOK) getMLReadyzRes() {}
@@ -297,6 +514,8 @@ func (s *Problem) SetErrors(val []ProblemFieldError) {
// - rate_limited (429): too many requests; see Retry-After.
// - internal (500): unexpected server error.
// - not_implemented (501): the operation is in the contract but not implemented yet.
// - service_unavailable (503): the service cannot serve the request now, for example while a model
// loads; retry later.
//
// The enum keeps the public API codes so both contracts share one Problem shape. The identity codes
// verification_token_invalid, verification_token_expired, invalid_credentials, email_not_verified, and
@@ -325,6 +544,7 @@ const (
ProblemCodeRateLimited ProblemCode = "rate_limited"
ProblemCodeInternal ProblemCode = "internal"
ProblemCodeNotImplemented ProblemCode = "not_implemented"
ProblemCodeServiceUnavailable ProblemCode = "service_unavailable"
)
// AllValues returns all ProblemCode values.
@@ -350,6 +570,7 @@ func (ProblemCode) AllValues() []ProblemCode {
ProblemCodeRateLimited,
ProblemCodeInternal,
ProblemCodeNotImplemented,
ProblemCodeServiceUnavailable,
}
}
@@ -396,6 +617,8 @@ func (s ProblemCode) MarshalText() ([]byte, error) {
return []byte(s), nil
case ProblemCodeNotImplemented:
return []byte(s), nil
case ProblemCodeServiceUnavailable:
return []byte(s), nil
default:
return nil, errors.Errorf("invalid value: %q", s)
}
@@ -464,6 +687,9 @@ func (s *ProblemCode) UnmarshalText(data []byte) error {
case ProblemCodeNotImplemented:
*s = ProblemCodeNotImplemented
return nil
case ProblemCodeServiceUnavailable:
*s = ProblemCodeServiceUnavailable
return nil
default:
return errors.Errorf("invalid value: %q", data)
}
@@ -9,6 +9,376 @@ import (
"github.com/ogen-go/ogen/validate"
)
func (s *CreateMLEmbeddingsBadRequest) Validate() error {
alias := (*ProblemStatusCode)(s)
if err := alias.Validate(); err != nil {
return err
}
return nil
}
func (s *CreateMLEmbeddingsRequestEntityTooLarge) Validate() error {
alias := (*ProblemStatusCode)(s)
if err := alias.Validate(); err != nil {
return err
}
return nil
}
func (s *CreateMLEmbeddingsServiceUnavailable) Validate() error {
alias := (*ProblemStatusCode)(s)
if err := alias.Validate(); err != nil {
return err
}
return nil
}
func (s EmbeddingInputKind) Validate() error {
switch s {
case "query":
return nil
case "document":
return nil
default:
return errors.Errorf("invalid value: %v", s)
}
}
func (s *EmbeddingModel) Validate() error {
if s == nil {
return validate.ErrNilPointer
}
var failures []validate.FieldError
if err := func() error {
if err := (validate.String{
MinLength: 1,
MinLengthSet: true,
MaxLength: 200,
MaxLengthSet: true,
Email: false,
Hostname: false,
Regex: regexMap["^[A-Za-z0-9._/-]+$"],
MinNumeric: 0,
MinNumericSet: false,
MaxNumeric: 0,
MaxNumericSet: false,
}).Validate(string(s.ID)); err != nil {
return errors.Wrap(err, "string")
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "id",
Error: err,
})
}
if err := func() error {
if err := (validate.String{
MinLength: 1,
MinLengthSet: true,
MaxLength: 64,
MaxLengthSet: true,
Email: false,
Hostname: false,
Regex: regexMap["^[A-Za-z0-9._-]+$"],
MinNumeric: 0,
MinNumericSet: false,
MaxNumeric: 0,
MaxNumericSet: false,
}).Validate(string(s.Revision)); err != nil {
return errors.Wrap(err, "string")
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "revision",
Error: err,
})
}
if err := func() error {
if err := (validate.Int{
MinSet: true,
Min: 1,
MaxSet: true,
Max: 4096,
MinExclusive: false,
MaxExclusive: false,
MultipleOfSet: false,
MultipleOf: 0,
Pattern: nil,
}).Validate(int64(s.Dimension)); err != nil {
return errors.Wrap(err, "int")
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "dimension",
Error: err,
})
}
if err := func() error {
if err := (validate.Int{
MinSet: true,
Min: 1,
MaxSet: true,
Max: 32768,
MinExclusive: false,
MaxExclusive: false,
MultipleOfSet: false,
MultipleOf: 0,
Pattern: nil,
}).Validate(int64(s.MaxTokens)); err != nil {
return errors.Wrap(err, "int")
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "max_tokens",
Error: err,
})
}
if err := func() error {
if err := (validate.String{
MinLength: 1,
MinLengthSet: true,
MaxLength: 64,
MaxLengthSet: true,
Email: false,
Hostname: false,
Regex: regexMap["^[a-z0-9._-]+$"],
MinNumeric: 0,
MinNumericSet: false,
MaxNumeric: 0,
MaxNumericSet: false,
}).Validate(string(s.PromptVersion)); err != nil {
return errors.Wrap(err, "string")
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "prompt_version",
Error: err,
})
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
}
return nil
}
func (s *EmbeddingRequest) Validate() error {
if s == nil {
return validate.ErrNilPointer
}
var failures []validate.FieldError
if err := func() error {
if value, ok := s.Model.Get(); ok {
if err := func() error {
if err := (validate.String{
MinLength: 1,
MinLengthSet: true,
MaxLength: 200,
MaxLengthSet: true,
Email: false,
Hostname: false,
Regex: regexMap["^[A-Za-z0-9._/-]+$"],
MinNumeric: 0,
MinNumericSet: false,
MaxNumeric: 0,
MaxNumericSet: false,
}).Validate(string(value)); err != nil {
return errors.Wrap(err, "string")
}
return nil
}(); err != nil {
return err
}
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "model",
Error: err,
})
}
if err := func() error {
if err := s.Kind.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "kind",
Error: err,
})
}
if err := func() error {
if s.Texts == nil {
return errors.New("nil is invalid value")
}
if err := (validate.Array{
MinLength: 1,
MinLengthSet: true,
MaxLength: 32,
MaxLengthSet: true,
}).ValidateLength(len(s.Texts)); err != nil {
return errors.Wrap(err, "array")
}
var failures []validate.FieldError
for i, elem := range s.Texts {
if err := func() error {
if err := elem.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: fmt.Sprintf("[%d]", i),
Error: err,
})
}
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "texts",
Error: err,
})
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
}
return nil
}
func (s *EmbeddingResponse) Validate() error {
if s == nil {
return validate.ErrNilPointer
}
var failures []validate.FieldError
if err := func() error {
if err := s.Model.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "model",
Error: err,
})
}
if err := func() error {
if err := s.Kind.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "kind",
Error: err,
})
}
if err := func() error {
if s.Vectors == nil {
return errors.New("nil is invalid value")
}
if err := (validate.Array{
MinLength: 1,
MinLengthSet: true,
MaxLength: 32,
MaxLengthSet: true,
}).ValidateLength(len(s.Vectors)); err != nil {
return errors.Wrap(err, "array")
}
var failures []validate.FieldError
for i, elem := range s.Vectors {
if err := func() error {
if err := elem.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: fmt.Sprintf("[%d]", i),
Error: err,
})
}
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "vectors",
Error: err,
})
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
}
return nil
}
func (s EmbeddingText) Validate() error {
alias := (string)(s)
if err := (validate.String{
MinLength: 1,
MinLengthSet: true,
MaxLength: 8000,
MaxLengthSet: true,
Email: false,
Hostname: false,
Regex: nil,
MinNumeric: 0,
MinNumericSet: false,
MaxNumeric: 0,
MaxNumericSet: false,
}).Validate(string(alias)); err != nil {
return errors.Wrap(err, "string")
}
return nil
}
func (s EmbeddingVector) Validate() error {
alias := ([]float32)(s)
if alias == nil {
return errors.New("nil is invalid value")
}
if err := (validate.Array{
MinLength: 1,
MinLengthSet: true,
MaxLength: 4096,
MaxLengthSet: true,
}).ValidateLength(len(alias)); err != nil {
return errors.Wrap(err, "array")
}
var failures []validate.FieldError
for i, elem := range alias {
if err := func() error {
if err := (validate.Float{}).Validate(float64(elem)); err != nil {
return errors.Wrap(err, "float")
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: fmt.Sprintf("[%d]", i),
Error: err,
})
}
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
}
return nil
}
func (s *GetMLReadyzOK) Validate() error {
alias := (*MLReadinessResponse)(s)
if err := alias.Validate(); err != nil {
@@ -349,6 +719,8 @@ func (s ProblemCode) Validate() error {
return nil
case "not_implemented":
return nil
case "service_unavailable":
return nil
default:
return errors.Errorf("invalid value: %v", s)
}
@@ -0,0 +1,228 @@
// Package ml is the client of the internal ML service. The generated ogen
// client in ./api carries the contract; this adapter adds the request
// timeout, a response size cap, a circuit breaker, batching, and the checks
// that turn the response into domain vectors.
package ml
import (
"context"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"sync"
"time"
"lincodex/backend/internal/adapter/secondary/ml/api"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
const (
// maxResponseBytes caps one response: 32 vectors of 4096 floats as JSON
// stay far below it.
maxResponseBytes = 16 << 20
// maxTextRunes is the contract bound of one text; longer texts are cut
// before they are sent, the model truncates at its token limit anyway.
maxTextRunes = 8000
)
// Settings configure the client.
type Settings struct {
// BaseURL is the ML service origin, for example http://ml:8000.
BaseURL string
// Timeout bounds one HTTP request.
Timeout time.Duration
// FailureThreshold consecutive failures open the circuit for OpenDuration.
FailureThreshold int
OpenDuration time.Duration
}
// Embedder implements outbound.TextEmbedder over HTTP.
type Embedder struct {
client *api.Client
breaker *breaker
}
var _ outbound.TextEmbedder = (*Embedder)(nil)
// NewEmbedder validates the settings and builds the client. Nothing connects.
func NewEmbedder(settings Settings, clock func() time.Time) (*Embedder, error) {
const location = "ml.NewEmbedder"
parsed, err := url.Parse(settings.BaseURL)
if err != nil || (parsed.Scheme != "http" && parsed.Scheme != "https") || parsed.Host == "" || parsed.User != nil {
return nil, errors.New(location + " - ML service URL must be an http or https origin without credentials")
}
if settings.Timeout <= 0 || settings.FailureThreshold < 1 || settings.OpenDuration <= 0 || clock == nil {
return nil, errors.New(location + " - timeout, failure threshold, open duration, and clock must be set")
}
httpClient := &http.Client{
Timeout: settings.Timeout,
Transport: limitedTransport{next: http.DefaultTransport},
// The service is a fixed internal origin; a redirect is never expected.
CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse },
}
client, err := api.NewClient(parsed.String(), api.WithClient(httpClient))
if err != nil {
return nil, fmt.Errorf("%s - create client: %w", location, err)
}
return &Embedder{
client: client,
breaker: &breaker{threshold: settings.FailureThreshold, open: settings.OpenDuration, clock: clock},
}, nil
}
// Embed encodes texts with the named model in contract-sized batches and
// checks that every batch came from the same model. The caller compares the
// returned identity with the one it expects.
func (embedder *Embedder) Embed(
ctx context.Context, modelID string, kind outbound.EmbeddingKind, texts []string,
) (domain.SemanticModel, []domain.SemanticVector, error) {
const location = "ml.Embedder.Embed"
var model domain.SemanticModel
vectors := make([]domain.SemanticVector, 0, len(texts))
for start := 0; start < len(texts); start += outbound.MaxEmbeddingBatch {
end := min(start+outbound.MaxEmbeddingBatch, len(texts))
batchModel, batch, err := embedder.embedBatch(ctx, modelID, kind, texts[start:end])
if err != nil {
return domain.SemanticModel{}, nil, fmt.Errorf("%s - encode batch: %w", location, err)
}
if start > 0 && batchModel != model {
return domain.SemanticModel{}, nil, fmt.Errorf("%s - the model changed between batches: %w", location, outbound.ErrEmbedderUnavailable)
}
model = batchModel
vectors = append(vectors, batch...)
}
return model, vectors, nil
}
func (embedder *Embedder) embedBatch(
ctx context.Context, modelID string, kind outbound.EmbeddingKind, texts []string,
) (domain.SemanticModel, []domain.SemanticVector, error) {
if len(texts) == 0 {
return domain.SemanticModel{}, nil, nil
}
if !embedder.breaker.allow() {
return domain.SemanticModel{}, nil, fmt.Errorf("circuit is open: %w", outbound.ErrEmbedderUnavailable)
}
request := &api.EmbeddingRequest{
Model: api.NewOptString(modelID), Kind: api.EmbeddingInputKind(kind), Texts: make([]api.EmbeddingText, 0, len(texts)),
}
for _, text := range texts {
request.Texts = append(request.Texts, api.EmbeddingText(cutRunes(text, maxTextRunes)))
}
result, err := embedder.client.CreateMLEmbeddings(ctx, request)
if err != nil {
embedder.breaker.failure()
// The client error can quote the URL but never the request body.
return domain.SemanticModel{}, nil, fmt.Errorf("call the ML service: %w", outbound.ErrEmbedderUnavailable)
}
switch response := result.(type) {
case *api.EmbeddingResponse:
model, vectors, err := decodeResponse(response, kind, len(texts))
if err != nil {
embedder.breaker.failure()
return domain.SemanticModel{}, nil, err
}
embedder.breaker.success()
return model, vectors, nil
case *api.CreateMLEmbeddingsServiceUnavailable:
embedder.breaker.failure()
return domain.SemanticModel{}, nil, fmt.Errorf("the ML service is not ready: %w", outbound.ErrEmbedderUnavailable)
default:
// 400 or 413: the request breaks the contract or names a model the
// service does not serve, and a repeat cannot fix it.
embedder.breaker.success()
return domain.SemanticModel{}, nil, fmt.Errorf("the ML service refused the request: %w", outbound.ErrEmbedderRejected)
}
}
func decodeResponse(response *api.EmbeddingResponse, kind outbound.EmbeddingKind, count int) (domain.SemanticModel, []domain.SemanticVector, error) {
model := domain.SemanticModel{
ID: response.Model.ID, Revision: response.Model.Revision, PromptVersion: response.Model.PromptVersion,
}
if err := model.Validate(); err != nil || string(response.Kind) != string(kind) || len(response.Vectors) != count {
return domain.SemanticModel{}, nil, fmt.Errorf("the response does not match the request: %w", outbound.ErrEmbedderRejected)
}
vectors := make([]domain.SemanticVector, 0, count)
for _, raw := range response.Vectors {
if len(raw) != int(response.Model.Dimension) {
return domain.SemanticModel{}, nil, fmt.Errorf("a vector has the wrong dimension: %w", outbound.ErrEmbedderRejected)
}
vector, err := domain.NewSemanticVector(raw)
if err != nil {
return domain.SemanticModel{}, nil, fmt.Errorf("a vector is invalid: %w", outbound.ErrEmbedderRejected)
}
vectors = append(vectors, vector)
}
return model, vectors, nil
}
func cutRunes(text string, limit int) string {
runes := []rune(text)
if len(runes) <= limit {
return text
}
return string(runes[:limit])
}
// limitedTransport caps the bytes read from a response body.
type limitedTransport struct {
next http.RoundTripper
}
func (transport limitedTransport) RoundTrip(request *http.Request) (*http.Response, error) {
response, err := transport.next.RoundTrip(request)
if err != nil {
return nil, err
}
response.Body = limitedBody{Reader: io.LimitReader(response.Body, maxResponseBytes), Closer: response.Body}
return response, nil
}
type limitedBody struct {
io.Reader
io.Closer
}
// breaker opens after threshold consecutive failures and lets one probe
// through after the open duration; a success closes it.
type breaker struct {
mutex sync.Mutex
threshold int
open time.Duration
clock func() time.Time
failures int
openUntil time.Time
probing bool
}
func (circuit *breaker) allow() bool {
circuit.mutex.Lock()
defer circuit.mutex.Unlock()
if circuit.failures < circuit.threshold {
return true
}
if circuit.clock().Before(circuit.openUntil) || circuit.probing {
return false
}
circuit.probing = true
return true
}
func (circuit *breaker) success() {
circuit.mutex.Lock()
defer circuit.mutex.Unlock()
circuit.failures, circuit.probing = 0, false
}
func (circuit *breaker) failure() {
circuit.mutex.Lock()
defer circuit.mutex.Unlock()
circuit.failures++
circuit.probing = false
if circuit.failures >= circuit.threshold {
circuit.openUntil = circuit.clock().Add(circuit.open)
}
}
@@ -0,0 +1,145 @@
package ml
import (
"context"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"time"
"lincodex/backend/internal/port/outbound"
)
type fakeService struct {
mutex sync.Mutex
requests int
batches []int
models []string
respond func(writer http.ResponseWriter, kind string, texts []string)
}
func (service *fakeService) ServeHTTP(writer http.ResponseWriter, request *http.Request) {
var body struct {
Model string `json:"model"`
Kind string `json:"kind"`
Texts []string `json:"texts"`
}
_ = json.NewDecoder(request.Body).Decode(&body)
service.mutex.Lock()
service.requests++
service.batches = append(service.batches, len(body.Texts))
service.models = append(service.models, body.Model)
service.mutex.Unlock()
service.respond(writer, body.Kind, body.Texts)
}
func validResponse(writer http.ResponseWriter, kind string, texts []string) {
vectors := make([][]float32, 0, len(texts))
for range texts {
vectors = append(vectors, []float32{0.6, 0.8})
}
writer.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(writer).Encode(map[string]any{
"model": map[string]any{"id": "example/model", "revision": "abc", "dimension": 2, "max_tokens": 1024, "prompt_version": "v1"},
"kind": kind, "vectors": vectors,
})
}
func newTestEmbedder(t *testing.T, service *fakeService, clock func() time.Time) *Embedder {
t.Helper()
server := httptest.NewServer(service)
t.Cleanup(server.Close)
embedder, err := NewEmbedder(Settings{BaseURL: server.URL, Timeout: time.Second, FailureThreshold: 2, OpenDuration: time.Minute}, clock)
if err != nil {
t.Fatalf("NewEmbedder() error = %v", err)
}
return embedder
}
func TestEmbedSplitsBatchesAndChecksTheResponse(t *testing.T) {
service := &fakeService{respond: validResponse}
embedder := newTestEmbedder(t, service, time.Now)
texts := make([]string, 40)
for index := range texts {
texts[index] = "text"
}
model, vectors, err := embedder.Embed(context.Background(), "example/model", outbound.EmbeddingDocument, texts)
if err != nil || len(vectors) != 40 || model.ID != "example/model" || model.PromptVersion != "v1" {
t.Fatalf("Embed() = %+v, %d vectors, %v", model, len(vectors), err)
}
if len(service.batches) != 2 || service.batches[0] != outbound.MaxEmbeddingBatch || service.batches[1] != 8 {
t.Fatalf("batches = %v, want 32 and 8", service.batches)
}
if strings.Join(service.models, ",") != "example/model,example/model" {
t.Fatalf("requested models = %v, want the named model in every batch", service.models)
}
}
func TestEmbedRejectsResponsesThatBreakTheContract(t *testing.T) {
for name, respond := range map[string]func(http.ResponseWriter, string, []string){
"too few vectors": func(writer http.ResponseWriter, kind string, texts []string) { validResponse(writer, kind, texts[:1]) },
"not normalized": func(writer http.ResponseWriter, kind string, _ []string) {
writer.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(writer).Encode(map[string]any{
"model": map[string]any{"id": "m/x", "revision": "r", "dimension": 2, "max_tokens": 1, "prompt_version": "v"},
"kind": kind, "vectors": [][]float32{{1, 1}, {1, 1}},
})
},
"bad request": func(writer http.ResponseWriter, _ string, _ []string) {
writer.Header().Set("Content-Type", "application/problem+json")
writer.WriteHeader(http.StatusBadRequest)
_, _ = writer.Write([]byte(`{"type":"urn:lincodex:problem:validation_failed","title":"x","status":400,"code":"validation_failed"}`))
},
} {
embedder := newTestEmbedder(t, &fakeService{respond: respond}, time.Now)
if _, _, err := embedder.Embed(context.Background(), "example/model", outbound.EmbeddingQuery, []string{"a", "b"}); !errors.Is(err, outbound.ErrEmbedderRejected) {
t.Errorf("%s: error = %v, want ErrEmbedderRejected", name, err)
}
}
}
func TestEmbedOpensTheCircuitAfterRepeatedFailures(t *testing.T) {
now := time.Date(2026, 10, 11, 12, 0, 0, 0, time.UTC)
clock := func() time.Time { return now }
service := &fakeService{respond: func(writer http.ResponseWriter, _ string, _ []string) {
writer.Header().Set("Content-Type", "application/problem+json")
writer.WriteHeader(http.StatusServiceUnavailable)
_, _ = writer.Write([]byte(`{"type":"urn:lincodex:problem:service_unavailable","title":"x","status":503,"code":"service_unavailable"}`))
}}
embedder := newTestEmbedder(t, service, clock)
for range 3 {
if _, _, err := embedder.Embed(context.Background(), "example/model", outbound.EmbeddingQuery, []string{"a"}); !errors.Is(err, outbound.ErrEmbedderUnavailable) {
t.Fatalf("error = %v, want ErrEmbedderUnavailable", err)
}
}
if service.requests != 2 {
t.Fatalf("requests = %d, want the circuit to stop calling after 2 failures", service.requests)
}
now = now.Add(2 * time.Minute)
service.respond = validResponse
if _, _, err := embedder.Embed(context.Background(), "example/model", outbound.EmbeddingQuery, []string{"a"}); err != nil {
t.Fatalf("probe after the open duration error = %v", err)
}
}
func TestEmbedNeverQuotesTextsInErrors(t *testing.T) {
embedder := newTestEmbedder(t, &fakeService{respond: func(writer http.ResponseWriter, _ string, _ []string) {
writer.WriteHeader(http.StatusInternalServerError)
}}, time.Now)
_, _, err := embedder.Embed(context.Background(), "example/model", outbound.EmbeddingDocument, []string{"Jane Doe private summary"})
if err == nil || strings.Contains(err.Error(), "Jane") {
t.Fatalf("error = %v, want a failure without the text", err)
}
}
func TestNewEmbedderRejectsUnsafeURLs(t *testing.T) {
for _, raw := range []string{"", "ftp://ml:8000", "http://user:secret@ml:8000", "ml:8000"} {
if _, err := NewEmbedder(Settings{BaseURL: raw, Timeout: time.Second, FailureThreshold: 1, OpenDuration: time.Second}, time.Now); err == nil {
t.Errorf("NewEmbedder(%q) accepted the URL", raw)
}
}
}
@@ -57,6 +57,9 @@ type privacyCohortCandidate struct {
acknowledgements []domain.ProfileParallelPeriodAcknowledgement
workFormats []domain.QuestionnaireWorkFormat
categories []domain.CandidateViewConfirmedCategoryInput
// verifiedRepositories holds the keys of the repositories whose latest
// check found them public.
verifiedRepositories map[string]bool
}
func (repository privacyCohortRepository) ListVisibleCandidateViewSources(
@@ -94,6 +97,7 @@ func (repository privacyCohortRepository) ListVisibleCandidateViewSources(
if err != nil {
return nil, fmt.Errorf("%s - restore candidate source: %w", location, err)
}
current.verifiedRepositories = verifiedRepositorySet(row.VerifiedRepositories)
}
if row.Kind.Valid {
claim, err := privacyCohortStoredClaim(row)
@@ -210,11 +214,22 @@ func buildPrivacyCohortSource(candidate privacyCohortCandidate) (domain.Candidat
return domain.CandidateViewSource{}, fmt.Errorf("validate safe profile claims: %w", domain.ErrInvalidCandidateViewSource)
}
return domain.NewCandidateViewSource(
candidate.id, candidate.fields, domain.CandidateViewProfileFromContent(content), candidate.categories,
candidate.workFormats, nil,
candidate.id, candidate.fields,
domain.CandidateViewProfileFromContentWithRepositories(content, candidate.verifiedRepositories),
candidate.categories, candidate.workFormats, nil,
)
}
// verifiedRepositorySet turns the keys of the verified repositories of one
// candidate into a set.
func verifiedRepositorySet(keys []string) map[string]bool {
set := make(map[string]bool, len(keys))
for _, key := range keys {
set[key] = true
}
return set
}
func privacyCohortJSONBytes(value any) ([]byte, error) {
switch typed := value.(type) {
case []byte:
@@ -134,6 +134,7 @@ func buildPreviewCandidateViewSource(
if err != nil {
return domain.CandidateViewSource{}, fmt.Errorf("%s - restore candidate input: %w", location, err)
}
candidate.verifiedRepositories = verifiedRepositorySet(first.VerifiedRepositories)
for _, row := range rows {
if row.Kind.Valid {
claim, err := previewStoredClaim(row)
@@ -0,0 +1,346 @@
package postgres
import (
"context"
"crypto/sha256"
"encoding/binary"
"errors"
"fmt"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgtype"
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
// SemanticVectors returns the vector repository of the transaction.
func (unit *UnitOfWork) SemanticVectors() outbound.SemanticVectorRepository {
return semanticVectorRepository{queries: unit.queries}
}
// ProjectRepositories returns the repository check store of the transaction.
func (unit *UnitOfWork) ProjectRepositories() outbound.ProjectRepositoryStore {
return projectRepositoryStore{queries: unit.queries}
}
type semanticVectorRepository struct {
queries *sqlc.Queries
}
func subjectColumns(kind domain.SemanticSubjectKind, subjectID uuid.UUID) (pgtype.UUID, pgtype.UUID, error) {
switch kind {
case domain.SemanticSubjectCandidate:
return pgUUID(subjectID), pgtype.UUID{}, nil
case domain.SemanticSubjectNeed:
return pgtype.UUID{}, pgUUID(subjectID), nil
default:
return pgtype.UUID{}, pgtype.UUID{}, fmt.Errorf("postgres.subjectColumns - subject kind is unknown: %w", domain.ErrInvalidSemanticVector)
}
}
func (repository semanticVectorRepository) Replace(
ctx context.Context,
kind domain.SemanticSubjectKind,
subjectID uuid.UUID,
model domain.SemanticModel,
items []outbound.StoredSemanticItem,
at time.Time,
) error {
const location = "semanticVectorRepository.Replace"
candidateID, needID, err := subjectColumns(kind, subjectID)
if err != nil {
return err
}
if err := repository.queries.DeleteSemanticVectorsOfModel(ctx, sqlc.DeleteSemanticVectorsOfModelParams{
SubjectKind: string(kind), SubjectID: pgUUID(subjectID),
ModelID: model.ID, ModelRevision: model.Revision, PromptVersion: model.PromptVersion,
}); err != nil {
return fmt.Errorf("%s - delete previous vectors: %w", location, markTransactionConflict(sanitizeConnectError(err)))
}
for _, item := range items {
if err := repository.queries.InsertSemanticVector(ctx, sqlc.InsertSemanticVectorParams{
SubjectKind: string(kind), SubjectID: pgUUID(subjectID), CandidateID: candidateID, NeedID: needID,
ModelID: model.ID, ModelRevision: model.Revision, PromptVersion: model.PromptVersion,
ItemKey: item.Key, ContentSha256: item.ContentDigest[:], LabelSha256: item.LabelDigest,
Dimension: int32(len(item.Vector)), Vector: item.Vector.Encode(), ComputedAt: pgTime(at), //nolint:gosec // a domain vector has at most 4096 dimensions
}); err != nil {
return fmt.Errorf("%s - insert vector: %w", location, markTransactionConflict(sanitizeConnectError(err)))
}
}
return nil
}
// semanticLockNamespace keeps the advisory lock keys of vector jobs apart
// from any other advisory lock of the database.
const semanticLockNamespace = 0x53454d41 // "SEMA"
func (repository semanticVectorRepository) Lock(ctx context.Context, kind domain.SemanticSubjectKind, subjectID uuid.UUID) error {
digest := sha256.Sum256([]byte(string(kind) + ":" + subjectID.String()))
key := int64(binary.BigEndian.Uint64(digest[:8])>>16) ^ semanticLockNamespace
if err := repository.queries.LockSemanticSubject(ctx, key); err != nil {
return fmt.Errorf("semanticVectorRepository.Lock - take lock: %w", markTransactionConflict(sanitizeConnectError(err)))
}
return nil
}
func (repository semanticVectorRepository) DeleteSubject(ctx context.Context, kind domain.SemanticSubjectKind, subjectID uuid.UUID) error {
if err := repository.queries.DeleteSemanticVectorsOfSubject(ctx, sqlc.DeleteSemanticVectorsOfSubjectParams{
SubjectKind: string(kind), SubjectID: pgUUID(subjectID),
}); err != nil {
return fmt.Errorf("semanticVectorRepository.DeleteSubject - delete vectors: %w", markTransactionConflict(sanitizeConnectError(err)))
}
return nil
}
func (repository semanticVectorRepository) Digests(
ctx context.Context, kind domain.SemanticSubjectKind, subjectID uuid.UUID, model domain.SemanticModel,
) (map[string][32]byte, error) {
rows, err := repository.queries.ListSemanticVectorDigests(ctx, sqlc.ListSemanticVectorDigestsParams{
SubjectKind: string(kind), SubjectID: pgUUID(subjectID),
ModelID: model.ID, ModelRevision: model.Revision, PromptVersion: model.PromptVersion,
})
if err != nil {
return nil, fmt.Errorf("semanticVectorRepository.Digests - select digests: %w", markTransactionConflict(sanitizeConnectError(err)))
}
digests := make(map[string][32]byte, len(rows))
for _, row := range rows {
var digest [32]byte
if len(row.ContentSha256) != len(digest) {
return nil, fmt.Errorf("semanticVectorRepository.Digests - digest length is invalid: %w", domain.ErrInvalidSemanticVector)
}
copy(digest[:], row.ContentSha256)
digests[row.ItemKey] = digest
}
return digests, nil
}
func pgUUIDs(ids []uuid.UUID) []pgtype.UUID {
values := make([]pgtype.UUID, 0, len(ids))
for _, id := range ids {
values = append(values, pgUUID(id))
}
return values
}
func (repository semanticVectorRepository) CandidateWholeVectors(
ctx context.Context, model domain.SemanticModel, candidateIDs []uuid.UUID,
) (map[uuid.UUID]domain.SemanticVector, error) {
const location = "semanticVectorRepository.CandidateWholeVectors"
vectors := make(map[uuid.UUID]domain.SemanticVector)
if len(candidateIDs) == 0 {
return vectors, nil
}
rows, err := repository.queries.ListCandidateWholeVectors(ctx, sqlc.ListCandidateWholeVectorsParams{
ModelID: model.ID, ModelRevision: model.Revision, PromptVersion: model.PromptVersion,
CandidateIds: pgUUIDs(candidateIDs),
})
if err != nil {
return nil, fmt.Errorf("%s - select vectors: %w", location, markTransactionConflict(sanitizeConnectError(err)))
}
for _, row := range rows {
vector, err := domain.DecodeSemanticVector(row.Vector, int(row.Dimension))
if err != nil || !row.CandidateID.Valid {
return nil, fmt.Errorf("%s - stored vector is invalid: %w", location, domain.ErrInvalidSemanticVector)
}
vectors[uuid.UUID(row.CandidateID.Bytes)] = vector
}
return vectors, nil
}
func (repository semanticVectorRepository) CandidateItemVectors(
ctx context.Context, model domain.SemanticModel, candidateIDs []uuid.UUID,
) (map[uuid.UUID][]outbound.SemanticItemVector, error) {
const location = "semanticVectorRepository.CandidateItemVectors"
vectors := make(map[uuid.UUID][]outbound.SemanticItemVector)
if len(candidateIDs) == 0 {
return vectors, nil
}
rows, err := repository.queries.ListCandidateItemVectors(ctx, sqlc.ListCandidateItemVectorsParams{
ModelID: model.ID, ModelRevision: model.Revision, PromptVersion: model.PromptVersion,
CandidateIds: pgUUIDs(candidateIDs),
})
if err != nil {
return nil, fmt.Errorf("%s - select vectors: %w", location, markTransactionConflict(sanitizeConnectError(err)))
}
for _, row := range rows {
vector, err := domain.DecodeSemanticVector(row.Vector, int(row.Dimension))
if err != nil || !row.CandidateID.Valid {
return nil, fmt.Errorf("%s - stored vector is invalid: %w", location, domain.ErrInvalidSemanticVector)
}
id := uuid.UUID(row.CandidateID.Bytes)
vectors[id] = append(vectors[id], outbound.SemanticItemVector{Key: row.ItemKey, LabelDigest: row.LabelSha256, Vector: vector})
}
return vectors, nil
}
func (repository semanticVectorRepository) NeedVectors(
ctx context.Context, needID uuid.UUID, model domain.SemanticModel, digests [][32]byte,
) (map[string]domain.SemanticVector, error) {
const location = "semanticVectorRepository.NeedVectors"
vectors := make(map[string]domain.SemanticVector)
if len(digests) == 0 {
return vectors, nil
}
values := make([][]byte, 0, len(digests))
for _, digest := range digests {
values = append(values, digest[:])
}
rows, err := repository.queries.ListNeedVectors(ctx, sqlc.ListNeedVectorsParams{
NeedID: pgUUID(needID), ModelID: model.ID, ModelRevision: model.Revision, PromptVersion: model.PromptVersion,
ContentDigests: values,
})
if err != nil {
return nil, fmt.Errorf("%s - select vectors: %w", location, markTransactionConflict(sanitizeConnectError(err)))
}
for _, row := range rows {
vector, err := domain.DecodeSemanticVector(row.Vector, int(row.Dimension))
if err != nil {
return nil, fmt.Errorf("%s - stored vector is invalid: %w", location, domain.ErrInvalidSemanticVector)
}
vectors[row.ItemKey] = vector
}
return vectors, nil
}
func (repository semanticVectorRepository) CandidatesAfter(ctx context.Context, after uuid.UUID, limit int) ([]uuid.UUID, error) {
rows, err := repository.queries.ListProfileCandidatesAfter(ctx, sqlc.ListProfileCandidatesAfterParams{
AfterID: pgUUID(after), PageSize: int32(limit), //nolint:gosec // the caller bounds the page size
})
if err != nil {
return nil, fmt.Errorf("semanticVectorRepository.CandidatesAfter - select candidates: %w", markTransactionConflict(sanitizeConnectError(err)))
}
ids := make([]uuid.UUID, 0, len(rows))
for _, row := range rows {
ids = append(ids, uuid.UUID(row.Bytes))
}
return ids, nil
}
func (repository semanticVectorRepository) NeedsAfter(ctx context.Context, after uuid.UUID, limit int) ([]outbound.NeedReference, error) {
rows, err := repository.queries.ListNeedsAfter(ctx, sqlc.ListNeedsAfterParams{
AfterID: pgUUID(after), PageSize: int32(limit), //nolint:gosec // the caller bounds the page size
})
if err != nil {
return nil, fmt.Errorf("semanticVectorRepository.NeedsAfter - select needs: %w", markTransactionConflict(sanitizeConnectError(err)))
}
needs := make([]outbound.NeedReference, 0, len(rows))
for _, row := range rows {
needs = append(needs, outbound.NeedReference{
NeedID: uuid.UUID(row.ID.Bytes), OrganizationID: uuid.UUID(row.OrganizationID.Bytes),
RequirementsVersion: row.RequirementsVersion,
})
}
return needs, nil
}
type projectRepositoryStore struct {
queries *sqlc.Queries
}
func repositoryCheckFromRow(row sqlc.CandidateProjectRepository) outbound.RepositoryCheck {
check := outbound.RepositoryCheck{
Key: row.RepositoryKey, State: outbound.RepositoryCheckState(row.State),
GitHubID: row.GithubID.Int64, RepositoryETag: row.RepositoryEtag.String, ReadmeETag: row.ReadmeEtag.String,
Failure: outbound.RepositoryFailureClass(row.FailureClass.String), RequestedAt: row.RequestedAt.Time.UTC(),
Evidence: domain.RepositoryEvidence{
Description: row.Description.String, Topics: row.Topics, Languages: row.Languages,
ReadmeExcerpt: row.ReadmeExcerpt.String,
},
}
if row.CheckedAt.Valid {
check.CheckedAt = row.CheckedAt.Time.UTC()
}
return check
}
func (store projectRepositoryStore) List(ctx context.Context, candidateID uuid.UUID) ([]outbound.RepositoryCheck, error) {
rows, err := store.queries.ListCandidateProjectRepositories(ctx, pgUUID(candidateID))
if err != nil {
return nil, fmt.Errorf("projectRepositoryStore.List - select checks: %w", markTransactionConflict(sanitizeConnectError(err)))
}
checks := make([]outbound.RepositoryCheck, 0, len(rows))
for _, row := range rows {
checks = append(checks, repositoryCheckFromRow(row))
}
return checks, nil
}
func (store projectRepositoryStore) GetForUpdate(ctx context.Context, candidateID uuid.UUID, key string) (outbound.RepositoryCheck, bool, error) {
row, err := store.queries.GetCandidateProjectRepositoryForUpdate(ctx, sqlc.GetCandidateProjectRepositoryForUpdateParams{
CandidateID: pgUUID(candidateID), RepositoryKey: key,
})
if errors.Is(err, pgx.ErrNoRows) {
return outbound.RepositoryCheck{}, false, nil
}
if err != nil {
return outbound.RepositoryCheck{}, false, fmt.Errorf("projectRepositoryStore.GetForUpdate - select check: %w", markTransactionConflict(sanitizeConnectError(err)))
}
return repositoryCheckFromRow(row), true, nil
}
func (store projectRepositoryStore) Request(ctx context.Context, candidateID uuid.UUID, key string, at time.Time) error {
if err := store.queries.RequestCandidateProjectRepositoryCheck(ctx, sqlc.RequestCandidateProjectRepositoryCheckParams{
CandidateID: pgUUID(candidateID), RepositoryKey: key, RequestedAt: pgTime(at),
}); err != nil {
return fmt.Errorf("projectRepositoryStore.Request - record request: %w", markTransactionConflict(sanitizeConnectError(err)))
}
return nil
}
func optionalPgText(value string) pgtype.Text {
if value == "" {
return pgtype.Text{}
}
return pgText(value)
}
func (store projectRepositoryStore) Save(ctx context.Context, candidateID uuid.UUID, check outbound.RepositoryCheck) error {
params := sqlc.SaveCandidateProjectRepositoryCheckParams{
State: string(check.State), Topics: []string{}, Languages: []string{},
RepositoryEtag: optionalPgText(check.RepositoryETag), ReadmeEtag: optionalPgText(check.ReadmeETag),
FailureClass: optionalPgText(string(check.Failure)), CheckedAt: pgTime(check.CheckedAt),
CandidateID: pgUUID(candidateID), RepositoryKey: check.Key,
}
if check.State == outbound.RepositoryCheckVerified {
params.GithubID = pgtype.Int8{Int64: check.GitHubID, Valid: check.GitHubID > 0}
params.Description = optionalPgText(check.Evidence.Description)
params.ReadmeExcerpt = optionalPgText(check.Evidence.ReadmeExcerpt)
if check.Evidence.Topics != nil {
params.Topics = check.Evidence.Topics
}
if check.Evidence.Languages != nil {
params.Languages = check.Evidence.Languages
}
}
if err := store.queries.SaveCandidateProjectRepositoryCheck(ctx, params); err != nil {
return fmt.Errorf("projectRepositoryStore.Save - store check: %w", markTransactionConflict(sanitizeConnectError(err)))
}
return nil
}
func (store projectRepositoryStore) DeleteUnlinked(ctx context.Context, candidateID uuid.UUID, linkedKeys []string) error {
if linkedKeys == nil {
linkedKeys = []string{}
}
if err := store.queries.DeleteUnlinkedCandidateProjectRepositories(ctx, sqlc.DeleteUnlinkedCandidateProjectRepositoriesParams{
CandidateID: pgUUID(candidateID), LinkedKeys: linkedKeys,
}); err != nil {
return fmt.Errorf("projectRepositoryStore.DeleteUnlinked - delete checks: %w", markTransactionConflict(sanitizeConnectError(err)))
}
return nil
}
func (store projectRepositoryStore) LatestRequest(ctx context.Context, candidateID uuid.UUID) (time.Time, error) {
latest, err := store.queries.GetLatestRepositoryCheckRequest(ctx, pgUUID(candidateID))
if err != nil {
return time.Time{}, fmt.Errorf("projectRepositoryStore.LatestRequest - select request: %w", markTransactionConflict(sanitizeConnectError(err)))
}
if !latest.Valid {
return time.Time{}, nil
}
return latest.Time.UTC(), nil
}
@@ -361,6 +361,24 @@ type CandidateProfileOverlapConfirmation struct {
SecondEndedOn pgtype.Text
}
type CandidateProjectRepository struct {
CandidateID pgtype.UUID
RepositoryKey string
State string
GithubID pgtype.Int8
Description pgtype.Text
Topics []string
Languages []string
ReadmeExcerpt pgtype.Text
RepositoryEtag pgtype.Text
ReadmeEtag pgtype.Text
FailureClass pgtype.Text
CheckedAt pgtype.Timestamptz
RequestedAt pgtype.Timestamptz
CreatedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
}
type CandidatePublication struct {
UserID pgtype.UUID
State string
@@ -838,6 +856,22 @@ type ScheduledJob struct {
UpdatedAt pgtype.Timestamptz
}
type SemanticVector struct {
SubjectKind string
SubjectID pgtype.UUID
CandidateID pgtype.UUID
NeedID pgtype.UUID
ModelID string
ModelRevision string
PromptVersion string
ItemKey string
ContentSha256 []byte
LabelSha256 []byte
Dimension int32
Vector []byte
ComputedAt pgtype.Timestamptz
}
type Session struct {
ID pgtype.UUID
UserID pgtype.UUID
@@ -68,11 +68,21 @@ SELECT
WHERE category.candidate_id = effective.user_id
),
'[]'::text
) AS confirmed_categories
) AS confirmed_categories,
COALESCE(
(
SELECT array_agg(repository.repository_key ORDER BY repository.repository_key)
FROM candidate_project_repositories AS repository
WHERE
repository.candidate_id = effective.user_id
AND repository.state = 'verified'
),
'{}'::text []
)::text [] AS verified_repositories
FROM candidate_effective_publications AS effective
LEFT JOIN candidate_profile_claims AS claim
ON claim.user_id = effective.user_id
AND claim.kind IN ('stack', 'role', 'experience')
AND claim.kind IN ('stack', 'role', 'experience', 'project')
LEFT JOIN candidate_questionnaires AS questionnaire
ON questionnaire.user_id = effective.user_id
WHERE NOT EXISTS (
@@ -98,15 +108,18 @@ type ListVisibleCandidateViewSourcesRow struct {
WorkFormats []string
ParallelPeriodAcknowledgements interface{}
ConfirmedCategories interface{}
VerifiedRepositories []string
}
// Organization-facing anonymous candidate projection inputs. The calling
// usecase has already authorized the active organization membership. This
// single statement snapshot filters both revoked/unpublished C2 states and
// candidates hidden from this organization before any profile value is read.
// The projection reads only stack, declared role, and experience dates. It
// deliberately excludes names, contacts, salary, location, soft skills,
// employer names, summaries, and imported excerpts. The only assessment data
// The projection reads only stack, declared role, experience dates, and
// projects with the keys of their verified repositories. It deliberately
// excludes names, contacts, salary, location, soft skills, employer names,
// summaries, and imported excerpts; the repository address of a project stays
// in the private input and never reaches the card. The only assessment data
// is the current category (specialization and grade) of the separate current
// category table; it carries no attempt, score, review, policy, or history.
func (q *Queries) ListVisibleCandidateViewSources(ctx context.Context, organizationID pgtype.UUID) ([]ListVisibleCandidateViewSourcesRow, error) {
@@ -132,6 +145,7 @@ func (q *Queries) ListVisibleCandidateViewSources(ctx context.Context, organizat
&i.WorkFormats,
&i.ParallelPeriodAcknowledgements,
&i.ConfirmedCategories,
&i.VerifiedRepositories,
); err != nil {
return nil, err
}
@@ -301,11 +315,21 @@ SELECT
WHERE category.candidate_id = effective.user_id
),
'[]'::text
) AS confirmed_categories
) AS confirmed_categories,
COALESCE(
(
SELECT array_agg(repository.repository_key ORDER BY repository.repository_key)
FROM candidate_project_repositories AS repository
WHERE
repository.candidate_id = effective.user_id
AND repository.state = 'verified'
),
'{}'::text []
)::text [] AS verified_repositories
FROM candidate_effective_publications AS effective
LEFT JOIN candidate_profile_claims AS claim
ON claim.user_id = effective.user_id
AND claim.kind IN ('stack', 'role', 'experience')
AND claim.kind IN ('stack', 'role', 'experience', 'project')
LEFT JOIN candidate_questionnaires AS questionnaire
ON questionnaire.user_id = effective.user_id
WHERE effective.user_id = $1
@@ -326,6 +350,7 @@ type ReadCandidateViewSourceForPreviewRow struct {
WorkFormats []string
ParallelPeriodAcknowledgements interface{}
ConfirmedCategories interface{}
VerifiedRepositories []string
}
// Read the candidate's current private projection inputs after the caller
@@ -354,6 +379,7 @@ func (q *Queries) ReadCandidateViewSourceForPreview(ctx context.Context, candida
&i.WorkFormats,
&i.ParallelPeriodAcknowledgements,
&i.ConfirmedCategories,
&i.VerifiedRepositories,
); err != nil {
return nil, err
}
@@ -0,0 +1,206 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
// source: project_repositories.sql
package sqlc
import (
"context"
"github.com/jackc/pgx/v5/pgtype"
)
const deleteUnlinkedCandidateProjectRepositories = `-- name: DeleteUnlinkedCandidateProjectRepositories :exec
DELETE FROM candidate_project_repositories
WHERE
candidate_id = $1
AND NOT (repository_key = ANY($2::text []))
`
type DeleteUnlinkedCandidateProjectRepositoriesParams struct {
CandidateID pgtype.UUID
LinkedKeys []string
}
// Removes the checks of repositories that no project links any more.
func (q *Queries) DeleteUnlinkedCandidateProjectRepositories(ctx context.Context, arg DeleteUnlinkedCandidateProjectRepositoriesParams) error {
_, err := q.db.Exec(ctx, deleteUnlinkedCandidateProjectRepositories, arg.CandidateID, arg.LinkedKeys)
return err
}
const getCandidateProjectRepositoryForUpdate = `-- name: GetCandidateProjectRepositoryForUpdate :one
SELECT
candidate_id, repository_key, state, github_id, description, topics,
languages, readme_excerpt, repository_etag, readme_etag, failure_class,
checked_at, requested_at, created_at, updated_at
FROM candidate_project_repositories
WHERE candidate_id = $1 AND repository_key = $2
FOR UPDATE
`
type GetCandidateProjectRepositoryForUpdateParams struct {
CandidateID pgtype.UUID
RepositoryKey string
}
func (q *Queries) GetCandidateProjectRepositoryForUpdate(ctx context.Context, arg GetCandidateProjectRepositoryForUpdateParams) (CandidateProjectRepository, error) {
row := q.db.QueryRow(ctx, getCandidateProjectRepositoryForUpdate, arg.CandidateID, arg.RepositoryKey)
var i CandidateProjectRepository
err := row.Scan(
&i.CandidateID,
&i.RepositoryKey,
&i.State,
&i.GithubID,
&i.Description,
&i.Topics,
&i.Languages,
&i.ReadmeExcerpt,
&i.RepositoryEtag,
&i.ReadmeEtag,
&i.FailureClass,
&i.CheckedAt,
&i.RequestedAt,
&i.CreatedAt,
&i.UpdatedAt,
)
return i, err
}
const getLatestRepositoryCheckRequest = `-- name: GetLatestRepositoryCheckRequest :one
SELECT MAX(requested_at)::timestamptz AS requested_at
FROM candidate_project_repositories
WHERE candidate_id = $1
`
// The latest check request of a candidate, for the per-candidate limit.
func (q *Queries) GetLatestRepositoryCheckRequest(ctx context.Context, candidateID pgtype.UUID) (pgtype.Timestamptz, error) {
row := q.db.QueryRow(ctx, getLatestRepositoryCheckRequest, candidateID)
var requested_at pgtype.Timestamptz
err := row.Scan(&requested_at)
return requested_at, err
}
const listCandidateProjectRepositories = `-- name: ListCandidateProjectRepositories :many
SELECT
candidate_id, repository_key, state, github_id, description, topics,
languages, readme_excerpt, repository_etag, readme_etag, failure_class,
checked_at, requested_at, created_at, updated_at
FROM candidate_project_repositories
WHERE candidate_id = $1
ORDER BY repository_key
`
// Server checks of the GitHub repositories that candidate projects link.
// Every statement is scoped by the candidate.
func (q *Queries) ListCandidateProjectRepositories(ctx context.Context, candidateID pgtype.UUID) ([]CandidateProjectRepository, error) {
rows, err := q.db.Query(ctx, listCandidateProjectRepositories, candidateID)
if err != nil {
return nil, err
}
defer rows.Close()
var items []CandidateProjectRepository
for rows.Next() {
var i CandidateProjectRepository
if err := rows.Scan(
&i.CandidateID,
&i.RepositoryKey,
&i.State,
&i.GithubID,
&i.Description,
&i.Topics,
&i.Languages,
&i.ReadmeExcerpt,
&i.RepositoryEtag,
&i.ReadmeEtag,
&i.FailureClass,
&i.CheckedAt,
&i.RequestedAt,
&i.CreatedAt,
&i.UpdatedAt,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const requestCandidateProjectRepositoryCheck = `-- name: RequestCandidateProjectRepositoryCheck :exec
INSERT INTO candidate_project_repositories (
candidate_id, repository_key, state, requested_at, created_at, updated_at
) VALUES (
$1, $2, 'pending', $3,
$3, $3
)
ON CONFLICT (candidate_id, repository_key) DO UPDATE
SET
requested_at = excluded.requested_at,
updated_at = GREATEST(candidate_project_repositories.updated_at, excluded.updated_at)
`
type RequestCandidateProjectRepositoryCheckParams struct {
CandidateID pgtype.UUID
RepositoryKey string
RequestedAt pgtype.Timestamptz
}
// A new repository starts pending; a known one only records the request.
func (q *Queries) RequestCandidateProjectRepositoryCheck(ctx context.Context, arg RequestCandidateProjectRepositoryCheckParams) error {
_, err := q.db.Exec(ctx, requestCandidateProjectRepositoryCheck, arg.CandidateID, arg.RepositoryKey, arg.RequestedAt)
return err
}
const saveCandidateProjectRepositoryCheck = `-- name: SaveCandidateProjectRepositoryCheck :exec
UPDATE candidate_project_repositories
SET
state = $1,
github_id = $2,
description = $3,
topics = $4,
languages = $5,
readme_excerpt = $6,
repository_etag = $7,
readme_etag = $8,
failure_class = $9,
checked_at = $10,
updated_at = GREATEST(updated_at, $10)
WHERE candidate_id = $11 AND repository_key = $12
`
type SaveCandidateProjectRepositoryCheckParams struct {
State string
GithubID pgtype.Int8
Description pgtype.Text
Topics []string
Languages []string
ReadmeExcerpt pgtype.Text
RepositoryEtag pgtype.Text
ReadmeEtag pgtype.Text
FailureClass pgtype.Text
CheckedAt pgtype.Timestamptz
CandidateID pgtype.UUID
RepositoryKey string
}
func (q *Queries) SaveCandidateProjectRepositoryCheck(ctx context.Context, arg SaveCandidateProjectRepositoryCheckParams) error {
_, err := q.db.Exec(ctx, saveCandidateProjectRepositoryCheck,
arg.State,
arg.GithubID,
arg.Description,
arg.Topics,
arg.Languages,
arg.ReadmeExcerpt,
arg.RepositoryEtag,
arg.ReadmeEtag,
arg.FailureClass,
arg.CheckedAt,
arg.CandidateID,
arg.RepositoryKey,
)
return err
}
@@ -217,9 +217,19 @@ type Querier interface {
DeleteExpiredCompanyCardViewQuotaUsage(ctx context.Context, arg DeleteExpiredCompanyCardViewQuotaUsageParams) (int64, error)
DeleteMailRequest(ctx context.Context, id pgtype.UUID) (int64, error)
DeleteOrganizationRepresentatives(ctx context.Context, organizationID pgtype.UUID) error
// Stored embedding vectors. A candidate keeps one set of rows for a model:
// the job deletes every other row of the candidate and model before it
// inserts the new set, in one transaction. A need keeps the rows of its
// latest computed requirements snapshot the same way.
DeleteSemanticVectorsOfModel(ctx context.Context, arg DeleteSemanticVectorsOfModelParams) error
// Removes every vector of a subject, of any model: a closed card or a need
// without requirements keeps no derived data.
DeleteSemanticVectorsOfSubject(ctx context.Context, arg DeleteSemanticVectorsOfSubjectParams) error
// No raw Idempotency-Key or request body reaches these statements. Failure
// responses pass {} as case_snapshot and the CASE stores SQL NULL instead.
DeleteSupportCaseCreateOutcome(ctx context.Context, scopeHash []byte) error
// Removes the checks of repositories that no project links any more.
DeleteUnlinkedCandidateProjectRepositories(ctx context.Context, arg DeleteUnlinkedCandidateProjectRepositoriesParams) error
// Deletes one batch of accounts that stayed unverified since before cutoff,
// oldest first, with their tokens, sessions, mail requests, mail deliveries
// (and through the deliveries their attempts), and consent records. The
@@ -314,6 +324,7 @@ type Querier interface {
// Reads one hiding of the candidate with the current name of the
// organization.
GetCandidateHiddenOrganization(ctx context.Context, arg GetCandidateHiddenOrganizationParams) (GetCandidateHiddenOrganizationRow, error)
GetCandidateProjectRepositoryForUpdate(ctx context.Context, arg GetCandidateProjectRepositoryForUpdateParams) (CandidateProjectRepository, error)
GetConsentText(ctx context.Context, arg GetConsentTextParams) (ConsentText, error)
GetContactConsentRecordByInvitation(ctx context.Context, arg GetContactConsentRecordByInvitationParams) (GetContactConsentRecordByInvitationRow, error)
// Read the grant of one invitation of one organization. An invitation of
@@ -374,6 +385,8 @@ type Querier interface {
// resend, which issues its token with the same credentials.
GetLatestPendingRegistration(ctx context.Context, arg GetLatestPendingRegistrationParams) (GetLatestPendingRegistrationRow, error)
GetLatestPolicyVersion(ctx context.Context, policyKey string) (PolicyVersion, error)
// The latest check request of a candidate, for the per-candidate limit.
GetLatestRepositoryCheckRequest(ctx context.Context, candidateID pgtype.UUID) (pgtype.Timestamptz, error)
// Reads the latest root in a specialization, optionally restricted to grade.
GetLatestRootAssessmentAttempt(ctx context.Context, arg GetLatestRootAssessmentAttemptParams) (AssessmentAttempt, error)
GetLiveIdempotencyRecord(ctx context.Context, arg GetLiveIdempotencyRecordParams) (IdempotencyRecord, error)
@@ -599,6 +612,7 @@ type Querier interface {
// moves a deadline. A concurrent insert of the same key waits for the first
// transaction and then inserts nothing, or inserts after its rollback.
InsertScheduledJob(ctx context.Context, arg InsertScheduledJobParams) (int64, error)
InsertSemanticVector(ctx context.Context, arg InsertSemanticVectorParams) error
InsertSession(ctx context.Context, arg InsertSessionParams) error
// The initial public history is inserted in the caller's case transaction.
// Any unique business conflict leaves the transaction usable so the caller can
@@ -687,6 +701,9 @@ type Querier interface {
// have no delivery and are never listed. The candidate scopes the rows, so
// no identifier of another candidate can appear.
ListCandidateInvitations(ctx context.Context, arg ListCandidateInvitationsParams) ([]ListCandidateInvitationsRow, error)
// The item vectors of the candidates that a search returns, at most a few
// dozen candidates.
ListCandidateItemVectors(ctx context.Context, arg ListCandidateItemVectorsParams) ([]ListCandidateItemVectorsRow, error)
// The same selection for the candidate's own card preview, so the candidate
// sees what an organization would read. It is scoped by the owner and runs
// after the caller locked the effective C2 and publication; it does not apply
@@ -697,6 +714,11 @@ type Querier interface {
// read time, and is the current name. The page continues after the
// (occurred_at, id) position of the last event of the previous page.
ListCandidatePrivacyEvents(ctx context.Context, arg ListCandidatePrivacyEventsParams) ([]ListCandidatePrivacyEventsRow, error)
// Server checks of the GitHub repositories that candidate projects link.
// Every statement is scoped by the candidate.
ListCandidateProjectRepositories(ctx context.Context, candidateID pgtype.UUID) ([]CandidateProjectRepository, error)
// The whole-view vectors of the candidates of one search.
ListCandidateWholeVectors(ctx context.Context, arg ListCandidateWholeVectorsParams) ([]ListCandidateWholeVectorsRow, error)
// One page of the subject's ledger, newest grant first, optionally limited
// to one state. Every record query is scoped by the subject, so a caller
// never reads or revokes another subject's consent. The state is computed,
@@ -721,6 +743,11 @@ type Querier interface {
// One bounded newest-first page. Both the organization scope and the tuple
// cursor are applied before the limit.
ListInvitations(ctx context.Context, arg ListInvitationsParams) ([]ListInvitationsRow, error)
// The vectors of a need whose texts match the given digests of the
// requirements snapshot that the search renders.
ListNeedVectors(ctx context.Context, arg ListNeedVectorsParams) ([]ListNeedVectorsRow, error)
// Needs and their current requirements snapshot for the backfill.
ListNeedsAfter(ctx context.Context, arg ListNeedsAfterParams) ([]ListNeedsAfterRow, error)
// List only the authenticated recipient's rows, optionally narrowed to one
// organization context. The caller resolves current source visibility before
// returning content.
@@ -763,13 +790,22 @@ type Querier interface {
// Owner-scoped newest-first list. It omits descriptions, complaint reason,
// and event history. The tuple cursor matches the composite sort key.
ListOwnedSupportCases(ctx context.Context, arg ListOwnedSupportCasesParams) ([]ListOwnedSupportCasesRow, error)
// Candidates with a saved profile for the backfill, in identifier order
// after a cursor. The job of a candidate who is not published removes the
// stored vectors, so a backfill also cleans up after a closed card.
ListProfileCandidatesAfter(ctx context.Context, arg ListProfileCandidatesAfterParams) ([]pgtype.UUID, error)
// The digests of the stored rows of a subject and model, for the job that
// decides whether anything changed.
ListSemanticVectorDigests(ctx context.Context, arg ListSemanticVectorDigestsParams) ([]ListSemanticVectorDigestsRow, error)
// Organization-facing anonymous candidate projection inputs. The calling
// usecase has already authorized the active organization membership. This
// single statement snapshot filters both revoked/unpublished C2 states and
// candidates hidden from this organization before any profile value is read.
// The projection reads only stack, declared role, and experience dates. It
// deliberately excludes names, contacts, salary, location, soft skills,
// employer names, summaries, and imported excerpts. The only assessment data
// The projection reads only stack, declared role, experience dates, and
// projects with the keys of their verified repositories. It deliberately
// excludes names, contacts, salary, location, soft skills, employer names,
// summaries, and imported excerpts; the repository address of a project stays
// in the private input and never reaches the card. The only assessment data
// is the current category (specialization and grade) of the separate current
// category table; it carries no attempt, score, review, policy, or history.
ListVisibleCandidateViewSources(ctx context.Context, organizationID pgtype.UUID) ([]ListVisibleCandidateViewSourcesRow, error)
@@ -904,6 +940,10 @@ type Querier interface {
LockPublicationForCandidatePreview(ctx context.Context, candidateID pgtype.UUID) (pgtype.UUID, error)
// Locks the active registration C1 while its pending registration is applied.
LockRegistrationConsentRecord(ctx context.Context, arg LockRegistrationConsentRecordParams) (LockRegistrationConsentRecordRow, error)
// Serializes the vector jobs of one subject: a job takes this lock before it
// reads the subject, so the job that runs last also read last and its vectors
// describe the latest committed state. User requests never take it.
LockSemanticSubject(ctx context.Context, lockKey int64) error
// Serialize per-owner budget checks even before the first event exists.
LockSupportCaseRequestBudget(ctx context.Context, ownerID pgtype.UUID) error
// Lock and recheck one candidate's exact current publication only after the
@@ -1080,6 +1120,8 @@ type Querier interface {
// the job did not cause the failure. The same guard as the completion
// applies, one (id, attempt) pair per job. It returns the IDs it released.
ReleaseScheduledJobs(ctx context.Context, arg ReleaseScheduledJobsParams) ([]int64, error)
// A new repository starts pending; a known one only records the request.
RequestCandidateProjectRepositoryCheck(ctx context.Context, arg RequestCandidateProjectRepositoryCheckParams) error
// Stores the replay record of a command. A record whose retention has passed
// is replaced, so the key is accepted as new after the retention. A live
// record is left as it is and nothing is returned; the caller then reads it
@@ -1109,6 +1151,7 @@ type Querier interface {
// grading policy is read from the immutable opening, and the guard trigger
// compares it with the policy captured in the assigned result.
SaveCandidateAssessmentCategory(ctx context.Context, arg SaveCandidateAssessmentCategoryParams) (int64, error)
SaveCandidateProjectRepositoryCheck(ctx context.Context, arg SaveCandidateProjectRepositoryCheckParams) error
SaveCompanyCardViewQuotaUsage(ctx context.Context, arg SaveCompanyCardViewQuotaUsageParams) error
SaveInvitationCreationResult(ctx context.Context, arg SaveInvitationCreationResultParams) error
// Stores the immutable domain snapshot of a successful create command. The
@@ -0,0 +1,427 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
// source: semantic.sql
package sqlc
import (
"context"
"github.com/jackc/pgx/v5/pgtype"
)
const deleteSemanticVectorsOfModel = `-- name: DeleteSemanticVectorsOfModel :exec
DELETE FROM semantic_vectors
WHERE
subject_kind = $1
AND subject_id = $2
AND model_id = $3
AND model_revision = $4
AND prompt_version = $5
`
type DeleteSemanticVectorsOfModelParams struct {
SubjectKind string
SubjectID pgtype.UUID
ModelID string
ModelRevision string
PromptVersion string
}
// Stored embedding vectors. A candidate keeps one set of rows for a model:
// the job deletes every other row of the candidate and model before it
// inserts the new set, in one transaction. A need keeps the rows of its
// latest computed requirements snapshot the same way.
func (q *Queries) DeleteSemanticVectorsOfModel(ctx context.Context, arg DeleteSemanticVectorsOfModelParams) error {
_, err := q.db.Exec(ctx, deleteSemanticVectorsOfModel,
arg.SubjectKind,
arg.SubjectID,
arg.ModelID,
arg.ModelRevision,
arg.PromptVersion,
)
return err
}
const deleteSemanticVectorsOfSubject = `-- name: DeleteSemanticVectorsOfSubject :exec
DELETE FROM semantic_vectors
WHERE subject_kind = $1 AND subject_id = $2
`
type DeleteSemanticVectorsOfSubjectParams struct {
SubjectKind string
SubjectID pgtype.UUID
}
// Removes every vector of a subject, of any model: a closed card or a need
// without requirements keeps no derived data.
func (q *Queries) DeleteSemanticVectorsOfSubject(ctx context.Context, arg DeleteSemanticVectorsOfSubjectParams) error {
_, err := q.db.Exec(ctx, deleteSemanticVectorsOfSubject, arg.SubjectKind, arg.SubjectID)
return err
}
const insertSemanticVector = `-- name: InsertSemanticVector :exec
INSERT INTO semantic_vectors (
subject_kind, subject_id, candidate_id, need_id, model_id, model_revision,
prompt_version, item_key, content_sha256, label_sha256, dimension, vector,
computed_at
) VALUES (
$1, $2, $3,
$4, $5, $6,
$7, $8, $9,
$10, $11, $12,
$13
)
`
type InsertSemanticVectorParams struct {
SubjectKind string
SubjectID pgtype.UUID
CandidateID pgtype.UUID
NeedID pgtype.UUID
ModelID string
ModelRevision string
PromptVersion string
ItemKey string
ContentSha256 []byte
LabelSha256 []byte
Dimension int32
Vector []byte
ComputedAt pgtype.Timestamptz
}
func (q *Queries) InsertSemanticVector(ctx context.Context, arg InsertSemanticVectorParams) error {
_, err := q.db.Exec(ctx, insertSemanticVector,
arg.SubjectKind,
arg.SubjectID,
arg.CandidateID,
arg.NeedID,
arg.ModelID,
arg.ModelRevision,
arg.PromptVersion,
arg.ItemKey,
arg.ContentSha256,
arg.LabelSha256,
arg.Dimension,
arg.Vector,
arg.ComputedAt,
)
return err
}
const listCandidateItemVectors = `-- name: ListCandidateItemVectors :many
SELECT candidate_id, item_key, label_sha256, dimension, vector
FROM semantic_vectors
WHERE
subject_kind = 'candidate'
AND item_key <> 'whole'
AND model_id = $1
AND model_revision = $2
AND prompt_version = $3
AND candidate_id = ANY($4::uuid [])
ORDER BY candidate_id, item_key
`
type ListCandidateItemVectorsParams struct {
ModelID string
ModelRevision string
PromptVersion string
CandidateIds []pgtype.UUID
}
type ListCandidateItemVectorsRow struct {
CandidateID pgtype.UUID
ItemKey string
LabelSha256 []byte
Dimension int32
Vector []byte
}
// The item vectors of the candidates that a search returns, at most a few
// dozen candidates.
func (q *Queries) ListCandidateItemVectors(ctx context.Context, arg ListCandidateItemVectorsParams) ([]ListCandidateItemVectorsRow, error) {
rows, err := q.db.Query(ctx, listCandidateItemVectors,
arg.ModelID,
arg.ModelRevision,
arg.PromptVersion,
arg.CandidateIds,
)
if err != nil {
return nil, err
}
defer rows.Close()
var items []ListCandidateItemVectorsRow
for rows.Next() {
var i ListCandidateItemVectorsRow
if err := rows.Scan(
&i.CandidateID,
&i.ItemKey,
&i.LabelSha256,
&i.Dimension,
&i.Vector,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const listCandidateWholeVectors = `-- name: ListCandidateWholeVectors :many
SELECT candidate_id, dimension, vector
FROM semantic_vectors
WHERE
subject_kind = 'candidate'
AND item_key = 'whole'
AND model_id = $1
AND model_revision = $2
AND prompt_version = $3
AND candidate_id = ANY($4::uuid [])
ORDER BY candidate_id
`
type ListCandidateWholeVectorsParams struct {
ModelID string
ModelRevision string
PromptVersion string
CandidateIds []pgtype.UUID
}
type ListCandidateWholeVectorsRow struct {
CandidateID pgtype.UUID
Dimension int32
Vector []byte
}
// The whole-view vectors of the candidates of one search.
func (q *Queries) ListCandidateWholeVectors(ctx context.Context, arg ListCandidateWholeVectorsParams) ([]ListCandidateWholeVectorsRow, error) {
rows, err := q.db.Query(ctx, listCandidateWholeVectors,
arg.ModelID,
arg.ModelRevision,
arg.PromptVersion,
arg.CandidateIds,
)
if err != nil {
return nil, err
}
defer rows.Close()
var items []ListCandidateWholeVectorsRow
for rows.Next() {
var i ListCandidateWholeVectorsRow
if err := rows.Scan(&i.CandidateID, &i.Dimension, &i.Vector); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const listNeedVectors = `-- name: ListNeedVectors :many
SELECT item_key, content_sha256, dimension, vector
FROM semantic_vectors
WHERE
subject_kind = 'need'
AND need_id = $1
AND model_id = $2
AND model_revision = $3
AND prompt_version = $4
AND content_sha256 = ANY($5::bytea [])
ORDER BY item_key
`
type ListNeedVectorsParams struct {
NeedID pgtype.UUID
ModelID string
ModelRevision string
PromptVersion string
ContentDigests [][]byte
}
type ListNeedVectorsRow struct {
ItemKey string
ContentSha256 []byte
Dimension int32
Vector []byte
}
// The vectors of a need whose texts match the given digests of the
// requirements snapshot that the search renders.
func (q *Queries) ListNeedVectors(ctx context.Context, arg ListNeedVectorsParams) ([]ListNeedVectorsRow, error) {
rows, err := q.db.Query(ctx, listNeedVectors,
arg.NeedID,
arg.ModelID,
arg.ModelRevision,
arg.PromptVersion,
arg.ContentDigests,
)
if err != nil {
return nil, err
}
defer rows.Close()
var items []ListNeedVectorsRow
for rows.Next() {
var i ListNeedVectorsRow
if err := rows.Scan(
&i.ItemKey,
&i.ContentSha256,
&i.Dimension,
&i.Vector,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const listNeedsAfter = `-- name: ListNeedsAfter :many
SELECT id, organization_id, requirements_version
FROM organization_needs
WHERE id > $1
ORDER BY id
LIMIT $2
`
type ListNeedsAfterParams struct {
AfterID pgtype.UUID
PageSize int32
}
type ListNeedsAfterRow struct {
ID pgtype.UUID
OrganizationID pgtype.UUID
RequirementsVersion int64
}
// Needs and their current requirements snapshot for the backfill.
func (q *Queries) ListNeedsAfter(ctx context.Context, arg ListNeedsAfterParams) ([]ListNeedsAfterRow, error) {
rows, err := q.db.Query(ctx, listNeedsAfter, arg.AfterID, arg.PageSize)
if err != nil {
return nil, err
}
defer rows.Close()
var items []ListNeedsAfterRow
for rows.Next() {
var i ListNeedsAfterRow
if err := rows.Scan(&i.ID, &i.OrganizationID, &i.RequirementsVersion); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const listProfileCandidatesAfter = `-- name: ListProfileCandidatesAfter :many
SELECT profiles.user_id
FROM candidate_profiles AS profiles
WHERE profiles.user_id > $1
ORDER BY profiles.user_id
LIMIT $2
`
type ListProfileCandidatesAfterParams struct {
AfterID pgtype.UUID
PageSize int32
}
// Candidates with a saved profile for the backfill, in identifier order
// after a cursor. The job of a candidate who is not published removes the
// stored vectors, so a backfill also cleans up after a closed card.
func (q *Queries) ListProfileCandidatesAfter(ctx context.Context, arg ListProfileCandidatesAfterParams) ([]pgtype.UUID, error) {
rows, err := q.db.Query(ctx, listProfileCandidatesAfter, arg.AfterID, arg.PageSize)
if err != nil {
return nil, err
}
defer rows.Close()
var items []pgtype.UUID
for rows.Next() {
var user_id pgtype.UUID
if err := rows.Scan(&user_id); err != nil {
return nil, err
}
items = append(items, user_id)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const listSemanticVectorDigests = `-- name: ListSemanticVectorDigests :many
SELECT item_key, content_sha256
FROM semantic_vectors
WHERE
subject_kind = $1
AND subject_id = $2
AND model_id = $3
AND model_revision = $4
AND prompt_version = $5
ORDER BY item_key, content_sha256
`
type ListSemanticVectorDigestsParams struct {
SubjectKind string
SubjectID pgtype.UUID
ModelID string
ModelRevision string
PromptVersion string
}
type ListSemanticVectorDigestsRow struct {
ItemKey string
ContentSha256 []byte
}
// The digests of the stored rows of a subject and model, for the job that
// decides whether anything changed.
func (q *Queries) ListSemanticVectorDigests(ctx context.Context, arg ListSemanticVectorDigestsParams) ([]ListSemanticVectorDigestsRow, error) {
rows, err := q.db.Query(ctx, listSemanticVectorDigests,
arg.SubjectKind,
arg.SubjectID,
arg.ModelID,
arg.ModelRevision,
arg.PromptVersion,
)
if err != nil {
return nil, err
}
defer rows.Close()
var items []ListSemanticVectorDigestsRow
for rows.Next() {
var i ListSemanticVectorDigestsRow
if err := rows.Scan(&i.ItemKey, &i.ContentSha256); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const lockSemanticSubject = `-- name: LockSemanticSubject :exec
SELECT pg_advisory_xact_lock($1::bigint)
`
// Serializes the vector jobs of one subject: a job takes this lock before it
// reads the subject, so the job that runs last also read last and its vectors
// describe the latest committed state. User requests never take it.
func (q *Queries) LockSemanticSubject(ctx context.Context, lockKey int64) error {
_, err := q.db.Exec(ctx, lockSemanticSubject, lockKey)
return err
}
@@ -233,6 +233,7 @@ var problemCodes = []string{
"state_conflict", "version_conflict", "payload_too_large", "unsupported_media_type",
"idempotency_key_reused", "precondition_required", "rate_limited", "internal",
"not_implemented",
"service_unavailable",
}
// ObserveProblem counts one error response. A code outside the contract
+6 -1
View File
@@ -49,7 +49,12 @@ func newJobWorker(
logger *slog.Logger,
metrics *prometheus.Metrics,
) (*jobrunner.Worker, func(), error) {
return buildJobWorker(ctx, settings, logger, metrics, jobHandlers(logger.With(slog.String("component", "assessment_review"))))
handlers := jobHandlers(logger.With(slog.String("component", "assessment_review")))
semanticHandlers, err := semanticJobHandlers(settings, logger.With(slog.String("component", "semantic")))
if err != nil {
return nil, nil, err
}
return buildJobWorker(ctx, settings, logger, metrics, append(handlers, semanticHandlers...))
}
// buildJobWorker builds the scheduled job worker and the PostgreSQL pool it
+1
View File
@@ -36,6 +36,7 @@ func newNeedHandler(
Transactor: postgres.NewTransactor(pool),
Keyring: keyring,
Clock: time.Now,
Semantic: newSemanticTrigger(settings),
})
if err != nil {
pool.Close()
+3 -1
View File
@@ -47,7 +47,9 @@ func newPrivacyHandler(
pool.Close()
return nil, nil, fmt.Errorf("bootstrap.newPrivacyHandler - create view service: %w", err)
}
privacy, err := candidateprivacy.NewService(candidateprivacy.Dependencies{Transactor: transactor, Clock: time.Now})
privacy, err := candidateprivacy.NewService(candidateprivacy.Dependencies{
Transactor: transactor, Clock: time.Now, Semantic: newSemanticTrigger(settings),
})
if err != nil {
pool.Close()
return nil, nil, fmt.Errorf("bootstrap.newPrivacyHandler - create settings service: %w", err)
+2 -1
View File
@@ -22,6 +22,7 @@ func newProfileHandler(ctx context.Context, settings config.Config, logger *slog
if err != nil {
return nil, nil, err
}
service := profileusecase.NewService(postgres.NewTransactor(pool), time.Now)
service := profileusecase.NewService(postgres.NewTransactor(pool), time.Now).
WithSemantic(newSemanticTrigger(settings), settings.Semantic.RepositoryCheckInterval)
return v1.NewProfileHandler(service), pool.Close, nil
}
+55
View File
@@ -0,0 +1,55 @@
package bootstrap
import (
"fmt"
"log/slog"
"time"
"lincodex/backend/config"
"lincodex/backend/internal/adapter/secondary/github"
"lincodex/backend/internal/adapter/secondary/ml"
"lincodex/backend/internal/port/inbound"
"lincodex/backend/internal/usecase/semantic"
)
// newSemanticTrigger returns the scheduler of the enabled background work.
// It is never nil; with both features off it schedules no job.
func newSemanticTrigger(settings config.Config) *semantic.Trigger {
return semantic.NewTrigger(settings.Semantic.SemanticMatchingEnabled, settings.Semantic.GitHubChecksEnabled)
}
// semanticJobHandlers registers the vector jobs when semantic matching is on
// and the repository check when GitHub checks are on. Jobs of a kind without
// a handler wait in the database, so turning a feature off never loses work.
func semanticJobHandlers(settings config.Config, logger *slog.Logger) ([]inbound.JobHandler, error) {
var handlers []inbound.JobHandler
trigger := newSemanticTrigger(settings)
if settings.Semantic.SemanticMatchingEnabled {
embedder, err := ml.NewEmbedder(ml.Settings{
BaseURL: settings.Semantic.MLServiceURL, Timeout: settings.Semantic.MLRequestTimeout,
FailureThreshold: settings.Semantic.MLCircuitFailures, OpenDuration: settings.Semantic.MLCircuitOpen,
}, time.Now)
if err != nil {
return nil, fmt.Errorf("bootstrap.semanticJobHandlers - create ML client: %w", err)
}
jobs, err := semantic.NewVectorJobs(embedder, time.Now, logger)
if err != nil {
return nil, fmt.Errorf("bootstrap.semanticJobHandlers - create vector jobs: %w", err)
}
handlers = append(handlers, jobs.CandidateHandler(), jobs.NeedHandler())
} else {
logger.Info("semantic matching is disabled; searches use the neutral semantic value")
}
if settings.Semantic.GitHubChecksEnabled {
fetcher, err := github.NewFetcher(settings.Semantic.GitHubTimeout, settings.Semantic.GitHubToken, time.Now)
if err != nil {
return nil, fmt.Errorf("bootstrap.semanticJobHandlers - create GitHub fetcher: %w", err)
}
check, err := semantic.NewRepositoryCheckJob(fetcher, trigger, time.Now, logger)
if err != nil {
return nil, fmt.Errorf("bootstrap.semanticJobHandlers - create repository check: %w", err)
}
handlers = append(handlers, check)
}
return handlers, nil
}
+38 -4
View File
@@ -444,9 +444,12 @@ type CandidateProfileInput struct {
// the exact periods and indices in Experience.
ParallelPeriodAcknowledgements []ProfileParallelPeriodAcknowledgement
SoftSkills []ProfileClaimInput[string]
Location *ProfileClaimInput[string]
Relocation *ProfileClaimInput[bool]
SalaryMinimum *ProfileClaimInput[ProfileSalaryMinimum]
// Projects replaces the stored projects; nil keeps them, so a client
// that does not know the section never deletes it.
Projects *[]ProfileClaimInput[ProfileProject]
Location *ProfileClaimInput[string]
Relocation *ProfileClaimInput[bool]
SalaryMinimum *ProfileClaimInput[ProfileSalaryMinimum]
}
// CandidateProfileContent is the validated content of a profile: every claim
@@ -464,6 +467,7 @@ type CandidateProfileContent struct {
experience []ProfileClaim[ProfileExperience]
parallelPeriodAcknowledgements []ProfileParallelPeriodAcknowledgement
softSkills []ProfileClaim[string]
projects []ProfileClaim[ProfileProject]
location *ProfileClaim[string]
relocation *ProfileClaim[bool]
salaryMinimum *ProfileClaim[ProfileSalaryMinimum]
@@ -562,6 +566,12 @@ func (content CandidateProfileContent) SoftSkills() []ProfileClaim[string] {
return slices.Clone(content.softSkills)
}
// Projects returns a copy of the projects in the order the candidate gave
// them.
func (content CandidateProfileContent) Projects() []ProfileClaim[ProfileProject] {
return slices.Clone(content.projects)
}
// Equal reports whether both contents hold the same claims with the same
// provenance, which tells a change from a body that changes nothing.
func (content CandidateProfileContent) Equal(other CandidateProfileContent) bool {
@@ -576,7 +586,8 @@ func (content CandidateProfileContent) Equal(other CandidateProfileContent) bool
slices.EqualFunc(content.roles, other.roles, claimsEqual) &&
slices.EqualFunc(content.experience, other.experience, claimsEqual) &&
slices.Equal(content.parallelPeriodAcknowledgements, other.parallelPeriodAcknowledgements) &&
slices.EqualFunc(content.softSkills, other.softSkills, claimsEqual)
slices.EqualFunc(content.softSkills, other.softSkills, claimsEqual) &&
slices.EqualFunc(content.projects, other.projects, claimsEqual)
}
func (CandidateProfileContent) String() string { return redactedProfile }
@@ -790,6 +801,7 @@ type profileRules struct {
softSkills claimRules[string]
roles claimRules[ProfileRole]
experience claimRules[ProfileExperience]
projects claimRules[ProfileProject]
}
func newProfileRules(now time.Time) profileRules {
@@ -815,6 +827,7 @@ func newProfileRules(now time.Time) profileRules {
validate: roleRules, key: func(role ProfileRole) string { return string(role.Specialization) }, keyPointer: "/specialization",
},
experience: claimRules[ProfileExperience]{validate: experienceRules(now)},
projects: claimRules[ProfileProject]{validate: projectRules, key: projectKey, keyPointer: "/repository_url"},
}
}
@@ -1028,6 +1041,14 @@ func ResolveCandidateProfileContent(stored CandidateProfileContent, input Candid
content.softSkills, err = resolveItems(rules.softSkills, location, "/soft_skills", input.SoftSkills, stored.softSkills, maxProfileSoftSkills, at)
return err
},
func() (err error) {
if input.Projects == nil {
content.projects = slices.Clone(stored.projects)
return nil
}
content.projects, err = resolveItems(rules.projects, location, "/projects", *input.Projects, stored.projects, maxProfileProjects, at)
return err
},
func() (err error) {
content.location, err = resolveOptional(rules.location, location, "/terms/location", input.Location, stored.location, at)
return err
@@ -1188,6 +1209,7 @@ const (
profileKindLocation = "terms_location"
profileKindRelocation = "terms_relocation"
profileKindSalaryMinimum = "terms_salary_minimum"
profileKindProject = "project"
)
// StoredProfileClaim is a claim as the claims table holds it: the kind, the
@@ -1302,6 +1324,7 @@ func (content CandidateProfileContent) StoredClaims() ([]StoredProfileClaim, err
entries = appendList(entries, profileKindRole, content.roles, roleStoredValue)
entries = appendList(entries, profileKindExperience, content.experience, experienceStoredValue)
entries = appendList(entries, profileKindSoftSkill, content.softSkills, plainValue[string])
entries = appendList(entries, profileKindProject, content.projects, projectStoredValue)
rows := make([]StoredProfileClaim, 0, len(entries))
for _, entry := range entries {
@@ -1394,6 +1417,8 @@ func restoreCandidateProfileClaim(
return restoreItem(&content.roles, rules.roles, row, status, source)
case profileKindExperience:
return restoreItem(&content.experience, rules.experience, row, status, source)
case profileKindProject:
return restoreItem(&content.projects, rules.projects, row, status, source)
default:
return errors.New("kind is unknown")
}
@@ -1443,6 +1468,15 @@ func decodeStoredValue[V comparable](row StoredProfileClaim) (V, error) {
EmployerName: stringOrEmpty(stored.EmployerName), Specialization: SpecializationCode(stored.Specialization),
StartedOn: stored.StartedOn, EndedOn: stringOrEmpty(stored.EndedOn), Summary: stringOrEmpty(stored.Summary),
}
case *ProfileProject:
var stored storedProjectValue
if err := decodeStrictJSON(row.Value, &stored); err != nil {
return value, err
}
if stored.Stack == nil {
return value, errors.New("value has an unexpected shape")
}
*target = NewProfileProject(stored.Title, stringOrEmpty(stored.Description), stored.Stack, stringOrEmpty(stored.RepositoryURL))
case *ProfileSalaryMinimum:
var stored storedSalaryValue
if err := decodeStrictJSON(row.Value, &stored); err != nil {
@@ -90,7 +90,7 @@ func validateCandidateCardAccessFields(input CandidateCardAccessInput, requireAc
}
switch input.Kind {
case CandidateCardAccessCardViewed:
if len(input.ContactFields) != 0 || len(input.ProjectionFields) > 6 {
if len(input.ContactFields) != 0 || len(input.ProjectionFields) > maxCardViewedFields {
return ErrInvalidCandidateCardAccess
}
seen := make(map[CardField]struct{}, len(input.ProjectionFields))
@@ -116,10 +116,14 @@ func validateCandidateCardAccessFields(input CandidateCardAccessInput, requireAc
return nil
}
// maxCardViewedFields is the number of card groups that a view can return;
// the CHECK of candidate_card_access_events allows the same.
const maxCardViewedFields = 7
func candidateCardProjectionField(field CardField) bool {
switch field {
case CardFieldCategories, CardFieldStack, CardFieldExperience, CardFieldSelfAssessment,
CardFieldWorkFormats, CardFieldSalaryCompatibility:
CardFieldWorkFormats, CardFieldSalaryCompatibility, CardFieldProjects:
return true
case CardFieldSoftSkills, CardFieldLocation, CardFieldRelocation:
return false
@@ -0,0 +1,235 @@
package domain
import (
"errors"
"fmt"
"log/slog"
"regexp"
"strings"
"unicode/utf8"
)
// ErrInvalidGitHubRepository reports a repository address that is not a
// GitHub repository address of the accepted form.
var ErrInvalidGitHubRepository = errors.New("invalid GitHub repository address")
const (
maxProfileProjects = 10
maxProfileProjectTitleRunes = 100
maxProfileProjectDescription = 500
maxProfileProjectStackItems = 10
maxRepositoryURLRunes = 160
githubRepositoryPrefix = "https://github.com/"
// projectStackSeparator joins the tags of a project into one comparable
// string. A tag is one line, so a line break never occurs inside one.
projectStackSeparator = "\n"
)
var (
// GitHub owner names: letters, digits, and single hyphens, at most 39
// characters, not starting with a hyphen.
githubOwnerPattern = regexp.MustCompile(`^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})$`)
// GitHub repository names: letters, digits, '.', '_', and '-'.
githubNamePattern = regexp.MustCompile(`^[A-Za-z0-9._-]{1,100}$`)
)
// GitHubRepository is a validated public repository coordinate. Owner and
// Name keep the letter case the candidate typed; Key is the lower-case form
// that GitHub treats as the same repository.
type GitHubRepository struct {
owner string
name string
}
// ParseGitHubRepositoryURL accepts only https://github.com/<owner>/<name>
// with an optional trailing slash or .git suffix. Any other scheme, host,
// port, user information, query, fragment, or path is rejected, so the
// address can never point the server at another host.
func ParseGitHubRepositoryURL(raw string) (GitHubRepository, error) {
const location = "domain.ParseGitHubRepositoryURL"
fail := func(reason string) (GitHubRepository, error) {
return GitHubRepository{}, fmt.Errorf("%s - %s: %w", location, reason, ErrInvalidGitHubRepository)
}
if !utf8.ValidString(raw) || utf8.RuneCountInString(raw) > maxRepositoryURLRunes {
return fail("address is too long or not UTF-8")
}
if !strings.HasPrefix(raw, githubRepositoryPrefix) {
return fail("address must start with https://github.com/")
}
path := strings.TrimPrefix(raw, githubRepositoryPrefix)
path = strings.TrimSuffix(path, "/")
parts := strings.Split(path, "/")
if len(parts) != 2 {
return fail("address must name exactly an owner and a repository")
}
owner, name := parts[0], strings.TrimSuffix(parts[1], ".git")
switch {
case !githubOwnerPattern.MatchString(owner) || strings.Contains(owner, "--"):
return fail("owner is not a GitHub account name")
case !githubNamePattern.MatchString(name) || name == "." || name == "..":
return fail("repository is not a GitHub repository name")
}
return GitHubRepository{owner: owner, name: name}, nil
}
// Owner returns the account part of the address.
func (repository GitHubRepository) Owner() string { return repository.owner }
// Name returns the repository part of the address.
func (repository GitHubRepository) Name() string { return repository.name }
// URL returns the canonical address https://github.com/<owner>/<name>.
func (repository GitHubRepository) URL() string {
return githubRepositoryPrefix + repository.owner + "/" + repository.name
}
// Key is "<owner>/<name>" in lower case: the identity of the repository for
// deduplication and for its stored check.
func (repository GitHubRepository) Key() string {
return strings.ToLower(repository.owner + "/" + repository.name)
}
// IsZero reports a repository that was not parsed.
func (repository GitHubRepository) IsZero() bool { return repository.owner == "" }
// The coordinate names an account, so formatting redacts it like profile data.
func (GitHubRepository) String() string { return redactedProfile }
func (GitHubRepository) GoString() string { return redactedProfile }
func (GitHubRepository) LogValue() slog.Value {
return slog.StringValue(redactedProfile)
}
func (GitHubRepository) Format(state fmt.State, _ rune) { writeRedacted(state, redactedProfile) }
// ProfileProject is one project of the profile. Description and
// RepositoryURL are "" when not given. The stack is kept as one string so the
// value stays comparable; StackTags returns the tags. The project is personal
// data: formatting redacts it.
type ProfileProject struct {
Title string
Description string
RepositoryURL string
stack string
}
// NewProfileProject builds a project value from request parts. Validation
// happens when the profile resolves it.
func NewProfileProject(title, description string, stack []string, repositoryURL string) ProfileProject {
return ProfileProject{
Title: title, Description: description, RepositoryURL: repositoryURL,
stack: strings.Join(stack, projectStackSeparator),
}
}
// StackTags returns the stack tags in the order the candidate gave them.
func (project ProfileProject) StackTags() []string {
if project.stack == "" {
return nil
}
return strings.Split(project.stack, projectStackSeparator)
}
// Repository returns the parsed repository and whether the project links one.
func (project ProfileProject) Repository() (GitHubRepository, bool) {
if project.RepositoryURL == "" {
return GitHubRepository{}, false
}
repository, err := ParseGitHubRepositoryURL(project.RepositoryURL)
if err != nil {
return GitHubRepository{}, false
}
return repository, true
}
func (ProfileProject) String() string { return redactedProfile }
func (ProfileProject) GoString() string { return redactedProfile }
func (ProfileProject) LogValue() slog.Value {
return slog.StringValue(redactedProfile)
}
func (ProfileProject) Format(state fmt.State, _ rune) { writeRedacted(state, redactedProfile) }
// projectRules validates and normalizes one project. The repository address
// becomes canonical, so a trailing slash or a .git suffix never creates a
// second value for the same repository.
func projectRules(value ProfileProject) (ProfileProject, string, string) {
value.Description = strings.ReplaceAll(value.Description, "\r\n", "\n")
if problem := singleLineTextProblem(value.Title, maxProfileProjectTitleRunes); problem != "" {
return value, "/title", problem
}
if value.Description != "" {
if problem := multiLineTextProblem(value.Description, maxProfileProjectDescription); problem != "" {
return value, "/description", problem
}
}
tags := value.StackTags()
if len(tags) > maxProfileProjectStackItems {
return value, "/stack", fmt.Sprintf("must have at most %d items", maxProfileProjectStackItems)
}
seen := make(map[string]struct{}, len(tags))
for index, tag := range tags {
if problem := singleLineTextProblem(tag, maxProfileTagRunes); problem != "" {
return value, fmt.Sprintf("/stack/%d", index), problem
}
key := strings.ToLower(tag)
if _, repeated := seen[key]; repeated {
return value, fmt.Sprintf("/stack/%d", index), "must not repeat an earlier item"
}
seen[key] = struct{}{}
}
if value.RepositoryURL != "" {
repository, err := ParseGitHubRepositoryURL(value.RepositoryURL)
if err != nil {
return value, "/repository_url", "must be a GitHub repository address https://github.com/<owner>/<repository>"
}
value.RepositoryURL = repository.URL()
}
return value, "", ""
}
// projectKey identifies a project for the repeat rule: two projects may not
// link the same repository. A project without a repository never repeats.
func projectKey(value ProfileProject) string {
repository, ok := value.Repository()
if !ok {
return "\x00" + value.Title + "\x00" + value.Description + "\x00" + value.stack
}
return repository.Key()
}
// storedProjectValue is the JSON shape of a project claim that the CHECK of
// candidate_profile_claims requires.
type storedProjectValue struct {
Title string `json:"title"`
Description *string `json:"description"`
Stack []string `json:"stack"`
RepositoryURL *string `json:"repository_url"`
}
func projectStoredValue(project ProfileProject) any {
stack := project.StackTags()
if stack == nil {
stack = []string{}
}
return storedProjectValue{
Title: project.Title, Description: optionalString(project.Description), Stack: stack,
RepositoryURL: optionalString(project.RepositoryURL),
}
}
// ProjectRepositories returns the distinct repositories that the projects of
// the content link, in project order.
func (content CandidateProfileContent) ProjectRepositories() []GitHubRepository {
var repositories []GitHubRepository
seen := make(map[string]struct{})
for _, claim := range content.projects {
repository, ok := claim.value.Repository()
if !ok {
continue
}
if _, repeated := seen[repository.Key()]; repeated {
continue
}
seen[repository.Key()] = struct{}{}
repositories = append(repositories, repository)
}
return repositories
}
@@ -0,0 +1,169 @@
package domain
import (
"errors"
"fmt"
"strings"
"testing"
"time"
)
func TestParseGitHubRepositoryURLAcceptsOnlyCanonicalGitHubAddresses(t *testing.T) {
for _, test := range []struct {
raw, url, key string
}{
{"https://github.com/Example-Org/Payments.Ledger", "https://github.com/Example-Org/Payments.Ledger", "example-org/payments.ledger"},
{"https://github.com/example/repo/", "https://github.com/example/repo", "example/repo"},
{"https://github.com/example/repo.git", "https://github.com/example/repo", "example/repo"},
} {
repository, err := ParseGitHubRepositoryURL(test.raw)
if err != nil || repository.URL() != test.url || repository.Key() != test.key {
t.Errorf("ParseGitHubRepositoryURL(%q) = %q %q, %v", test.raw, repository.URL(), repository.Key(), err)
}
}
for _, raw := range []string{
"http://github.com/example/repo",
"https://gitlab.com/example/repo",
"https://github.com.evil.example/example/repo",
"https://user:secret@github.com/example/repo",
"https://github.com:443/example/repo",
"https://github.com/example",
"https://github.com/example/repo/tree/main",
"https://github.com/example/repo?tab=readme",
"https://github.com/example/repo#readme",
"https://github.com/-example/repo",
"https://github.com/exa--mple/repo",
"https://github.com/example/..",
"https://github.com/example/re po",
"https://github.com/../../evil",
"https://api.github.com/repos/example/repo",
"https://github.com/" + strings.Repeat("a", 40) + "/repo",
"https://GITHUB.com/example/repo",
} {
if _, err := ParseGitHubRepositoryURL(raw); !errors.Is(err, ErrInvalidGitHubRepository) {
t.Errorf("ParseGitHubRepositoryURL(%q) accepted an address outside the allowed form", raw)
}
}
}
func TestGitHubRepositoryRedactsItselfInLogs(t *testing.T) {
repository, err := ParseGitHubRepositoryURL("https://github.com/private-owner/repo")
if err != nil {
t.Fatalf("ParseGitHubRepositoryURL() error = %v", err)
}
if text := fmt.Sprintf("%v %+v %#v %s", repository, repository, repository, repository); strings.Contains(text, "private-owner") {
t.Fatalf("formatting leaks the owner: %s", text)
}
}
func projectInput(title, description string, stack []string, repository string) ProfileClaimInput[ProfileProject] {
return ProfileClaimInput[ProfileProject]{Value: NewProfileProject(title, description, stack, repository), Status: ProfileClaimConfirmed}
}
func TestProfileProjectsAreValidatedNormalizedAndOptionalInARequest(t *testing.T) {
at := time.Date(2026, 10, 11, 9, 0, 0, 0, time.UTC)
projects := []ProfileClaimInput[ProfileProject]{
projectInput("Ledger", "Idempotent\r\ncallbacks", []string{"Go", "PostgreSQL"}, "https://github.com/example/ledger.git"),
projectInput("Notes", "", nil, ""),
}
content, err := ResolveCandidateProfileContent(CandidateProfileContent{}, CandidateProfileInput{Projects: &projects}, at)
if err != nil {
t.Fatalf("ResolveCandidateProfileContent() error = %v", err)
}
stored := content.Projects()
if len(stored) != 2 || stored[0].Value().RepositoryURL != "https://github.com/example/ledger" ||
stored[0].Value().Description != "Idempotent\ncallbacks" || strings.Join(stored[0].Value().StackTags(), ",") != "Go,PostgreSQL" {
t.Fatalf("projects = %+v, want the normalized values", stored)
}
if repositories := content.ProjectRepositories(); len(repositories) != 1 || repositories[0].Key() != "example/ledger" {
t.Fatalf("ProjectRepositories() = %d, want the linked repository", len(repositories))
}
// A request without the section keeps the stored projects.
kept, err := ResolveCandidateProfileContent(content, CandidateProfileInput{}, at)
if err != nil || len(kept.Projects()) != 2 || !kept.Equal(content) {
t.Fatalf("a request without projects changed them: %v", err)
}
// An empty list removes them.
empty := []ProfileClaimInput[ProfileProject]{}
cleared, err := ResolveCandidateProfileContent(content, CandidateProfileInput{Projects: &empty}, at)
if err != nil || len(cleared.Projects()) != 0 {
t.Fatalf("an empty list kept the projects: %v", err)
}
// The stored rows restore to the same content.
rows, err := content.StoredClaims()
if err != nil {
t.Fatalf("StoredClaims() error = %v", err)
}
restored, err := RestoreCandidateProfileContent(rows)
if err != nil || !restored.Equal(content) {
t.Fatalf("RestoreCandidateProfileContent() = %v, want the same projects", err)
}
for _, test := range []struct {
name string
projects []ProfileClaimInput[ProfileProject]
pointer string
}{
{"empty title", []ProfileClaimInput[ProfileProject]{projectInput("", "", nil, "")}, "/projects/0/title"},
{"long title", []ProfileClaimInput[ProfileProject]{projectInput(strings.Repeat("a", 101), "", nil, "")}, "/projects/0/title"},
{"another host", []ProfileClaimInput[ProfileProject]{projectInput("A", "", nil, "https://gitlab.com/a/b")}, "/projects/0/repository_url"},
{"repeated tag", []ProfileClaimInput[ProfileProject]{projectInput("A", "", []string{"Go", "go"}, "")}, "/projects/0/stack/1"},
{"repeated repository", []ProfileClaimInput[ProfileProject]{
projectInput("A", "", nil, "https://github.com/a/b"), projectInput("B", "", nil, "https://github.com/A/B/"),
}, "/projects/1/repository_url"},
{"too many", func() []ProfileClaimInput[ProfileProject] {
many := make([]ProfileClaimInput[ProfileProject], 0, maxProfileProjects+1)
for index := range maxProfileProjects + 1 {
many = append(many, projectInput(fmt.Sprintf("P%d", index), "", nil, ""))
}
return many
}(), "/projects"},
} {
_, err := ResolveCandidateProfileContent(CandidateProfileContent{}, CandidateProfileInput{Projects: &test.projects}, at)
var field *CandidateProfileFieldError
if !errors.As(err, &field) || field.Pointer != test.pointer {
t.Errorf("%s: error = %v, want pointer %s", test.name, err, test.pointer)
}
}
}
func TestPublishedProjectsReachTheCardWithoutTheRepository(t *testing.T) {
at := time.Date(2026, 10, 11, 9, 0, 0, 0, time.UTC)
projects := []ProfileClaimInput[ProfileProject]{
projectInput("Ledger", "Callbacks", []string{"Go"}, "https://github.com/private-owner/ledger"),
}
content, err := ResolveCandidateProfileContent(CandidateProfileContent{}, CandidateProfileInput{Projects: &projects}, at)
if err != nil {
t.Fatalf("ResolveCandidateProfileContent() error = %v", err)
}
profile := CandidateViewProfileFromContentWithRepositories(content, map[string]bool{"private-owner/ledger": true})
pseudonym := "cv1_" + strings.Repeat("A", 43)
for _, test := range []struct {
fields []CardField
want int
}{
{[]CardField{CardFieldStack}, 0},
{[]CardField{CardFieldStack, CardFieldProjects}, 1},
} {
fields, err := NewCardFieldSet(test.fields)
if err != nil {
t.Fatalf("NewCardFieldSet() error = %v", err)
}
view, err := NewAnonymousCandidateView(CandidateViewInput{Pseudonym: pseudonym, PublishedFields: fields, Profile: profile, AsOf: at})
if err != nil {
t.Fatalf("NewAnonymousCandidateView() error = %v", err)
}
card := view.DTO()
if len(card.Projects) != test.want {
t.Fatalf("fields %v: projects = %d, want %d", test.fields, len(card.Projects), test.want)
}
if test.want == 1 && (!card.Projects[0].RepositoryVerified || card.Projects[0].Title != "Ledger") {
t.Fatalf("card project = %+v, want the verified title", card.Projects[0])
}
if text := fmt.Sprintf("%+v", card.Projects); strings.Contains(text, "private-owner") || strings.Contains(text, "github") {
t.Fatalf("card projects carry the repository: %s", text)
}
}
}
+73 -1
View File
@@ -191,6 +191,14 @@ type candidateViewRoleClaim struct {
status ProfileClaimStatus
}
// candidateViewProjectClaim is a project with the verification of its
// repository. The repository key never leaves the private projection input.
type candidateViewProjectClaim struct {
value ProfileProject
status ProfileClaimStatus
verified bool
}
type candidateViewExperienceClaim struct {
startedOn string
endedOn string
@@ -204,6 +212,7 @@ type CandidateViewProfile struct {
stack []candidateViewStackClaim
roles []candidateViewRoleClaim
experience []candidateViewExperienceClaim
projects []candidateViewProjectClaim
}
func (CandidateViewProfile) String() string { return "[candidate view profile]" }
@@ -213,9 +222,28 @@ func (CandidateViewProfile) LogValue() slog.Value {
}
// CandidateViewProfileFromContent removes private profile values that are
// not needed to build the anonymous organization-facing view.
// not needed to build the anonymous organization-facing view. No project is
// marked as backed by a verified repository.
func CandidateViewProfileFromContent(content CandidateProfileContent) CandidateViewProfile {
return CandidateViewProfileFromContentWithRepositories(content, nil)
}
// CandidateViewProfileFromContentWithRepositories also marks each project
// whose repository key is in verifiedRepositories, the keys whose latest
// check found a public repository.
func CandidateViewProfileFromContentWithRepositories(
content CandidateProfileContent, verifiedRepositories map[string]bool,
) CandidateViewProfile {
profile := CandidateViewProfile{}
for _, claim := range content.Projects() {
verified := false
if repository, ok := claim.Value().Repository(); ok {
verified = verifiedRepositories[repository.Key()]
}
profile.projects = append(profile.projects, candidateViewProjectClaim{
value: claim.Value(), status: claim.Status(), verified: verified,
})
}
for _, claim := range content.Stack() {
profile.stack = append(profile.stack, candidateViewStackClaim{value: claim.Value(), status: claim.Status()})
}
@@ -263,6 +291,15 @@ func (compatibility CandidateViewSalaryCompatibility) IsKnown() bool {
return compatibility == CandidateViewSalaryCompatible || compatibility == CandidateViewSalaryNotCompatible
}
// CandidateViewProject is one published project as the card shows it: no
// repository address, owner, or fetched repository text.
type CandidateViewProject struct {
Title string `json:"title"`
Description *string `json:"description"`
Stack []string `json:"stack"`
RepositoryVerified bool `json:"repository_verified"`
}
// AnonymousCandidateViewDTO is the complete closed organization-facing data
// transfer object. It contains no account ID, raw profile fields, or history.
type AnonymousCandidateViewDTO struct {
@@ -273,6 +310,9 @@ type AnonymousCandidateViewDTO struct {
ExperienceBand *CandidateExperienceBand `json:"experience_band"`
WorkFormats []QuestionnaireWorkFormat `json:"work_formats"`
SalaryCompatibility *CandidateViewSalaryCompatibility `json:"salary_compatibility"`
// Projects are published free text; cohort generalization leaves them
// unchanged and they are not a cohort feature.
Projects []CandidateViewProject `json:"projects"`
}
func (AnonymousCandidateViewDTO) String() string { return "[anonymous candidate view]" }
@@ -348,6 +388,9 @@ func NewAnonymousCandidateView(input CandidateViewInput) (AnonymousCandidateView
value := *input.SalaryCompatibility
view.dto.SalaryCompatibility = &value
}
if input.PublishedFields.Contains(CardFieldProjects) {
view.dto.Projects = candidateViewProjects(input.Profile)
}
return view, nil
}
@@ -366,9 +409,38 @@ func cloneAnonymousCandidateViewDTO(dto AnonymousCandidateViewDTO) AnonymousCand
dto.ExperienceBand = clonePointer(dto.ExperienceBand)
dto.WorkFormats = slices.Clone(dto.WorkFormats)
dto.SalaryCompatibility = clonePointer(dto.SalaryCompatibility)
if dto.Projects != nil {
projects := make([]CandidateViewProject, len(dto.Projects))
for index, project := range dto.Projects {
project.Description = clonePointer(project.Description)
project.Stack = slices.Clone(project.Stack)
projects[index] = project
}
dto.Projects = projects
}
return dto
}
// candidateViewProjects lists the confirmed projects in profile order, so
// the position of a project in the card equals its position in the profile.
func candidateViewProjects(profile CandidateViewProfile) []CandidateViewProject {
var projects []CandidateViewProject
for _, claim := range profile.projects {
if claim.status != ProfileClaimConfirmed {
continue
}
stack := claim.value.StackTags()
if stack == nil {
stack = []string{}
}
projects = append(projects, CandidateViewProject{
Title: claim.value.Title, Description: optionalString(claim.value.Description),
Stack: stack, RepositoryVerified: claim.verified,
})
}
return projects
}
func validCandidateViewPseudonym(pseudonym string) bool {
if !strings.HasPrefix(pseudonym, candidateViewPseudonymPrefix) {
return false
@@ -74,6 +74,7 @@ func cloneCandidateViewProfile(profile CandidateViewProfile) CandidateViewProfil
return CandidateViewProfile{
stack: slices.Clone(profile.stack), roles: slices.Clone(profile.roles),
experience: slices.Clone(profile.experience),
projects: slices.Clone(profile.projects),
}
}
+11
View File
@@ -106,3 +106,14 @@ func DemoProductPolicyV4() ProductPolicy {
policy.Matching = &matching
return policy
}
// DemoProductPolicyV5 returns DemoProductPolicyV4 with the semantic matching
// section and the semantic Fit weights (DemoSemanticMatchingPolicy). V4 stays
// the PRD point with Sem weight 0.10. It is published explicitly with the
// policy-publish command; startup seeding publishes V1 only.
func DemoProductPolicyV5() ProductPolicy {
policy := DemoProductPolicyV4()
matching := DemoSemanticMatchingPolicy()
policy.Matching = &matching
return policy
}
@@ -185,6 +185,34 @@ type matchingPolicyDocument struct {
PercentileMinCohort *int32 `json:"percentile_min_cohort"`
MaxResultsPerGroup *int32 `json:"max_results_per_group"`
SkillTaxonomy *[]matchingSkillGroupDocument `json:"skill_taxonomy"`
// Semantics is optional: a document without it is a matching section
// that ranks with the neutral Sem.
Semantics *matchingSemanticsDocument `json:"semantics,omitempty"`
}
type matchingSemanticsDocument struct {
Members *[]matchingSemanticMemberDocument `json:"members"`
Calibration *[]matchingCalibrationPointDocument `json:"calibration"`
SkillMediumBP *BasisPoints `json:"skill_medium_bp"`
SkillHighBP *BasisPoints `json:"skill_high_bp"`
TaskMediumBP *BasisPoints `json:"task_medium_bp"`
TaskHighBP *BasisPoints `json:"task_high_bp"`
MaxEvidencePerEntry *int32 `json:"max_evidence_per_entry"`
Source *string `json:"source"`
}
type matchingSemanticMemberDocument struct {
ModelID *string `json:"model_id"`
ModelRevision *string `json:"model_revision"`
PromptVersion *string `json:"prompt_version"`
WeightBP *BasisPoints `json:"weight_bp"`
MeanBP *int32 `json:"mean_bp"`
StandardDeviationBP *int32 `json:"standard_deviation_bp"`
}
type matchingCalibrationPointDocument struct {
ScoreBP *int32 `json:"score_bp"`
ProbabilityBP *BasisPoints `json:"probability_bp"`
}
type matchingSkillGroupDocument struct {
@@ -359,6 +387,31 @@ func encodeMatchingPolicy(policy *MatchingPolicy) *matchingPolicyDocument {
PercentileMinCohort: pointer(policy.PercentileMinCohort),
MaxResultsPerGroup: pointer(policy.MaxResultsPerGroup),
SkillTaxonomy: pointer(encodeMatchingSkillGroups(policy.SkillTaxonomy)),
Semantics: encodeMatchingSemantics(policy.Semantics),
}
}
func encodeMatchingSemantics(policy *MatchingSemanticsPolicy) *matchingSemanticsDocument {
if policy == nil {
return nil
}
points := make([]matchingCalibrationPointDocument, 0, len(policy.Calibration))
for _, point := range policy.Calibration {
points = append(points, matchingCalibrationPointDocument{ScoreBP: pointer(point.Score), ProbabilityBP: pointer(point.Probability)})
}
members := make([]matchingSemanticMemberDocument, 0, len(policy.Members))
for _, member := range policy.Members {
members = append(members, matchingSemanticMemberDocument{
ModelID: pointer(member.Model.ID), ModelRevision: pointer(member.Model.Revision),
PromptVersion: pointer(member.Model.PromptVersion), WeightBP: pointer(member.Weight),
MeanBP: pointer(member.Mean), StandardDeviationBP: pointer(member.StandardDeviation),
})
}
return &matchingSemanticsDocument{
Members: pointer(members), Calibration: pointer(points),
SkillMediumBP: pointer(policy.SkillMedium), SkillHighBP: pointer(policy.SkillHigh),
TaskMediumBP: pointer(policy.TaskMedium), TaskHighBP: pointer(policy.TaskHigh),
MaxEvidencePerEntry: pointer(policy.MaxEvidencePerEntry), Source: pointer(policy.Source),
}
}
@@ -621,6 +674,43 @@ func decodeOptionalMatchingPolicy(reader *documentReader, document *matchingPoli
PercentileMinCohort: require(reader, "matching.percentile_min_cohort", document.PercentileMinCohort),
MaxResultsPerGroup: require(reader, "matching.max_results_per_group", document.MaxResultsPerGroup),
SkillTaxonomy: taxonomy,
Semantics: decodeOptionalMatchingSemantics(reader, document.Semantics),
}
}
func decodeOptionalMatchingSemantics(reader *documentReader, document *matchingSemanticsDocument) *MatchingSemanticsPolicy {
if document == nil {
return nil
}
points := make([]MatchingCalibrationPoint, 0)
for _, point := range require(reader, "matching.semantics.calibration", document.Calibration) {
points = append(points, MatchingCalibrationPoint{
Score: require(reader, "matching.semantics.calibration.score_bp", point.ScoreBP),
Probability: require(reader, "matching.semantics.calibration.probability_bp", point.ProbabilityBP),
})
}
members := make([]MatchingSemanticMember, 0)
for _, member := range require(reader, "matching.semantics.members", document.Members) {
members = append(members, MatchingSemanticMember{
Model: SemanticModel{
ID: require(reader, "matching.semantics.members.model_id", member.ModelID),
Revision: require(reader, "matching.semantics.members.model_revision", member.ModelRevision),
PromptVersion: require(reader, "matching.semantics.members.prompt_version", member.PromptVersion),
},
Weight: require(reader, "matching.semantics.members.weight_bp", member.WeightBP),
Mean: require(reader, "matching.semantics.members.mean_bp", member.MeanBP),
StandardDeviation: require(reader, "matching.semantics.members.standard_deviation_bp", member.StandardDeviationBP),
})
}
return &MatchingSemanticsPolicy{
Members: members,
Calibration: points,
SkillMedium: require(reader, "matching.semantics.skill_medium_bp", document.SkillMediumBP),
SkillHigh: require(reader, "matching.semantics.skill_high_bp", document.SkillHighBP),
TaskMedium: require(reader, "matching.semantics.task_medium_bp", document.TaskMediumBP),
TaskHigh: require(reader, "matching.semantics.task_high_bp", document.TaskHighBP),
MaxEvidencePerEntry: require(reader, "matching.semantics.max_evidence_per_entry", document.MaxEvidencePerEntry),
Source: require(reader, "matching.semantics.source", document.Source),
}
}
+31 -2
View File
@@ -70,6 +70,11 @@ type MatchingPolicy struct {
// that stays below the daily card-view allowance of the first tier.
MaxResultsPerGroup int32
// Semantics is the optional semantic section: the encoder of the stored
// vectors, the calibration of Sem, and the explanation thresholds. A
// version without it ranks with the neutral Sem, as before.
Semantics *MatchingSemanticsPolicy
// SkillTaxonomy lists, for each specialization, the technologies that fall
// inside it. Evidence for a specialization is broader evidence for each of
// them, and evidence for one of them is narrower evidence for the
@@ -90,6 +95,10 @@ func (policy MatchingPolicy) Clone() MatchingPolicy {
for index := range policy.SkillTaxonomy {
policy.SkillTaxonomy[index].Skills = slices.Clone(policy.SkillTaxonomy[index].Skills)
}
if policy.Semantics != nil {
semantics := policy.Semantics.Clone()
policy.Semantics = &semantics
}
return policy
}
@@ -164,6 +173,20 @@ func DemoMatchingPolicy() MatchingPolicy {
}
}
// DemoSemanticMatchingPolicy returns DemoMatchingPolicy with semantic
// similarity in Fit. The research shows that the PRD weight 0.10 hides
// almost all of the encoder's gain (TEST nDCG@10 of Fit 0.649 against 0.818
// for the encoder alone) and that 0.5 recovers it (0.838). Sem therefore
// weighs 0.5 and Cov and Dom keep their PRD ratio 5:1 in the rest
// (0.4167 and 0.0833), so the weights still add up to one.
func DemoSemanticMatchingPolicy() MatchingPolicy {
policy := DemoMatchingPolicy()
policy.FitCoverageWeight, policy.FitDomainWeight, policy.FitSemanticsWeight = 4167, 833, 5000
semantics := DemoMatchingSemanticsPolicy()
policy.Semantics = &semantics
return policy
}
// TrustCoefficient returns the coefficient of an evidence trust level. An
// unknown level has none.
func (policy MatchingPolicy) TrustCoefficient(trust EvidenceTrust) (BasisPoints, bool) {
@@ -214,11 +237,17 @@ func (policy MatchingPolicy) RelationCoefficient(relation EvidenceSkillRelation)
// Validate rejects a zero, out-of-range, or inconsistent section.
func (policy MatchingPolicy) Validate() error {
return firstError(
if err := firstError(
policy.validateShares(),
policy.validateWeights(),
policy.validateOrdering(),
)
); err != nil {
return err
}
if policy.Semantics != nil {
return policy.Semantics.Validate()
}
return nil
}
func (policy MatchingPolicy) validateShares() error {
@@ -0,0 +1,304 @@
package domain
import (
"fmt"
"math"
"slices"
"unicode/utf8"
)
// MatchingSemanticsPolicy is the versioned semantic part of matching: which
// encoders the stored vectors must come from, how their cosines of the two
// whole views become Sem, and which item similarities an explanation may show.
// Values come from the research run named in Source; they are not product
// measurements.
type MatchingSemanticsPolicy struct {
// Members are the encoders whose cosines form the semantic score: the
// weighted sum of each cosine standardized by the member's mean and
// standard deviation. The first member also provides the item vectors of
// the explanation. The default is one member, Giga-480M, with weight 1,
// mean 0, and standard deviation 1, so the score is its cosine; an
// ensemble (for example 0.4 Giga + 0.6 Qwen3-Embedding) adds a member and
// needs a calibration fitted on its fused score.
Members []MatchingSemanticMember
// Calibration maps the fused score of the need view and the card view to
// Sem by linear interpolation between points, clipped at both ends. The
// points are an isotonic fit, so both coordinates never decrease.
Calibration []MatchingCalibrationPoint
// The item thresholds are cosines in basis points: a requirement whose
// closest card item reaches Medium is shown as "medium", reaching High as
// "high". Skills and tasks have their own pairs.
SkillMedium BasisPoints
SkillHigh BasisPoints
TaskMedium BasisPoints
TaskHigh BasisPoints
// MaxEvidencePerEntry bounds the explanation items of one entry.
MaxEvidencePerEntry int32
// Source names the data and the fit behind the values.
Source string
}
// MatchingSemanticMember is one encoder of the semantic score. Mean and
// StandardDeviation describe its cosine of a need and a card in basis
// points; the member contributes Weight * (cosine - Mean) / StandardDeviation.
type MatchingSemanticMember struct {
Model SemanticModel
Weight BasisPoints
Mean int32
StandardDeviation int32
}
// ExplanationModel is the encoder whose item vectors explain an entry.
func (policy MatchingSemanticsPolicy) ExplanationModel() SemanticModel {
if len(policy.Members) == 0 {
return SemanticModel{}
}
return policy.Members[0].Model
}
// FusedScore combines the whole-view cosines of the members, in member order,
// into the score that the calibration reads. It returns false unless every
// member has a cosine: a partial ensemble would put the entry on another scale.
func (policy MatchingSemanticsPolicy) FusedScore(cosines []float64) (float64, bool) {
if len(policy.Members) == 0 || len(cosines) != len(policy.Members) {
return 0, false
}
var score float64
for index, cosine := range cosines {
member := policy.Members[index]
weight := float64(member.Weight) / float64(basisPointsPerUnit)
mean := float64(member.Mean) / float64(basisPointsPerUnit)
deviation := float64(member.StandardDeviation) / float64(basisPointsPerUnit)
// The explicit conversion rounds the product, so no platform fuses it
// with the sum and every server computes the same score.
score += float64(weight * ((cosine - mean) / deviation))
}
return score, true
}
// MatchingCalibrationPoint is one point of the calibration curve: a fused
// score in basis points (-1..1 for a single cosine) and the probability that
// the pair is relevant.
type MatchingCalibrationPoint struct {
Score int32
Probability BasisPoints
}
const (
minCalibrationPoints = 2
maxCalibrationPoints = 256
maxSemanticEvidencePerEntry = 12
maxSemanticSourceRunes = 300
maxSemanticMembers = 4
// A standardized fused score can leave -1..1; the bound only rejects a
// value in the wrong unit.
minScoreBasisPoints = -100000
maxScoreBasisPoints = 100000
)
// Clone copies the members and the calibration points.
func (policy MatchingSemanticsPolicy) Clone() MatchingSemanticsPolicy {
policy.Members = slices.Clone(policy.Members)
policy.Calibration = slices.Clone(policy.Calibration)
return policy
}
// Validate rejects a malformed section.
func (policy MatchingSemanticsPolicy) Validate() error {
const location = "MatchingSemanticsPolicy.Validate"
if err := policy.validateMembers(); err != nil {
return err
}
if len(policy.Calibration) < minCalibrationPoints || len(policy.Calibration) > maxCalibrationPoints {
return invalidPolicy(location, fmt.Sprintf("matching.semantics.calibration needs between %d and %d points", minCalibrationPoints, maxCalibrationPoints))
}
for index, point := range policy.Calibration {
if err := firstError(
checkRange(location, "matching.semantics.calibration.score_bp", point.Score, minScoreBasisPoints, maxScoreBasisPoints),
checkRange(location, "matching.semantics.calibration.probability_bp", point.Probability, 0, basisPointsPerUnit),
); err != nil {
return err
}
if index > 0 {
previous := policy.Calibration[index-1]
if point.Score < previous.Score || point.Probability < previous.Probability {
return invalidPolicy(location, "matching.semantics.calibration must not decrease")
}
}
}
if first, last := policy.Calibration[0], policy.Calibration[len(policy.Calibration)-1]; first.Score == last.Score {
return invalidPolicy(location, "matching.semantics.calibration must span a cosine range")
}
if err := firstError(
checkRange(location, "matching.semantics.skill_medium_bp", policy.SkillMedium, 1, basisPointsPerUnit),
checkRange(location, "matching.semantics.skill_high_bp", policy.SkillHigh, policy.SkillMedium, basisPointsPerUnit),
checkRange(location, "matching.semantics.task_medium_bp", policy.TaskMedium, 1, basisPointsPerUnit),
checkRange(location, "matching.semantics.task_high_bp", policy.TaskHigh, policy.TaskMedium, basisPointsPerUnit),
checkRange(location, "matching.semantics.max_evidence_per_entry", policy.MaxEvidencePerEntry, 0, maxSemanticEvidencePerEntry),
); err != nil {
return err
}
if policy.Source == "" || utf8.RuneCountInString(policy.Source) > maxSemanticSourceRunes || singleLineTextProblem(policy.Source, maxSemanticSourceRunes) != "" {
return invalidPolicy(location, "matching.semantics.source must name the data behind the values")
}
return nil
}
func (policy MatchingSemanticsPolicy) validateMembers() error {
const location = "MatchingSemanticsPolicy.Validate"
if len(policy.Members) == 0 || len(policy.Members) > maxSemanticMembers {
return invalidPolicy(location, fmt.Sprintf("matching.semantics.members needs between 1 and %d members", maxSemanticMembers))
}
var total BasisPoints
seen := make(map[SemanticModel]struct{}, len(policy.Members))
for _, member := range policy.Members {
if err := member.Model.Validate(); err != nil {
return invalidPolicy(location, "matching.semantics.members model identity is malformed")
}
if _, repeated := seen[member.Model]; repeated {
return invalidPolicy(location, "matching.semantics.members repeats a model")
}
seen[member.Model] = struct{}{}
if err := firstError(
checkRange(location, "matching.semantics.members.weight_bp", member.Weight, 1, basisPointsPerUnit),
checkRange(location, "matching.semantics.members.mean_bp", member.Mean, -basisPointsPerUnit32, basisPointsPerUnit32),
checkRange(location, "matching.semantics.members.standard_deviation_bp", member.StandardDeviation, 1, basisPointsPerUnit32),
); err != nil {
return err
}
total += member.Weight
}
if total != basisPointsPerUnit {
return invalidPolicy(location, "matching.semantics.members weights must add up to 1.0000")
}
return nil
}
// basisPointsPerUnit32 is basisPointsPerUnit for int32 fields.
const basisPointsPerUnit32 = int32(basisPointsPerUnit)
// Probability maps a fused score to Sem in micro units (1e-6), interpolating
// linearly between calibration points in integer arithmetic. A score at a
// repeated point takes the higher probability, the right limit of the step.
func (policy MatchingSemanticsPolicy) Probability(score float64) int64 {
const microPerBasisPoint = 100
points := policy.Calibration
if len(points) == 0 {
return 0
}
// The score in micro units, rounded half away from zero.
value := int64(math.Round(score * 1_000_000))
micro := func(point MatchingCalibrationPoint) (int64, int64) {
return int64(point.Score) * microPerBasisPoint, int64(point.Probability) * microPerBasisPoint
}
firstX, firstY := micro(points[0])
if value < firstX {
return firstY
}
for index := len(points) - 1; index >= 0; index-- {
x0, y0 := micro(points[index])
if value < x0 {
continue
}
if index == len(points)-1 {
return y0
}
x1, y1 := micro(points[index+1])
if x1 == x0 {
return y1
}
return y0 + ((y1-y0)*(value-x0)+(x1-x0)/2)/(x1-x0)
}
return firstY
}
// ItemBand returns the explanation band of an item similarity for a skill or
// a task requirement, or "" below the medium threshold.
func (policy MatchingSemanticsPolicy) ItemBand(task bool, cosine float64) SemanticSimilarityBand {
medium, high := policy.SkillMedium, policy.SkillHigh
if task {
medium, high = policy.TaskMedium, policy.TaskHigh
}
scaled := cosine * float64(basisPointsPerUnit)
switch {
case scaled >= float64(high):
return SemanticSimilarityHigh
case scaled >= float64(medium):
return SemanticSimilarityMedium
default:
return ""
}
}
// SemanticSimilarityBand is the coarse band of an explanation item.
type SemanticSimilarityBand string
const (
SemanticSimilarityHigh SemanticSimilarityBand = "high"
SemanticSimilarityMedium SemanticSimilarityBand = "medium"
)
// Giga-Embeddings-instruct-480M at the pinned revision with the service
// prompt recipe; the ML service reports the same identity.
const (
GigaEmbeddingsModelID = "ai-sage/Giga-Embeddings-instruct-480M-0826"
GigaEmbeddingsModelRevision = "1763d603adac8057bd6482a708001b0ed2e0a903"
GigaEmbeddingsPromptVersion = "giga-card-mean-v1"
)
// DemoMatchingSemanticsPolicy returns the semantic section fitted on the DEV
// split of the LincodexMatch research (30 needs, 3220 judged pairs, 994 with
// consensus >= 2):
// - Calibration is the isotonic fit of P(consensus >= 2) on the cosine of
// the need view with the query prompt and the profile view without one
// (ECE 0.015-0.049 against 0.17-0.57 for the raw cosine), rounded to four
// decimals.
// - The item thresholds are where an isotonic fit of P(pair relevant) on
// the best item cosine of a requirement reaches 0.5 (medium) and 0.7
// (high): skills 0.3673 and 0.4607, tasks 0.2997 and 0.4192.
//
// The research profiles carry experience texts that the anonymous card does
// not, so product cosines are lower; the values are a calibrated starting
// point, not a product measurement.
func DemoMatchingSemanticsPolicy() MatchingSemanticsPolicy {
return MatchingSemanticsPolicy{
Members: []MatchingSemanticMember{{
Model: SemanticModel{
ID: GigaEmbeddingsModelID, Revision: GigaEmbeddingsModelRevision, PromptVersion: GigaEmbeddingsPromptVersion,
},
Weight: basisPointsPerUnit, Mean: 0, StandardDeviation: basisPointsPerUnit32,
}},
Calibration: demoSemanticCalibration(),
SkillMedium: 3673,
SkillHigh: 4607,
TaskMedium: 2997,
TaskHigh: 4192,
MaxEvidencePerEntry: 6,
Source: "LincodexMatch research 2026-10-10, DEV split, giga-480m isotonic fit (reports/step3)",
}
}
func demoSemanticCalibration() []MatchingCalibrationPoint {
return []MatchingCalibrationPoint{
{674, 0}, {2120, 0}, {2120, 45}, {2567, 45},
{2570, 154}, {2692, 154}, {2692, 458}, {2970, 458},
{2972, 735}, {3064, 735}, {3067, 758}, {3319, 758},
{3319, 833}, {3334, 833}, {3335, 1000}, {3345, 1000},
{3345, 1006}, {3666, 1006}, {3669, 1071}, {3726, 1071},
{3727, 1702}, {3762, 1702}, {3763, 1744}, {3837, 1744},
{3838, 1962}, {3998, 1962}, {3999, 2000}, {4002, 2000},
{4003, 2143}, {4018, 2143}, {4019, 2353}, {4070, 2353},
{4070, 2674}, {4130, 2674}, {4130, 2816}, {4286, 2816},
{4287, 3404}, {4330, 3404}, {4331, 3497}, {4462, 3497},
{4463, 4000}, {4494, 4000}, {4494, 4286}, {4503, 4286},
{4506, 4583}, {4537, 4583}, {4538, 5000}, {4543, 5000},
{4543, 5117}, {4760, 5117}, {4760, 5667}, {4795, 5667},
{4795, 5714}, {4822, 5714}, {4824, 5769}, {4852, 5769},
{4854, 5890}, {4935, 5890}, {4935, 6111}, {4949, 6111},
{4950, 7097}, {4988, 7097}, {4988, 7324}, {5078, 7324},
{5078, 7647}, {5108, 7647}, {5113, 7714}, {5161, 7714},
{5162, 7778}, {5392, 7778}, {5394, 8049}, {5461, 8049},
{5463, 9167}, {5532, 9167}, {5533, 9259}, {5926, 9259},
{5932, 9574}, {6260, 9574}, {6269, 10000}, {7049, 10000},
}
}
Loaded 100 of 215 files, more files were not shown because too many files have changed in this diff. Show more