feat(ml): add isolated embeddings service and scoped client

This commit is contained in:
Anya Tokugawa committed 2026-11-30 23:03:13 +09:00
1 parent 46c185d928
commit 0c7897d695
13 files changed
+1112

No files matched your search

+38
View File
@@ -0,0 +1,38 @@
# Optional pilot only; does not enable indexing or modify the Pages database.
# docker compose -f docker-compose.yml -f docker-compose.ml.yml up -d --build machine-learning
services:
app:
networks:
ml-front: {}
machine-learning:
build: ./services/machine-learning
image: pageswiki-machine-learning:dev
environment:
PAGES_ML_TOKEN_FILE: /run/secrets/ml-token
PAGES_ML_MODEL_DIR: /models
PAGES_ML_ALLOW_OPENAI: "false"
volumes:
- ${PAGES_ML_TOKEN_PATH:?Set absolute shared token file path}:/run/secrets/ml-token:ro
- ${PAGES_ML_MODELS_PATH:?Set absolute trusted model directory path}:/models:ro
expose: ["8010"]
networks:
ml-front: {}
read_only: true
tmpfs: [/tmp:size=32m,mode=1777]
cap_drop: [ALL]
security_opt: [no-new-privileges:true]
mem_limit: 1g
cpus: 1.0
pids_limit: 64
restart: unless-stopped
healthcheck:
test: [CMD, python, -c, "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8010/healthz', timeout=2).read()"]
interval: 30s
timeout: 3s
retries: 3
networks:
ml-front:
internal: true
ipam:
config:
- subnet: ${PAGES_ML_FRONT_SUBNET:-172.24.1.0/27}
+177
View File
@@ -0,0 +1,177 @@
// Package machinelearning implements the private Pages Machine Learning v1
// transport. Callers must authorize corpus scope and external transmission,
// enqueue work, and recheck revision/policy generations before persisting results.
// This package does not discover documents, retry requests, or change City paths.
package machinelearning
import (
"bytes"
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"math"
"net/http"
"net/url"
"regexp"
"strings"
"time"
"unicode/utf8"
"github.com/google/uuid"
)
const maxBody = 128 * 1024
const maxResponse = 2 * 1024 * 1024
var safeToken = regexp.MustCompile(`^[A-Za-z0-9_-]{32,256}$`)
var safeID = regexp.MustCompile(`^[A-Za-z0-9_.:-]{1,128}$`)
var modelHash = regexp.MustCompile(`^[0-9a-f]{64}$`)
type Input struct {
ID string `json:"id"`
Text string `json:"text"`
}
type Request struct {
Protocol string `json:"protocol"`
DomainUUID string `json:"domain_uuid"`
ScopeUUID string `json:"scope_uuid"`
Provider string `json:"provider"`
Model string `json:"model"`
Dimensions int `json:"dimensions"`
Inputs []Input `json:"inputs"`
AllowExternal bool `json:"allow_external"`
}
type Output struct {
ID string `json:"id"`
InputSHA256 string `json:"input_sha256"`
Vector []float64 `json:"vector"`
}
type Result struct {
Protocol string `json:"protocol"`
DomainUUID string `json:"domain_uuid"`
ScopeUUID string `json:"scope_uuid"`
Provider string `json:"provider"`
Model string `json:"model"`
ModelRevision string `json:"model_revision"`
Dimensions int `json:"dimensions"`
Tokenizer string `json:"tokenizer"`
Outputs []Output `json:"outputs"`
Usage struct {
TotalTokens int64 `json:"total_tokens"`
} `json:"usage"`
}
// StatusError intentionally excludes the remote response body and request URL.
// Retry scheduling belongs to Pages; failures can include uncertain API charges.
type StatusError struct{ Status int }
func (e *StatusError) Error() string { return fmt.Sprintf("machine learning HTTP status %d", e.Status) }
type Client struct {
endpoint string
token string
http *http.Client
}
// NewClient accepts an operator-configured private service origin, never a
// document-provided URL. HTTP is for an isolated local network only; use HTTPS
// and network access control for remote hosts. There is no insecure TLS option.
func NewClient(origin, token string) (*Client, error) {
u, err := url.Parse(origin)
if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Hostname() == "" || u.User != nil || u.RawQuery != "" || u.Fragment != "" || (u.Path != "" && u.Path != "/") || !safeToken.MatchString(token) {
return nil, errors.New("invalid machine learning service configuration")
}
transport := http.DefaultTransport.(*http.Transport).Clone()
transport.Proxy = nil // Do not leak the private shared token to an env proxy.
return &Client{endpoint: strings.TrimSuffix(origin, "/") + "/v1/embeddings", token: token,
http: &http.Client{Transport: transport, Timeout: 40 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}}, nil
}
func validUUID(s string) bool { id, err := uuid.Parse(s); return err == nil && id.String() == s }
func validate(req Request) error {
if req.Protocol != "1" || !validUUID(req.DomainUUID) || !validUUID(req.ScopeUUID) || req.Dimensions < 1 || req.Dimensions > 1536 || len(req.Inputs) < 1 || len(req.Inputs) > 16 {
return errors.New("invalid machine learning request")
}
if req.Provider == "openai" {
if !req.AllowExternal || req.Model != "text-embedding-3-small" {
return errors.New("external embeddings not permitted or unsupported model")
}
} else if req.Provider != "doc2vec" || !modelHash.MatchString(req.Model) {
return errors.New("invalid machine learning provider/model")
}
seen := make(map[string]bool)
for _, input := range req.Inputs {
if !safeID.MatchString(input.ID) || seen[input.ID] || strings.TrimSpace(input.Text) == "" || !utf8.ValidString(input.Text) || len(input.Text) > 6000 {
return errors.New("invalid machine learning input")
}
seen[input.ID] = true
}
return nil
}
func (c *Client) Embed(ctx context.Context, input Request) (*Result, error) {
if err := validate(input); err != nil {
return nil, err
}
body, err := json.Marshal(input)
if err != nil || len(body) > maxBody {
return nil, errors.New("machine learning input too large")
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.endpoint, bytes.NewReader(body))
if err != nil {
return nil, errors.New("machine learning request failed")
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+c.token)
response, err := c.http.Do(req)
if err != nil {
if ctx.Err() != nil {
return nil, ctx.Err()
}
return nil, errors.New("machine learning transport failed")
}
defer response.Body.Close()
if response.StatusCode != http.StatusOK {
return nil, &StatusError{Status: response.StatusCode}
}
raw, err := io.ReadAll(io.LimitReader(response.Body, maxResponse+1))
if err != nil || len(raw) > maxResponse {
return nil, errors.New("invalid machine learning response")
}
var result Result
if json.Unmarshal(raw, &result) != nil || result.Protocol != input.Protocol || result.DomainUUID != input.DomainUUID || result.ScopeUUID != input.ScopeUUID || result.Provider != input.Provider || result.Model != input.Model || result.ModelRevision != input.Model || result.Dimensions != input.Dimensions || len(result.Outputs) != len(input.Inputs) || result.Usage.TotalTokens < 0 {
return nil, errors.New("machine learning result metadata mismatch")
}
expectedTokenizer := "provider"
if input.Provider == "doc2vec" {
expectedTokenizer = "unicode-cjk-bigram-v1"
}
if result.Tokenizer != expectedTokenizer {
return nil, errors.New("machine learning tokenizer mismatch")
}
for i, output := range result.Outputs {
hash := sha256.Sum256([]byte(input.Inputs[i].Text))
if output.ID != input.Inputs[i].ID || output.InputSHA256 != hex.EncodeToString(hash[:]) || len(output.Vector) != input.Dimensions {
return nil, errors.New("machine learning output mismatch")
}
nonzero := false
for _, value := range output.Vector {
if math.IsNaN(value) || math.IsInf(value, 0) {
return nil, errors.New("non-finite machine learning vector")
}
nonzero = nonzero || value != 0
}
if !nonzero {
return nil, errors.New("empty machine learning vector")
}
}
return &result, nil
}
+134
View File
@@ -0,0 +1,134 @@
package machinelearning
import (
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"os"
"strings"
"testing"
)
func fixture() Request {
return Request{Protocol: "1", DomainUUID: "11111111-1111-4111-8111-111111111111", ScopeUUID: "22222222-2222-4222-8222-222222222222", Provider: "doc2vec", Model: strings.Repeat("a", 64), Dimensions: 2, Inputs: []Input{{ID: "page:chunk0", Text: "合成文書 library books"}}}
}
func resultFor(req Request) Result {
r := Result{Protocol: req.Protocol, DomainUUID: req.DomainUUID, ScopeUUID: req.ScopeUUID, Provider: req.Provider, Model: req.Model, ModelRevision: req.Model, Dimensions: req.Dimensions, Tokenizer: "unicode-cjk-bigram-v1"}
for _, item := range req.Inputs {
hash := sha256.Sum256([]byte(item.Text))
r.Outputs = append(r.Outputs, Output{ID: item.ID, InputSHA256: hex.EncodeToString(hash[:]), Vector: []float64{0.5, -0.2}})
}
return r
}
func TestClient(t *testing.T) {
req := fixture()
for _, test := range []struct {
name string
mutate func(*Result)
wantErr bool
}{
{"valid", func(*Result) {}, false},
{"wrong-domain", func(r *Result) { r.DomainUUID = req.ScopeUUID }, true},
{"wrong-scope", func(r *Result) { r.ScopeUUID = req.DomainUUID }, true},
{"wrong-hash", func(r *Result) { r.Outputs[0].InputSHA256 = "wrong" }, true},
{"wrong-dimensions", func(r *Result) { r.Outputs[0].Vector = []float64{1} }, true},
{"wrong-model", func(r *Result) { r.ModelRevision = "other" }, true},
{"wrong-tokenizer", func(r *Result) { r.Tokenizer = "other" }, true},
{"zero", func(r *Result) { r.Outputs[0].Vector = []float64{0, 0} }, true},
} {
t.Run(test.name, func(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/v1/embeddings" || r.Method != "POST" || r.Header.Get("Authorization") != "Bearer "+strings.Repeat("t", 40) {
t.Error("request contract")
}
var sent Request
if err := json.NewDecoder(r.Body).Decode(&sent); err != nil || sent.Inputs[0].Text != req.Inputs[0].Text {
t.Error("input changed")
}
result := resultFor(req)
test.mutate(&result)
_ = json.NewEncoder(w).Encode(result)
}))
defer server.Close()
client, err := NewClient(server.URL, strings.Repeat("t", 40))
if err != nil {
t.Fatal(err)
}
_, err = client.Embed(context.Background(), req)
if (err != nil) != test.wantErr {
t.Fatalf("unexpected error: %v", err)
}
})
}
}
func TestNoRedirectRetryOrSecretErrors(t *testing.T) {
calls := 0
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
calls++
w.Header().Set("Location", "/secret")
w.WriteHeader(307)
_, _ = w.Write([]byte("secret provider body"))
}))
defer server.Close()
client, _ := NewClient(server.URL, strings.Repeat("t", 40))
_, err := client.Embed(context.Background(), fixture())
var status *StatusError
if !errors.As(err, &status) || status.Status != 307 || calls != 1 || strings.Contains(err.Error(), "secret") {
t.Fatalf("redirect/error handling: %v calls=%d", err, calls)
}
ctx, cancel := context.WithCancel(context.Background())
cancel()
_, err = client.Embed(ctx, fixture())
if !errors.Is(err, context.Canceled) {
t.Fatal(err)
}
}
func TestRequestValidation(t *testing.T) {
for _, mutate := range []func(*Request){
func(r *Request) { r.DomainUUID = "../" }, func(r *Request) { r.Inputs[0].Text = strings.Repeat("x", 6001) },
func(r *Request) { r.Provider = "openai"; r.Model = "text-embedding-3-small" },
func(r *Request) { r.Inputs = append(r.Inputs, r.Inputs[0]) }, func(r *Request) { r.Dimensions = 1537 },
} {
req := fixture()
mutate(&req)
if validate(req) == nil {
t.Fatal("accepted invalid request")
}
}
for _, origin := range []string{"file:///tmp/x", "http://user:pass@localhost", "https://ml.invalid/path", "https://ml.invalid?x=1"} {
if _, err := NewClient(origin, strings.Repeat("t", 40)); err == nil {
t.Fatal("accepted origin", origin)
}
}
}
// Optional end-to-end contract test against a local synthetic fixture service.
// No real Pages documents, credentials, or paid OpenAI requests are used.
func TestLocalDoc2VecService(t *testing.T) {
origin := os.Getenv("PAGES_ML_TEST_ORIGIN")
if origin == "" {
t.Skip("set PAGES_ML_TEST_ORIGIN for synthetic service integration")
}
client, err := NewClient(origin, strings.Repeat("t", 40))
if err != nil {
t.Fatal(err)
}
req := fixture()
req.Model = os.Getenv("PAGES_ML_TEST_MODEL")
req.Dimensions = 8
result, err := client.Embed(context.Background(), req)
if err != nil {
t.Fatal(err)
}
if len(result.Outputs) != 1 || len(result.Outputs[0].Vector) != 8 {
t.Fatal("wrong result shape")
}
}
+119
View File
@@ -0,0 +1,119 @@
package machinelearning
import (
"errors"
"path"
"strings"
"unicode"
"unicode/utf8"
)
var ErrPolicy = errors.New("invalid machine learning policy")
var ErrNotAllowed = errors.New("machine learning scope is disabled, stale or excluded")
// Policy contains no credentials. Generation changes on every saved update,
// including disable/re-enable, so queued work cannot reuse old consent.
type Policy struct {
Generation string `json:"generation"`
Enabled bool `json:"enabled"`
ScopeUUID string `json:"scope_uuid"`
Provider string `json:"provider"`
Model string `json:"model"`
Dimensions int `json:"dimensions"`
Prefixes []string `json:"prefixes"`
Exclude []string `json:"exclude"`
AllowExternal bool `json:"allow_external"`
MaxBatchBytes int `json:"max_batch_bytes"`
DailyInputBytes int64 `json:"daily_input_bytes"`
}
// Canonical paths are decoded logical Wiki paths, not URLs or raw request URIs.
// Reject ambiguous encodings instead of silently broadening a configured scope.
func canonicalPath(p string) bool {
return utf8.ValidString(p) && len(p) <= 4096 && strings.HasPrefix(p, "/") && path.Clean(p) == p &&
!strings.ContainsAny(p, "%?#\\") && strings.IndexFunc(p, unicode.IsControl) < 0
}
func (p Policy) Validate() error {
if p.DailyInputBytes < 0 || p.DailyInputBytes > 1000000000 {
return ErrPolicy
}
if !validUUID(p.Generation) {
return ErrPolicy
}
// A new disabled configuration may have no model yet.
if !p.Enabled && p.Provider == "" && p.ScopeUUID == "" && p.Model == "" && p.Dimensions == 0 && len(p.Prefixes) == 0 && len(p.Exclude) == 0 && !p.AllowExternal && p.MaxBatchBytes == 0 {
return nil
}
if !validUUID(p.ScopeUUID) || p.Dimensions < 1 || p.Dimensions > 1536 || len(p.Prefixes) < 1 || len(p.Prefixes) > 64 || len(p.Exclude) > 64 || p.MaxBatchBytes < 1 || p.MaxBatchBytes > 96000 {
return ErrPolicy
}
switch p.Provider {
case "doc2vec":
if !modelHash.MatchString(p.Model) || p.AllowExternal {
return ErrPolicy
}
case "openai":
if p.Model != "text-embedding-3-small" || (p.Enabled && !p.AllowExternal) {
return ErrPolicy
}
default:
return ErrPolicy
}
for _, paths := range [][]string{p.Prefixes, p.Exclude} {
seen := map[string]bool{}
for _, prefix := range paths {
if !canonicalPath(prefix) || seen[prefix] {
return ErrPolicy
}
seen[prefix] = true
}
}
return nil
}
func under(p, prefix string) bool {
return prefix == "/" || p == prefix || strings.HasPrefix(p, prefix+"/")
}
// Allows is an additional scope check, NOT document authorization. Callers must
// still check the current principal, revision, and learning cohort membership.
func (p Policy) Allows(logicalPath, generation string) bool {
if p.Validate() != nil || !p.Enabled || generation != p.Generation || !canonicalPath(logicalPath) {
return false
}
for _, prefix := range p.Exclude {
if under(logicalPath, prefix) {
return false
}
}
for _, prefix := range p.Prefixes {
if under(logicalPath, prefix) {
return true
}
}
return false
}
// Prepare binds model and consent to a freshly loaded policy rather than to
// caller-provided JSON. Inputs must be authorized chunks of this one document.
// The batch limit is not a daily budget or a monetary cost ceiling.
func (p Policy) Prepare(domain, logicalPath, generation string, inputs []Input) (Request, error) {
if !p.Allows(logicalPath, generation) {
return Request{}, ErrNotAllowed
}
bytes := 0
for _, input := range inputs {
bytes += len(input.Text)
if bytes > p.MaxBatchBytes {
return Request{}, ErrNotAllowed
}
}
req := Request{Protocol: "1", DomainUUID: domain, ScopeUUID: p.ScopeUUID, Provider: p.Provider, Model: p.Model, Dimensions: p.Dimensions, Inputs: inputs, AllowExternal: p.AllowExternal}
if err := validate(req); err != nil {
return Request{}, err
}
// Do not retain caller-owned slice memory across a queued operation.
req.Inputs = append([]Input(nil), inputs...)
return req, nil
}
+72
View File
@@ -0,0 +1,72 @@
package machinelearning
import (
"strings"
"testing"
)
func policyFixture() Policy {
return Policy{Generation: "33333333-3333-4333-8333-333333333333", Enabled: true, ScopeUUID: fixture().ScopeUUID, Provider: "doc2vec", Model: strings.Repeat("a", 64), Dimensions: 8, Prefixes: []string{"/lab"}, Exclude: []string{"/lab/private"}, MaxBatchBytes: 12000}
}
func TestPolicyPaths(t *testing.T) {
p := policyFixture()
for _, tc := range []struct {
path string
allow bool
}{
{"/lab", true}, {"/lab/文書", true}, {"/labs", false}, {"/lab/private", false}, {"/lab/private/child", false},
{"/lab/private-other", true}, {"/lab/../secret", false}, {"/lab/%70rivate", false}, {"/lab//a", false}, {"https://example.com/lab", false}, {"/lab/a?b", false},
} {
if p.Allows(tc.path, p.Generation) != tc.allow {
t.Errorf("path %q", tc.path)
}
}
p.Prefixes = []string{"/"}
if !p.Allows("/other", p.Generation) || p.Allows("/lab/private/x", p.Generation) {
t.Fatal("root/exclusion")
}
if p.Allows("/lab", "stale") {
t.Fatal("stale generation accepted")
}
p.Enabled = false
if p.Allows("/lab", p.Generation) {
t.Fatal("disabled scope accepted")
}
}
func TestPolicyValidationAndPrepare(t *testing.T) {
for _, mutate := range []func(*Policy){
func(p *Policy) { p.Prefixes = []string{"/lab/"} }, func(p *Policy) { p.Exclude = []string{"relative"} },
func(p *Policy) { p.AllowExternal = true }, func(p *Policy) { p.MaxBatchBytes = 0 },
func(p *Policy) { p.Provider = "openai"; p.Model = "text-embedding-3-small" },
} {
p := policyFixture()
mutate(&p)
if p.Validate() == nil {
t.Fatal("invalid policy accepted")
}
}
p := policyFixture()
inputs := []Input{{ID: "chunk:0", Text: "合成文書"}}
req, err := p.Prepare(fixture().DomainUUID, "/lab/page", p.Generation, inputs)
if err != nil {
t.Fatal(err)
}
inputs[0].Text = "changed"
if req.Inputs[0].Text == "changed" || req.AllowExternal {
t.Fatal("input/consent binding")
}
p.MaxBatchBytes = 2
if _, err = p.Prepare(fixture().DomainUUID, "/lab/page", p.Generation, inputs); err == nil {
t.Fatal("batch budget")
}
p = policyFixture()
p.Provider = "openai"
p.Model = "text-embedding-3-small"
p.AllowExternal = true
req, err = p.Prepare(fixture().DomainUUID, "/lab/page", p.Generation, inputs)
if err != nil || !req.AllowExternal {
t.Fatalf("explicit external policy: %v", err)
}
}
+5
View File
@@ -0,0 +1,5 @@
*
!Dockerfile
!requirements.txt
!pages_ml.py
!train.py
+5
View File
@@ -0,0 +1,5 @@
__pycache__/
*.pyc
.venv/
models/
*.jsonl
+10
View File
@@ -0,0 +1,10 @@
FROM python:3.12-slim-bookworm
ENV PYTHONUNBUFFERED=1 PYTHONDONTWRITEBYTECODE=1 PYTHONHASHSEED=0 \
OPENBLAS_NUM_THREADS=1 OMP_NUM_THREADS=1 MKL_NUM_THREADS=1
WORKDIR /app
COPY requirements.txt ./
RUN pip install --no-cache-dir -r requirements.txt
COPY pages_ml.py train.py ./
USER 65532:65532
EXPOSE 8010
CMD ["gunicorn", "--bind", "0.0.0.0:8010", "--workers", "1", "--worker-class", "gthread", "--threads", "2", "--timeout", "60", "--worker-tmp-dir", "/tmp", "--no-control-socket", "--limit-request-line", "1024", "--limit-request-fields", "30", "pages_ml:create_app()"]
+265
View File
@@ -0,0 +1,265 @@
"""Internal stateless ML API. No Pages database access or document fetching.
Run with one gunicorn worker, two threads: inference is serialized while health
checks and busy responses remain available. Never publish this API to browsers.
"""
import hashlib
import hmac
import json
import logging
import math
import os
from pathlib import Path
import re
import threading
import unicodedata
import urllib.error
import urllib.request
import uuid
VERSION = "1"
TOKENIZER = "unicode-cjk-bigram-v1"
MAX_BODY = 128 * 1024
MAX_ITEMS = 16
MAX_TEXT_BYTES = 6000
MAX_DIMENSIONS = 1536
MAX_RESPONSE = 2 * 1024 * 1024
class Failure(Exception):
def __init__(self, status, code):
self.status, self.code = status, code
def digest(data):
return hashlib.sha256(data).hexdigest()
def valid_uuid(value):
try:
return isinstance(value, str) and str(uuid.UUID(value)) == value
except ValueError:
return False
def tokens(text):
"""Deterministic baseline, not a Japanese morphological analyzer."""
text = unicodedata.normalize("NFKC", text).casefold()
result = []
for part in re.findall(r"[\u3040-\u30ff\u3400-\u9fff]+|[^\W_\u3040-\u30ff\u3400-\u9fff]+", text):
if re.fullmatch(r"[\u3040-\u30ff\u3400-\u9fff]+", part):
result.extend(part[i:i+2] for i in range(max(1, len(part)-1)))
else:
result.append(part)
return result
def validate_request(data):
fields = {"protocol", "domain_uuid", "scope_uuid", "provider", "model", "dimensions", "inputs", "allow_external"}
if not isinstance(data, dict) or set(data) - fields or data.get("protocol") != VERSION:
raise Failure(400, "invalid_request")
if not valid_uuid(data.get("domain_uuid")) or not valid_uuid(data.get("scope_uuid")):
raise Failure(400, "invalid_scope")
dims = data.get("dimensions")
if type(dims) is not int or not 1 <= dims <= MAX_DIMENSIONS:
raise Failure(400, "invalid_dimensions")
if data.get("provider") not in ("openai", "doc2vec") or not isinstance(data.get("model"), str):
raise Failure(400, "invalid_provider")
if "allow_external" in data and type(data["allow_external"]) is not bool:
raise Failure(400, "invalid_external_consent")
inputs = data.get("inputs")
if not isinstance(inputs, list) or not 1 <= len(inputs) <= MAX_ITEMS:
raise Failure(400, "invalid_inputs")
ids = set()
for item in inputs:
if not isinstance(item, dict) or set(item) != {"id", "text"}:
raise Failure(400, "invalid_input")
ident, text = item["id"], item["text"]
if not isinstance(ident, str) or not re.fullmatch(r"[A-Za-z0-9_.:-]{1,128}", ident) or ident in ids:
raise Failure(400, "invalid_input_id")
if not isinstance(text, str) or not text.strip() or len(text.encode("utf-8")) > MAX_TEXT_BYTES:
raise Failure(400, "invalid_text")
ids.add(ident)
return data
def validate_vectors(vectors, count, dims):
if not isinstance(vectors, list) or len(vectors) != count:
raise Failure(502, "invalid_provider_output")
for vector in vectors:
if not isinstance(vector, list) or len(vector) != dims or any(
type(x) not in (int, float) or not -1e100 <= x <= 1e100 or not math.isfinite(x) for x in vector
) or not any(x != 0 for x in vector):
raise Failure(502, "invalid_provider_output")
class NoRedirect(urllib.request.HTTPRedirectHandler):
def redirect_request(self, req, fp, code, msg, headers, newurl):
return None
class Engine:
def __init__(self, model_root, external_enabled=False, api_key=""):
self.model_root = Path(model_root)
self.external_enabled = external_enabled
self.api_key = api_key
self.cached = None # One resident model at most, serialized inference.
def embed(self, data):
if data["provider"] == "openai":
vectors, revision, usage = self.openai(data)
tokenizer = "provider"
else:
vectors, revision, usage = self.doc2vec(data)
tokenizer = TOKENIZER
validate_vectors(vectors, len(data["inputs"]), data["dimensions"])
return {
"protocol": VERSION, "domain_uuid": data["domain_uuid"], "scope_uuid": data["scope_uuid"],
"provider": data["provider"], "model": data["model"], "model_revision": revision,
"dimensions": data["dimensions"], "tokenizer": tokenizer, "usage": usage,
"outputs": [{"id": item["id"], "input_sha256": digest(item["text"].encode("utf-8")), "vector": vector}
for item, vector in zip(data["inputs"], vectors)],
}
def openai(self, data):
if not self.external_enabled or data.get("allow_external") is not True or not self.api_key:
raise Failure(403, "external_disabled")
if data["model"] != "text-embedding-3-small":
raise Failure(400, "unsupported_model")
# Fixed HTTPS endpoint; request bodies cannot choose an origin or API key.
body = json.dumps({"model": data["model"], "input": [x["text"] for x in data["inputs"]],
"dimensions": data["dimensions"], "encoding_format": "float"}).encode()
request = urllib.request.Request("https://api.openai.com/v1/embeddings", body,
{"Authorization": "Bearer " + self.api_key, "Content-Type": "application/json"})
try:
with urllib.request.build_opener(NoRedirect()).open(request, timeout=30) as response:
raw = response.read(MAX_RESPONSE + 1)
if len(raw) > MAX_RESPONSE:
raise Failure(502, "invalid_provider_output")
result = json.loads(raw)
entries = result["data"]
if any(type(x["index"]) is not int for x in entries) or sorted(x["index"] for x in entries) != list(range(len(data["inputs"]))):
raise ValueError("indices")
if result["model"] != data["model"]:
raise ValueError("model")
usage = result["usage"]["total_tokens"]
if type(usage) is not int or usage < 0:
raise ValueError("usage")
return [x["embedding"] for x in sorted(entries, key=lambda x: x["index"])], result["model"], {"total_tokens": usage}
except urllib.error.HTTPError as error:
# Never expose upstream bodies (may include input or secrets).
raise Failure(429 if error.code == 429 else 502, "provider_rate_limited" if error.code == 429 else "provider_failed") from None
except (OSError, ValueError, KeyError, TypeError):
raise Failure(502, "provider_failed") from None
def doc2vec(self, data):
model_id = data["model"]
if not re.fullmatch(r"[0-9a-f]{64}", model_id):
raise Failure(400, "invalid_model")
directory = self.model_root / data["domain_uuid"] / data["scope_uuid"] / model_id
# Operator-created read-only models only; no uploads or arbitrary paths.
try:
if directory.is_symlink() or not directory.resolve().is_relative_to(self.model_root.resolve()):
raise Failure(404, "model_not_found")
manifest_path = directory / "manifest.json"
if manifest_path.is_symlink() or manifest_path.stat().st_size > 8192:
raise Failure(409, "model_metadata_mismatch")
manifest = json.loads(manifest_path.read_text())
expected = {"domain_uuid": data["domain_uuid"], "scope_uuid": data["scope_uuid"],
"tokenizer": TOKENIZER, "dimensions": data["dimensions"], "model_sha256": model_id}
if any(manifest.get(k) != v for k, v in expected.items()):
raise Failure(409, "model_metadata_mismatch")
path = directory / "model.bin"
if path.is_symlink():
raise Failure(409, "model_metadata_mismatch")
stat = path.stat()
key = (str(directory), stat.st_ino, stat.st_size, stat.st_mtime_ns)
if self.cached is None or self.cached[0] != key:
self.cached = None
if stat.st_size > 256 * 1024 * 1024:
raise Failure(413, "model_too_large")
if digest(path.read_bytes()) != model_id:
raise Failure(409, "model_digest_mismatch")
from gensim.models.doc2vec import Doc2Vec
model = Doc2Vec.load(str(path))
if model.vector_size != data["dimensions"]:
raise Failure(409, "model_metadata_mismatch")
self.cached = (key, model)
model = self.cached[1]
vectors = []
for item in data["inputs"]:
words = tokens(item["text"])
if not any(word in model.wv for word in words):
raise Failure(422, "no_known_tokens")
model.random.seed(int(digest(item["text"].encode())[:8], 16))
vectors.append(model.infer_vector(words, epochs=30).tolist())
return vectors, model_id, {"total_tokens": 0}
except FileNotFoundError:
self.cached = None
raise Failure(404, "model_not_found") from None
class Application:
def __init__(self, token, engine):
if not re.fullmatch(r"[A-Za-z0-9_-]{32,256}", token):
raise ValueError("ML token must contain 32-256 URL-safe characters")
self.token, self.engine = token, engine
self.slot = threading.BoundedSemaphore(1)
def __call__(self, environ, start_response):
try:
method, path = environ.get("REQUEST_METHOD"), environ.get("PATH_INFO")
if method == "GET" and path == "/healthz":
return self.response(start_response, 200, {"status": "ok", "protocol": VERSION})
authorization = environ.get("HTTP_AUTHORIZATION", "").encode()
if not hmac.compare_digest(authorization, ("Bearer " + self.token).encode()):
raise Failure(401, "unauthorized")
if method != "POST" or path != "/v1/embeddings":
raise Failure(404, "not_found")
if environ.get("CONTENT_TYPE", "").split(";", 1)[0].strip() != "application/json":
raise Failure(415, "json_required")
try:
length = int(environ.get("CONTENT_LENGTH", ""))
except ValueError:
raise Failure(411, "length_required") from None
if not 0 < length <= MAX_BODY:
raise Failure(413, "body_too_large")
if not self.slot.acquire(blocking=False):
raise Failure(429, "busy")
try:
raw = environ["wsgi.input"].read(length)
if len(raw) != length:
raise Failure(400, "incomplete_body")
try:
data = validate_request(json.loads(raw))
except (ValueError, UnicodeError):
raise Failure(400, "invalid_json") from None
result = self.engine.embed(data)
finally:
self.slot.release()
return self.response(start_response, 200, result)
except Failure as error:
return self.response(start_response, error.status, {"error": error.code})
except Exception:
logging.error("ML operation failed (internal_error)")
return self.response(start_response, 500, {"error": "internal_error"})
@staticmethod
def response(start_response, status, data):
from http import HTTPStatus
body = json.dumps(data, allow_nan=False, separators=(",", ":")).encode()
headers = [("Content-Type", "application/json"), ("Content-Length", str(len(body))), ("Cache-Control", "no-store")]
if status == 429:
headers.append(("Retry-After", "5"))
start_response(f"{status} {HTTPStatus(status).phrase}", headers)
return [body]
def create_app():
token = Path(os.environ["PAGES_ML_TOKEN_FILE"]).read_text().strip()
enabled = os.getenv("PAGES_ML_ALLOW_OPENAI", "false") == "true"
key_file = os.getenv("PAGES_ML_OPENAI_KEY_FILE", "")
key = Path(key_file).read_text().strip() if enabled and key_file else ""
if enabled and not key:
raise ValueError("OpenAI enabled but no key file configured")
return Application(token, Engine(os.getenv("PAGES_ML_MODEL_DIR", "/models"), enabled, key))
@@ -0,0 +1,7 @@
gensim==4.4.0
gunicorn==27.0.1
numpy==2.2.6
scipy==1.15.3
smart_open==7.3.0.post1
wrapt==1.17.3
packaging==25.0
+71
View File
@@ -0,0 +1,71 @@
"""Synthetic training -> Gunicorn HTTP -> Go client. No Docker or paid API.
Run using the same pinned dependencies as the service. All artifacts are placed
in a temporary directory and removed on exit. Requires localhost listening.
"""
import json
import os
from pathlib import Path
import socket
import subprocess
import sys
import tempfile
import time
import urllib.request
from train import train
DOMAIN = "11111111-1111-4111-8111-111111111111"
SCOPE = "22222222-2222-4222-8222-222222222222"
def main():
service = Path(__file__).resolve().parent
with tempfile.TemporaryDirectory(prefix="pages-ml-smoke-") as root:
root = Path(root)
source = root / "fixture.jsonl"
source.write_text("\n".join(json.dumps({"text": t}) for t in [
"合成文書 library books reading", "図書館 本 library books documents",
"network server routing 文書", "サーバー network server machines"]))
manifest = train(source, root / "models", DOMAIN, SCOPE, 8)
token_path = root / "token"
token_path.write_text("t" * 40)
token_path.chmod(0o600)
env = dict(os.environ, PAGES_ML_TOKEN_FILE=str(token_path),
PAGES_ML_MODEL_DIR=str(root / "models"), PAGES_ML_ALLOW_OPENAI="false")
with socket.socket() as sock:
sock.bind(("127.0.0.1", 0)); sock.listen()
origin = "http://127.0.0.1:" + str(sock.getsockname()[1])
process = subprocess.Popen([
sys.executable, "-m", "gunicorn", "--bind", f"fd://{sock.fileno()}",
"--workers", "1", "--worker-class", "gthread", "--threads", "2",
"--timeout", "60", "--no-control-socket", "pages_ml:create_app()"],
pass_fds=(sock.fileno(),), cwd=service, env=env)
try:
deadline = time.monotonic() + 15
while True:
if process.poll() is not None:
raise RuntimeError("ML service exited before readiness")
try:
with urllib.request.urlopen(origin + "/healthz", timeout=1) as response:
if json.load(response)["protocol"] == "1":
break
except OSError:
pass
if time.monotonic() > deadline:
raise RuntimeError("ML service did not become ready")
time.sleep(0.1)
env.update(PAGES_ML_TEST_ORIGIN=origin, PAGES_ML_TEST_MODEL=manifest["model_sha256"])
subprocess.run(["go", "test", "./internal/machinelearning", "-run", "TestLocalDoc2VecService", "-count=1", "-v"],
cwd=service.parent.parent, env=env, check=True, timeout=120)
print("Synthetic Doc2Vec -> HTTP -> Go client: PASS")
finally:
process.terminate()
try:
process.wait(timeout=10)
except subprocess.TimeoutExpired:
process.kill(); process.wait()
if __name__ == "__main__":
main()
+141
View File
@@ -0,0 +1,141 @@
import copy
import io
import json
import os
from pathlib import Path
import tempfile
import unittest
from unittest.mock import patch
import urllib.error
from pages_ml import Application, Engine, Failure, MAX_BODY, digest, tokens, validate_vectors
from train import train
DOMAIN = "11111111-1111-4111-8111-111111111111"
SCOPE = "22222222-2222-4222-8222-222222222222"
TOKEN = "t" * 40
def request():
return {"protocol": "1", "domain_uuid": DOMAIN, "scope_uuid": SCOPE,
"provider": "openai", "model": "text-embedding-3-small", "dimensions": 2,
"inputs": [{"id": "page:chunk0", "text": "合成文書 library books"}], "allow_external": True}
def call(app, data=None, **changes):
body = json.dumps(data if data is not None else request()).encode()
env = {"PATH_INFO": "/v1/embeddings", "REQUEST_METHOD": "POST", "CONTENT_TYPE": "application/json",
"CONTENT_LENGTH": str(len(body)), "HTTP_AUTHORIZATION": "Bearer " + TOKEN, "wsgi.input": io.BytesIO(body)}
env.update(changes)
result = []
raw = b"".join(app(env, lambda status, headers: result.extend([int(status.split()[0]), dict(headers)])))
return result[0], json.loads(raw), result[1]
class BoundaryTests(unittest.TestCase):
def setUp(self):
self.engine = Engine("/nonexistent")
self.app = Application(TOKEN, self.engine)
def test_auth_and_health(self):
for value in ("", "Bearer wrong", "Bearer ü"):
self.assertEqual(call(self.app, HTTP_AUTHORIZATION=value)[0], 401)
self.assertEqual(call(self.app, PATH_INFO="/healthz", REQUEST_METHOD="GET", HTTP_AUTHORIZATION="")[0], 200)
self.assertEqual(call(self.app, PATH_INFO="/healthz?token=secret")[0], 404)
with self.assertRaises(ValueError):
Application("short", self.engine)
def test_external_off_without_network(self):
with patch("urllib.request.build_opener") as opener:
self.assertEqual(call(self.app)[0], 403)
self.engine.external_enabled, self.engine.api_key = True, "fake-key"
data = request(); data["allow_external"] = False
self.assertEqual(call(self.app, data)[0], 403)
opener.assert_not_called()
def test_bounds_and_busy(self):
for changes, status in [({"CONTENT_LENGTH": str(MAX_BODY+1)}, 413),
({"CONTENT_LENGTH": ""}, 411), ({"CONTENT_TYPE": "text/plain"}, 415),
({"wsgi.input": io.BytesIO(b"{")}, 400)]:
self.assertEqual(call(self.app, **changes)[0], status)
for key, value in [("scope_uuid", "../../"), ("dimensions", True), ("dimensions", 1537),
("inputs", []), ("inputs", [{"id": "a", "text": "x"*6001}]),
("allow_external", "true"), ("unexpected", "x")]:
data = request(); data[key] = value
self.assertEqual(call(self.app, data)[0], 400)
data = request(); data["inputs"] *= 2
self.assertEqual(call(self.app, data)[0], 400)
self.app.slot.acquire()
try:
status, _, headers = call(self.app)
self.assertEqual(status, 429); self.assertEqual(headers["Retry-After"], "5")
self.assertEqual(call(self.app, PATH_INFO="/healthz", REQUEST_METHOD="GET")[0], 200)
finally:
self.app.slot.release()
def test_openai_contract(self):
self.engine.external_enabled, self.engine.api_key = True, "fake-key"
data = request()
result = {"model": data["model"], "data": [{"index": 0, "embedding": [0.5, -0.2]}], "usage": {"total_tokens": 10}}
with patch("urllib.request.build_opener") as opener:
opener.return_value.open.return_value.__enter__.return_value.read.return_value = json.dumps(result).encode()
status, body, _ = call(self.app, data)
self.assertEqual(status, 200)
self.assertEqual(body["outputs"][0]["input_sha256"], digest(data["inputs"][0]["text"].encode()))
sent = opener.return_value.open.call_args.args[0]
self.assertEqual(sent.full_url, "https://api.openai.com/v1/embeddings")
self.assertEqual(json.loads(sent.data)["encoding_format"], "float")
result["data"][0]["embedding"] = [float("nan"), 1]
opener.return_value.open.return_value.__enter__.return_value.read.return_value = json.dumps(result).encode()
self.assertEqual(call(self.app)[0], 502)
opener.return_value.open.side_effect = urllib.error.HTTPError(sent.full_url, 429, "secret input", {}, io.BytesIO(b"secret"))
status, body, _ = call(self.app)
self.assertEqual(status, 429); self.assertNotIn("secret", json.dumps(body))
# No automatic provider retries.
self.assertEqual(opener.return_value.open.call_count, 3)
def test_bad_vectors_and_tokenizer(self):
for vectors in ([[0, 0]], [[1]], [[True, 1]], [[float("inf"), 1]], [[10**1000, 1]], []):
with self.assertRaises(Failure): validate_vectors(vectors, 1, 2)
self.assertEqual(tokens("図書館 BOOK"), ["図書", "書館", "book"])
class Doc2VecTests(unittest.TestCase):
def test_real_train_infer_and_isolation(self):
# Only generated fixture text, never data/ or user documents.
with tempfile.TemporaryDirectory() as root:
source = Path(root) / "synthetic.jsonl"
source.write_text("\n".join(json.dumps({"text": text}) for text in [
"図書館 読書 本 library books reading", "図書館 本 文書 library documents books",
"ネットワーク サーバー network server routing", "サーバー 通信 network routing server"]))
manifest = train(source, root, DOMAIN, SCOPE, 8)
engine = Engine(root); app = Application(TOKEN, engine)
data = request(); data.update(provider="doc2vec", model=manifest["model_sha256"], dimensions=8, allow_external=False)
status, result, _ = call(app, data)
self.assertEqual(status, 200)
self.assertEqual(len(result["outputs"][0]["vector"]), 8)
self.assertEqual(call(app, data)[1]["outputs"], result["outputs"])
for key in ("domain_uuid", "scope_uuid"):
other = copy.deepcopy(data); other[key] = "33333333-3333-4333-8333-333333333333"
self.assertEqual(call(app, other)[0], 404)
unknown = copy.deepcopy(data); unknown["inputs"][0]["text"] = "zzzzunknownword"
self.assertEqual(call(app, unknown)[0], 422)
wrong = copy.deepcopy(data); wrong["dimensions"] = 9
self.assertEqual(call(app, wrong)[0], 409)
model_dir = Path(root) / DOMAIN / SCOPE / data["model"]
model_file = model_dir / "model.bin"
original = model_file.read_bytes()
model_file.write_bytes(b"untrusted replacement")
self.assertEqual(call(app, data)[0], 409)
model_file.write_bytes(original)
self.assertEqual(call(app, data)[0], 200)
model_file.unlink()
self.assertEqual(call(app, data)[0], 404)
model_file.write_bytes(original)
self.assertEqual(call(app, data)[0], 200)
(model_dir / "manifest.json").unlink()
self.assertEqual(call(app, data)[0], 404) # Cached model cannot outlive removal.
if __name__ == "__main__":
unittest.main()
+68
View File
@@ -0,0 +1,68 @@
"""Offline operator-only Doc2Vec training. Never called by the HTTP API."""
import argparse
import json
import os
from pathlib import Path
import shutil
import tempfile
from pages_ml import TOKENIZER, MAX_TEXT_BYTES, digest, tokens, valid_uuid
def train(source, root, domain, scope, dimensions=128):
if not valid_uuid(domain) or not valid_uuid(scope) or not 1 <= dimensions <= 1536:
raise ValueError("invalid scope or dimensions")
if os.getenv("PYTHONHASHSEED") != "0":
raise ValueError("set PYTHONHASHSEED=0 before starting training")
from gensim.models.doc2vec import Doc2Vec, TaggedDocument
docs, hashes, total_bytes = [], [], 0
# Export permission and cohort membership must be checked by Pages/operator.
# No URLs or paths inside the corpus are followed.
with open(source, "rb") as stream:
while line := stream.readline(65537):
total_bytes += len(line)
if len(line) > 65536 or total_bytes > 16 * 1024 * 1024 or len(docs) >= 10000:
raise ValueError("corpus exceeds pilot limits")
item = json.loads(line)
if not isinstance(item, dict) or set(item) != {"text"} or not isinstance(item["text"], str):
raise ValueError("expected JSONL records with text only")
text = item["text"]
if not text.strip() or len(text.encode()) > MAX_TEXT_BYTES:
raise ValueError("empty or oversized document")
words = tokens(text)
if not words:
raise ValueError("no tokens")
docs.append(TaggedDocument(words, [str(len(docs))]))
hashes.append(digest(text.encode()))
if len(docs) < 2:
raise ValueError("at least two documents required; this does not guarantee model quality")
model = Doc2Vec(documents=docs, vector_size=dimensions, dm=0, workers=1,
epochs=40, min_count=1, seed=0)
parent = Path(root) / domain / scope
parent.mkdir(parents=True, exist_ok=True)
temp = Path(tempfile.mkdtemp(prefix=".training-", dir=parent))
try:
model.save(str(temp / "model.bin"), separately=[])
model_hash = digest((temp / "model.bin").read_bytes())
manifest = {"domain_uuid": domain, "scope_uuid": scope, "dimensions": dimensions,
"tokenizer": TOKENIZER, "model_sha256": model_hash,
"corpus_sha256": digest("\n".join(hashes).encode()), "documents": len(docs),
"algorithm": "pv-dbow", "epochs": 40, "gensim": "4.4.0", "seed": 0, "workers": 1}
(temp / "manifest.json").write_text(json.dumps(manifest, indent=2) + "\n")
# Never replace an existing generation in place.
temp.rename(parent / model_hash)
return manifest
finally:
if temp.exists():
shutil.rmtree(temp)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("source", help="Authorized JSONL corpus, one text record per line")
parser.add_argument("--model-dir", required=True)
parser.add_argument("--domain", required=True)
parser.add_argument("--scope", required=True, help="UUID identifying one authorized learning cohort")
parser.add_argument("--dimensions", type=int, default=128)
args = parser.parse_args()
print(json.dumps(train(args.source, args.model_dir, args.domain, args.scope, args.dimensions)))