diff --git a/.agents/standards/ml.md b/.agents/standards/ml.md index 18548e8..0c74bbc 100644 --- a/.agents/standards/ml.md +++ b/.agents/standards/ml.md @@ -1,6 +1,6 @@ # ML service standard -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. +The ML service is a separate Python HTTP service. It serves health and readiness routes and one model-backed endpoint, `POST /v1/embeddings`, with pinned embedding models whose files are verified against the lock files in ml/model/ (baked into the image, or local files on a GPU host). Every route except health and readiness requires the shared bearer token. Ordinary tests use the deterministic fake encoder; the real models run only in the marked slow tests. 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. diff --git a/.env.example b/.env.example index b9cf5f6..bcfe470 100644 --- a/.env.example +++ b/.env.example @@ -142,5 +142,9 @@ GRAFANA_ADMIN_PASSWORD=replace-this-grafana-password ML_BIND_ADDRESS=127.0.0.1 ML_HTTP_PORT=8000 ML_METRICS_TARGET= +# Shared bearer token of the ML service and the backend (a secret of at least +# 32 characters, for example openssl rand -hex 32); required by the ML +# container and by the backend while SEMANTIC_MATCHING_ENABLED is true. +ML_SERVICE_TOKEN= # For rootless Docker, use the Unix socket from `docker context inspect`. DOCKER_SOCKET_PATH=/var/run/docker.sock diff --git a/api/ml/components/schemas.yml b/api/ml/components/schemas.yml index 9e314b3..ec37885 100644 --- a/api/ml/components/schemas.yml +++ b/api/ml/components/schemas.yml @@ -16,7 +16,7 @@ EmbeddingText: 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.' + 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 installation, device, precision, and thread count give the same vectors.' additionalProperties: false required: - kind @@ -27,7 +27,7 @@ EmbeddingRequest: 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`. + description: Identifier of the model to use, as `EmbeddingModel.id` reports it. Absent means the default model of the service, the first one it is configured with. 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: diff --git a/api/ml/components/schemas/embedding_schemas.yml b/api/ml/components/schemas/embedding_schemas.yml index cd9fa7c..2844fcb 100644 --- a/api/ml/components/schemas/embedding_schemas.yml +++ b/api/ml/components/schemas/embedding_schemas.yml @@ -25,7 +25,7 @@ schemas: 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. + installation, device, precision, and thread count give the same vectors. additionalProperties: false required: - kind @@ -38,10 +38,10 @@ schemas: 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`. + Absent means the default model of the service, the first one it is + configured with. 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: diff --git a/api/ml/openapi.bundle.yml b/api/ml/openapi.bundle.yml index 3a525e3..d87d7c6 100644 --- a/api/ml/openapi.bundle.yml +++ b/api/ml/openapi.bundle.yml @@ -2,8 +2,21 @@ openapi: 3.2.0 info: title: Lincodex ML Operational API version: 0.1.0 + description: |- + Internal API of the ML service. Only the Go backend calls it; it is never + exposed to browsers or to the public network. + + Authentication: every operation except the health routes requires + `Authorization: Bearer ` when the service has a token, and the + service refuses to listen on a non-loopback address without one. The + token is a shared random secret of at least 32 printable characters from + the deployment secret store, never from this repository. A missing or + wrong token answers 401 `unauthenticated`. A service without a token + answers only callers on its own loopback interface. servers: - url: / +security: + - bearerAuth: [] paths: /healthz: get: @@ -46,12 +59,11 @@ paths: /v1/embeddings: post: operationId: CreateMLEmbeddings - summary: Encode texts into normalized vectors with the pinned embedding model. + summary: Encode texts into normalized vectors with a 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. + Internal operation for the Go backend; it is not reachable from browsers and needs the service bearer token. 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: [] + The service may load several pinned models, for example the members of an ensemble; `model` selects one, and the response names the model, revision, dimension, and prompt version that produced the vectors. The service answers 503 service_unavailable until every configured model is loaded and a warm-up encode has finished, and when the device runs out of memory for a request; `/readyz` reports the same state. A request without a valid token answers 401, 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. tags: - inference requestBody: @@ -69,6 +81,8 @@ paths: $ref: '#/components/schemas/EmbeddingResponse' '400': $ref: '#/components/responses/Problem' + '401': + $ref: '#/components/responses/Problem' '413': $ref: '#/components/responses/Problem' '503': @@ -76,6 +90,11 @@ paths: default: $ref: '#/components/responses/Problem' components: + securitySchemes: + bearerAuth: + type: http + scheme: bearer + description: 'Shared random service token sent as `Authorization: Bearer `. The service compares it in constant time and never logs it. Rotation replaces the secret on both sides; there are no per-user tokens.' responses: Problem: description: Any error response. The body is a Problem whose `status` equals the HTTP status and whose `code` is one of ProblemCode. @@ -275,7 +294,7 @@ components: 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.' + 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 installation, device, precision, and thread count give the same vectors.' additionalProperties: false required: - kind @@ -286,7 +305,7 @@ components: 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`. + description: Identifier of the model to use, as `EmbeddingModel.id` reports it. Absent means the default model of the service, the first one it is configured with. 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: diff --git a/api/ml/openapi.yml b/api/ml/openapi.yml index e749fac..2a75405 100644 --- a/api/ml/openapi.yml +++ b/api/ml/openapi.yml @@ -2,8 +2,21 @@ openapi: 3.2.0 info: title: Lincodex ML Operational API version: 0.1.0 + description: |- + Internal API of the ML service. Only the Go backend calls it; it is never + exposed to browsers or to the public network. + + Authentication: every operation except the health routes requires + `Authorization: Bearer ` when the service has a token, and the + service refuses to listen on a non-loopback address without one. The + token is a shared random secret of at least 32 printable characters from + the deployment secret store, never from this repository. A missing or + wrong token answers 401 `unauthenticated`. A service without a token + answers only callers on its own loopback interface. servers: - url: / +security: + - bearerAuth: [] paths: /healthz: $ref: ./routes/healthz.yml @@ -12,6 +25,14 @@ paths: /v1/embeddings: $ref: ./routes/embeddings.yml components: + securitySchemes: + bearerAuth: + type: http + scheme: bearer + description: >- + Shared random service token sent as `Authorization: Bearer `. + The service compares it in constant time and never logs it. Rotation + replaces the secret on both sides; there are no per-user tokens. responses: Problem: $ref: ./components/responses.yml#/Problem diff --git a/api/ml/routes/embeddings.yml b/api/ml/routes/embeddings.yml index 3c03fdd..2792947 100644 --- a/api/ml/routes/embeddings.yml +++ b/api/ml/routes/embeddings.yml @@ -1,11 +1,10 @@ post: operationId: CreateMLEmbeddings - summary: Encode texts into normalized vectors with the pinned embedding model. + summary: Encode texts into normalized vectors with a 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. + Internal operation for the Go backend; it is not reachable from browsers and needs the service bearer token. 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: [] + The service may load several pinned models, for example the members of an ensemble; `model` selects one, and the response names the model, revision, dimension, and prompt version that produced the vectors. The service answers 503 service_unavailable until every configured model is loaded and a warm-up encode has finished, and when the device runs out of memory for a request; `/readyz` reports the same state. A request without a valid token answers 401, 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. tags: - inference requestBody: @@ -23,6 +22,8 @@ post: $ref: ../components/schemas.yml#/EmbeddingResponse "400": $ref: ../components/responses.yml#/Problem + "401": + $ref: ../components/responses.yml#/Problem "413": $ref: ../components/responses.yml#/Problem "503": diff --git a/backend/README.en.md b/backend/README.en.md index e070244..b082be1 100644 --- a/backend/README.en.md +++ b/backend/README.en.md @@ -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:'` (`cmd/policy-publish`), the semantic section with `ARGS='semantic --actor operator:'`, and schedules vectors for existing data with `make semantic-backfill ARGS='all --run