Skip to content

armgit / sie

Public Imported from GitHub
0

Open-source inference server and production cluster for all the models your agent needs.

fix(api): preserve LoRA selector semantics across wire encodings

svonava81faec66b17b
diff --git a/packages/sie_gateway/src/handlers/lora.rs b/packages/sie_gateway/src/handlers/lora.rs
index ce9e8c978..ba1f4fa51 100644
--- a/packages/sie_gateway/src/handlers/lora.rs
+++ b/packages/sie_gateway/src/handlers/lora.rs
@@ -41,7 +41,13 @@ pub(crate) fn validate_options_rmpv(options: Option<&rmpv::Value>) -> Result<(),
};
let mut selected = Map::new();
for (key, value) in fields {
- let Some(key) = key.as_str().filter(|key| FIELDS.contains(key)) else {
+ // The generic bridge and ancestor lookup also accept UTF-8 binary keys.
+ let key = match key {
+ rmpv::Value::String(key) => key.as_str(),
+ rmpv::Value::Binary(key) => std::str::from_utf8(key).ok(),
+ _ => None,
+ };
+ let Some(key) = key.filter(|key| FIELDS.contains(key)) else {
continue;
};
let value = match value {
@@ -97,8 +103,44 @@ mod tests {
rmpv::Value::Ext(1, vec![1]),
rmpv::Value::Boolean(false),
] {
- let options = rmpv::Value::Map(vec![("lora_adapter".into(), value)]);
- assert!(validate_options_rmpv(Some(&options)).is_err());
+ for key in FIELDS {
+ for key in [key.into(), rmpv::Value::Binary(key.as_bytes().to_vec())] {
+ let options = rmpv::Value::Map(vec![(key, value.clone())]);
+ assert!(validate_options_rmpv(Some(&options)).is_err());
+ }
+ }
+ }
+ }
+
+ #[test]
+ fn msgpack_binary_lora_keys_preserve_selection_and_reject_duplicates() {
+ for key in FIELDS {
+ let binary_key = rmpv::Value::Binary(key.as_bytes().to_vec());
+ for value in [rmpv::Value::Nil, "legal".into()] {
+ let options = rmpv::Value::Map(vec![(binary_key.clone(), value)]);
+ assert!(validate_options_rmpv(Some(&options)).is_ok());
+ }
+ let empty = rmpv::Value::Map(vec![(binary_key.clone(), " ".into())]);
+ assert!(validate_options_rmpv(Some(&empty)).is_err());
+ for duplicate_first in [false, true] {
+ let mut fields = vec![
+ (key.into(), "legal".into()),
+ (binary_key.clone(), rmpv::Value::Nil),
+ ];
+ if duplicate_first {
+ fields.reverse();
+ }
+ let error = validate_options_rmpv(Some(&rmpv::Value::Map(fields))).unwrap_err();
+ assert!(error.contains("duplicate LoRA selector"));
+ }
}
+ let conflict = rmpv::Value::Map(vec![
+ (
+ rmpv::Value::Binary(b"lora_adapter".to_vec()),
+ rmpv::Value::Nil,
+ ),
+ (rmpv::Value::Binary(b"lora".to_vec()), "legal".into()),
+ ]);
+ assert!(validate_options_rmpv(Some(&conflict)).is_err());
}
}
diff --git a/packages/sie_gateway/src/handlers/proxy.rs b/packages/sie_gateway/src/handlers/proxy.rs
index 3504e4ba3..ac46e9884 100644
--- a/packages/sie_gateway/src/handlers/proxy.rs
+++ b/packages/sie_gateway/src/handlers/proxy.rs
@@ -29768,6 +29768,82 @@ profiles:
assert!(gateway.dispatcher.dispatched().is_empty());
}
+ #[tokio::test]
+ async fn binary_lora_selector_keys_fail_before_dispatch_with_supported_ancestors() {
+ let gateway = TestGateway::new(&[LORA_MODEL]).await;
+ gateway.add_worker("local-1", LOCAL_LANE, &[]).await;
+ let binary = |key: &str| rmpv::Value::Binary(key.as_bytes().to_vec());
+ for endpoint in ["encode", "extract", "score"] {
+ for field in crate::handlers::lora::FIELDS {
+ for invalid in [
+ vec![(binary(field), rmpv::Value::F64(f64::NAN))],
+ vec![(binary(field), " ".into())],
+ vec![
+ (field.into(), "legal".into()),
+ (binary(field), rmpv::Value::Nil),
+ ],
+ ] {
+ let mut options = vec![("profile".into(), "served".into())];
+ options.extend(invalid);
+ let options = rmpv::Value::Map(options);
+ let mut body = vec![(
+ "items".into(),
+ rmpv::Value::Array(vec![rmpv::Value::Map(vec![(
+ "text".into(),
+ "x".into(),
+ )])]),
+ )];
+ if endpoint == "score" {
+ body.push((
+ "query".into(),
+ rmpv::Value::Map(vec![("text".into(), "q".into())]),
+ ));
+ // Score rejects binary map keys before LoRA validation.
+ body.push(("options".into(), options));
+ } else {
+ body.push((
+ binary("params"),
+ rmpv::Value::Map(vec![
+ (binary("options"), options),
+ ("labels".into(), rmpv::Value::Array(vec!["a".into()])),
+ ]),
+ ));
+ }
+ let mut encoded = Vec::new();
+ rmpv::encode::write_value(&mut encoded, &rmpv::Value::Map(body)).unwrap();
+ let request = Request::builder()
+ .uri(format!("/v1/{endpoint}/acme/lora"))
+ .header("content-type", "application/msgpack")
+ .body(Body::from(encoded))
+ .unwrap();
+ let response =
+ proxy_request(State(Arc::clone(&gateway.state)), request, endpoint).await;
+ assert_eq!(
+ response.status(),
+ StatusCode::BAD_REQUEST,
+ "{endpoint}/{field}"
+ );
+ let body = to_bytes(response.into_body(), 64 * 1024).await.unwrap();
+ let value: Value = serde_json::from_slice(&body).unwrap();
+ let expected = if endpoint == "score" {
+ "'options' field names must be MessagePack strings"
+ } else {
+ "lora"
+ };
+ assert!(
+ value["detail"]["message"]
+ .as_str()
+ .is_some_and(|message| message
+ .to_ascii_lowercase()
+ .contains(&expected.to_ascii_lowercase())),
+ "{endpoint}/{field}: {value}"
+ );
+ }
+ }
+ }
+ assert!(gateway.dispatcher.dispatched().is_empty());
+ }
+
#[tokio::test]
async fn an_undeclared_lora_is_refused_on_encode_extract_and_score_before_dispatch() {
let gateway = TestGateway::new(&[LORA_MODEL]).await;
diff --git a/packages/sie_server/openapi.json b/packages/sie_server/openapi.json
index 91f5ab471..12ea29192 100644
--- a/packages/sie_server/openapi.json
+++ b/packages/sie_server/openapi.json
@@ -1342,6 +1342,42 @@
}
],
"title": "Safety Identifier"
+ },
+ "lora_adapter": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "SIE extension: declared LoRA name or source; null selects base, omission keeps the profile default.",
+ "title": "Lora Adapter"
+ },
+ "lora": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Compatibility alias for lora_adapter; supplied aliases must agree.",
+ "title": "Lora"
+ },
+ "lora_id": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Compatibility alias restricted to a declared source id; supplied aliases must agree.",
+ "title": "Lora Id"
}
},
"required": [
diff --git a/packages/sie_server/src/sie_server/api/decisions.py b/packages/sie_server/src/sie_server/api/decisions.py
index 0753b39b7..368690d46 100644
--- a/packages/sie_server/src/sie_server/api/decisions.py
+++ b/packages/sie_server/src/sie_server/api/decisions.py
@@ -34,6 +34,16 @@ class DecisionRequest(BaseModel):
min_length=1, max_length=MAX_QUESTIONS, description="Predicate, choice, or score questions, in answer order."
)
safety_identifier: str | None = Field(default=None, max_length=128)
+ lora_adapter: str | None = Field(
+ default=None,
+ description="SIE extension: declared LoRA name or source; null selects base, omission keeps the profile default.",
+ )
+ lora: str | None = Field(
+ default=None, description="Compatibility alias for lora_adapter; supplied aliases must agree."
+ )
+ lora_id: str | None = Field(
+ default=None, description="Compatibility alias restricted to a declared source id; supplied aliases must agree."
+ )
class DecisionUsage(BaseModel):
diff --git a/packages/sie_server/tests/api/test_decisions.py b/packages/sie_server/tests/api/test_decisions.py
index 79a4f1ca9..a92f88212 100644
--- a/packages/sie_server/tests/api/test_decisions.py
+++ b/packages/sie_server/tests/api/test_decisions.py
@@ -98,6 +98,16 @@ def test_route_uses_native_worker_and_preserves_headers(dispatch):
assert args.kwargs["options"]["overflow_policy"] == "error"
+def test_openapi_publishes_optional_nullable_lora_extensions(dispatch):
+ schema = dispatch.client.app.openapi()["paths"]["/v1/decisions"]["post"]["requestBody"]["content"][
+ "application/json"
+ ]["schema"]
+ for field in ("lora_adapter", "lora", "lora_id"):
+ assert field not in schema["required"]
+ assert {option["type"] for option in schema["properties"][field]["anyOf"]} == {"string", "null"}
+ assert schema["properties"][field]["description"]
+
+
@pytest.mark.parametrize("case", FIXTURE["invalid_requests"], ids=lambda case: case["name"])
def test_invalid_request_does_not_dispatch(dispatch, case):
response = dispatch.client.post("/v1/decisions", json=case["request"])
diff --git a/packages/sie_ts_sdk/src/client.ts b/packages/sie_ts_sdk/src/client.ts
index 9878541ce..5be2fe148 100644
--- a/packages/sie_ts_sdk/src/client.ts
+++ b/packages/sie_ts_sdk/src/client.ts
@@ -109,7 +109,7 @@ import {
requireConnectionSchemaPolicy,
requireConnectorIdempotencyKey,
} from "./jobs.js";
-import { validateLoraSelectors } from "./lora.js";
+import { normalizeLoraOptions, validateLoraSelectors } from "./lora.js";
import { packMessage, unpackMessage } from "./msgpack.js";
import { SSECompletion, parseSseStream } from "./sse.js";
import {
@@ -892,12 +892,12 @@ function runtimeOptions(
adapterOptions: Record<string, unknown> | undefined,
typed: Record<string, unknown>,
): Record<string, unknown> | undefined {
- validateLoraSelectors(adapterOptions);
+ const normalized = normalizeLoraOptions(adapterOptions);
const set = Object.fromEntries(Object.entries(typed).filter(([, value]) => value !== undefined));
if (adapterOptions === undefined && Object.keys(set).length === 0) {
return undefined;
}
- return { ...adapterOptions, ...set };
+ return { ...normalized, ...set };
}
/** The response-level timing block, in the camelCase `TimingInfo` shape. */
@@ -2101,7 +2101,7 @@ export class SIEClient {
items: Item[],
options: ScoreOptions = {},
): Promise<ScoreResult> {
- validateLoraSelectors(options.adapterOptions);
+ const adapterOptions = normalizeLoraOptions(options.adapterOptions);
const queryForWire = await itemImagesForWire(query);
const itemsForWire = await itemsImagesForWire(items);
@@ -2113,8 +2113,8 @@ export class SIEClient {
if (options.instruction !== undefined) {
body.instruction = options.instruction;
}
- if (options.adapterOptions !== undefined) {
- body.options = options.adapterOptions;
+ if (adapterOptions !== undefined) {
+ body.options = adapterOptions;
}
const waitForCapacity = options.waitForCapacity ?? this.defaultWaitForCapacity;
diff --git a/packages/sie_ts_sdk/src/lora.ts b/packages/sie_ts_sdk/src/lora.ts
index f4ed2137c..aa26773b4 100644
--- a/packages/sie_ts_sdk/src/lora.ts
+++ b/packages/sie_ts_sdk/src/lora.ts
@@ -3,7 +3,7 @@ export function validateLoraSelectors(options: Record<string, unknown> | undefin
let selected: string | null | undefined;
for (const key of ["lora_adapter", "lora", "lora_id"]) {
const value = options?.[key];
- // Undefined is omitted by the wire encoders; null is an explicit base selection.
+ // Undefined is omitted by normalization; null is an explicit base selection.
if (value === undefined) continue;
if (value !== null && (typeof value !== "string" || value.trim().length === 0)) {
throw new TypeError(`'${key}' must be a non-empty string or null`);
@@ -14,3 +14,16 @@ export function validateLoraSelectors(options: Record<string, unknown> | undefin
selected = value;
}
}
+
+/** Keep optional selectors absent even when the MessagePack encoder maps undefined to null. */
+export function normalizeLoraOptions(
+ options: Record<string, unknown> | undefined,
+): Record<string, unknown> | undefined {
+ validateLoraSelectors(options);
+ if (options === undefined) return undefined;
+ const normalized = { ...options };
+ for (const key of ["lora_adapter", "lora", "lora_id"]) {
+ if (normalized[key] === undefined) delete normalized[key];
+ }
+ return normalized;
+}
diff --git a/packages/sie_ts_sdk/src/types.ts b/packages/sie_ts_sdk/src/types.ts
index 0917cac99..e41e8998d 100644
--- a/packages/sie_ts_sdk/src/types.ts
+++ b/packages/sie_ts_sdk/src/types.ts
@@ -1451,8 +1451,9 @@ export interface ChatCompletionRequest {
safety_identifier?: string;
/**
* Multi-LoRA: served-name of the adapter to apply on the worker (SIE
- * extension). Must be a non-empty string; unknown names are rejected by
- * the gateway with 400 `unknown_lora`.
+ * extension). A non-empty string selects an adapter; explicit `null` or
+ * omission selects the base model. Unknown names are rejected by the
+ * gateway with 400 `unknown_lora`.
*/
lora_adapter?: string | null;
/** SIE-native routing affinity hint. */
diff --git a/packages/sie_ts_sdk/tests/lora.test.ts b/packages/sie_ts_sdk/tests/lora.test.ts
index 513322aad..5e1b5eba7 100644
--- a/packages/sie_ts_sdk/tests/lora.test.ts
+++ b/packages/sie_ts_sdk/tests/lora.test.ts
@@ -27,6 +27,40 @@ function nativeCall(client: SIEClient, kind: string, adapterOptions: Record<stri
describe("LoRA selector boundaries", () => {
for (const kind of ["encode", "extract", "score", "systemOne"]) {
+ for (const selected of [undefined, null, "legal"]) {
+ it.each(["lora_adapter", "lora", "lora_id"])(
+ `${kind} omits undefined %s alongside ${selected}`,
+ async (key) => {
+ fetchMock.mockResolvedValueOnce(refusal());
+ const other = key === "lora_adapter" ? "lora" : "lora_adapter";
+ const options = Object.freeze({
+ [key]: undefined,
+ [other]: selected,
+ profile: "served",
+ unrelated: undefined,
+ });
+ const client = new SIEClient("http://localhost:8080");
+ await expect(nativeCall(client, kind, options)).rejects.toThrow();
+ expect(fetchMock).toHaveBeenCalledOnce();
+ const body = unpackMessage(fetchMock.mock.calls[0]?.[1].body) as {
+ options: Record<string, unknown>;
+ params: { options: Record<string, unknown> };
+ };
+ const actual = kind === "score" ? body.options : body.params.options;
+ expect(actual).not.toHaveProperty(key);
+ if (selected === undefined) expect(actual).not.toHaveProperty(other);
+ else expect(actual[other]).toBe(selected);
+ expect(actual.profile).toBe("served");
+ // Only selector omission changes; unrelated MessagePack fields retain their semantics.
+ expect(actual.unrelated).toBeNull();
+ expect(Object.hasOwn(options, key)).toBe(true);
+ expect(options[key]).toBeUndefined();
+ expect(options[other]).toBe(selected);
+ await client.close();
+ },
+ );
+ }
+
it.each(["lora_adapter", "lora", "lora_id"])(
`${kind} preserves explicit null via %s`,
async (key) => {