From d4509478eb7b331ec2ca5766fdcc3f89a9be9e1b Mon Sep 17 00:00:00 2001 From: larryro <371767072@qq.com> Date: Fri, 2 Oct 2026 14:54:57 +0800 Subject: [PATCH 1/2] fix(platform): treat an embedding 429 as a rate limit, pace and retry it DashScope's tokens-per-minute limit (Throttling.AllocationQuota) reaches the OpenAI-compatible client as code `insufficient_quota`, OpenAI's billing code, so it read as a spent balance: unretried, the scan ended on its first 429 and the dialog sent the admin to the account. The code no longer decides; the wording does, and a 429 outside it is `throttled`. A throttled batch pauses its whole lane and comes back on the minute scale (10/20/40/60/60 s); a search query keeps the short schedule. Two optional embedding.json keys, maxTokensPerMinute and maxRequestsPerMinute, pace what a lane sends per minute so a crawl is held under the provider's limit instead of refused. --- docs/de/develop/api-reference.md | 2 +- docs/de/platform/knowledge/crawling.md | 2 +- .../configuration/data-residency.md | 5 +- docs/de/self-hosted/install/cli-install.md | 4 +- docs/en/develop/api-reference.md | 2 +- docs/en/platform/knowledge/crawling.md | 2 +- .../configuration/data-residency.md | 5 +- docs/en/self-hosted/install/cli-install.md | 4 +- docs/fr/develop/api-reference.md | 2 +- docs/fr/platform/knowledge/crawling.md | 2 +- .../configuration/data-residency.md | 5 +- docs/fr/self-hosted/install/cli-install.md | 4 +- packages/shared/src/schemas/knowledge.test.ts | 2 + packages/shared/src/schemas/knowledge.ts | 26 +++ .../features/websites/lib/scan-error.test.ts | 3 + .../app/features/websites/lib/scan-error.ts | 3 + .../knowledge/crawl_action.vectors.test.ts | 22 +++ .../backend/core/knowledge/embedding.test.ts | 173 +++++++++++++++- .../backend/core/knowledge/embedding.ts | 185 ++++++++++++++++-- .../backend/core/websites/scan_scheduling.ts | 2 + .../backend/domains/knowledge/service.ts | 7 +- services/platform/lib/knowledge/types.ts | 6 + services/platform/messages/de.yml | 1 + services/platform/messages/en.yml | 1 + services/platform/messages/fr.yml | 1 + .../tests/manual/reference/automation.md | 2 +- tools/cli/src/lib/config/platform-model.ts | 6 +- 27 files changed, 435 insertions(+), 44 deletions(-) diff --git a/docs/de/develop/api-reference.md b/docs/de/develop/api-reference.md index 77f504d63c..84f8aa78ba 100644 --- a/docs/de/develop/api-reference.md +++ b/docs/de/develop/api-reference.md @@ -291,7 +291,7 @@ Die `domain` einer Website ist unveränderlich: `PATCH /api/v1/websites/{id}` ak Eine Ausnahme gilt für URL-Listen: Ist die Domain bereits als Liste registriert und stimmt ihre Schreibweise exakt überein, erweitert ein erneuter Aufruf diese Liste und liefert **200** mit derselben ID. Eine URL-Liste kann keinen bestehenden vollständigen Website-Crawl ersetzen; das ergibt **409** und reiht nichts ein. Prüfe vor dem Aufruf `kind` und verwende die Domain-Schreibweise aus der bestehenden Ressource oder der Konfliktantwort. -Der `status` einer Website beschreibt den Scan. `GET /api/v1/websites?status=` akzeptiert `scanning` (hier beginnt eine registrierte Website), `active`, `error` oder `deleting`; andere Werte ergeben `400 INVALID_QUERY`, ebenso `?scanInterval=` außerhalb seiner sieben Werte. `active` bedeutet, dass nach dem abgeschlossenen Scan mindestens eine Seite gespeichert ist. Es bedeutet nicht, dass alle Seiten aktualisiert wurden. Bei einem fehlgeschlagenen Scan oder wenn nach den Abrufversuchen keine gespeicherten Seiten verbleiben, lautet der Status `error`; lies dazu `metadata.lastSyncError`. Ein Fehler des Embedding-Modells beginnt mit `The embedding model could not embed the pages []:`, wobei die Klasse `credential`, `credit`, `unresolved`, `dimension` oder `upstream` ist, gefolgt vom Satz des Anbieters. +Der `status` einer Website beschreibt den Scan. `GET /api/v1/websites?status=` akzeptiert `scanning` (hier beginnt eine registrierte Website), `active`, `error` oder `deleting`; andere Werte ergeben `400 INVALID_QUERY`, ebenso `?scanInterval=` außerhalb seiner sieben Werte. `active` bedeutet, dass nach dem abgeschlossenen Scan mindestens eine Seite gespeichert ist. Es bedeutet nicht, dass alle Seiten aktualisiert wurden. Bei einem fehlgeschlagenen Scan oder wenn nach den Abrufversuchen keine gespeicherten Seiten verbleiben, lautet der Status `error`; lies dazu `metadata.lastSyncError`. Ein Fehler des Embedding-Modells beginnt mit `The embedding model could not embed the pages []:`, wobei die Klasse `credential`, `credit`, `unresolved`, `dimension`, `throttled` oder `upstream` ist, gefolgt vom Satz des Anbieters. Das `lastErrorKind` einer Seite unterscheidet Netzwerk- und TLS-Probleme (`network_error`, `tls_error`), abgewiesene Ziele (`private_ip`), HTTP-Fehler (`http_error`), Extraktions- oder Darstellungsfehler, nicht in Text umwandelbare Inhalte (`unsupported_content`) und eine `robots_noindex`-Ablehnung — der Ursprung hat mit `X-Robots-Tag: noindex` geantwortet oder die Seite trägt ein ``-Tag. Nach einer fehlgeschlagenen Aktualisierung kann älterer indexierter Inhalt erhalten bleiben. Prüfe deshalb neben dem Website-Status auch die Seitenfehler. diff --git a/docs/de/platform/knowledge/crawling.md b/docs/de/platform/knowledge/crawling.md index 90bbad8392..07c6d4194d 100644 --- a/docs/de/platform/knowledge/crawling.md +++ b/docs/de/platform/knowledge/crawling.md @@ -91,7 +91,7 @@ Prüfe zuerst Adresse, Quelltyp und letzte Scan-Zeit. Öffne danach die Quelle, | Nicht unterstützter Inhalt oder kein lesbarer Text | JSON-/XML-Endpunkte, Binärdownloads, Bilder oder Scans liefern möglicherweise keinen verwertbaren Seitentext. Stelle eine HTML-Seite oder ein unterstütztes Dokument mit extrahierbarem Text bereit. | | Darstellung oder Textextraktion fehlgeschlagen | Prüfe, ob die öffentliche Seite lädt und sich das Originaldokument öffnen lässt. Repariere oder exportiere eine beschädigte Quelle erneut. | | Der Assistent meldet, die Suche in Webseiten sei nicht eingerichtet | Die Organisation hat kein funktionierendes Embedding-Modell. Ein Administrator legt es unter **Einstellungen > Datenresidenz** fest; danach scannt Tale die betroffenen Quellen erneut. | -| **Fehler** mit „Das Embedding-Modell konnte die Seiten nicht verarbeiten.“ | Der Embedding-Anbieter hat die Anfrage abgelehnt oder konnte sie nicht bedienen: abgelehnte Zugangsdaten, aufgebrauchtes Guthaben oder ein Ausfall. Die Details der Quelle sagen, was davon zutrifft, mit der Antwort des Anbieters darunter. Ein Administrator repariert das Modell unter **Einstellungen > Datenresidenz** oder die Zugangsdaten unter **Einstellungen > KI-Anbieter**; beim Speichern werden die betroffenen Quellen erneut gescannt. Nach einem Ausfall beim Anbieter wählst du **Jetzt scannen**, sobald er wieder erreichbar ist. | +| **Fehler** mit „Das Embedding-Modell konnte die Seiten nicht verarbeiten.“ | Der Embedding-Anbieter hat die Anfrage abgelehnt oder konnte sie nicht bedienen: abgelehnte Zugangsdaten, aufgebrauchtes Guthaben, ein Ratenlimit, das über alle Wiederholungen anhielt, oder ein Ausfall. Die Details der Quelle sagen, was davon zutrifft, mit der Antwort des Anbieters darunter. Ein Administrator repariert das Modell unter **Einstellungen > Datenresidenz** oder die Zugangsdaten unter **Einstellungen > KI-Anbieter**; beim Speichern werden die betroffenen Quellen erneut gescannt. Nach einem Ausfall beim Anbieter wählst du **Jetzt scannen**, sobald er wieder erreichbar ist. | | **Fehler** mit „Der Scan ist nicht gelaufen.“ | Der Browser des Crawlers konnte nicht starten, deshalb wurde keine Seite dargestellt; sein Bericht steht in den Details der Quelle unter **Technische Details**. An der Adresse liegt es nicht: Lass deinen Betreiber den Sandbox-Dienst prüfen und wähle danach **Jetzt scannen**. | Ein späterer erfolgreicher Abruf entfernt den vorherigen Fehler. Nach einer fehlgeschlagenen Aktualisierung kann die früher indexierte Fassung weiterhin verfügbar sein: **Aktiv** und die Anzahl indexierter Seiten belegen nicht, dass jede Seite aktuell ist. Vergleiche gespeicherte Textabschnitte und Abrufdatum mit dem Original, bevor du dich auf eine kürzliche Änderung verlässt. diff --git a/docs/de/self-hosted/configuration/data-residency.md b/docs/de/self-hosted/configuration/data-residency.md index aad28f19fa..849de4af02 100644 --- a/docs/de/self-hosted/configuration/data-residency.md +++ b/docs/de/self-hosted/configuration/data-residency.md @@ -56,6 +56,7 @@ Zwei weitere optionale Einstellungen in `embedding.json` beschreiben, wie viel A - `maxConcurrentRequests` (1 bis 64, Standard 3) legt fest, wie viele Embedding-Anfragen an dieses Modell Tale für die Organisation gleichzeitig offen hält. Dokumentindexierung, die Indexierung eingehender E-Mails, Website-Scans und Suchen teilen sich dieses Limit. Weitere Anfragen warten in der Reihenfolge ihres Eintreffens; nur eine Suchanfrage zieht an wartenden Indexierungs-Batches vorbei. Jeder Tale-Prozess zählt für sich, sodass die API und jedes Worker-Replikat das Limit jeweils ausschöpfen können. Ein niedrigerer Wert gilt sofort, ein höherer erst, wenn die unter dem alten Wert gestarteten Anfragen abgeschlossen sind. Berechnet der Server eine Anfrage nach der anderen, erzeugt ein höherer Wert keine zusätzliche Last; jede Anfrage wartet nur länger. - `minTokensPerSecond` (eine beliebige positive Zahl) ist die niedrigste Rate, mit der der Server unter seiner üblichen Last Embeddings für dieses Modell berechnet. Miss sie, während auf derselben Hardware andere Arbeit läuft, etwa ein Chat-Modell, aber zähle die Zeit nicht mit, die eine Anfrage hinter anderen Anfragen wartet. Diese Wartezeit rechnet Tale selbst hinzu. +- `maxTokensPerMinute` und `maxRequestsPerMinute` (ganze Zahlen) dosieren, was Tale diesem Modell innerhalb einer Minute schickt, für die Organisation in jedem Tale-Prozess. Setze sie auf die Minutenlimits eines gehosteten Anbieters, die pro Anbieterkonto über alle Deployments gezählt werden, die sich den Schlüssel teilen: Ein Indexierungs-Batch, der ein Limit überschreiten würde, wartet, bis genug von der letzten Minute verstrichen ist, sodass ein Crawl über Hunderte Seiten dosiert wird statt mit `429` abgewiesen zu werden. Tale schätzt Tokens anhand der Zeichen, eher zu hoch. Ein `429`, das der Anbieter trotzdem schickt, hält jede Anfrage der Organisation an dieses Modell an und wird im Minutentakt wiederholt; eine Suchanfrage wird von beidem nicht gebremst. Alibaba Cloud Model Studio erlaubt für text-embedding-v4 zum Beispiel 1.800 Anfragen und 1.000.000 Tokens pro Minute. ```json { @@ -64,7 +65,9 @@ Zwei weitere optionale Einstellungen in `embedding.json` beschreiben, wie viel A "dimensions": 1024, "baseUrl": "https://embeddings.example.internal/v1", "maxConcurrentRequests": 2, - "minTokensPerSecond": 800 + "minTokensPerSecond": 800, + "maxTokensPerMinute": 1000000, + "maxRequestsPerMinute": 1800 } ``` diff --git a/docs/de/self-hosted/install/cli-install.md b/docs/de/self-hosted/install/cli-install.md index 7e39ed95ae..b8f8ab82ff 100644 --- a/docs/de/self-hosted/install/cli-install.md +++ b/docs/de/self-hosted/install/cli-install.md @@ -375,7 +375,7 @@ Diese Ressourcenarten nutzen die gemeinsamen Plattform-Schemas und nativen Berec | `knowledge-embedding` | Anbieter, Modell, Dimensionen, Endpunkt und Servergrenzen | Organisation | | `deployment` | Instanz-Einstellungen einschließlich Sandbox-Runtime | Instanz | -Aufbewahrungs- und DSAR-Richtlinien brauchen ihre eigenen nativen Workflows. Pausiere Uploads, Synchronisation und Crawls, bevor du das Embedding-Modell wechselst. Die CLI prüft die Anzahl der Dokumente und Websites der gesamten Organisation; sie sperrt den Import nicht und migriert keine bestehenden Vektoren. Hat die Organisation Dokumente oder registrierte Websites, braucht ein Modellwechsel eine separate native Indexmigration. Eine Änderung, die nur `minSimilarity`, `maxConcurrentRequests` oder `minTokensPerSecond` betrifft, lässt die vorhandenen Vektoren gültig; für sie entfällt diese Prüfung. Instanz-Einstellungen erfordern zusätzlich die native Freigabeliste für Deployment-Editoren. Bei Boot-Einstellungen meldet der einzelne Konfigurationsaufruf `restartRequired`; Speichern allein aktiviert diese Einstellungen noch nicht. Prüfe die Folgen im Plan vor dem Anwenden. +Aufbewahrungs- und DSAR-Richtlinien brauchen ihre eigenen nativen Workflows. Pausiere Uploads, Synchronisation und Crawls, bevor du das Embedding-Modell wechselst. Die CLI prüft die Anzahl der Dokumente und Websites der gesamten Organisation; sie sperrt den Import nicht und migriert keine bestehenden Vektoren. Hat die Organisation Dokumente oder registrierte Websites, braucht ein Modellwechsel eine separate native Indexmigration. Eine Änderung, die nur `minSimilarity`, `maxConcurrentRequests`, `minTokensPerSecond`, `maxTokensPerMinute` oder `maxRequestsPerMinute` betrifft, lässt die vorhandenen Vektoren gültig; für sie entfällt diese Prüfung. Instanz-Einstellungen erfordern zusätzlich die native Freigabeliste für Deployment-Editoren. Bei Boot-Einstellungen meldet der einzelne Konfigurationsaufruf `restartRequired`; Speichern allein aktiviert diese Einstellungen noch nicht. Prüfe die Folgen im Plan vor dem Anwenden. Verwaltete Deployments nutzen denselben Ablauf über `configuration`. Ergänze die Deployment-Deklaration um dieses Beispiel, wenn ein externer Betreiber den Anbieter bereits bereitstellt. Ersetze den synthetischen Endpunkt und Katalog durch geprüfte Werte und übergib `EXTERNAL_PROVIDER_SECRET` aus deinem Secret Manager: @@ -434,7 +434,7 @@ Verwaltete Deployments nutzen denselben Ablauf über `configuration`. Ergänze d Für `envName` gelten das native Präfix `TALE_PROVIDER_KEY_` und die Grenze von 40 Zeichen. Jeder Alias braucht eine verpflichtende `environment`-Referenz. Private Endpunkte erfordern zusätzlich eine explizite Referenz `TALE_ALLOW_PRIVATE_PROVIDER_HOSTS` mit dem Wert `1`; native Host-Regeln gelten weiter. `expectedModels` prüft Tales frisch aufgelösten Katalog beim Rücklesen. Das belegt weder Inferenzkapazität und Latenz noch fachliche Ergebnisse. -Die Bildmodellauswahl nutzt `governance` mit `key: "vision_model"` und den nativen Feldern `providerSlug`/`modelId`. Embedding nutzt `knowledge-embedding` mit `providerSlug`, `model`, `dimensions` und `baseUrl`, dazu die optionalen Einstellungen, die die Plattform neben dem Modell in [`embedding.json`](/de/self-hosted/configuration/data-residency#das-embedding-modell-der-organisation) hält: `minSimilarity`, die Kosinus-Untergrenze des Assistenten für dieses Modell, sowie die Servergrenzen `maxConcurrentRequests` und `minTokensPerSecond` ([Anfragen an einen selbst betriebenen Embedding-Server dosieren](/de/self-hosted/configuration/data-residency#kapazitaet-des-embedding-servers)). Für jede gilt die Regel der Plattform selbst: Ein Wert setzt sie, ein weggelassener Schlüssel lässt stehen, was die Datei hält (ein von Hand gesetzter Wert überlebt ein Release, das ihn nicht erwähnt), und `null` löscht sie — `"minSimilarity": null` etwa ist der einzige Weg, eine Untergrenze über die CLI zu entfernen. Wenn du Standardzugangsdaten ersetzt, deklariere auch die bisherigen Umgebungszugangsdaten mit `isDefault: false`; die CLI wendet diese explizite Änderung zuerst an. Schlüsselwerte stehen weder in der Deklaration noch im Beleg. +Die Bildmodellauswahl nutzt `governance` mit `key: "vision_model"` und den nativen Feldern `providerSlug`/`modelId`. Embedding nutzt `knowledge-embedding` mit `providerSlug`, `model`, `dimensions` und `baseUrl`, dazu die optionalen Einstellungen, die die Plattform neben dem Modell in [`embedding.json`](/de/self-hosted/configuration/data-residency#das-embedding-modell-der-organisation) hält: `minSimilarity`, die Kosinus-Untergrenze des Assistenten für dieses Modell, sowie die Servergrenzen `maxConcurrentRequests`, `minTokensPerSecond`, `maxTokensPerMinute` und `maxRequestsPerMinute` ([Anfragen an einen selbst betriebenen Embedding-Server dosieren](/de/self-hosted/configuration/data-residency#kapazitaet-des-embedding-servers)). Für jede gilt die Regel der Plattform selbst: Ein Wert setzt sie, ein weggelassener Schlüssel lässt stehen, was die Datei hält (ein von Hand gesetzter Wert überlebt ein Release, das ihn nicht erwähnt), und `null` löscht sie — `"minSimilarity": null` etwa ist der einzige Weg, eine Untergrenze über die CLI zu entfernen. Wenn du Standardzugangsdaten ersetzt, deklariere auch die bisherigen Umgebungszugangsdaten mit `isDefault: false`; die CLI wendet diese explizite Änderung zuerst an. Schlüsselwerte stehen weder in der Deklaration noch im Beleg. Die native Einrichtung folgt auf die Identitätsprüfung und läuft vor den Konfigurations-Releases. Der Beleg `native.configuration` bindet Deklarations- und Bundle-Hashes, Organisation, Ressourcen-Hashes und native Revisionen. Vor der ersten Änderung entsteht ein ausstehender Beleg. Scheitert eine spätere Ressource, können frühere Änderungen bestehen bleiben. Lies den nativen Zustand und den Beleg, bevor du denselben geprüften Plan erneut ausführst. Natives Compare-and-set schützt jede Ressource vor konkurrierenden Admin-Änderungen; eine ressourcenübergreifende Transaktion gibt es nicht. Bewahre Deployment-Zustand, Snapshots und Belege für die Wiederherstellung auf. diff --git a/docs/en/develop/api-reference.md b/docs/en/develop/api-reference.md index ee38a08b25..449a737dd8 100644 --- a/docs/en/develop/api-reference.md +++ b/docs/en/develop/api-reference.md @@ -274,7 +274,7 @@ A website's `domain` is immutable: `PATCH /api/v1/websites/{id}` accepts the sto The one exception is a URL list posted onto a domain registered as a list under the same spelling, which extends it and returns **200** with the existing id; a list posted onto a whole-site crawl is the same **409** — the crawl keeps its kind and nothing is queued — so read `kind` before you post, or re-post under the spelling the 409 names. -A website’s `status` describes its scan lifecycle. Filter with `GET /api/v1/websites?status=` using `scanning` (a registered site starts here), `active`, `error`, or `deleting`; other values return `400 INVALID_QUERY`, and so does `?scanInterval=` outside its seven values. `active` means a finished scan has stored at least one page, not that every page was refreshed. `error` means the scan failed or no pages remain stored after attempted fetches; inspect `metadata.lastSyncError`. A failure of the embedding model opens with `The embedding model could not embed the pages []:`, where the class is one of `credential`, `credit`, `unresolved`, `dimension` or `upstream`, followed by the provider's own sentence. +A website’s `status` describes its scan lifecycle. Filter with `GET /api/v1/websites?status=` using `scanning` (a registered site starts here), `active`, `error`, or `deleting`; other values return `400 INVALID_QUERY`, and so does `?scanInterval=` outside its seven values. `active` means a finished scan has stored at least one page, not that every page was refreshed. `error` means the scan failed or no pages remain stored after attempted fetches; inspect `metadata.lastSyncError`. A failure of the embedding model opens with `The embedding model could not embed the pages []:`, where the class is one of `credential`, `credit`, `unresolved`, `dimension`, `throttled` or `upstream`, followed by the provider's own sentence. Each page’s `lastErrorKind` helps distinguish a network or TLS failure (`network_error`, `tls_error`), a refused target (`private_ip`), an HTTP failure (`http_error`), extraction or rendering failures, content that cannot be turned into text (`unsupported_content`), and a `robots_noindex` refusal — the origin answered `X-Robots-Tag: noindex` or the page carries a `` tag. A failed refresh can retain previously indexed content, so inspect page failures alongside the site’s status. diff --git a/docs/en/platform/knowledge/crawling.md b/docs/en/platform/knowledge/crawling.md index 40500a3ef2..7319e2822a 100644 --- a/docs/en/platform/knowledge/crawling.md +++ b/docs/en/platform/knowledge/crawling.md @@ -91,7 +91,7 @@ First check the address, source type, and latest scan time. Then open the source | Unsupported content or no readable text | JSON/XML endpoints, binary downloads, images, or scans may provide no supported page text. Supply an HTML page or a supported document with extractable text. | | Rendering or document extraction failed | Check that the public page loads and the original document opens. Repair or re-export the source if it is damaged. | | The assistant says web-page search is not set up | The organization has no working embedding model. An administrator sets one under **Settings > Data residency**; Tale then scans the affected sources again. | -| **Error** with "The embedding model couldn't process the pages." | The embedding provider refused or failed the request: a rejected credential, an exhausted balance, or an outage. The source's details say which, with the provider's own reply beneath. An administrator repairs the model under **Settings > Data residency** or its credential under **Settings > AI providers**; saving either one scans the affected sources again. After an outage on the provider's side, choose **Scan now** once it is back. | +| **Error** with "The embedding model couldn't process the pages." | The embedding provider refused or failed the request: a rejected credential, an exhausted balance, a rate limit that held through every retry, or an outage. The source's details say which, with the provider's own reply beneath. An administrator repairs the model under **Settings > Data residency** or its credential under **Settings > AI providers**; saving either one scans the affected sources again. After an outage on the provider's side, choose **Scan now** once it is back. | | **Error** with "Scanning didn't run." | The crawler's browser could not start, so no page was rendered; its report is under **Technical details** in the source's details. The address is not the cause: ask your operator to check the sandbox service, then choose **Scan now**. | A successful later fetch clears the previous error. A failed refresh can leave an earlier indexed copy available: **Active** and an indexed count do not prove every page is up to date. Compare the stored chunks and last-crawled information with the original before relying on a recent change. diff --git a/docs/en/self-hosted/configuration/data-residency.md b/docs/en/self-hosted/configuration/data-residency.md index cd9e3a9494..3808fde256 100644 --- a/docs/en/self-hosted/configuration/data-residency.md +++ b/docs/en/self-hosted/configuration/data-residency.md @@ -56,6 +56,7 @@ Two more optional `embedding.json` settings describe how much work the embedding - `maxConcurrentRequests` (1 to 64, default 3) is how many embedding requests to this model Tale keeps in flight at once for the organization. Document indexing, the indexing of incoming email, website scans and searches share this limit. Further requests wait in arrival order, except that a search query goes ahead of waiting indexing batches. Each Tale process counts separately, so the API and every worker replica can each reach the limit. A lower value takes effect at once; a higher one once the requests started under the old value have finished. On a server that computes one request at a time, a higher value adds no load; each request only waits longer. - `minTokensPerSecond` (any positive number) is the slowest rate at which the server computes embeddings for this model under its usual load. Measure it while other work runs on the same hardware, such as a chat model, but leave out the time a request waits behind other requests. Tale adds that waiting time itself. +- `maxTokensPerMinute` and `maxRequestsPerMinute` (whole numbers) pace what Tale sends this model within any one minute, for the organization in each Tale process. Set them to a hosted provider's per-minute limits, which are counted per provider account across every deployment that shares the key: an indexing batch that would cross a limit waits until enough of the last minute has aged out, so a crawl of hundreds of pages is paced instead of refused with `429`. Tale estimates tokens from characters, on the high side. A `429` the provider still answers pauses every request of the organization to that model and is retried on a minute scale; a search query is not held back by either. Alibaba Cloud Model Studio, for example, allows text-embedding-v4 1,800 requests and 1,000,000 tokens per minute. ```json { @@ -64,7 +65,9 @@ Two more optional `embedding.json` settings describe how much work the embedding "dimensions": 1024, "baseUrl": "https://embeddings.example.internal/v1", "maxConcurrentRequests": 2, - "minTokensPerSecond": 800 + "minTokensPerSecond": 800, + "maxTokensPerMinute": 1000000, + "maxRequestsPerMinute": 1800 } ``` diff --git a/docs/en/self-hosted/install/cli-install.md b/docs/en/self-hosted/install/cli-install.md index e37f88501a..30ec85daab 100644 --- a/docs/en/self-hosted/install/cli-install.md +++ b/docs/en/self-hosted/install/cli-install.md @@ -375,7 +375,7 @@ These resource kinds use the platform’s shared schemas and native permissions: | `knowledge-embedding` | Provider, model, dimensions, endpoint and server limits | Organization | | `deployment` | Instance deployment settings, including sandbox runtime | Instance | -Retention and DSAR policies require their dedicated native workflows. Pause uploads, synchronization and crawls before changing the embedding model. The CLI checks organization-wide document and website counts; it does not lock ingestion or migrate existing vectors. For an organization with documents or registered websites, a model change requires a separate native indexing migration. A change limited to `minSimilarity`, `maxConcurrentRequests` or `minTokensPerSecond` keeps existing vectors valid, so it skips this check. Instance settings also require the native deployment editor allowlist. Standalone application reports `restartRequired` for boot settings; saving those settings alone does not activate them. Review the plan’s effects before applying. +Retention and DSAR policies require their dedicated native workflows. Pause uploads, synchronization and crawls before changing the embedding model. The CLI checks organization-wide document and website counts; it does not lock ingestion or migrate existing vectors. For an organization with documents or registered websites, a model change requires a separate native indexing migration. A change limited to `minSimilarity`, `maxConcurrentRequests`, `minTokensPerSecond`, `maxTokensPerMinute` or `maxRequestsPerMinute` keeps existing vectors valid, so it skips this check. Instance settings also require the native deployment editor allowlist. Standalone application reports `restartRequired` for boot settings; saving those settings alone does not activate them. Review the plan’s effects before applying. Managed deployments use the same engine through `configuration`. Merge this example into the deployment declaration when an external operator already serves the provider. Replace the synthetic endpoint and catalog with verified values, and inject `EXTERNAL_PROVIDER_SECRET` from your secret manager: @@ -434,7 +434,7 @@ Managed deployments use the same engine through `configuration`. Merge this exam `envName` uses the native `TALE_PROVIDER_KEY_` prefix and 40-character limit. Each alias needs a required `environment` reference. Private endpoints additionally require an explicit `TALE_ALLOW_PRIVATE_PROVIDER_HOSTS` reference whose value is `1`; native host restrictions still apply. `expectedModels` checks Tale’s freshly resolved catalog during readback. It does not prove inference capacity, latency or business output. -Use `governance` with `key: "vision_model"` and native `providerSlug`/`modelId` fields for vision selection. Embedding uses `knowledge-embedding` with `providerSlug`, `model`, `dimensions` and `baseUrl`, plus the optional settings the platform keeps next to the model in [`embedding.json`](/self-hosted/configuration/data-residency#the-organizations-embedding-model): `minSimilarity`, the assistant's cosine floor for this model, and the server limits `maxConcurrentRequests` and `minTokensPerSecond` ([Pace requests to a self-hosted embedding server](/self-hosted/configuration/data-residency#embedding-server-capacity)). Each follows the platform's own rule: a value sets it, an omitted key leaves whatever the file holds (a hand-set value survives a release that does not mention it), and `null` clears it — `"minSimilarity": null`, for example, is the only way to remove a floor through the CLI. To replace a default credential, also declare the existing environment credential with `isDefault: false`; the CLI applies that explicit change first. Credential values never enter the declaration or receipt. +Use `governance` with `key: "vision_model"` and native `providerSlug`/`modelId` fields for vision selection. Embedding uses `knowledge-embedding` with `providerSlug`, `model`, `dimensions` and `baseUrl`, plus the optional settings the platform keeps next to the model in [`embedding.json`](/self-hosted/configuration/data-residency#the-organizations-embedding-model): `minSimilarity`, the assistant's cosine floor for this model, and the server limits `maxConcurrentRequests`, `minTokensPerSecond`, `maxTokensPerMinute` and `maxRequestsPerMinute` ([Pace requests to a self-hosted embedding server](/self-hosted/configuration/data-residency#embedding-server-capacity)). Each follows the platform's own rule: a value sets it, an omitted key leaves whatever the file holds (a hand-set value survives a release that does not mention it), and `null` clears it — `"minSimilarity": null`, for example, is the only way to remove a floor through the CLI. To replace a default credential, also declare the existing environment credential with `isDefault: false`; the CLI applies that explicit change first. Credential values never enter the declaration or receipt. Native provisioning runs after identity and before configuration releases. The `native.configuration` receipt binds the declaration and bundle hashes, organization, resource hashes and native revisions. Writes retain a pending receipt before the first change; if a later resource fails, earlier changes may remain. Read the native state and retained receipt, then retry the same reviewed plan. Native compare-and-set protects each resource against concurrent admin changes; there is no cross-resource transaction. Keep deployment state, snapshots and receipts for recovery. diff --git a/docs/fr/develop/api-reference.md b/docs/fr/develop/api-reference.md index 660798be20..28e6adec80 100644 --- a/docs/fr/develop/api-reference.md +++ b/docs/fr/develop/api-reference.md @@ -317,7 +317,7 @@ Le `domain` d’un site web est immuable. `PATCH /api/v1/websites/{id}` accepte Une exception permet d’étendre une liste d’URL existante : si le site est déjà de type liste et que le domaine est écrit exactement de la même manière, l’ajout répond **200** avec l’ID existant. Envoyer une liste à un site configuré pour une exploration complète donne **409**, sans changer son type ni lancer d’exploration. Vérifie `kind` avant l’appel et utilise la forme du domaine indiquée dans le **409**. -Le `status` d’un site décrit le cycle de son exploration. `GET /api/v1/websites?status=` accepte `scanning` (un site enregistré commence ici), `active`, `error` ou `deleting` ; une autre valeur donne `400 INVALID_QUERY`, comme `?scanInterval=` hors de ses sept valeurs. `active` signifie qu’après l’exploration terminée, au moins une page est enregistrée, sans garantir leur actualisation à toutes. `error` signale une exploration en échec ou l’absence de pages enregistrées après les tentatives de récupération ; consulte `metadata.lastSyncError`. Un échec du modèle d’embedding commence par `The embedding model could not embed the pages []:`, où la classe est `credential`, `credit`, `unresolved`, `dimension` ou `upstream`, suivie de la phrase du fournisseur. +Le `status` d’un site décrit le cycle de son exploration. `GET /api/v1/websites?status=` accepte `scanning` (un site enregistré commence ici), `active`, `error` ou `deleting` ; une autre valeur donne `400 INVALID_QUERY`, comme `?scanInterval=` hors de ses sept valeurs. `active` signifie qu’après l’exploration terminée, au moins une page est enregistrée, sans garantir leur actualisation à toutes. `error` signale une exploration en échec ou l’absence de pages enregistrées après les tentatives de récupération ; consulte `metadata.lastSyncError`. Un échec du modèle d’embedding commence par `The embedding model could not embed the pages []:`, où la classe est `credential`, `credit`, `unresolved`, `dimension`, `throttled` ou `upstream`, suivie de la phrase du fournisseur. Le `lastErrorKind` d’une page distingue notamment réseau ou TLS (`network_error`, `tls_error`), cible refusée (`private_ip`), échec HTTP (`http_error`), extraction ou rendu en échec, contenu impossible à convertir en texte (`unsupported_content`) et le refus `robots_noindex` — l’origine a répondu `X-Robots-Tag: noindex` ou la page porte une balise ``. Une actualisation ratée peut conserver l’ancien contenu indexé. Lis donc les erreurs de pages en plus du statut du site. diff --git a/docs/fr/platform/knowledge/crawling.md b/docs/fr/platform/knowledge/crawling.md index b6e8aa5745..7dd12e5d9d 100644 --- a/docs/fr/platform/knowledge/crawling.md +++ b/docs/fr/platform/knowledge/crawling.md @@ -91,7 +91,7 @@ Vérifie d’abord l’adresse, le type de source et la date du dernier scan. Ou | Contenu non pris en charge ou sans texte lisible | Les points d’accès JSON/XML, téléchargements binaires, images ou scans peuvent ne fournir aucun texte exploitable. Fournis une page HTML ou un document pris en charge dont le texte peut être extrait. | | Échec du rendu ou de l’extraction | Vérifie que la page publique se charge et que le document d’origine s’ouvre. Répare ou exporte à nouveau une source endommagée. | | L’assistant répond que la recherche dans les pages web n’est pas configurée | L’organisation n’a pas de modèle d’embedding qui fonctionne. Un administrateur le définit dans **Paramètres > Résidence des données** ; Tale relance ensuite un scan des sources concernées. | -| **Erreur** avec « Le modèle d'embedding n'a pas pu traiter les pages. » | Le fournisseur d’embedding a refusé la requête ou n’a pas pu y répondre : identifiants rejetés, solde épuisé ou panne. Les détails de la source précisent lequel, avec la réponse du fournisseur en dessous. Un administrateur corrige le modèle dans **Paramètres > Résidence des données** ou ses identifiants dans **Paramètres > Fournisseurs IA** ; l’enregistrement relance le scan des sources concernées. Après une panne chez le fournisseur, choisis **Analyser maintenant** dès qu’il est de nouveau disponible. | +| **Erreur** avec « Le modèle d'embedding n'a pas pu traiter les pages. » | Le fournisseur d’embedding a refusé la requête ou n’a pas pu y répondre : identifiants rejetés, solde épuisé, limite de débit maintenue malgré toutes les tentatives, ou panne. Les détails de la source précisent lequel, avec la réponse du fournisseur en dessous. Un administrateur corrige le modèle dans **Paramètres > Résidence des données** ou ses identifiants dans **Paramètres > Fournisseurs IA** ; l’enregistrement relance le scan des sources concernées. Après une panne chez le fournisseur, choisis **Analyser maintenant** dès qu’il est de nouveau disponible. | | **Erreur** avec « L'analyse n'a pas eu lieu. » | Le navigateur du crawler n’a pas pu démarrer, aucune page n’a donc été rendue ; son rapport se trouve sous **Détails techniques** dans les détails de la source. L’adresse n’est pas en cause : demande à ton exploitant de vérifier le service de sandbox, puis choisis **Analyser maintenant**. | Une récupération réussie efface l’erreur précédente. Si une actualisation échoue, la copie déjà indexée peut rester disponible : **Actif** et le nombre de pages indexées ne prouvent pas que chaque page est à jour. Compare les fragments enregistrés et la date du passage avec l’original avant de t’appuyer sur une modification récente. diff --git a/docs/fr/self-hosted/configuration/data-residency.md b/docs/fr/self-hosted/configuration/data-residency.md index 6f8eb61c2c..ce874c954b 100644 --- a/docs/fr/self-hosted/configuration/data-residency.md +++ b/docs/fr/self-hosted/configuration/data-residency.md @@ -56,6 +56,7 @@ Deux autres réglages facultatifs de `embedding.json` décrivent la charge que l - `maxConcurrentRequests` (de 1 à 64, 3 par défaut) fixe le nombre de requêtes d’embedding que Tale garde en cours en même temps vers ce modèle pour l’organisation. L’indexation des documents, celle des e-mails reçus, les explorations de sites web et les recherches partagent cette limite. Les requêtes suivantes attendent dans leur ordre d’arrivée, mais une recherche passe devant les lots d’indexation en attente. Chaque processus Tale compte séparément : l’API et chaque réplique de worker peuvent donc chacune atteindre la limite. Une valeur plus basse s’applique aussitôt, une valeur plus haute une fois terminées les requêtes lancées sous l’ancienne. Sur un serveur qui calcule une requête à la fois, une valeur plus élevée n’ajoute aucune charge ; elle allonge seulement l’attente de chaque requête. - `minTokensPerSecond` (tout nombre positif) est le débit le plus bas auquel le serveur calcule les embeddings de ce modèle sous sa charge habituelle. Mesure-le pendant que d’autres traitements tournent sur le même matériel, comme un modèle de chat, mais sans compter le temps qu’une requête passe à attendre derrière d’autres requêtes. Tale ajoute lui-même ce temps d’attente. +- `maxTokensPerMinute` et `maxRequestsPerMinute` (nombres entiers) dosent ce que Tale envoie à ce modèle en une minute, pour l’organisation dans chaque processus Tale. Règle-les sur les limites par minute d’un fournisseur hébergé, comptées par compte fournisseur sur tous les déploiements qui partagent la clé : un lot d’indexation qui dépasserait une limite attend qu’une part suffisante de la dernière minute soit écoulée, si bien qu’une exploration de centaines de pages est dosée au lieu d’être refusée par des `429`. Tale estime les tokens d’après les caractères, en comptant large. Un `429` que le fournisseur renvoie malgré tout suspend toutes les requêtes de l’organisation vers ce modèle et est réessayé à l’échelle de la minute ; une recherche n’est freinée par aucun des deux. Alibaba Cloud Model Studio autorise par exemple 1 800 requêtes et 1 000 000 de tokens par minute pour text-embedding-v4. ```json { @@ -64,7 +65,9 @@ Deux autres réglages facultatifs de `embedding.json` décrivent la charge que l "dimensions": 1024, "baseUrl": "https://embeddings.example.internal/v1", "maxConcurrentRequests": 2, - "minTokensPerSecond": 800 + "minTokensPerSecond": 800, + "maxTokensPerMinute": 1000000, + "maxRequestsPerMinute": 1800 } ``` diff --git a/docs/fr/self-hosted/install/cli-install.md b/docs/fr/self-hosted/install/cli-install.md index 77664bce23..b2a8f2b2aa 100644 --- a/docs/fr/self-hosted/install/cli-install.md +++ b/docs/fr/self-hosted/install/cli-install.md @@ -375,7 +375,7 @@ Ces types de ressources utilisent les schémas partagés et les permissions nati | `knowledge-embedding` | Fournisseur, modèle, dimensions, endpoint et limites du serveur | Organisation | | `deployment` | Paramètres de l’instance, dont le runtime du sandbox | Instance | -Les politiques de conservation et DSAR exigent leurs workflows natifs dédiés. Interromps les envois, la synchronisation et les crawls avant de changer de modèle d’embedding. La CLI vérifie le nombre de documents et de sites web dans toute l’organisation ; elle ne verrouille pas l’import et ne migre pas les vecteurs existants. Pour une organisation avec des documents ou des sites web enregistrés, un changement de modèle exige une migration native distincte de l’index. Une modification limitée à `minSimilarity`, `maxConcurrentRequests` ou `minTokensPerSecond` laisse les vecteurs existants valables et échappe donc à cette vérification. Les paramètres d’instance exigent aussi la liste native des éditeurs autorisés. L’application autonome signale `restartRequired` pour les paramètres de démarrage ; les enregistrer ne les active pas encore. Examine les effets du plan avant de l’appliquer. +Les politiques de conservation et DSAR exigent leurs workflows natifs dédiés. Interromps les envois, la synchronisation et les crawls avant de changer de modèle d’embedding. La CLI vérifie le nombre de documents et de sites web dans toute l’organisation ; elle ne verrouille pas l’import et ne migre pas les vecteurs existants. Pour une organisation avec des documents ou des sites web enregistrés, un changement de modèle exige une migration native distincte de l’index. Une modification limitée à `minSimilarity`, `maxConcurrentRequests`, `minTokensPerSecond`, `maxTokensPerMinute` ou `maxRequestsPerMinute` laisse les vecteurs existants valables et échappe donc à cette vérification. Les paramètres d’instance exigent aussi la liste native des éditeurs autorisés. L’application autonome signale `restartRequired` pour les paramètres de démarrage ; les enregistrer ne les active pas encore. Examine les effets du plan avant de l’appliquer. Les déploiements gérés utilisent le même moteur via `configuration`. Ajoute cet exemple à la déclaration de déploiement quand un opérateur externe sert déjà le fournisseur. Remplace l’endpoint et le catalogue synthétiques par des valeurs vérifiées, puis injecte `EXTERNAL_PROVIDER_SECRET` depuis ton gestionnaire de secrets : @@ -434,7 +434,7 @@ Les déploiements gérés utilisent le même moteur via `configuration`. Ajoute `envName` suit le préfixe natif `TALE_PROVIDER_KEY_` et la limite de 40 caractères. Chaque alias exige une référence `environment` obligatoire. Les endpoints privés exigent aussi une référence explicite `TALE_ALLOW_PRIVATE_PROVIDER_HOSTS` dont la valeur est `1` ; les restrictions natives d’hôtes restent actives. `expectedModels` vérifie le catalogue fraîchement résolu par Tale lors de la relecture. Ce contrôle ne prouve ni la capacité d’inférence, ni la latence, ni les résultats métier. -Pour la sélection du modèle de vision, utilise `governance` avec `key: "vision_model"` et les champs natifs `providerSlug`/`modelId`. L’embedding utilise `knowledge-embedding` avec `providerSlug`, `model`, `dimensions` et `baseUrl`, plus les réglages facultatifs que la plateforme garde à côté du modèle dans [`embedding.json`](/fr/self-hosted/configuration/data-residency#le-modele-dembedding-de-lorganisation) : `minSimilarity`, le plancher de cosinus de l’assistant pour ce modèle, et les limites du serveur `maxConcurrentRequests` et `minTokensPerSecond` ([Doser les requêtes vers un serveur d’embedding auto-hébergé](/fr/self-hosted/configuration/data-residency#capacite-du-serveur-dembedding)). Chacun suit la règle de la plateforme elle-même : une valeur le fixe, une clé omise laisse ce que le fichier contient (une valeur posée à la main survit à une release qui ne la mentionne pas), et `null` l’efface — `"minSimilarity": null`, par exemple, est la seule façon de retirer un plancher par la CLI. Pour remplacer les identifiants par défaut, déclare aussi les anciens identifiants d’environnement avec `isDefault: false` ; la CLI applique ce changement explicite en premier. Les secrets ne figurent ni dans la déclaration ni dans le reçu. +Pour la sélection du modèle de vision, utilise `governance` avec `key: "vision_model"` et les champs natifs `providerSlug`/`modelId`. L’embedding utilise `knowledge-embedding` avec `providerSlug`, `model`, `dimensions` et `baseUrl`, plus les réglages facultatifs que la plateforme garde à côté du modèle dans [`embedding.json`](/fr/self-hosted/configuration/data-residency#le-modele-dembedding-de-lorganisation) : `minSimilarity`, le plancher de cosinus de l’assistant pour ce modèle, et les limites du serveur `maxConcurrentRequests`, `minTokensPerSecond`, `maxTokensPerMinute` et `maxRequestsPerMinute` ([Doser les requêtes vers un serveur d’embedding auto-hébergé](/fr/self-hosted/configuration/data-residency#capacite-du-serveur-dembedding)). Chacun suit la règle de la plateforme elle-même : une valeur le fixe, une clé omise laisse ce que le fichier contient (une valeur posée à la main survit à une release qui ne la mentionne pas), et `null` l’efface — `"minSimilarity": null`, par exemple, est la seule façon de retirer un plancher par la CLI. Pour remplacer les identifiants par défaut, déclare aussi les anciens identifiants d’environnement avec `isDefault: false` ; la CLI applique ce changement explicite en premier. Les secrets ne figurent ni dans la déclaration ni dans le reçu. La configuration native suit la vérification d’identité et précède les versions de configuration. Le reçu `native.configuration` lie les hashes de déclaration et de bundle, l’organisation, les hashes des ressources et les révisions natives. Un reçu en attente précède la première écriture. Si une ressource échoue ensuite, les changements précédents peuvent rester en place. Relis l’état natif et le reçu avant de reprendre le même plan vérifié. Le compare-and-set natif protège chaque ressource des modifications concurrentes d’un admin ; aucune transaction ne couvre l’ensemble. Conserve l’état du déploiement, les snapshots et les reçus pour la restauration. diff --git a/packages/shared/src/schemas/knowledge.test.ts b/packages/shared/src/schemas/knowledge.test.ts index 0f81d0f39b..330923210c 100644 --- a/packages/shared/src/schemas/knowledge.test.ts +++ b/packages/shared/src/schemas/knowledge.test.ts @@ -19,6 +19,8 @@ describe('knowledgeEmbeddingWriteSchema — what a write may clear', () => { it('names the settings a write keeps when it omits them', () => { expect([...KNOWLEDGE_EMBEDDING_KEPT_KEYS].sort()).toEqual([ 'maxConcurrentRequests', + 'maxRequestsPerMinute', + 'maxTokensPerMinute', 'minSimilarity', 'minTokensPerSecond', ]); diff --git a/packages/shared/src/schemas/knowledge.ts b/packages/shared/src/schemas/knowledge.ts index ccdb48afae..278b9c1739 100644 --- a/packages/shared/src/schemas/knowledge.ts +++ b/packages/shared/src/schemas/knowledge.ts @@ -170,6 +170,22 @@ export const knowledgeEmbeddingSchema = z.object({ * may wait its whole ceiling. */ minTokensPerSecond: z.number().positive().optional(), + /** + * The most tokens Tale sends this model in any one minute — the + * organization's requests in each Tale process together, estimated from + * their characters (a conservative count, 1.2–1.5 times the real one for + * prose). A batch that would cross it waits until the oldest minute's + * worth has aged out. Set it to the provider's tokens-per-minute limit + * (DashScope's text-embedding-v4 allows 1,000,000) so a crawl of hundreds + * of pages is paced instead of refused with 429s. Absent means unpaced. + */ + maxTokensPerMinute: z.number().int().positive().optional(), + /** + * The most requests Tale sends this model in any one minute, counted the + * same way; set it to the provider's requests-per-minute limit. Absent + * means unpaced. + */ + maxRequestsPerMinute: z.number().int().positive().optional(), }); export type KnowledgeEmbeddingConfig = z.infer; @@ -183,6 +199,8 @@ export const KNOWLEDGE_EMBEDDING_KEPT_KEYS = [ 'minSimilarity', 'maxConcurrentRequests', 'minTokensPerSecond', + 'maxTokensPerMinute', + 'maxRequestsPerMinute', ] as const; const embeddingFields = knowledgeEmbeddingSchema.shape; @@ -202,6 +220,14 @@ export const knowledgeEmbeddingWriteSchema = knowledgeEmbeddingSchema.extend({ .unwrap() .nullable() .optional(), + maxTokensPerMinute: embeddingFields.maxTokensPerMinute + .unwrap() + .nullable() + .optional(), + maxRequestsPerMinute: embeddingFields.maxRequestsPerMinute + .unwrap() + .nullable() + .optional(), }); export type KnowledgeEmbeddingWrite = z.infer< typeof knowledgeEmbeddingWriteSchema diff --git a/services/platform/app/features/websites/lib/scan-error.test.ts b/services/platform/app/features/websites/lib/scan-error.test.ts index 6d8455bc02..e97e9e395a 100644 --- a/services/platform/app/features/websites/lib/scan-error.test.ts +++ b/services/platform/app/features/websites/lib/scan-error.test.ts @@ -183,6 +183,9 @@ describe('embeddingFailureClass', () => { expect(embeddingHintKey('dimension')).toBe( 'viewDialog.scanDetail.dimension', ); + expect(embeddingHintKey('throttled')).toBe( + 'viewDialog.scanDetail.throttled', + ); expect(embeddingHintKey('upstream')).toBe('viewDialog.scanDetail.upstream'); expect(embeddingHintKey(null)).toBe('viewDialog.scanDetail.generic'); }); diff --git a/services/platform/app/features/websites/lib/scan-error.ts b/services/platform/app/features/websites/lib/scan-error.ts index 9c07bf51f1..fa50910502 100644 --- a/services/platform/app/features/websites/lib/scan-error.ts +++ b/services/platform/app/features/websites/lib/scan-error.ts @@ -163,6 +163,7 @@ export function embeddingHintKey( | 'viewDialog.scanDetail.credit' | 'viewDialog.scanDetail.unresolved' | 'viewDialog.scanDetail.dimension' + | 'viewDialog.scanDetail.throttled' | 'viewDialog.scanDetail.upstream' | 'viewDialog.scanDetail.generic' { switch (failureClass) { @@ -174,6 +175,8 @@ export function embeddingHintKey( return 'viewDialog.scanDetail.unresolved'; case 'dimension': return 'viewDialog.scanDetail.dimension'; + case 'throttled': + return 'viewDialog.scanDetail.throttled'; case 'upstream': return 'viewDialog.scanDetail.upstream'; default: diff --git a/services/platform/backend/core/knowledge/crawl_action.vectors.test.ts b/services/platform/backend/core/knowledge/crawl_action.vectors.test.ts index 8e07655990..09ea5c66c5 100644 --- a/services/platform/backend/core/knowledge/crawl_action.vectors.test.ts +++ b/services/platform/backend/core/knowledge/crawl_action.vectors.test.ts @@ -272,6 +272,28 @@ describe('PageIndexer.indexPage — the embedding provider fails', () => { ); }); + // The provider's per-minute limit, outlasting every retry: its own class, + // so the site says the next scan continues instead of blaming the account. + it('names the model and the rate limit when the provider throttled the pages', async () => { + const limited = OpenAI.APIError.generate( + 429, + { + error: { + code: 'insufficient_quota', + message: + 'Allocated quota exceeded, please increase your quota limit.', + }, + }, + undefined, + new Headers(), + ); + await expect(indexWith(() => Promise.reject(limited))).rejects.toThrow( + new RegExp( + `^${WEBSITE_EMBEDDING_FAILED_PREFIX} \\[throttled\\]: .*Allocated quota exceeded`, + ), + ); + }); + it('leaves an unrelated failure as it is', async () => { const unrelated = new Error('relation "chunks" does not exist'); await expect(indexWith(() => Promise.reject(unrelated))).rejects.toBe( diff --git a/services/platform/backend/core/knowledge/embedding.test.ts b/services/platform/backend/core/knowledge/embedding.test.ts index 52784a2b75..ab566b5a4e 100644 --- a/services/platform/backend/core/knowledge/embedding.test.ts +++ b/services/platform/backend/core/knowledge/embedding.test.ts @@ -298,7 +298,7 @@ describe('account refusals from the provider', () => { ); }); - it('classifies any other provider failure as upstream', () => { + it('classifies a rate limit as throttled and any other provider failure as upstream', () => { expect( classifyEmbeddingFailure( OpenAI.APIError.generate( @@ -313,7 +313,7 @@ describe('account refusals from the provider', () => { new Headers(), ), ), - ).toBe('upstream'); + ).toBe('throttled'); expect( classifyEmbeddingFailure(new OpenAI.APIConnectionTimeoutError()), ).toBe('upstream'); @@ -326,6 +326,173 @@ describe('account refusals from the provider', () => { }); }); +describe('a per-minute limit is waited out, not billed', () => { + // DashScope's compatible mode answers its token-per-minute limit + // (Throttling.AllocationQuota) with OpenAI's billing code: a scan of 300 + // pages used to end on the first one as "balance or plan", unretried. + const dashScopeLimit = () => + OpenAI.APIError.generate( + 429, + { + error: { + code: 'insufficient_quota', + message: + 'Allocated quota exceeded, please increase your quota limit. For details, see: https://www.alibabacloud.com/help/en/model-studio/error-code#token-limit', + }, + }, + undefined, + new Headers(), + ); + const openAiBilling = () => + OpenAI.APIError.generate( + 429, + { + error: { + code: 'insufficient_quota', + message: + 'You exceeded your current quota, please check your plan and billing details.', + }, + }, + undefined, + new Headers(), + ); + + it('tells the same code apart by its words', () => { + expect(classifyEmbeddingFailure(dashScopeLimit())).toBe('throttled'); + expect(classifyEmbeddingFailure(openAiBilling())).toBe('credit'); + }); + + it('still does not retry the billing refusal', async () => { + create.mockRejectedValue(openAiBilling()); + const embedder = new Embedder( + { ...MODEL, model: 'embedding-billing' }, + 'sk-test', + ); + await expect(embedder.embedAll(['a'])).rejects.toThrow( + 'exceeded your current quota', + ); + expect(create).toHaveBeenCalledTimes(1); + }); + + it('retries a limited batch on the minute scale and holds the lane meanwhile', async () => { + vi.useFakeTimers(); + create + .mockRejectedValueOnce(dashScopeLimit()) + .mockImplementation((args) => Promise.resolve(vectorsFor(args.input))); + const model = { ...MODEL, model: 'embedding-limited' }; + const embedder = new Embedder(model, 'sk-test'); + + const first = embedder.embedAll(['a']); + await vi.advanceTimersByTimeAsync(1); + expect(create).toHaveBeenCalledTimes(1); + // A second batch arrives while the lane is paused: it is held too. + const second = new Embedder(model, 'sk-test').embedAll(['b']); + await vi.advanceTimersByTimeAsync(9_000); + expect(create).toHaveBeenCalledTimes(1); + // 10 s (+ jitter under 500 ms): the first batch goes again and the + // second follows. + await vi.advanceTimersByTimeAsync(2_000); + expect(create).toHaveBeenCalledTimes(3); + await expect(first).resolves.toEqual([[1, 2, 3]]); + await expect(second).resolves.toEqual([[1, 2, 3]]); + }); + + it('answers a search query at once, pause or not', async () => { + vi.useFakeTimers(); + create + .mockRejectedValueOnce(dashScopeLimit()) + .mockImplementation((args) => Promise.resolve(vectorsFor(args.input))); + const model = { ...MODEL, model: 'embedding-limited-query' }; + const batch = new Embedder(model, 'sk-test').embedAll(['a']); + await vi.advanceTimersByTimeAsync(1); + expect(create).toHaveBeenCalledTimes(1); + const query = new Embedder(model, 'sk-test').embed('q'); + await vi.advanceTimersByTimeAsync(1); + expect(create).toHaveBeenCalledTimes(2); + await expect(query).resolves.toEqual([1, 2, 3]); + await vi.advanceTimersByTimeAsync(11_000); + await expect(batch).resolves.toEqual([[1, 2, 3]]); + }); + + it('gives up on a batch after six limited attempts', async () => { + vi.useFakeTimers(); + create.mockRejectedValue(dashScopeLimit()); + const embedder = new Embedder( + { ...MODEL, model: 'embedding-limited-forever' }, + 'sk-test', + ); + const outcome = embedder.embedAll(['a']).then( + () => 'resolved', + (error: unknown) => error, + ); + // 10 + 20 + 40 + 60 + 60 s of pauses, each with jitter under 500 ms. + await vi.advanceTimersByTimeAsync(200_000); + expect(await outcome).toBeInstanceOf(OpenAI.RateLimitError); + expect(create).toHaveBeenCalledTimes(6); + }); +}); + +describe("pacing under the provider's per-minute limits", () => { + it('holds the request that would cross maxRequestsPerMinute until the minute turns', async () => { + vi.useFakeTimers(); + create.mockImplementation((args) => + Promise.resolve(vectorsFor(args.input)), + ); + const embedder = new Embedder( + { + ...MODEL, + model: 'embedding-rpm', + maxConcurrentRequests: 3, + maxRequestsPerMinute: 2, + }, + 'sk-test', + ); + const a = embedder.embedAll(['a']); + const b = embedder.embedAll(['b']); + const c = embedder.embedAll(['c']); + await vi.advanceTimersByTimeAsync(1); + expect(create).toHaveBeenCalledTimes(2); + await expect(a).resolves.toEqual([[1, 2, 3]]); + await expect(b).resolves.toEqual([[1, 2, 3]]); + await vi.advanceTimersByTimeAsync(59_000); + expect(create).toHaveBeenCalledTimes(2); + await vi.advanceTimersByTimeAsync(2_000); + expect(create).toHaveBeenCalledTimes(3); + await expect(c).resolves.toEqual([[1, 2, 3]]); + }); + + it('holds the batch that would cross maxTokensPerMinute, and sends one alone that never could fit', async () => { + vi.useFakeTimers(); + create.mockImplementation((args) => + Promise.resolve(vectorsFor(args.input)), + ); + // Each text here counts a handful of tokens; the limit admits one. + const embedder = new Embedder( + { + ...MODEL, + model: 'embedding-tpm', + maxConcurrentRequests: 3, + maxTokensPerMinute: 5, + }, + 'sk-test', + ); + const a = embedder.embedAll(['ab']); + const b = embedder.embedAll(['cd']); + await vi.advanceTimersByTimeAsync(1); + expect(create).toHaveBeenCalledTimes(1); + await expect(a).resolves.toEqual([[1, 2, 3]]); + await vi.advanceTimersByTimeAsync(61_000); + expect(create).toHaveBeenCalledTimes(2); + await expect(b).resolves.toEqual([[1, 2, 3]]); + // Larger than the limit by itself: goes when the minute is empty. + await vi.advanceTimersByTimeAsync(61_000); + const big = embedder.embedAll(['a much longer text than the limit allows']); + await vi.advanceTimersByTimeAsync(1); + expect(create).toHaveBeenCalledTimes(3); + await expect(big).resolves.toEqual([[1, 2, 3]]); + }); +}); + describe('credential refusals before any provider call', () => { // The resolver refuses the credential the settings select before a // request is built. Unclassified, the refusal reached indexing's catch-all @@ -1288,7 +1455,7 @@ describe('provider refusals no wait can lift', () => { message: 'Rate limit reached for embeddings', }, }, - 'upstream', + 'throttled', ], ['500', 500, { error: { message: 'The server had an error' } }, 'upstream'], ])('classifies %s as %s', (_label, status, body, expected) => { diff --git a/services/platform/backend/core/knowledge/embedding.ts b/services/platform/backend/core/knowledge/embedding.ts index ec0962c1b1..a9a86a6910 100644 --- a/services/platform/backend/core/knowledge/embedding.ts +++ b/services/platform/backend/core/knowledge/embedding.ts @@ -63,6 +63,20 @@ export const MAX_BATCH = 64; const RETRIES = 3; const RETRY_BASE_MS = 1000; +/** A provider's per-minute limit clears on the minute, not in seconds: a + * batch refused with 429 pauses its whole lane — every slot, every waiting + * batch, or the other slots keep hitting the same limit — and comes back on + * a minute scale (10 s, 20 s, 40 s, then 60 s), for more attempts than the + * connection-class retry gets. A search query a person waits on keeps the + * short schedule and skips the lane pause: it is more use answered as a + * refusal in seconds than as a vector after a minute. */ +const RATE_LIMIT_RETRIES = 6; +const RATE_LIMIT_BASE_MS = 10_000; +const RATE_LIMIT_MAX_PAUSE_MS = 60_000; + +/** The window `maxTokensPerMinute` and `maxRequestsPerMinute` count in. */ +const PACE_WINDOW_MS = 60_000; + /** The longest pause a busy server may ask for (`Retry-After`) that a request * waits out while holding its slot. A server that asks for more is left * alone: the request fails, and its caller's own slower retry — the @@ -224,6 +238,99 @@ interface Lane { readonly bounds: Map; } +/** + * What a lane remembers between its requests, kept apart from the queue — + * which is forgotten the moment no caller holds it, while a crawl goes + * quiet for seconds between pages: the moment until which the provider's + * rate limit has the lane paused, and the requests of the last minute, by + * which the pacing limits (`maxTokensPerMinute`, `maxRequestsPerMinute`) + * are counted. Forgotten once the minute has aged out and the pause is + * over. + */ +interface LanePace { + pausedUntil: number; + readonly sent: { at: number; tokens: number }[]; +} + +const lanePaces = new Map(); + +function lanePace(key: string): LanePace { + let pace = lanePaces.get(key); + if (pace === undefined) { + pace = { pausedUntil: 0, sent: [] }; + lanePaces.set(key, pace); + } + return pace; +} + +/** Hold every batch of the lane until `until` — the later of what is + * already held and this. */ +function pauseLane(key: string, until: number): void { + const pace = lanePace(key); + if (until > pace.pausedUntil) pace.pausedUntil = until; +} + +function forgetAgedSends(pace: LanePace, now: number): void { + while ( + pace.sent.length > 0 && + (pace.sent[0]?.at ?? now) <= now - PACE_WINDOW_MS + ) { + pace.sent.shift(); + } +} + +/** + * How long a batch of `tokens` has to wait before the lane admits it: the + * rest of a rate-limit pause, then until enough of the last minute's + * requests have aged out for the request count and the token count to fit + * under the limits. A single request larger than the token limit goes when + * the minute is empty — it could never fit otherwise, and the provider is + * the one to refuse it. Zero when it may go now. + */ +function paceWaitMs( + pace: LanePace, + tokens: number, + limits: Pick, + now: number, +): number { + forgetAgedSends(pace, now); + let wait = Math.max(0, pace.pausedUntil - now); + const oldest = pace.sent[0]; + if ( + limits.maxRequestsPerMinute !== undefined && + oldest !== undefined && + pace.sent.length >= limits.maxRequestsPerMinute + ) { + wait = Math.max(wait, oldest.at + PACE_WINDOW_MS - now); + } + if (limits.maxTokensPerMinute !== undefined && oldest !== undefined) { + let used = 0; + for (const entry of pace.sent) used += entry.tokens; + let freedAt = now; + let index = 0; + while ( + used + tokens > limits.maxTokensPerMinute && + index < pace.sent.length + ) { + const entry = pace.sent[index]; + if (entry === undefined) break; + used -= entry.tokens; + freedAt = entry.at + PACE_WINDOW_MS; + index += 1; + } + if (index > 0) wait = Math.max(wait, freedAt - now); + } + return wait; +} + +/** Drop a lane's pace once nothing in it matters any more. */ +function forgetIdlePace(key: string, now: number): void { + const pace = lanePaces.get(key); + if (pace === undefined) return; + forgetAgedSends(pace, now); + if (pace.sent.length === 0 && pace.pausedUntil <= now) lanePaces.delete(key); +} + /** * The most texts one request may carry per lane (organization, endpoint and * model), once the provider has said so (see {@link batchCapFrom}). Learned @@ -550,20 +657,37 @@ export class Embedder implements QueryEmbedder { return filled; } + /** + * Wait for the lane to admit a batch: out of a rate-limit pause, and under + * the pacing limits for the minute. A search query skips both — it is + * answered sooner as a refusal than as a vector after the minute. + */ + private async admit( + tokens: number, + signal: AbortSignal, + kind: EmbedKind, + ): Promise { + if (kind === 'query') return; + const pace = lanePace(this.lane); + for (;;) { + const wait = paceWaitMs(pace, tokens, this.model, Date.now()); + if (wait <= 0) break; + await sleep(wait, signal); + } + pace.sent.push({ at: Date.now(), tokens }); + } + /** One provider call, retried on the failures that are worth retrying. */ private async request( texts: readonly string[], signal: AbortSignal, kind: EmbedKind, ): Promise { - const timeout = embeddingRequestTimeoutMs( - estimateEmbeddingTokens(texts), - this.model, - kind, - ); - let lastError: unknown; - for (let attempt = 0; attempt < RETRIES; attempt++) { + const tokens = estimateEmbeddingTokens(texts); + const timeout = embeddingRequestTimeoutMs(tokens, this.model, kind); + for (let attempt = 0; ; attempt++) { signal.throwIfAborted(); + await this.admit(tokens, signal, kind); try { const response = await this.client.embeddings.create( { @@ -584,25 +708,29 @@ export class Embedder implements QueryEmbedder { ); const vectors: number[][] = []; for (const item of response.data) vectors.push(item.embedding); + forgetIdlePace(this.lane, Date.now()); return vectors; } catch (err) { - lastError = err; - if (signal.aborted || !isRetryable(err) || attempt === RETRIES - 1) { - throw err; - } + if (signal.aborted || !isRetryable(err)) throw err; + // A rate limit on a batch is waited out on the minute scale, and + // the whole lane with it; anything else keeps the seconds schedule. + const limited = + kind === 'batch' && err instanceof OpenAI.RateLimitError; + const attempts = limited ? RATE_LIMIT_RETRIES : RETRIES; + if (attempt >= attempts - 1) throw err; const asked = serverAskedPauseMs(err); if (asked !== undefined && asked > MAX_SERVER_ASKED_PAUSE_MS) throw err; - const delay = Math.max( - RETRY_BASE_MS * 2 ** attempt + Math.random() * 500, - asked ?? 0, - ); + const backoff = limited + ? Math.min(RATE_LIMIT_BASE_MS * 2 ** attempt, RATE_LIMIT_MAX_PAUSE_MS) + : RETRY_BASE_MS * 2 ** attempt; + const delay = Math.max(backoff + Math.random() * 500, asked ?? 0); + if (limited) pauseLane(this.lane, Date.now() + delay); logger.warn( - `the embedding request failed (attempt ${attempt + 1} of ${RETRIES}), retrying`, + `the embedding request ${limited ? 'was rate-limited' : 'failed'} (attempt ${attempt + 1} of ${attempts}), retrying${limited ? ` in ${Math.round(delay / 1000)} s` : ''}`, ); await sleep(delay, signal); } } - throw lastError; } private zeros(): number[] { @@ -696,6 +824,12 @@ export async function embedderForOrg( ...(args.config.minTokensPerSecond !== undefined && { minTokensPerSecond: args.config.minTokensPerSecond, }), + ...(args.config.maxTokensPerMinute !== undefined && { + maxTokensPerMinute: args.config.maxTokensPerMinute, + }), + ...(args.config.maxRequestsPerMinute !== undefined && { + maxRequestsPerMinute: args.config.maxRequestsPerMinute, + }), }, credential.secret, { organizationId: args.organizationId }, @@ -728,10 +862,16 @@ async function connectorBaseUrl( * subscription plan does not include the model), and OpenAI's billing and * spend-limit codes. Every one arrives as HTTP 429 or 402 — which reads as * "wait and retry" when no wait helps. */ +/** Codes that name the ACCOUNT. `insufficient_quota` is deliberately not + * among them: OpenAI sends it for a spent balance ("You exceeded your + * current quota, please check your plan and billing details" — which the + * wording below catches), but DashScope's compatible mode sends the same + * code for its per-minute token limit (`Throttling.AllocationQuota`, + * "Allocated quota exceeded, please increase your quota limit"), which a + * wait does lift. The code alone cannot tell the two apart; the words can. */ const CREDIT_REFUSAL_CODES: ReadonlySet = new Set([ '1113', '1311', - 'insufficient_quota', 'billing_hard_limit_reached', 'billing_not_active', 'credit_balance_exhausted', @@ -773,13 +913,15 @@ function isCredentialRefusal(err: unknown): boolean { * serve direct embeddings, or the provider rejected it; `unresolved` — the * credential the settings select does not resolve at all (none configured, * deleted, of another provider, disabled, a secret that cannot be read), so - * no call reached the provider; `upstream` — anything else (a rate limit, a - * 5xx, unreachable, a timeout), worth a later retry. The first three hold - * until an admin acts. */ + * no call reached the provider; `throttled` — the provider's rate limit + * held through every retry, so pacing the requests is the fix; `upstream` + * — anything else (a 5xx, unreachable, a timeout), worth a later retry. + * The first three hold until an admin acts. */ export type EmbeddingFailure = | 'credit' | 'credential' | 'unresolved' + | 'throttled' | 'upstream'; /** Classify a credential refusal or provider error for the callers that turn @@ -794,6 +936,7 @@ export function classifyEmbeddingFailure( if (!(err instanceof OpenAI.APIError)) return null; if (isCreditRefusal(err)) return 'credit'; if (isCredentialRefusal(err)) return 'credential'; + if (err instanceof OpenAI.RateLimitError) return 'throttled'; return 'upstream'; } diff --git a/services/platform/backend/core/websites/scan_scheduling.ts b/services/platform/backend/core/websites/scan_scheduling.ts index 6d381acc9e..6d188e3187 100644 --- a/services/platform/backend/core/websites/scan_scheduling.ts +++ b/services/platform/backend/core/websites/scan_scheduling.ts @@ -129,6 +129,7 @@ export const WEBSITE_EMBEDDING_FAILED_PREFIX = * provider refused the account (balance, plan, billing); `unresolved` — the * credential the settings select does not resolve, so no call was made; * `dimension` — the model's vectors do not fit the knowledge database; + * `throttled` — the provider's rate limit held through every retry; * `upstream` — the provider failed or was unreachable. The reason carries * it as `[class]` right after the prefix, so the Websites page can say * which it was and whom to ask without reading the provider's words. */ @@ -137,6 +138,7 @@ export const WEBSITE_EMBEDDING_FAILURE_CLASSES = [ 'credit', 'unresolved', 'dimension', + 'throttled', 'upstream', ] as const; diff --git a/services/platform/backend/domains/knowledge/service.ts b/services/platform/backend/domains/knowledge/service.ts index fdbe71bd3c..0a26eec3de 100644 --- a/services/platform/backend/domains/knowledge/service.ts +++ b/services/platform/backend/domains/knowledge/service.ts @@ -671,6 +671,7 @@ const EMBEDDING_FAILURE_CODE = { credit: 'EMBEDDING_CREDIT_EXHAUSTED', credential: 'EMBEDDING_CREDENTIAL_REJECTED', unresolved: 'EMBEDDING_CREDENTIAL_REJECTED', + throttled: 'EMBEDDING_UPSTREAM_ERROR', upstream: 'EMBEDDING_UPSTREAM_ERROR', } as const; const EMBEDDING_FAILURE_PROSE = { @@ -680,6 +681,8 @@ const EMBEDDING_FAILURE_PROSE = { "The organization's embedding provider rejected its credential or refused it the model — provider settings an admin must fix", unresolved: "The organization's embedding model has no usable provider credential — an admin must add or fix it", + throttled: + "The organization's embedding provider is rate-limiting its requests", upstream: "The organization's embedding provider could not serve the request", } as const; @@ -1374,10 +1377,10 @@ export async function indexUploadedFile( orgSlug, error: error instanceof Error ? error.message : String(error), }); - if (refusal === 'upstream') { + if (refusal === 'upstream' || refusal === 'throttled') { await recordIndexingFailure(sql, { ...failure, - ragError: `${EMBEDDING_FAILURE_PROSE.upstream}; indexing is retried automatically.`, + ragError: `${EMBEDDING_FAILURE_PROSE[refusal]}; indexing is retried automatically.`, ragErrorCode: RAG_ERROR_EMBEDDING_UPSTREAM, }); throw error; diff --git a/services/platform/lib/knowledge/types.ts b/services/platform/lib/knowledge/types.ts index 4cb98c3bd8..b488cf4564 100644 --- a/services/platform/lib/knowledge/types.ts +++ b/services/platform/lib/knowledge/types.ts @@ -57,6 +57,12 @@ export interface EmbeddingModel { * this model. Absent, a request may wait its whole ceiling: fifteen minutes * for a batch, five for a search query. */ readonly minTokensPerSecond?: number; + /** The most tokens Tale sends this model in any one minute, across every + * request of the organization in this process; absent means unpaced. */ + readonly maxTokensPerMinute?: number; + /** The most requests Tale sends this model in any one minute; absent + * means unpaced. */ + readonly maxRequestsPerMinute?: number; } /** One chunk of one document, as retrieval returns it. */ diff --git a/services/platform/messages/de.yml b/services/platform/messages/de.yml index 5dfe809a7c..a9facd2284 100644 --- a/services/platform/messages/de.yml +++ b/services/platform/messages/de.yml @@ -8111,6 +8111,7 @@ websites: unresolved: Die Zugangsdaten des Embedding-Modells lassen sich nicht verwenden. Ein Admin kann sie unter Einstellungen → KI-Anbieter prüfen. dimension: Die Vektoren des Modells passen nicht zu dieser Wissensdatenbank. Ein Admin kann das Embedding-Modell unter Einstellungen → Datenresidenz prüfen. upstream: Der Anbieter ist ausgefallen oder nicht erreichbar. Wähle Jetzt scannen, sobald er wieder da ist. + throttled: Das Ratenlimit des Anbieters hielt über alle Wiederholungen an. Der nächste Scan macht von selbst weiter; ein Admin kann die Anfragen unter Einstellungen → Datenresidenz drosseln. generic: Ein Admin kann das Embedding-Modell unter Einstellungen → Datenresidenz prüfen. technicalDetails: Technische Details scanPausedBadge: Pausiert diff --git a/services/platform/messages/en.yml b/services/platform/messages/en.yml index c0a9dd0a78..4772f2a7d1 100644 --- a/services/platform/messages/en.yml +++ b/services/platform/messages/en.yml @@ -8217,6 +8217,7 @@ websites: unresolved: The embedding model's credential can't be used. An admin can check it under Settings → AI providers. dimension: The model's vectors don't fit this knowledge database. An admin can check the embedding model under Settings → Data residency. upstream: The provider failed or couldn't be reached. Choose Scan now once it's back. + throttled: The provider's rate limit held through every retry. The next scan continues on its own; an admin can pace requests under Settings → Data residency. generic: An admin can check the embedding model under Settings → Data residency. technicalDetails: Technical details scanPausedBadge: Paused diff --git a/services/platform/messages/fr.yml b/services/platform/messages/fr.yml index e75df2ff6d..316bd9a8f2 100644 --- a/services/platform/messages/fr.yml +++ b/services/platform/messages/fr.yml @@ -8218,6 +8218,7 @@ websites: unresolved: Les identifiants du modèle d'embedding ne peuvent pas être utilisés. Un administrateur peut les vérifier sous Paramètres → Fournisseurs IA. dimension: Les vecteurs du modèle ne correspondent pas à cette base de connaissances. Un administrateur peut vérifier le modèle d'embedding sous Paramètres → Résidence des données. upstream: Le fournisseur est en panne ou injoignable. Choisis Analyser maintenant dès qu'il est de retour. + throttled: La limite de débit du fournisseur a tenu malgré toutes les tentatives. La prochaine analyse reprend d'elle-même ; un administrateur peut espacer les requêtes sous Paramètres → Résidence des données. generic: Un administrateur peut vérifier le modèle d'embedding sous Paramètres → Résidence des données. technicalDetails: Détails techniques scanPausedBadge: Suspendu diff --git a/services/platform/tests/manual/reference/automation.md b/services/platform/tests/manual/reference/automation.md index 65041f0c27..22f4fc92e1 100644 --- a/services/platform/tests/manual/reference/automation.md +++ b/services/platform/tests/manual/reference/automation.md @@ -143,7 +143,7 @@ Legend: ✅ fully automated · 🔶 partially automated · ⛔ manual-only (no s | [knowledge](../suites/knowledge.md) | Crawled page text reads as a reader sees it: inline formatting is zero-width (a text split into one `` per letter — example.com — stays words, `Important` one word), and the render lane writes the page's CSS layout into the markup it returns (flex/grid items and blocks on their own lines, inline blocks and table cells apart) without touching the live page | ✅ unit + browser | `lib/knowledge/html-to-text.test.ts`, `backend/core/node_only/sandbox/render_layout.browser.test.ts`, `backend/core/node_only/sandbox/render_fetch.test.ts` | | [knowledge](../suites/knowledge.md) | A render lane that renders nothing fails the scan visibly instead of looping: a worker that stopped before its first page (a browser that would not launch) fails the batch with its own stderr and still tears its session down; a page the worker was cut off in is charged as a `timeout` rather than handed back to every later batch | ✅ unit | `backend/core/node_only/sandbox/render_fetch.test.ts`, `lib/knowledge/crawl-parse.test.ts` | | [knowledge](../suites/knowledge.md) | Website pages chunked without vectors (crawled before an embedding model was configured) are embedded by the next scan once a model can, although their text is unchanged; unchanged pages with vectors are left alone and never touch the provider; a scan that was running when a model was saved embeds, from their stored text and before it ends, the pages it had already stored without vectors, looking for the model again when the link found none | ✅ unit | `backend/core/knowledge/crawl_action.vectors.test.ts` | -| [knowledge](../suites/knowledge.md) | `KNOW-F18` (the embedding reason): a scan the embedding provider refused or failed (a rejected credential, an exhausted balance, an outage) ends under a reason that names the embedding model and its class (`[credential]`, `[credit]`, `[unresolved]`, `[dimension]`, `[upstream]`), which the view shows as a destructive Alert — the class's hint, then the provider's own sentence — instead of a muted caption with the words on hover; a failure that is not the provider's passes through unchanged; repairing the credential the embedding model resolves (a create, or an edit of what the resolver reads) scans the failed and vector-less sites again, as saving the model does, and leaves them alone for any other credential | ✅ unit + route + component | `backend/core/knowledge/crawl_action.vectors.test.ts`, `backend/domains/provider_credentials/routes.requeue.test.ts`, `app/features/websites/lib/scan-error.test.ts`, `app/features/websites/components/website-view-dialog.test.tsx` | +| [knowledge](../suites/knowledge.md) | `KNOW-F18` (the embedding reason): a scan the embedding provider refused or failed (a rejected credential, an exhausted balance, an outage) ends under a reason that names the embedding model and its class (`[credential]`, `[credit]`, `[unresolved]`, `[dimension]`, `[throttled]`, `[upstream]`), which the view shows as a destructive Alert — the class's hint, then the provider's own sentence — instead of a muted caption with the words on hover; a failure that is not the provider's passes through unchanged; repairing the credential the embedding model resolves (a create, or an edit of what the resolver reads) scans the failed and vector-less sites again, as saving the model does, and leaves them alone for any other credential | ✅ unit + route + component | `backend/core/knowledge/crawl_action.vectors.test.ts`, `backend/domains/provider_credentials/routes.requeue.test.ts`, `app/features/websites/lib/scan-error.test.ts`, `app/features/websites/components/website-view-dialog.test.tsx` | | [knowledge](../suites/knowledge.md) | `KNOW-F33` (the logic half): every website row write hints the organization's lists — a create, a delete, and a patch that changes what a reader sees; a sync that only stamps its own clock stays quiet — and the details dialog reads its shown pages again when the row's counts move; the scan queue is worked through one-job slots, so one site's scan link does not hold another site's | ✅ unit + component | `backend/domains/websites/service.hints.test.ts`, `app/features/websites/components/website-view-dialog.test.tsx`, `backend/jobs/runner.test.ts` | | [knowledge](../suites/knowledge.md) | `KNOW-F32` (the logic half): **Scan now** queues a scan and clears the failure bookkeeping in one transaction, answers that nothing was queued while a scan runs, and is offered only to writers for a site that is neither scanning, deleting nor paused; a whole-site row the corpus does not know is registered again before its scan, a URL list is not, and the details say which: a missing site reads that its next scan adds it again, a missing URL list that it has to be deleted and added again | ✅ unit + component + real Postgres | `backend/domains/websites/service.scan-now.test.ts`, `app/features/websites/components/website-row-actions.test.tsx`, `app/features/websites/components/website-view-dialog.test.tsx`, `app/features/websites/lib/scan-error.test.ts`, `backend/integration-check.ts` (`checkWebsitesCrawl`) | | [knowledge](../suites/knowledge.md) / [data-residency](../suites/data-residency.md) | `KNOW-F34` (the logic half): search readiness is false without an embedding model or without a credential that resolves; the notice links an admin to the setting, points a member at an admin without mounting the admin reads, and stays silent while the dashboard banner already says it; saving a model queues a scan of the sites with vector-less pages and of those whose last scan failed, and hints the page either way | ✅ unit + component | `backend/domains/websites/search-readiness.test.ts`, `backend/domains/websites/service.embedding-follow.test.ts`, `app/features/websites/components/website-search-notice.test.tsx`, `app/features/websites/components/websites-table.test.tsx` | diff --git a/tools/cli/src/lib/config/platform-model.ts b/tools/cli/src/lib/config/platform-model.ts index c232ce5ec4..8e09b2ecc8 100644 --- a/tools/cli/src/lib/config/platform-model.ts +++ b/tools/cli/src/lib/config/platform-model.ts @@ -57,7 +57,8 @@ export const platformResourceSchema = z.union([ z.strictObject({ kind: z.literal('knowledge-embedding'), // The platform keeps a stored similarity floor or serving limit - // (`minSimilarity`, `maxConcurrentRequests`, `minTokensPerSecond`) when + // (`minSimilarity`, `maxConcurrentRequests`, `minTokensPerSecond`, + // `maxTokensPerMinute`, `maxRequestsPerMinute`) when // a save omits it and clears it only on an explicit null (the Settings // form never carries them) — so the declaration speaks the same three // ways: a value sets it, `null` clears it, omitted leaves what is stored. @@ -326,7 +327,8 @@ export function sameEmbeddingModel(declared: object, current: unknown) { * platform's own terms rather than never at all. * * Every resource compares whole, except the embedding's kept settings - * (`minSimilarity`, `maxConcurrentRequests`, `minTokensPerSecond`): the + * (`minSimilarity`, `maxConcurrentRequests`, `minTokensPerSecond`, + * `maxTokensPerMinute`, `maxRequestsPerMinute`): the * platform keeps a stored one when the write omits it and clears it on an * explicit null, so a declaration that omits one converges with ANY stored * value, one that declares `null` converges only once none is stored, and a From c45f6fdf7c13b364cf71973556e03fda54ce2fe3 Mon Sep 17 00:00:00 2001 From: larryro <371767072@qq.com> Date: Fri, 2 Oct 2026 15:12:29 +0800 Subject: [PATCH 2/2] fix(platform): keep a sixtieth of each embedding limit within a second Alibaba Cloud support confirmed that a model's RPM and TPM are enforced per second as well, each divided by sixty: a minute's worth sent in one second is refused while the minute is nearly empty, which is what three in-flight batches of twenty-five chunks do. Under maxTokensPerMinute and maxRequestsPerMinute the lane now also keeps every second under a sixtieth of the limit, and sizes each request to fit that second, so no single request can be the burst the per-second rule refuses. --- .../configuration/data-residency.md | 2 +- .../configuration/data-residency.md | 2 +- .../configuration/data-residency.md | 2 +- packages/shared/src/schemas/knowledge.ts | 9 +- .../backend/core/knowledge/embedding.test.ts | 65 +++++++- .../backend/core/knowledge/embedding.ts | 155 ++++++++++++++---- 6 files changed, 196 insertions(+), 39 deletions(-) diff --git a/docs/de/self-hosted/configuration/data-residency.md b/docs/de/self-hosted/configuration/data-residency.md index 849de4af02..fa698ddfc7 100644 --- a/docs/de/self-hosted/configuration/data-residency.md +++ b/docs/de/self-hosted/configuration/data-residency.md @@ -56,7 +56,7 @@ Zwei weitere optionale Einstellungen in `embedding.json` beschreiben, wie viel A - `maxConcurrentRequests` (1 bis 64, Standard 3) legt fest, wie viele Embedding-Anfragen an dieses Modell Tale für die Organisation gleichzeitig offen hält. Dokumentindexierung, die Indexierung eingehender E-Mails, Website-Scans und Suchen teilen sich dieses Limit. Weitere Anfragen warten in der Reihenfolge ihres Eintreffens; nur eine Suchanfrage zieht an wartenden Indexierungs-Batches vorbei. Jeder Tale-Prozess zählt für sich, sodass die API und jedes Worker-Replikat das Limit jeweils ausschöpfen können. Ein niedrigerer Wert gilt sofort, ein höherer erst, wenn die unter dem alten Wert gestarteten Anfragen abgeschlossen sind. Berechnet der Server eine Anfrage nach der anderen, erzeugt ein höherer Wert keine zusätzliche Last; jede Anfrage wartet nur länger. - `minTokensPerSecond` (eine beliebige positive Zahl) ist die niedrigste Rate, mit der der Server unter seiner üblichen Last Embeddings für dieses Modell berechnet. Miss sie, während auf derselben Hardware andere Arbeit läuft, etwa ein Chat-Modell, aber zähle die Zeit nicht mit, die eine Anfrage hinter anderen Anfragen wartet. Diese Wartezeit rechnet Tale selbst hinzu. -- `maxTokensPerMinute` und `maxRequestsPerMinute` (ganze Zahlen) dosieren, was Tale diesem Modell innerhalb einer Minute schickt, für die Organisation in jedem Tale-Prozess. Setze sie auf die Minutenlimits eines gehosteten Anbieters, die pro Anbieterkonto über alle Deployments gezählt werden, die sich den Schlüssel teilen: Ein Indexierungs-Batch, der ein Limit überschreiten würde, wartet, bis genug von der letzten Minute verstrichen ist, sodass ein Crawl über Hunderte Seiten dosiert wird statt mit `429` abgewiesen zu werden. Tale schätzt Tokens anhand der Zeichen, eher zu hoch. Ein `429`, das der Anbieter trotzdem schickt, hält jede Anfrage der Organisation an dieses Modell an und wird im Minutentakt wiederholt; eine Suchanfrage wird von beidem nicht gebremst. Alibaba Cloud Model Studio erlaubt für text-embedding-v4 zum Beispiel 1.800 Anfragen und 1.000.000 Tokens pro Minute. +- `maxTokensPerMinute` und `maxRequestsPerMinute` (ganze Zahlen) dosieren, was Tale diesem Modell innerhalb einer Minute schickt, für die Organisation in jedem Tale-Prozess. Setze sie auf die Minutenlimits eines gehosteten Anbieters, die pro Anbieterkonto über alle Deployments gezählt werden, die sich den Schlüssel teilen: Ein Indexierungs-Batch, der ein Limit überschreiten würde, wartet, bis genug von der letzten Minute verstrichen ist, sodass ein Crawl über Hunderte Seiten dosiert wird statt mit `429` abgewiesen zu werden. Tale schätzt Tokens anhand der Zeichen, eher zu hoch, hält zusätzlich ein Sechzigstel jedes Limits innerhalb jeder einzelnen Sekunde ein – ein Anbieter setzt seinen Minutenwert auch pro Sekunde durch – und bemisst jede Anfrage so, dass sie in diese Sekunde passt. Ein `429`, das der Anbieter trotzdem schickt, hält jede Anfrage der Organisation an dieses Modell an und wird im Minutentakt wiederholt; eine Suchanfrage wird von beidem nicht gebremst. Alibaba Cloud Model Studio erlaubt für text-embedding-v4 zum Beispiel 1.800 Anfragen und 1.000.000 Tokens pro Minute. ```json { diff --git a/docs/en/self-hosted/configuration/data-residency.md b/docs/en/self-hosted/configuration/data-residency.md index 3808fde256..8fbeb39a93 100644 --- a/docs/en/self-hosted/configuration/data-residency.md +++ b/docs/en/self-hosted/configuration/data-residency.md @@ -56,7 +56,7 @@ Two more optional `embedding.json` settings describe how much work the embedding - `maxConcurrentRequests` (1 to 64, default 3) is how many embedding requests to this model Tale keeps in flight at once for the organization. Document indexing, the indexing of incoming email, website scans and searches share this limit. Further requests wait in arrival order, except that a search query goes ahead of waiting indexing batches. Each Tale process counts separately, so the API and every worker replica can each reach the limit. A lower value takes effect at once; a higher one once the requests started under the old value have finished. On a server that computes one request at a time, a higher value adds no load; each request only waits longer. - `minTokensPerSecond` (any positive number) is the slowest rate at which the server computes embeddings for this model under its usual load. Measure it while other work runs on the same hardware, such as a chat model, but leave out the time a request waits behind other requests. Tale adds that waiting time itself. -- `maxTokensPerMinute` and `maxRequestsPerMinute` (whole numbers) pace what Tale sends this model within any one minute, for the organization in each Tale process. Set them to a hosted provider's per-minute limits, which are counted per provider account across every deployment that shares the key: an indexing batch that would cross a limit waits until enough of the last minute has aged out, so a crawl of hundreds of pages is paced instead of refused with `429`. Tale estimates tokens from characters, on the high side. A `429` the provider still answers pauses every request of the organization to that model and is retried on a minute scale; a search query is not held back by either. Alibaba Cloud Model Studio, for example, allows text-embedding-v4 1,800 requests and 1,000,000 tokens per minute. +- `maxTokensPerMinute` and `maxRequestsPerMinute` (whole numbers) pace what Tale sends this model within any one minute, for the organization in each Tale process. Set them to a hosted provider's per-minute limits, which are counted per provider account across every deployment that shares the key: an indexing batch that would cross a limit waits until enough of the last minute has aged out, so a crawl of hundreds of pages is paced instead of refused with `429`. Tale estimates tokens from characters, on the high side, keeps a sixtieth of each limit within any one second as well — a provider enforces its per-minute figure per second too — and sizes each request to fit that second. A `429` the provider still answers pauses every request of the organization to that model and is retried on a minute scale; a search query is not held back by either. Alibaba Cloud Model Studio, for example, allows text-embedding-v4 1,800 requests and 1,000,000 tokens per minute. ```json { diff --git a/docs/fr/self-hosted/configuration/data-residency.md b/docs/fr/self-hosted/configuration/data-residency.md index ce874c954b..1d5b27c101 100644 --- a/docs/fr/self-hosted/configuration/data-residency.md +++ b/docs/fr/self-hosted/configuration/data-residency.md @@ -56,7 +56,7 @@ Deux autres réglages facultatifs de `embedding.json` décrivent la charge que l - `maxConcurrentRequests` (de 1 à 64, 3 par défaut) fixe le nombre de requêtes d’embedding que Tale garde en cours en même temps vers ce modèle pour l’organisation. L’indexation des documents, celle des e-mails reçus, les explorations de sites web et les recherches partagent cette limite. Les requêtes suivantes attendent dans leur ordre d’arrivée, mais une recherche passe devant les lots d’indexation en attente. Chaque processus Tale compte séparément : l’API et chaque réplique de worker peuvent donc chacune atteindre la limite. Une valeur plus basse s’applique aussitôt, une valeur plus haute une fois terminées les requêtes lancées sous l’ancienne. Sur un serveur qui calcule une requête à la fois, une valeur plus élevée n’ajoute aucune charge ; elle allonge seulement l’attente de chaque requête. - `minTokensPerSecond` (tout nombre positif) est le débit le plus bas auquel le serveur calcule les embeddings de ce modèle sous sa charge habituelle. Mesure-le pendant que d’autres traitements tournent sur le même matériel, comme un modèle de chat, mais sans compter le temps qu’une requête passe à attendre derrière d’autres requêtes. Tale ajoute lui-même ce temps d’attente. -- `maxTokensPerMinute` et `maxRequestsPerMinute` (nombres entiers) dosent ce que Tale envoie à ce modèle en une minute, pour l’organisation dans chaque processus Tale. Règle-les sur les limites par minute d’un fournisseur hébergé, comptées par compte fournisseur sur tous les déploiements qui partagent la clé : un lot d’indexation qui dépasserait une limite attend qu’une part suffisante de la dernière minute soit écoulée, si bien qu’une exploration de centaines de pages est dosée au lieu d’être refusée par des `429`. Tale estime les tokens d’après les caractères, en comptant large. Un `429` que le fournisseur renvoie malgré tout suspend toutes les requêtes de l’organisation vers ce modèle et est réessayé à l’échelle de la minute ; une recherche n’est freinée par aucun des deux. Alibaba Cloud Model Studio autorise par exemple 1 800 requêtes et 1 000 000 de tokens par minute pour text-embedding-v4. +- `maxTokensPerMinute` et `maxRequestsPerMinute` (nombres entiers) dosent ce que Tale envoie à ce modèle en une minute, pour l’organisation dans chaque processus Tale. Règle-les sur les limites par minute d’un fournisseur hébergé, comptées par compte fournisseur sur tous les déploiements qui partagent la clé : un lot d’indexation qui dépasserait une limite attend qu’une part suffisante de la dernière minute soit écoulée, si bien qu’une exploration de centaines de pages est dosée au lieu d’être refusée par des `429`. Tale estime les tokens d’après les caractères, en comptant large, respecte aussi un soixantième de chaque limite à l’intérieur de chaque seconde – un fournisseur applique sa valeur par minute à la seconde également – et dimensionne chaque requête pour tenir dans cette seconde. Un `429` que le fournisseur renvoie malgré tout suspend toutes les requêtes de l’organisation vers ce modèle et est réessayé à l’échelle de la minute ; une recherche n’est freinée par aucun des deux. Alibaba Cloud Model Studio autorise par exemple 1 800 requêtes et 1 000 000 de tokens par minute pour text-embedding-v4. ```json { diff --git a/packages/shared/src/schemas/knowledge.ts b/packages/shared/src/schemas/knowledge.ts index 278b9c1739..07e6b2d7fa 100644 --- a/packages/shared/src/schemas/knowledge.ts +++ b/packages/shared/src/schemas/knowledge.ts @@ -175,9 +175,12 @@ export const knowledgeEmbeddingSchema = z.object({ * organization's requests in each Tale process together, estimated from * their characters (a conservative count, 1.2–1.5 times the real one for * prose). A batch that would cross it waits until the oldest minute's - * worth has aged out. Set it to the provider's tokens-per-minute limit - * (DashScope's text-embedding-v4 allows 1,000,000) so a crawl of hundreds - * of pages is paced instead of refused with 429s. Absent means unpaced. + * worth has aged out; a sixtieth of it is kept per second as well, and + * no single request carries more than that, because a provider enforces + * its per-minute figure per second too. Set it to the provider's + * tokens-per-minute limit (DashScope's text-embedding-v4 allows + * 1,000,000) so a crawl of hundreds of pages is paced instead of refused + * with 429s. Absent means unpaced. */ maxTokensPerMinute: z.number().int().positive().optional(), /** diff --git a/services/platform/backend/core/knowledge/embedding.test.ts b/services/platform/backend/core/knowledge/embedding.test.ts index ab566b5a4e..0fe939b7c0 100644 --- a/services/platform/backend/core/knowledge/embedding.test.ts +++ b/services/platform/backend/core/knowledge/embedding.test.ts @@ -451,16 +451,77 @@ describe("pacing under the provider's per-minute limits", () => { const b = embedder.embedAll(['b']); const c = embedder.embedAll(['c']); await vi.advanceTimersByTimeAsync(1); + // A sixtieth of two a minute is one a second: the second waits a second. + expect(create).toHaveBeenCalledTimes(1); + await expect(a).resolves.toEqual([[1, 2, 3]]); + await vi.advanceTimersByTimeAsync(1_100); + expect(create).toHaveBeenCalledTimes(2); + await expect(b).resolves.toEqual([[1, 2, 3]]); + // The third is the minute's: it waits until the first has aged out. + await vi.advanceTimersByTimeAsync(57_000); + expect(create).toHaveBeenCalledTimes(2); + await vi.advanceTimersByTimeAsync(3_000); + expect(create).toHaveBeenCalledTimes(3); + await expect(c).resolves.toEqual([[1, 2, 3]]); + }); + + // The provider enforces its per-minute figure per second as well — the + // figure divided by sixty — so a minute's worth sent in one second is + // refused although the minute is nearly empty (Alibaba Cloud support). + it('keeps a sixtieth of maxTokensPerMinute within any one second', async () => { + vi.useFakeTimers(); + create.mockImplementation((args) => + Promise.resolve(vectorsFor(args.input)), + ); + // 600 a minute is 10 a second; each text here counts 4. + const embedder = new Embedder( + { + ...MODEL, + model: 'embedding-tps', + maxConcurrentRequests: 3, + maxTokensPerMinute: 600, + }, + 'sk-test', + ); + const a = embedder.embedAll(['abcd']); + const b = embedder.embedAll(['efgh']); + const c = embedder.embedAll(['ijkl']); + await vi.advanceTimersByTimeAsync(1); expect(create).toHaveBeenCalledTimes(2); await expect(a).resolves.toEqual([[1, 2, 3]]); await expect(b).resolves.toEqual([[1, 2, 3]]); - await vi.advanceTimersByTimeAsync(59_000); + await vi.advanceTimersByTimeAsync(900); expect(create).toHaveBeenCalledTimes(2); - await vi.advanceTimersByTimeAsync(2_000); + await vi.advanceTimersByTimeAsync(200); expect(create).toHaveBeenCalledTimes(3); await expect(c).resolves.toEqual([[1, 2, 3]]); }); + it('sizes each request to a second of maxTokensPerMinute', async () => { + vi.useFakeTimers(); + create.mockImplementation((args) => + Promise.resolve(vectorsFor(args.input)), + ); + const embedder = new Embedder( + { ...MODEL, model: 'embedding-tps-batch', maxTokensPerMinute: 600 }, + 'sk-test', + ); + // Four texts of 4 tokens: two fit a second's 10, the rest follow. + const all = embedder.embedAll(['abcd', 'efgh', 'ijkl', 'mnop']); + await vi.advanceTimersByTimeAsync(1); + expect(create).toHaveBeenCalledTimes(1); + expect(create.mock.calls[0]?.[0].input).toEqual(['abcd', 'efgh']); + await vi.advanceTimersByTimeAsync(1_100); + expect(create).toHaveBeenCalledTimes(2); + expect(create.mock.calls[1]?.[0].input).toEqual(['ijkl', 'mnop']); + await expect(all).resolves.toEqual([ + [1, 2, 3], + [1, 2, 3], + [1, 2, 3], + [1, 2, 3], + ]); + }); + it('holds the batch that would cross maxTokensPerMinute, and sends one alone that never could fit', async () => { vi.useFakeTimers(); create.mockImplementation((args) => diff --git a/services/platform/backend/core/knowledge/embedding.ts b/services/platform/backend/core/knowledge/embedding.ts index a9a86a6910..db8e63985b 100644 --- a/services/platform/backend/core/knowledge/embedding.ts +++ b/services/platform/backend/core/knowledge/embedding.ts @@ -76,6 +76,56 @@ const RATE_LIMIT_MAX_PAUSE_MS = 60_000; /** The window `maxTokensPerMinute` and `maxRequestsPerMinute` count in. */ const PACE_WINDOW_MS = 60_000; +/** A provider that states a per-minute figure enforces it per second as + * well — the figure divided by sixty (Alibaba Cloud support, 2026-10-02): + * a minute's worth sent in one second is refused although the minute is + * nearly empty. So each limit is kept over a second too. */ +const PACE_SECOND_MS = 1_000; +const SECONDS_PER_WINDOW = PACE_WINDOW_MS / PACE_SECOND_MS; + +/** The most estimated tokens one request may carry under a per-minute + * limit: a second's share of it, so no single request can be the burst + * the per-second rule refuses. Undefined without the limit. */ +function tokensPerRequestUnder( + limits: Pick, +): number | undefined { + return limits.maxTokensPerMinute === undefined + ? undefined + : Math.floor(limits.maxTokensPerMinute / SECONDS_PER_WINDOW); +} + +/** + * Texts in request-sized batches: at most `cap` texts each, and — under a + * per-minute token limit — at most a second's share of estimated tokens + * each, a text that alone exceeds it going by itself. + */ +function splitBatches( + texts: readonly string[], + cap: number, + tokenBudget: number | undefined, +): string[][] { + const batches: string[][] = []; + let batch: string[] = []; + let batchTokens = 0; + for (const text of texts) { + const tokens = + tokenBudget === undefined ? 0 : estimateEmbeddingTokens([text]); + const full = + batch.length >= cap || + (tokenBudget !== undefined && + batch.length > 0 && + batchTokens + tokens > tokenBudget); + if (full) { + batches.push(batch); + batch = []; + batchTokens = 0; + } + batch.push(text); + batchTokens += tokens; + } + if (batch.length > 0) batches.push(batch); + return batches; +} /** The longest pause a busy server may ask for (`Retry-After`) that a request * waits out while holding its slot. A server that asks for more is left @@ -280,42 +330,37 @@ function forgetAgedSends(pace: LanePace, now: number): void { } /** - * How long a batch of `tokens` has to wait before the lane admits it: the - * rest of a rate-limit pause, then until enough of the last minute's - * requests have aged out for the request count and the token count to fit - * under the limits. A single request larger than the token limit goes when - * the minute is empty — it could never fit otherwise, and the provider is - * the one to refuse it. Zero when it may go now. + * How long a request of `tokens` has to wait for the requests sent within + * `windowMs` to make room for it under `requests` and `tokens` limits: + * until the oldest of them has aged out, then the next, until the counts + * fit. A request that could never fit — larger than the token limit by + * itself — goes once the window is empty, and the provider is the one to + * refuse it. Zero when it may go now. */ -function paceWaitMs( - pace: LanePace, +function windowWaitMs( + sent: readonly { at: number; tokens: number }[], + windowMs: number, tokens: number, - limits: Pick, + limits: { readonly tokens?: number; readonly requests?: number }, now: number, ): number { - forgetAgedSends(pace, now); - let wait = Math.max(0, pace.pausedUntil - now); - const oldest = pace.sent[0]; - if ( - limits.maxRequestsPerMinute !== undefined && - oldest !== undefined && - pace.sent.length >= limits.maxRequestsPerMinute - ) { - wait = Math.max(wait, oldest.at + PACE_WINDOW_MS - now); + const inWindow = sent.filter((entry) => entry.at > now - windowMs); + const oldest = inWindow[0]; + if (oldest === undefined) return 0; + let wait = 0; + if (limits.requests !== undefined && inWindow.length >= limits.requests) { + wait = oldest.at + windowMs - now; } - if (limits.maxTokensPerMinute !== undefined && oldest !== undefined) { + if (limits.tokens !== undefined) { let used = 0; - for (const entry of pace.sent) used += entry.tokens; + for (const entry of inWindow) used += entry.tokens; let freedAt = now; let index = 0; - while ( - used + tokens > limits.maxTokensPerMinute && - index < pace.sent.length - ) { - const entry = pace.sent[index]; + while (used + tokens > limits.tokens && index < inWindow.length) { + const entry = inWindow[index]; if (entry === undefined) break; used -= entry.tokens; - freedAt = entry.at + PACE_WINDOW_MS; + freedAt = entry.at + windowMs; index += 1; } if (index > 0) wait = Math.max(wait, freedAt - now); @@ -323,6 +368,54 @@ function paceWaitMs( return wait; } +/** + * How long a batch of `tokens` has to wait before the lane admits it: the + * rest of a rate-limit pause, then room under the per-minute limits, then + * room under their per-second share. Zero when it may go now. + */ +function paceWaitMs( + pace: LanePace, + tokens: number, + limits: Pick, + now: number, +): number { + forgetAgedSends(pace, now); + let wait = Math.max(0, pace.pausedUntil - now); + const { maxTokensPerMinute, maxRequestsPerMinute } = limits; + if (maxTokensPerMinute === undefined && maxRequestsPerMinute === undefined) { + return wait; + } + wait = Math.max( + wait, + windowWaitMs( + pace.sent, + PACE_WINDOW_MS, + tokens, + { tokens: maxTokensPerMinute, requests: maxRequestsPerMinute }, + now, + ), + ); + return Math.max( + wait, + windowWaitMs( + pace.sent, + PACE_SECOND_MS, + tokens, + { + tokens: tokensPerRequestUnder(limits), + requests: + maxRequestsPerMinute === undefined + ? undefined + : Math.max( + 1, + Math.floor(maxRequestsPerMinute / SECONDS_PER_WINDOW), + ), + }, + now, + ), + ); +} + /** Drop a lane's pace once nothing in it matters any more. */ function forgetIdlePace(key: string, now: number): void { const pace = lanePaces.get(key); @@ -526,11 +619,11 @@ export class Embedder implements QueryEmbedder { ): Promise { options.signal?.throwIfAborted(); if (texts.length === 0) return []; - const batches: string[][] = []; - const cap = laneBatchCap(this.lane); - for (let i = 0; i < texts.length; i += cap) { - batches.push(texts.slice(i, i + cap)); - } + const batches = splitBatches( + texts, + laneBatchCap(this.lane), + tokensPerRequestUnder(this.model), + ); const stop = new AbortController(); const signal = options.signal === undefined