Skip to content

Releases

BFE v1.9.0

Choose a tag to compare

@mileszhang2016 mileszhang2016 released this 14 Nov 06:57
cb99da2

[v1.9.0] - 2026-11-12

Added

  • Add Server.ConditionEngineMode (LegacyFirst default / ExprCompatible / ExprOnly): the expr condition engine with three modes — LegacyFirst keeps the generated parser as baseline with expr fallback, ExprCompatible allows mixing legacy primitives with expr syntax, ExprOnly is pure expressions; an illegal mode or illegal condition fails fast at load time
  • Add AIConf.PriceMissAction three-state control for a missing (model, mode) price entry (issues #1408/#1479): fallback_chat (default, the previous behaviour), bill_zero (bill at 0 and count PriceMissZeroBilled), and reject (refuse before forwarding with 503 + error.code=PRICE_NOT_CONFIGURED, no upstream call, no billing, count PriceRejected; a missing ModelTable as a whole rejects the same way). Price-miss signals come in four layers: a structured throttled PRICE_MISS log, the counters PriceMissZeroBilled / PriceFallbackUsed / PriceRejected / PriceFallbackSubItemMiss, the access-log fields ai_price_miss (763, now also written on non-2xx reject rows) and ai_price_warn (766), and ready-made reconciliation queries
  • Add a configurable key-penalty TTL (issue #1448): the AI upstream key penalty (circuit breaker, issue #1439) duration is configurable instead of hard-coded, so a 429 punishment window can be tuned per deployment
  • Add reasoning-content normalization (2026-11-03): normalize reasoning_content / thinking-block variants across providers so downstream clients see a stable shape; the gateway skips rewriting when the request body exceeds Server.AccessibleBodySize and counts ReasoningSkip instead of touching a truncated body
  • Add AIConf.EnsureReasoningContent ([]string, default empty = disabled): the model access protocols for which the gateway fills an empty reasoning_content on the assistant messages that sit after the last user message. Some thinking-mode upstreams require that field to be echoed back yet have turns that produce no reasoning text, so a client mirroring the upstream response gets a 400 on the next turn, and the first request after a route switch always does (the assistant turn came from the previous backend). openai adds "reasoning_content": ""; anthropic prepends an empty thinking block. Only openai and anthropic are accepted — gemini has no such field in its contents/parts body, so it is rejected at load time rather than silently doing nothing; each entry must also be declared by the cluster's ModelProtocols. The rewrite is in place (sjson): field order and every other byte are preserved, existing non-empty values are never touched, and any parse/structure failure (including a body that is not valid JSON, or one larger than Server.AccessibleBodySize) passes the request through unchanged. New counters ReasoningPatched / ReasoningSkip / ReasoningFail / ReasoningStill400 — the last one is the exit signal: it counts requests that were patched and still got a 400, i.e. the upstream changed the contract and the switch must be cleared
  • Add Server.AIUpstreamAcceptEncoding (auto/identity/off, default auto): how Accept-Encoding is rewritten on an AI upstream request, so content negotiation stays inside the coding set the gateway can decode (gzip, deflate). auto keeps only the decodable codings of the client's list (q values preserved, an empty intersection is left untouched, identity;q=0 is honoured), identity strips compression for diagnostics, off keeps the previous behaviour. The rewrite only touches the outbound header: the inbound request, the access log, mod_ai_cache and mod_compress still see the client value (issue #1468)
  • Add bfe_util.NewContentDecoder / CanDecodeContentEncoding / SupportedContentEncodings, a streaming Content-Encoding decoder covering gzip/x-gzip and deflate (zlib header sniffed, raw DEFLATE accepted). DecodeContentEncoding now delegates to it, so the non-streaming parse-only copy also understands deflate (issue #1468)
  • Add the ResStreamCompressed / ResStreamDecoded / ResStreamDecodeSkipped / ResStreamRawOnly mod_body_process counters: how many responses carried a Content-Encoding, how many got the decompress-for-parsing tap, how many could not be decoded and how many degraded mid-stream. The last two mean "this request is billed by estimation", i.e. the only signal that an upstream ignored the narrowed Accept-Encoding (issue #1468)

Changed

  • Downgrade the normative client-close semantics of the "non-streaming boundary" clause 3 (issue #1474, product ruling 2026-11-12): when a non-streaming 200 response body is truncated mid-transfer, the connection now closes gracefully with FIN (consistent with the general proxy path and mainstream reverse proxies such as nginx), and the gateway is no longer required to abort the connection / send RST; truncation detectability relies on the response framing (a short read on a fixed-length response or a missing terminating chunk on a chunked response is detected by a conformant HTTP stack per RFC 9112 §7.1), and for close-delimited shapes (Content-Length stripped by transport-level gzip decompression, HTTP/1.0 clients) a clean EOF is indistinguishable from a complete response — an accepted residual limitation. The previously implemented abortive-close fix (closeDirectly + RST) has been reverted; the system-test acceptance criterion SC3201-TC035 A-06 is relaxed accordingly, while the err_code=BK_READ_RESP_BODY and billing-attribution criteria are unchanged
  • Finalize the non-2xx usage counter semantics as a dual-counter scheme (issues #1409/#1480/#1493, driven by the QA re-check SC2201-TC005): suppressed estimate residue counts Non2xxEstimateDropped, while a non-2xx response body that carries a real usage object is reported as an observation with ai_usage_source=parsed (never billed) and counted by Non2xxRealUsageKept — the non-streaming parse gate is opened from this release (the previous StatusOK gate made that branch unreachable), and the billing completion gate and estimate seeding stay 2xx-only. The issue #1480 renaming to Non2xxUsageReported and the failed-source reporting were rejected and never shipped
  • An AI upstream request whose client Accept-Encoding contains codings the gateway cannot decode no longer receives them (Server.AIUpstreamAcceptEncoding = auto, the default): the upstream is offered gzip/deflate only, so a client that asked for zstd may now receive gzip instead (still inside its own Accept-Encoding, <1% size difference). Set Server.AIUpstreamAcceptEncoding = off to keep the previous negotiation (issue #1468)

Fixed

  • Fix a data race on the forwarded request body size that -race reports intermittently in bfe_server (e.g. TestForwardExpectContinue) and therefore reddens CI: bfe_http.(*Request).write stores req.State.BodySize on the transport's writeLoop goroutine after the body is written, while clusterInvoke reads it from the serving goroutine as soon as the response header arrives. The two have no happens-before edge — an upstream that answers before reading the body, or a client that sends its body slowly (Expect: 100-continue is the typical shape), lets the response land first — so the pair was undefined behaviour; the store and the load are now atomic.StoreUint32/atomic.LoadUint32. No behavioural change: when the response wins the race, req_body_len still reads 0, which is what the (previously undefined) plain read observed anyway. The race has been present since the initial commit and is unrelated to any recent feature work
  • Stop recording a fully delivered AI streaming response as a client write error when the client hangs up right after the protocol's terminal event (issue #1473): the cancelOnClientClose watcher closes the upstream body, the collateral read error was labelled CLIENT_WRITE and counted in ErrClientWrite, and its err_msg blamed the upstream (BodyProcessError: read tcp ...) — so 52% of production CLIENT_WRITE rows were normal hangs, real faults drowned in the noise, and the metric could not be alerted on. The AI send path now attributes the copy error in three states: an upstream drop stays BK_READ_RESP_BODY (issue #1474), a close observed after IsResponseCompleted() sets no err_code and no ErrClientWrite but the new access-log field ai_client_closed_after_complete (816) plus the ReqAiClientClosedAfterComplete counter, and everything else (abort before the terminal event, failed write) keeps CLIENT_WRITE with a direction-correct err_msg (client closed connection / client write failed). Also wire the last missing ai_stream_truncated (815) path: a clean EOF without the protocol's terminal event now marks truncation even when NormalizeUpstreamError is unconfigured (the injector is then the only observer), with the event parser authoritative over the byte-level markers so data:-only Anthropic-compatible streams are not misreported, and a cross-read overlap window so a marker split across reads is not missed. Requires bfe-access-pb v0.3.18
  • Stop reporting an affinity binding miss as a Redis failure in the AI upstream key session affinity (issue #1472): RedisClient.Get reports an absent key as redis.ErrNil, and redisGetBinding passed it on as a real error, so the first request of every session (and every request after the binding TTL expires or is dropped by a 429/401) logged aiKeyAffinity: redis get binding error[redigo: nil returned], counted ReqAiKeyAffinityRedisErr and returned early — leaving ReqAiKeyAffinityMiss (and ReqAiKeyAffinityPenaltySkip) at zero in production and the new binding unwritten until a successful forward, which also kept a session whose first request failed from ever binding. The miss is now normalized with redis_client.IsKeyNotFound at the read point (redisGetBinding, and redisGetBatchBinding for the batch namespace), so a plai...
Read more

BFE v1.8.9.1

Choose a tag to compare

@mileszhang2016 mileszhang2016 released this 27 Oct 12:34
d818fd5

Added

  • Add Server.AIUpstreamAcceptEncoding (auto/identity/off, default auto): how Accept-Encoding is rewritten on an AI upstream request, so content negotiation stays inside the coding set the gateway can decode (gzip, deflate). auto keeps only the decodable codings of the client's list (q values preserved, an empty intersection is left untouched, identity;q=0 is honoured), identity strips compression for diagnostics, off keeps the previous behaviour. The rewrite only touches the outbound header: the inbound request, the access log, mod_ai_cache and mod_compress still see the client value (issue #1468)
  • Add bfe_util.NewContentDecoder / CanDecodeContentEncoding / SupportedContentEncodings, a streaming Content-Encoding decoder covering gzip/x-gzip and deflate (zlib header sniffed, raw DEFLATE accepted). DecodeContentEncoding now delegates to it, so the non-streaming parse-only copy also understands deflate (issue #1468)
  • Add the ResStreamCompressed / ResStreamDecoded / ResStreamDecodeSkipped / ResStreamRawOnly mod_body_process counters: how many responses carried a Content-Encoding, how many got the decompress-for-parsing tap, how many could not be decoded and how many degraded mid-stream. The last two mean "this request is billed by estimation", i.e. the only signal that an upstream ignored the narrowed Accept-Encoding (issue #1468)

Changed

  • An AI upstream request whose client Accept-Encoding contains codings the gateway cannot decode no longer receives them (Server.AIUpstreamAcceptEncoding = auto, the default): the upstream is offered gzip/deflate only, so a client that asked for zstd may now receive gzip instead (still inside its own Accept-Encoding, <1% size difference). Set Server.AIUpstreamAcceptEncoding = off to keep the previous negotiation (issue #1468)

Fixed

  • Parse the usage of a compressed streaming (SSE) response instead of estimating it: mod_body_process bypassed any Content-Encoding body to a byte-wise pass-through, so cache_read_tokens stayed 0, prompt_tokens fell back to the request-body estimate and completion_tokens to the compressed-bytes estimate, and the whole prompt was billed at the input price — measured on the field at a 96% cache-hit rate that overcharges by roughly 46x and writes ai_usage_source=estimated. Compressed SSE now goes through CompressedStreamDecoder, which tees the source into a decompressor used only for parsing while the original compressed bytes are forwarded verbatim together with the Content-Encoding header; a decompression failure or an unsupported coding degrades to a byte-exact pass-through plus the estimate, visibly (issue #1468)
  • Report a skipped stream_options.include_usage injection when the request body exceeds Server.AccessibleBodySize: the injection used to fail silently, which raised the probability of an upstream returning no usage at all (issue #1468)

BFE v1.8.8.7

Choose a tag to compare

@mileszhang2016 mileszhang2016 released this 27 Oct 12:52

Added

  • Add Server.AIUpstreamAcceptEncoding (auto/identity/off, default auto): how Accept-Encoding is rewritten on an AI upstream request, so content negotiation stays inside the coding set the gateway can decode (gzip, deflate). auto keeps only the decodable codings of the client's list (q values preserved, an empty intersection is left untouched, identity;q=0 is honoured), identity strips compression for diagnostics, off keeps the previous behaviour. The rewrite only touches the outbound header: the inbound request, the access log, mod_ai_cache and mod_compress still see the client value (issue #1468)
  • Add bfe_util.NewContentDecoder / CanDecodeContentEncoding / SupportedContentEncodings, a streaming Content-Encoding decoder covering gzip/x-gzip and deflate (zlib header sniffed, raw DEFLATE accepted). DecodeContentEncoding now delegates to it, so the non-streaming parse-only copy also understands deflate (issue #1468)
  • Add the ResStreamCompressed / ResStreamDecoded / ResStreamDecodeSkipped / ResStreamRawOnly mod_body_process counters: how many responses carried a Content-Encoding, how many got the decompress-for-parsing tap, how many could not be decoded and how many degraded mid-stream. The last two mean "this request is billed by estimation", i.e. the only signal that an upstream ignored the narrowed Accept-Encoding (issue #1468)

Changed

  • An AI upstream request whose client Accept-Encoding contains codings the gateway cannot decode no longer receives them (Server.AIUpstreamAcceptEncoding = auto, the default): the upstream is offered gzip/deflate only, so a client that asked for zstd may now receive gzip instead (still inside its own Accept-Encoding, <1% size difference). Set Server.AIUpstreamAcceptEncoding = off to keep the previous negotiation (issue #1468)

Fixed

  • Parse the usage of a compressed streaming (SSE) response instead of estimating it: mod_body_process bypassed any Content-Encoding body to a byte-wise pass-through, so cache_read_tokens stayed 0, prompt_tokens fell back to the request-body estimate and completion_tokens to the compressed-bytes estimate, and the whole prompt was billed at the input price — measured on the field at a 96% cache-hit rate that overcharges by roughly 46x and writes ai_usage_source=estimated. Compressed SSE now goes through CompressedStreamDecoder, which tees the source into a decompressor used only for parsing while the original compressed bytes are forwarded verbatim together with the Content-Encoding header; a decompression failure or an unsupported coding degrades to a byte-exact pass-through plus the estimate, visibly (issue #1468)
  • Report a skipped stream_options.include_usage injection when the request body exceeds Server.AccessibleBodySize: the injection used to fail silently, which raised the probability of an upstream returning no usage at all (issue #1468)

BFE v1.8.9

Choose a tag to compare

@mileszhang2016 mileszhang2016 released this 27 Oct 12:22
5adefa9

Added

  • Add ai_zero_cost_reason access-log marker (requires bfe-access-pb >= v0.3.16): why a 2xx request holding an RMB quota plan was charged 0, together with the BillingZeroCost and AbortBillingSkipped module counters (issue #1414). Requests that never became a model call (batch/files management endpoints) and AI cache hits are excluded from BillingZeroCost, since their zero cost is by design rather than an anomaly
  • Support condition primitive time_weekday_in(weekday_list, zone): judge whether the weekday of the current time is in the given list (0=Sunday, 1=Monday, …, 6=Saturday, the same convention as the weekdays field of the cluster pricing tiers). zone is a single military time zone letter (see bfe_util.TimeZoneMap, e.g. H for UTC+8) and defaults to Z (UTC) when omitted — the weekday depends on the time zone, so deployments in UTC+8 should pass "H". weekday_list is a |-separated enumeration (no range notation), validated at config load time; the current time is read from the system clock, or from the X-Bfe-Debug-Time header when present
  • Add mod_ai_batch, an OpenAI Batch API (/v1/files, /v1/batches) passthrough module: dedicated file/batch request modes so batch traffic stops falling into the default chat billing mode, operation classification, upload line/byte counting with large-file streaming (no retry buffering), batch-level key affinity bindings (SETNX claim-first, 404 delete plus penalty failover, create chains bound via input_file_id parsed from the buffered body before key selection), post-paid quota (reserve at create with balance pre-check, settle per-model usage at batch prices on result-file download, release on cancel/terminal status, with idempotent BATCH_RESERVE / BATCH_SETTLED Redis markers), batch rate-limit dimensions (batch_limits: create RPM, active batches, file bytes/lines; batch-only policies are now valid) and access-log batch fields (bfe-access-pb >= v0.3.13, fields 901-907) with ownership checks on file download (404 / allow_log policy). Requires the new mod_ai_batch module and its mod_ai_batch.data config
  • Add mod_ai_cache, an exact-match Redis AI cache: rule matching at HandleFoundProduct, before route rule evaluation, so a cache hit short-circuits routing; skip header x-bfe-skip-ai-cache, question extraction (last/all questions), tenant-isolated keys, template-based hit responses (JSON and SSE with [DONE]), response capture with a complete flag (aborted responses are never cached), size limits and fail-open Redis access; cache hits skip RMB deduction and log ai_cache_status / ai_cache_key (bfe-access-pb >= v0.3.7, fields 789-790)
  • Extend mod_ai_cache with a semantic cache phase: OpenAI-compatible embeddings client plus Chroma vector lookup (cosine space, tenant- and TTL-enforced queries), hybrid exact-first / semantic-fallback with dual write-back, per-rule enableSemanticCache (hot-reloadable, backward compatible with phase-1 rule files); a provider init failure degrades semantic caching globally with a WARN and never fails startup. Adds the hit_semantic status, ai_cache_semantic / ai_cache_similarity log fields (bfe-access-pb >= v0.3.10, fields 791-792) and SEMANTIC_HIT / EMBEDDING_ERR / VECTOR_ERR / SEMANTIC_SKIPPED counters; compatible with the Chroma 0.6.x UUID-only collections API
  • Add mod_ai_intent, a semantic-routing intent module: lazy intent resolve triggered by condition evaluation (zero overhead for rules without intent conditions), System One decision-service client (Laya/Kev/Jev interchangeable via config) with timeout and circuit breaker, hot-reloadable intent_questions.data (question set with choice/score and per-question/global MinConfidence), explicit X-AI-Intent header precedence, in-process LRU+TTL cache, and the new req_ai_intent_in(String, String [, Float]) condition primitive; the consumed intent is logged in ai_intent_* access-log fields (bfe-access-pb >= v0.3.9, fields 803-809) from resolved-intent context only, never triggering a resolve. An empty question set disables intent classification
  • Add mod_ai_context, an AI context compression/pruning module (phase 1, OpenAI chat format, fail-open): a lossless trim layer (tool-result truncation, latest-N inline images, thinking-block removal) plus a rule-based rewrite layer with tombstone preservation and a fidelity gate, registered at HandleAfterAITargetModel so the token budget is computed against the resolved target model and cache hits never pay for compression; adds access-log fields 793-796 (bfe-access-pb >= v0.3.11)
  • Add mod_traffic_mirror, a traffic mirroring module for AI gateway shadow traffic: matched AI requests (method/path/headers/body, with model rewrite, path rewrite and header sanitize rules) are snapshotted at HandleForward and mirrored asynchronously to a shadow cluster via the new side-effect-free BalanceGslb.PickBackend(); the async side drains SSE responses to [DONE] while parsing usage/error/finish_reason and reports via a module-private Prometheus registry — the main request is never blocked, retried or double-mirrored on AI fallback (once-marker). Adds mirror_hit / mirror_cluster access-log fields (bfe-access-pb >= v0.3.8, fields 842-843); mirrored traffic is billing-isolated
  • Add upstream error normalization behind AIConf.NormalizeUpstreamError (Enabled / StreamEnabled / UnrecognizedAction / MaxBodyBytes / RedactSecrets): per-protocol ErrorParser / StreamErrorParser adapters (openai/anthropic/gemini) map upstream errors into a unified UPSTREAM_* catalog; the interception point normalizes upstream failures after the fallback loop, with an SSE error-event filter, truncation detection and credential redaction covering raw/base64/URL/JSON-escaped forms; gateway-generated responses are skipped via the X-Bfe-Gw-Error marker. Adds ai_upstream_status / ai_upstream_err_code / ai_err_normalized / ai_err_normalize_miss / ai_stream_error_rewritten / ai_stream_truncated access-log fields (bfe-access-pb >= v0.3.12, fields 810-815); see ai_error_codes.md §2.5
  • Add field-level enc$v1$ encryption at rest for distributed config files: sensitive fields in token_rule.data (Tokens outer keys) and cluster_conf.data (AIConf.Keys[].Key) may carry enc$v1$ AES-256-GCM ciphertext produced by the control plane at export, decrypted in memory at load time via a keyring configured in the new bfe.conf [Security] section (multiple keyIDs coexist, fail-closed parsing, error messages never carry ciphertext); hot reload re-reads the keyring on every data-file load, an unreadable or wrong keyring fails the reload and keeps the old config (fail-fast on first startup); plaintext without the marker passes through, keeping canary/rollback compatible
  • Make the "usage unrecognized and not estimatable" billing bypass observable (issue #1410): the request-finish guard keeps its yardstick behavior (billing fields zeroed, no RMB deduction) but now increments the UsageUnrecognized module counter (exported via monitorHandlers, alertable) and logs a warn with cluster/key_id/model and the response_completed/allow_estimate sub-criteria. The access log gains ai_usage_source (bfe-access-pb >= v0.3.15, field 764) distinguishing parsed (final usage from the upstream response) / estimated (approved EstimateToken fallback) / unrecognized (billing skipped), orthogonal to the non-2xx suppression, so billing bypasses become directly queryable instead of requiring out-of-band reconciliation

Changed

  • X-Bfe-Log-Id and the access-log logid are now a decimal string denoting a value in [1, 2^63-1] instead of a 32-char hex string, so the id converts losslessly into the uint64 logid field of the access log; the 63-bit bound keeps it inside the signed BIGINT of the report databases. Any consumer that parses or joins on the 32-hex form (X-Bfe-Log-Id, the text access log log_id, %bfe_log_id, WAF/mirroring logs) must be updated (#1417)
  • Sessions/requests whose log id cannot be converted (mod_logid not loaded, malformed value, or a legacy 32-char hex header during a rolling upgrade) now carry a locally regenerated non-zero id and are counted by the new LogidRegenerated / SessionIdRegenerated module counters, instead of silently writing 0 (#1417)
  • AI key session affinity now uses a server-owned Redis connection configured via the new [AIKeyAffinity] section in bfe.conf, instead of implicitly borrowing the mod_ai_rate_limit module's Redis. Config migration required: deployments that enabled affinity (AIConf.KeyPolicy.SessionAffinity=true) must add the [AIKeyAffinity] section (with Disabled=false and the Redis ServiceConf) before upgrading; otherwise affinity silently turns off after the upgrade (fail-open, no error, bindings lost)
  • Server.EstimateToken now applies only when the upstream returned no usage at all, decided by the presence of the usage object: a response whose usage object reports all zeros is billed at 0 instead of being estimated, and is reported as ai_usage_source=parsed. Only that edge case changes amount (downward); requests whose response carries no usage keep the previous estimate behaviour (issue #1414)
  • ai_cost_value is now written for every observed 2xx row, 0 included, so "charged nothing" is distinguishable from "field absent" (non-2xx / never billed). Reconciliation that tests ai_cost_value IS NULL for "no cost" should switch to ai_cost_value = 0 / IS NULL (issue #1414)
  • mod_ai_token_auth.UsageUnrecognized no longer counts client aborts — they are counted by the new AbortBillingSkipped counter, so the two causes (upstream/parsing problem vs client-side disconnect) stay separable; existing thresholds on UsageUnrecognized need to be realigned. ai_usage_source gained the fourth value aborted (no new protobuf field: the ...
Read more

v1.8.8.6

Choose a tag to compare

@mileszhang2016 mileszhang2016 released this 22 Oct 09:44

What's Changed

Fixed

  • Make the outbound credential headers mutually exclusive so a client-supplied credential can no longer override the gateway-injected upstream key: once BFE takes ownership of the upstream credential, the outbound request keeps only the header the request's model_protocol adapter injects and drops Authorization / x-api-key / x-goog-api-key, which used to be forwarded as-is — an upstream that prefers a residual header (kimi: x-api-key wins over Authorization; bailian: Authorization wins and never falls back) authenticated with the client token, answered 401, and that 401 was charged to the selected key: two requests from one client marked both kimi keys dead for 3600s, the cluster circuit-broke and traffic was silently degraded to bailian/deepseek-v4.1-flash while the client still saw 200 (issue #1447)

Full Changelog: https://github.com/bfenetworks/bfe/blob/v1.8.8.6/CHANGELOG.md

v1.8.8.5

Choose a tag to compare

@mileszhang2016 mileszhang2016 released this 21 Oct 09:56

What's Changed

Fixed

  • Return a decidable synthetic 429 when no AI key can be selected for the target cluster (all keys penalized / Weight=0 / dead), instead of (res=nil, err=nil): a configured fallback cluster is actually tried, and without one the client gets a retryable 429 instead of an opaque empty-body 500. shouldTriggerFallback also treats (nil, nil) as fallback-eligible as a hard invariant (issue #1440)
  • Exclude Weight=0 keys from the session-affinity penalty filter and replace the "fallback to the original list" branch with a circuit breaker: when every usable key is penalized the filter returns no candidates — key selection fails, the synthetic 429 triggers cluster fallback, and the cluster makes zero upstream interaction until the penalty TTL expires (new 429s extend the window) (issue #1439)
  • Emit the unified error contract on gateway-synthesized AI failures: the key-exhaustion 429 now carries error.code = NO_AVAILABLE_KEY (429, rate_limit_error), error.details.retry_after_seconds and a standard Retry-After header, and sets err_code = NO_AVAILABLE_KEY for access-log attribution; gateway-side failures (findProduct failure, no cluster, backend connect/transport errors) return BACKEND_UNAVAILABLE (502) with the unified body instead of a bare empty-body 500 (issue #1441)

Full Changelog: https://github.com/bfenetworks/bfe/blob/v1.8.8.5/CHANGELOG.md

BFE v1.8.9-preview.1

BFE v1.8.9-preview.1 Pre-release
Pre-release

Choose a tag to compare

@mileszhang2016 mileszhang2016 released this 20 Oct 06:53
4b340a7

Preview build for testing only — not a production release.

Branch: v1.8.9-dev · Version: 1.8.9-preview.1

Added

  • Add ai_zero_cost_reason access-log marker (requires bfe-access-pb >= v0.3.16): why a 2xx request holding an RMB quota plan was charged 0, together with the BillingZeroCost and AbortBillingSkipped module counters (issue #1414). Requests that never became a model call (batch/files management endpoints) and AI cache hits are excluded from BillingZeroCost, since their zero cost is by design rather than an anomaly
  • Support condition primitive time_weekday_in(weekday_list, zone): judge whether the weekday of the current time is in the given list (0=Sunday, 1=Monday, …, 6=Saturday, the same convention as the weekdays field of the cluster pricing tiers). zone is a single military time zone letter (see bfe_util.TimeZoneMap, e.g. H for UTC+8) and defaults to Z (UTC) when omitted — the weekday depends on the time zone, so deployments in UTC+8 should pass "H". weekday_list is a |-separated enumeration (no range notation), validated at config load time; the current time is read from the system clock, or from the X-Bfe-Debug-Time header when present

Changed

  • X-Bfe-Log-Id and the access-log logid are now a decimal string denoting a value in [1, 2^63-1] instead of a 32-char hex string, so the id converts losslessly into the uint64 logid field of the access log; the 63-bit bound keeps it inside the signed BIGINT of the report databases. Any consumer that parses or joins on the 32-hex form (X-Bfe-Log-Id, the text access log log_id, %bfe_log_id, WAF/mirroring logs) must be updated (#1417)
  • Sessions/requests whose log id cannot be converted (mod_logid not loaded, malformed value, or a legacy 32-char hex header during a rolling upgrade) now carry a locally regenerated non-zero id and are counted by the new LogidRegenerated / SessionIdRegenerated module counters, instead of silently writing 0 (#1417)
  • AI key session affinity now uses a server-owned Redis connection configured via the new [AIKeyAffinity] section in bfe.conf, instead of implicitly borrowing the mod_ai_rate_limit module's Redis. Config migration required: deployments that enabled affinity (AIConf.KeyPolicy.SessionAffinity=true) must add the [AIKeyAffinity] section (with Disabled=false and the Redis ServiceConf) before upgrading; otherwise affinity silently turns off after the upgrade (fail-open, no error, bindings lost)
  • Server.EstimateToken now applies only when the upstream returned no usage at all, decided by the presence of the usage object: a response whose usage object reports all zeros is billed at 0 instead of being estimated, and is reported as ai_usage_source=parsed. Only that edge case changes amount (downward); requests whose response carries no usage keep the previous estimate behaviour (issue #1414)
  • ai_cost_value is now written for every observed 2xx row, 0 included, so "charged nothing" is distinguishable from "field absent" (non-2xx / never billed). Reconciliation that tests ai_cost_value IS NULL for "no cost" should switch to ai_cost_value = 0 / IS NULL (issue #1414)
  • mod_ai_token_auth.UsageUnrecognized no longer counts client aborts — they are counted by the new AbortBillingSkipped counter, so the two causes (upstream/parsing problem vs client-side disconnect) stay separable; existing thresholds on UsageUnrecognized need to be realigned. ai_usage_source gained the fourth value aborted (no new protobuf field: the value is added to the existing ai_usage_source) (issue #1414)

Fixed

  • Populate the access-log logid with the request's real log id: strconv.ParseUint(req.LogId, 10, 64) parsed the hex log id as decimal and discarded the error, so logid was written as 0 for every request. Together with the report table's second-granularity dedup key and its full-row ON DUPLICATE KEY UPDATE, one API key and model firing n concurrent requests inside one second kept only 1 row — the measured loss was exactly (n-1)/n, 13.5% of a production hour. The session id column (session_id, and the session log's logid) had the same defect (#1417)
  • Make usage recognition presence-based instead of value-based: an upstream that explicitly reports all-zero usage is no longer misclassified as "usage unrecognized" nor over-billed by EstimateToken (issue #1414)
  • Report every zero-cost 2xx request that holds an RMB plan through the new BillingZeroCost counter and ai_zero_cost_reason marker, covering unrecognized usage, client aborts, batch releases, price-table gaps and pricing configuration loss at deduction time (issue #1414)
  • Count failed quota deductions (DeductFailed) instead of leaving them as a log line only (issue #1414)
  • Fix the token-triple consistency check (AiUsageInconsistent) returning early on ai_total_tokens == 0, which disabled it for exactly the input > 0 while total == 0 rows it exists to catch (issue #1414)
  • Batch settlement now marks price misses (ai_price_miss), warns when the model table is missing and records a release without billing instead of staying silent (issue #1414)

BFE v1.8.8.4

Choose a tag to compare

@mileszhang2016 mileszhang2016 released this 19 Oct 02:44

Fixed

  • Bill streaming (SSE) responses that end at a clean HTTP EOF without the protocol termination event ([DONE] / message_stop) and without any usage, instead of silently deducting 0: ServeHTTPForAI now marks the response completed once the body has been fully delivered (200 SSE, copyResponse success). A nil copy error is the transport-level completion fact — a chunked response only EOFs at its terminating chunk and a fixed-length response only after its Content-Length bytes — so client aborts and mid-stream upstream drops still surface as copy errors and never satisfy the billing gate (issue #1415)
  • Keep the client connection reusable after internally constructed AI responses (issue #1416): the no-route 404 (AI route not found), the findProduct 500, the protocol-mismatch rejection, the HandleAfterAITargetModel BfeHandlerResponse rejection and the no-cluster 500 no longer set the server-level closeAfterReply. Those responses are self-delimited (explicit Content-Length) and chunk_writer drains the request body before writing headers, so BFE was closing the connection without advertising Connection: close and the next request on a pooled keep-alive connection failed with EOF; module-contract BfeHandlerFinish / BfeHandlerClose paths and the protocol-level close shapes (HTTP/1.0, Connection: close, undrainable bodies) still close with advertisement

BFEv1.8.8.3

Choose a tag to compare

@mileszhang2016 mileszhang2016 released this 11 Oct 13:11

Fixed

  • Fix token usage collection for non-streaming gzip responses (Content-Encoding: gzip with Transfer-Encoding: chunked): the compressed body is now decompressed on a parse-only copy (forwarding bytes untouched), the whole-body parse gate accepts chunked non-SSE JSON bodies, and the content-type decoder tolerates media type parameters (e.g. application/json; charset=utf-8) while passing compressed bodies through untouched, so ai_output_tokens / ai_total_tokens / ai_cache_read_tokens and RMB billing reflect the real usage instead of 0 (issue #1406)
  • Fall back to the model's chat-mode price when the (model, mode) price entry is missing but a chat entry exists (product decision: an unpriced mode bills the same as chat), and mark such requests with the new ai_price_miss access-log field (bfe-access-pb >= v0.3.14, field 763) counted by PriceFallbackUsed, so under-priced rows stay visible in reconciliation (issue #1408)
  • Drop the EstimateToken residue (auth-time prompt seeding / response-byte completion guessing) from the shared TokenUsage and suppress the token fields in the access log for non-2xx responses (new usage disposition, UsageDispositionNone): a failed request no longer logs request-body/4 as ai_input_tokens while ai_total_tokens stays 0 (issue #1409)

Added

  • Make the "usage unrecognized and not estimatable" billing bypass observable (issue #1410): the request-finish guard keeps its yardstick behavior (billing fields zeroed, no RMB deduction) but now increments the UsageUnrecognized module counter (exported via monitorHandlers, alertable) and logs a warn with cluster/key_id/model and the response_completed/allow_estimate sub-criteria; the client-abort zero-deduction branch is counted too (counter-only). The access log gains ai_usage_source (bfe-access-pb >= v0.3.15, field 764): parsed (final usage from the upstream response, including zero-output final events) / estimated (approved EstimateToken fallback) / unrecognized (billing skipped, the reported token fields are auth-time seeding residue), orthogonal to the non-2xx suppression, so billing bypasses become directly queryable (ai_usage_source='unrecognized') instead of requiring out-of-band reconciliation. SC03 TC-24 covers the three-way distinction end to end

BFEv1.8.8.2

Choose a tag to compare

@mileszhang2016 mileszhang2016 released this 09 Oct 15:24

BFE v1.8.8.2

Fixed (issue #1401):

  • parse the final usage embedded in the streaming finish chunk's choice
    (choices[N].usage, cache field cached_tokens) used by kimi-for-coding
    and other upstreams ignoring the injected stream_options.include_usage
  • default EstimateToken/InjectStreamUsage as program defaults so the
    fixes survive binary upgrades without new conf keys
  • clamp the negative completion-tokens sentinel at the access log
    boundary (no more negative output token counts)

Based on bfenetworks/bfe v1.8.8.