Repository navigation
Releases
Releases · bfenetworks/bfe
BFE v1.9.0
[v1.9.0] - 2026-11-12
Added
- Add
Server.ConditionEngineMode(LegacyFirstdefault /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.PriceMissActionthree-state control for a missing(model, mode)price entry (issues #1408/#1479):fallback_chat(default, the previous behaviour),bill_zero(bill at 0 and countPriceMissZeroBilled), andreject(refuse before forwarding with 503 +error.code=PRICE_NOT_CONFIGURED, no upstream call, no billing, countPriceRejected; a missingModelTableas a whole rejects the same way). Price-miss signals come in four layers: a structured throttledPRICE_MISSlog, the countersPriceMissZeroBilled/PriceFallbackUsed/PriceRejected/PriceFallbackSubItemMiss, the access-log fieldsai_price_miss(763, now also written on non-2xx reject rows) andai_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 exceedsServer.AccessibleBodySizeand countsReasoningSkipinstead of touching a truncated body - Add
AIConf.EnsureReasoningContent([]string, default empty = disabled): the model access protocols for which the gateway fills an emptyreasoning_contenton 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).openaiadds"reasoning_content": "";anthropicprepends an empty thinking block. Onlyopenaiandanthropicare accepted —geminihas no such field in itscontents/partsbody, so it is rejected at load time rather than silently doing nothing; each entry must also be declared by the cluster'sModelProtocols. 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 thanServer.AccessibleBodySize) passes the request through unchanged. New countersReasoningPatched/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, defaultauto): howAccept-Encodingis rewritten on an AI upstream request, so content negotiation stays inside the coding set the gateway can decode (gzip,deflate).autokeeps only the decodable codings of the client's list (q values preserved, an empty intersection is left untouched,identity;q=0is honoured),identitystrips compression for diagnostics,offkeeps the previous behaviour. The rewrite only touches the outbound header: the inbound request, the access log,mod_ai_cacheandmod_compressstill see the client value (issue #1468) - Add
bfe_util.NewContentDecoder/CanDecodeContentEncoding/SupportedContentEncodings, a streamingContent-Encodingdecoder coveringgzip/x-gzipanddeflate(zlib header sniffed, raw DEFLATE accepted).DecodeContentEncodingnow delegates to it, so the non-streaming parse-only copy also understandsdeflate(issue #1468) - Add the
ResStreamCompressed/ResStreamDecoded/ResStreamDecodeSkipped/ResStreamRawOnlymod_body_processcounters: how many responses carried aContent-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 narrowedAccept-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_BODYand 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 withai_usage_source=parsed(never billed) and counted byNon2xxRealUsageKept— the non-streaming parse gate is opened from this release (the previousStatusOKgate made that branch unreachable), and the billing completion gate and estimate seeding stay 2xx-only. The issue #1480 renaming toNon2xxUsageReportedand thefailed-source reporting were rejected and never shipped - An AI upstream request whose client
Accept-Encodingcontains codings the gateway cannot decode no longer receives them (Server.AIUpstreamAcceptEncoding = auto, the default): the upstream is offeredgzip/deflateonly, so a client that asked forzstdmay now receivegzipinstead (still inside its ownAccept-Encoding, <1% size difference). SetServer.AIUpstreamAcceptEncoding = offto keep the previous negotiation (issue #1468)
Fixed
- Fix a data race on the forwarded request body size that
-racereports intermittently inbfe_server(e.g.TestForwardExpectContinue) and therefore reddens CI:bfe_http.(*Request).writestoresreq.State.BodySizeon the transport'swriteLoopgoroutine after the body is written, whileclusterInvokereads 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-continueis the typical shape), lets the response land first — so the pair was undefined behaviour; the store and the load are nowatomic.StoreUint32/atomic.LoadUint32. No behavioural change: when the response wins the race,req_body_lenstill 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
cancelOnClientClosewatcher closes the upstream body, the collateral read error was labelledCLIENT_WRITEand counted inErrClientWrite, and itserr_msgblamed the upstream (BodyProcessError: read tcp ...) — so 52% of productionCLIENT_WRITErows 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 staysBK_READ_RESP_BODY(issue #1474), a close observed afterIsResponseCompleted()sets noerr_codeand noErrClientWritebut the new access-log fieldai_client_closed_after_complete(816) plus theReqAiClientClosedAfterCompletecounter, and everything else (abort before the terminal event, failed write) keepsCLIENT_WRITEwith a direction-correcterr_msg(client closed connection/client write failed). Also wire the last missingai_stream_truncated(815) path: a clean EOF without the protocol's terminal event now marks truncation even whenNormalizeUpstreamErroris unconfigured (the injector is then the only observer), with the event parser authoritative over the byte-level markers sodata:-only Anthropic-compatible streams are not misreported, and a cross-read overlap window so a marker split across reads is not missed. Requiresbfe-access-pbv0.3.18 - Stop reporting an affinity binding miss as a Redis failure in the AI upstream key session affinity (issue #1472):
RedisClient.Getreports an absent key asredis.ErrNil, andredisGetBindingpassed 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) loggedaiKeyAffinity: redis get binding error[redigo: nil returned], countedReqAiKeyAffinityRedisErrand returned early — leavingReqAiKeyAffinityMiss(andReqAiKeyAffinityPenaltySkip) 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 withredis_client.IsKeyNotFoundat the read point (redisGetBinding, andredisGetBatchBindingfor the batch namespace), so a plai...
BFE v1.8.9.1
Added
- Add
Server.AIUpstreamAcceptEncoding(auto/identity/off, defaultauto): howAccept-Encodingis rewritten on an AI upstream request, so content negotiation stays inside the coding set the gateway can decode (gzip,deflate).autokeeps only the decodable codings of the client's list (q values preserved, an empty intersection is left untouched,identity;q=0is honoured),identitystrips compression for diagnostics,offkeeps the previous behaviour. The rewrite only touches the outbound header: the inbound request, the access log,mod_ai_cacheandmod_compressstill see the client value (issue #1468) - Add
bfe_util.NewContentDecoder/CanDecodeContentEncoding/SupportedContentEncodings, a streamingContent-Encodingdecoder coveringgzip/x-gzipanddeflate(zlib header sniffed, raw DEFLATE accepted).DecodeContentEncodingnow delegates to it, so the non-streaming parse-only copy also understandsdeflate(issue #1468) - Add the
ResStreamCompressed/ResStreamDecoded/ResStreamDecodeSkipped/ResStreamRawOnlymod_body_processcounters: how many responses carried aContent-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 narrowedAccept-Encoding(issue #1468)
Changed
- An AI upstream request whose client
Accept-Encodingcontains codings the gateway cannot decode no longer receives them (Server.AIUpstreamAcceptEncoding = auto, the default): the upstream is offeredgzip/deflateonly, so a client that asked forzstdmay now receivegzipinstead (still inside its ownAccept-Encoding, <1% size difference). SetServer.AIUpstreamAcceptEncoding = offto keep the previous negotiation (issue #1468)
Fixed
- Parse the usage of a compressed streaming (SSE) response instead of estimating it:
mod_body_processbypassed anyContent-Encodingbody to a byte-wise pass-through, socache_read_tokensstayed 0,prompt_tokensfell back to the request-body estimate andcompletion_tokensto 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 writesai_usage_source=estimated. Compressed SSE now goes throughCompressedStreamDecoder, which tees the source into a decompressor used only for parsing while the original compressed bytes are forwarded verbatim together with theContent-Encodingheader; 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_usageinjection when the request body exceedsServer.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
Added
- Add
Server.AIUpstreamAcceptEncoding(auto/identity/off, defaultauto): howAccept-Encodingis rewritten on an AI upstream request, so content negotiation stays inside the coding set the gateway can decode (gzip,deflate).autokeeps only the decodable codings of the client's list (q values preserved, an empty intersection is left untouched,identity;q=0is honoured),identitystrips compression for diagnostics,offkeeps the previous behaviour. The rewrite only touches the outbound header: the inbound request, the access log,mod_ai_cacheandmod_compressstill see the client value (issue #1468) - Add
bfe_util.NewContentDecoder/CanDecodeContentEncoding/SupportedContentEncodings, a streamingContent-Encodingdecoder coveringgzip/x-gzipanddeflate(zlib header sniffed, raw DEFLATE accepted).DecodeContentEncodingnow delegates to it, so the non-streaming parse-only copy also understandsdeflate(issue #1468) - Add the
ResStreamCompressed/ResStreamDecoded/ResStreamDecodeSkipped/ResStreamRawOnlymod_body_processcounters: how many responses carried aContent-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 narrowedAccept-Encoding(issue #1468)
Changed
- An AI upstream request whose client
Accept-Encodingcontains codings the gateway cannot decode no longer receives them (Server.AIUpstreamAcceptEncoding = auto, the default): the upstream is offeredgzip/deflateonly, so a client that asked forzstdmay now receivegzipinstead (still inside its ownAccept-Encoding, <1% size difference). SetServer.AIUpstreamAcceptEncoding = offto keep the previous negotiation (issue #1468)
Fixed
- Parse the usage of a compressed streaming (SSE) response instead of estimating it:
mod_body_processbypassed anyContent-Encodingbody to a byte-wise pass-through, socache_read_tokensstayed 0,prompt_tokensfell back to the request-body estimate andcompletion_tokensto 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 writesai_usage_source=estimated. Compressed SSE now goes throughCompressedStreamDecoder, which tees the source into a decompressor used only for parsing while the original compressed bytes are forwarded verbatim together with theContent-Encodingheader; 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_usageinjection when the request body exceedsServer.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
Added
- Add
ai_zero_cost_reasonaccess-log marker (requiresbfe-access-pb >= v0.3.16): why a 2xx request holding an RMB quota plan was charged 0, together with theBillingZeroCostandAbortBillingSkippedmodule counters (issue #1414). Requests that never became a model call (batch/files management endpoints) and AI cache hits are excluded fromBillingZeroCost, 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 theweekdaysfield of the cluster pricing tiers).zoneis a single military time zone letter (seebfe_util.TimeZoneMap, e.g.Hfor UTC+8) and defaults toZ(UTC) when omitted — the weekday depends on the time zone, so deployments in UTC+8 should pass"H".weekday_listis a|-separated enumeration (no range notation), validated at config load time; the current time is read from the system clock, or from theX-Bfe-Debug-Timeheader 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 viainput_file_idparsed 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 idempotentBATCH_RESERVE/BATCH_SETTLEDRedis 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_logpolicy). Requires the newmod_ai_batchmodule and itsmod_ai_batch.dataconfig - Add
mod_ai_cache, an exact-match Redis AI cache: rule matching atHandleFoundProduct, before route rule evaluation, so a cache hit short-circuits routing; skip headerx-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 logai_cache_status/ai_cache_key(bfe-access-pb >= v0.3.7, fields 789-790) - Extend
mod_ai_cachewith 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-ruleenableSemanticCache(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 thehit_semanticstatus,ai_cache_semantic/ai_cache_similaritylog fields (bfe-access-pb >= v0.3.10, fields 791-792) andSEMANTIC_HIT/EMBEDDING_ERR/VECTOR_ERR/SEMANTIC_SKIPPEDcounters; 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-reloadableintent_questions.data(question set with choice/score and per-question/globalMinConfidence), explicitX-AI-Intentheader precedence, in-process LRU+TTL cache, and the newreq_ai_intent_in(String, String [, Float])condition primitive; the consumed intent is logged inai_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 atHandleAfterAITargetModelso 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 atHandleForwardand mirrored asynchronously to a shadow cluster via the new side-effect-freeBalanceGslb.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). Addsmirror_hit/mirror_clusteraccess-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-protocolErrorParser/StreamErrorParseradapters (openai/anthropic/gemini) map upstream errors into a unifiedUPSTREAM_*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 theX-Bfe-Gw-Errormarker. Addsai_upstream_status/ai_upstream_err_code/ai_err_normalized/ai_err_normalize_miss/ai_stream_error_rewritten/ai_stream_truncatedaccess-log fields (bfe-access-pb >= v0.3.12, fields 810-815); seeai_error_codes.md§2.5 - Add field-level
enc$v1$encryption at rest for distributed config files: sensitive fields intoken_rule.data(Tokens outer keys) andcluster_conf.data(AIConf.Keys[].Key) may carryenc$v1$AES-256-GCM ciphertext produced by the control plane at export, decrypted in memory at load time via a keyring configured in the newbfe.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
UsageUnrecognizedmodule counter (exported via monitorHandlers, alertable) and logs a warn with cluster/key_id/model and theresponse_completed/allow_estimatesub-criteria. The access log gainsai_usage_source(bfe-access-pb >= v0.3.15, field 764) distinguishingparsed(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-Idand the access-loglogidare 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 theuint64logidfield of the access log; the 63-bit bound keeps it inside the signedBIGINTof the report databases. Any consumer that parses or joins on the 32-hex form (X-Bfe-Log-Id, the text access loglog_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/SessionIdRegeneratedmodule counters, instead of silently writing 0 (#1417) - AI key session affinity now uses a server-owned Redis connection configured via the new
[AIKeyAffinity]section inbfe.conf, instead of implicitly borrowing themod_ai_rate_limitmodule's Redis. Config migration required: deployments that enabled affinity (AIConf.KeyPolicy.SessionAffinity=true) must add the[AIKeyAffinity]section (withDisabled=falseand the RedisServiceConf) before upgrading; otherwise affinity silently turns off after the upgrade (fail-open, no error, bindings lost) Server.EstimateTokennow 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 asai_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_valueis now written for every observed 2xx row, 0 included, so "charged nothing" is distinguishable from "field absent" (non-2xx / never billed). Reconciliation that testsai_cost_value IS NULLfor "no cost" should switch toai_cost_value = 0/IS NULL(issue #1414)mod_ai_token_auth.UsageUnrecognizedno longer counts client aborts — they are counted by the newAbortBillingSkippedcounter, so the two causes (upstream/parsing problem vs client-side disconnect) stay separable; existing thresholds onUsageUnrecognizedneed to be realigned.ai_usage_sourcegained the fourth valueaborted(no new protobuf field: the ...
v1.8.8.6
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_protocoladapter injects and dropsAuthorization/x-api-key/x-goog-api-key, which used to be forwarded as-is — an upstream that prefers a residual header (kimi:x-api-keywins overAuthorization; bailian:Authorizationwins 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 tobailian/deepseek-v4.1-flashwhile 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
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.shouldTriggerFallbackalso treats(nil, nil)as fallback-eligible as a hard invariant (issue #1440) - Exclude
Weight=0keys 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_secondsand a standardRetry-Afterheader, and setserr_code = NO_AVAILABLE_KEYfor access-log attribution; gateway-side failures (findProduct failure, no cluster, backend connect/transport errors) returnBACKEND_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
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_reasonaccess-log marker (requiresbfe-access-pb >= v0.3.16): why a 2xx request holding an RMB quota plan was charged 0, together with theBillingZeroCostandAbortBillingSkippedmodule counters (issue #1414). Requests that never became a model call (batch/files management endpoints) and AI cache hits are excluded fromBillingZeroCost, 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 theweekdaysfield of the cluster pricing tiers).zoneis a single military time zone letter (seebfe_util.TimeZoneMap, e.g.Hfor UTC+8) and defaults toZ(UTC) when omitted — the weekday depends on the time zone, so deployments in UTC+8 should pass"H".weekday_listis a|-separated enumeration (no range notation), validated at config load time; the current time is read from the system clock, or from theX-Bfe-Debug-Timeheader when present
Changed
X-Bfe-Log-Idand the access-loglogidare 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 theuint64logidfield of the access log; the 63-bit bound keeps it inside the signedBIGINTof the report databases. Any consumer that parses or joins on the 32-hex form (X-Bfe-Log-Id, the text access loglog_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/SessionIdRegeneratedmodule counters, instead of silently writing 0 (#1417) - AI key session affinity now uses a server-owned Redis connection configured via the new
[AIKeyAffinity]section inbfe.conf, instead of implicitly borrowing themod_ai_rate_limitmodule's Redis. Config migration required: deployments that enabled affinity (AIConf.KeyPolicy.SessionAffinity=true) must add the[AIKeyAffinity]section (withDisabled=falseand the RedisServiceConf) before upgrading; otherwise affinity silently turns off after the upgrade (fail-open, no error, bindings lost) Server.EstimateTokennow 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 asai_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_valueis now written for every observed 2xx row, 0 included, so "charged nothing" is distinguishable from "field absent" (non-2xx / never billed). Reconciliation that testsai_cost_value IS NULLfor "no cost" should switch toai_cost_value = 0/IS NULL(issue #1414)mod_ai_token_auth.UsageUnrecognizedno longer counts client aborts — they are counted by the newAbortBillingSkippedcounter, so the two causes (upstream/parsing problem vs client-side disconnect) stay separable; existing thresholds onUsageUnrecognizedneed to be realigned.ai_usage_sourcegained the fourth valueaborted(no new protobuf field: the value is added to the existingai_usage_source) (issue #1414)
Fixed
- Populate the access-log
logidwith the request's real log id:strconv.ParseUint(req.LogId, 10, 64)parsed the hex log id as decimal and discarded the error, sologidwas written as 0 for every request. Together with the report table's second-granularity dedup key and its full-rowON 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'slogid) 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
BillingZeroCostcounter andai_zero_cost_reasonmarker, 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 onai_total_tokens == 0, which disabled it for exactly theinput > 0 while total == 0rows 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
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:ServeHTTPForAInow marks the response completed once the body has been fully delivered (200 SSE,copyResponsesuccess). 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 itsContent-Lengthbytes — 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), thefindProduct500, the protocol-mismatch rejection, theHandleAfterAITargetModelBfeHandlerResponserejection and the no-cluster 500 no longer set the server-levelcloseAfterReply. Those responses are self-delimited (explicitContent-Length) andchunk_writerdrains the request body before writing headers, so BFE was closing the connection without advertisingConnection: closeand the next request on a pooled keep-alive connection failed with EOF; module-contractBfeHandlerFinish/BfeHandlerClosepaths and the protocol-level close shapes (HTTP/1.0,Connection: close, undrainable bodies) still close with advertisement
BFEv1.8.8.3
Fixed
- Fix token usage collection for non-streaming gzip responses (
Content-Encoding: gzipwithTransfer-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, soai_output_tokens/ai_total_tokens/ai_cache_read_tokensand 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 newai_price_missaccess-log field (bfe-access-pb >= v0.3.14, field 763) counted byPriceFallbackUsed, 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
TokenUsageand 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 asai_input_tokenswhileai_total_tokensstays 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
UsageUnrecognizedmodule counter (exported via monitorHandlers, alertable) and logs a warn with cluster/key_id/model and theresponse_completed/allow_estimatesub-criteria; the client-abort zero-deduction branch is counted too (counter-only). The access log gainsai_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
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.