From 53ff1d0c2bfeb4e303e633fb758e28fc0535ecaa Mon Sep 17 00:00:00 2001 From: "zhangxiaoyu.york" Date: Fri, 4 Dec 2026 00:03:22 +0800 Subject: [PATCH 1/4] Rust SDK documentation describes stored credential discovery and renewal An empty API key continues credential discovery. Explain profile precedence and token renewal in the packaged guides. Signed-off-by: zhangxiaoyu.york --- sdk/rust/README.md | 70 +++++++++++++++++++++++++++++++++---- sdk/rust/examples/README.md | 41 +++++++++++++++++----- 2 files changed, 96 insertions(+), 15 deletions(-) diff --git a/sdk/rust/README.md b/sdk/rust/README.md index 94f84ed5dbc..9fb90692f00 100644 --- a/sdk/rust/README.md +++ b/sdk/rust/README.md @@ -71,7 +71,6 @@ use clickhouse_loom::{Client, SearchRequest, SetRequest}; async fn main() -> Result<(), Box> { let bot = Client::builder("dev", "local", "my-agent") .base_url("http://localhost:7777") - .api_key("") .build()?; let mut write = SetRequest::new("deploy_window", "Deploy Tue/Thu, never Friday"); write.memory_type = Some("semantic".into()); @@ -109,13 +108,70 @@ Server setup is covered in the ## Configuration `Client::builder(org, namespace, agent)` accepts `base_url`, `api_key`, `timeout`, -`user_id`, `session_id`, `run_id`, `retry`, `pacing` and `ratelimit_max_wait`. +`user_id`, `session_id`, `run_id`, `retry`, `pacing`, `ratelimit_max_wait`, +`profile`, `credential_provider` and `consumer`. The default timeout is 60 seconds per attempt. It covers the whole HTTP request -and response body. The server address comes from `LOOM_BASE_URL`, defaulting to -`http://localhost:7777`. The token comes from `LOOM_API_KEY`; without a token, -requests carry no Authorization header. -Explicit settings override the environment. `.api_key("")` disables authorization. -Empty environment values are treated as unset. +and response body. An explicit `.base_url(...)` selects the server. Otherwise, +the SDK uses the profile or provider's server when it has one, then +`LOOM_BASE_URL`, then `http://localhost:7777`. An explicit server must match a +profile or provider's server binding. + +### Authentication + +A nonempty `.api_key(...)` uses that token. Alternatively, select +`.profile(...)` or `.credential_provider(...)`; configure only one of these +credential sources. An explicit profile or provider takes precedence over +`LOOM_API_KEY`. + +Without an explicit credential source, the SDK checks: + +1. A nonempty `LOOM_API_KEY`. +2. The profile selected by `LOOM_PROFILE` (default `default`) in + `.loom/credentials` in the user's home directory, if its server matches the + selected server. +3. The first line of `.loom/token` in the user's home directory. + +`.api_key("")` and empty environment values are treated as unset; they do not +disable credential discovery. Requests carry no Authorization header only when +no credential is found, or an explicit provider returns an empty token. For an +unauthenticated local connection, check that no matching stored login or legacy +token is present. + +Sign in with the Loom CLI, then select that profile: + +```bash +loom login --profile team +``` + +```rust +use clickhouse_loom::Client; + +let bot = Client::builder("my-org", "my-namespace", "rust-agent") + .profile("team") + .build()?; +let memory = bot.get("preference").await?; +``` + +The profile supplies its server and tokens. `StoredLogin::from_file(path, profile)` +reads a profile from an application-selected credentials file; pass it to +`.credential_provider(...)`. Applications can also implement +`CredentialProvider` to supply and replace tokens themselves. + +Stored login refreshes an access token when it has at most 60 seconds left. +Concurrent refreshes share a credentials-file lock and save rotated tokens before +returning them. If renewal is temporarily unavailable, an unexpired token that +has not been rejected can still be used. Otherwise, the call returns a +retryable `Error::Credentials`. A revoked refresh token requires `loom login` +again. + +On HTTP 401, the SDK asks the provider to replace the rejected token and resends +only if it changed. An unchanged token or a second rejection ends authentication +retries. Fixed API keys are not refreshed. These rules apply to the async and +blocking clients and to routes outside the op registry. + +See the [stored login example](examples/README.md#renew_loginrs). + +### Identity and request defaults Builder identity values apply to declared caller and authorship fields. `knowledge_add` and `knowledge_upsert` receive agent and session identity; diff --git a/sdk/rust/examples/README.md b/sdk/rust/examples/README.md index d1bb38738a0..d7f2284bdde 100644 --- a/sdk/rust/examples/README.md +++ b/sdk/rust/examples/README.md @@ -6,11 +6,12 @@ package. Cargo includes these examples in the distributable crate. The three basic examples below write, read and delete their own memory keys and knowledge URIs. Installation and client configuration are covered in the [SDK README](../README.md#install). -| Example | Client | Demonstrates | -| ------------------------------ | -------- | -------------------------------------------------------------------------------------- | -| [memory.rs](memory.rs) | Async | Memory save, key lookup, lexical search, deletion and absence check | -| [operations.rs](operations.rs) | Async | Capabilities, memory and knowledge calls, request options, metadata and request `send` | -| [blocking.rs](blocking.rs) | Blocking | The same memory, knowledge and context flow from a synchronous `main` | +| Example | Client | Demonstrates | +| -------------------------------- | -------- | -------------------------------------------------------------------------------------- | +| [memory.rs](memory.rs) | Async | Memory save, key lookup, lexical search, deletion and absence check | +| [operations.rs](operations.rs) | Async | Capabilities, memory and knowledge calls, request options, metadata and request `send` | +| [blocking.rs](blocking.rs) | Blocking | The same memory, knowledge and context flow from a synchronous `main` | +| [renew_login.rs](renew_login.rs) | Async | Stored login credentials and automatic renewal | ## Configure and run @@ -33,13 +34,17 @@ cargo run --manifest-path sdk/rust/Cargo.toml --example operations cargo run --manifest-path sdk/rust/Cargo.toml --features blocking --example blocking ``` -The empty token is for a local server that permits unauthenticated requests. -For a team deployment, set `LOOM_API_KEY` to your token before running Cargo. +An empty `LOOM_API_KEY` leaves credential discovery enabled. For unauthenticated +local requests, no matching stored login or legacy token may be present. +For a team deployment, set `LOOM_API_KEY` to your token or sign in with +`loom login` and select a matching profile through `LOOM_PROFILE`. +See the [authentication contract](../README.md#authentication). | Variable | Default | Purpose | | ------------------- | ----------------------- | ------------------------------------------------------------------ | | `LOOM_BASE_URL` | `http://localhost:7777` | Server address, read by the SDK | -| `LOOM_API_KEY` | Unset | Bearer token; empty means no Authorization header | +| `LOOM_API_KEY` | Unset | Bearer token; empty continues stored credential discovery | +| `LOOM_PROFILE` | `default` | Stored login profile, used when its server matches `LOOM_BASE_URL` | | `LOOM_ORG` | `dev` | Organization, read by each example | | `LOOM_NAMESPACE` | `local` | Namespace, read by each example | | `LOOM_CHECK_HEALTH` | Unset | `1` adds an `ops.health` call in `operations.rs` and `blocking.rs` | @@ -124,6 +129,26 @@ context: truncated= request= A health-enabled run also prints `health: ` after the schema version. Successful memory and knowledge lookups and cleanup do not print separate lines. +## renew_login.rs + +The [renew_login.rs](renew_login.rs) example reads the `preference` memory using +a stored login. Sign in through the Loom CLI first: + +```bash +loom login --profile team +cargo run --manifest-path sdk/rust/Cargo.toml --example renew_login -- team +``` + +The example passes `StoredLogin::profile("team")` to `.credential_provider(...)`. +That profile supplies the server and rotating tokens; environment tokens do not +override it. Omitting the example's profile argument selects `default`. +The server resolves the org and namespace from the token. The example prints +`found: false` when the memory is absent. + +Stored login renews expiring tokens and can replace a token rejected with HTTP 401. It does not start a login itself. A missing or revoked login must be +restored with `loom login`; temporary renewal failures follow the +[authentication contract](../README.md#authentication). + ## blocking.rs The [blocking.rs](blocking.rs) example calls `Client::probe` and prints the build, From 25d6d6ef1c2e97fa4c27085c1b97a10d046433bb Mon Sep 17 00:00:00 2001 From: "zhangxiaoyu.york" Date: Fri, 4 Dec 2026 00:11:46 +0800 Subject: [PATCH 2/4] Rust authentication examples name a namespace and route retries include 401 Keep the explicit-scope profile snippet instead of advertising the existing scope-free example. Describe changed-token retries for route requests. Signed-off-by: zhangxiaoyu.york --- sdk/rust/README.md | 9 ++++----- sdk/rust/examples/README.md | 31 +++++-------------------------- 2 files changed, 9 insertions(+), 31 deletions(-) diff --git a/sdk/rust/README.md b/sdk/rust/README.md index 9fb90692f00..81790778992 100644 --- a/sdk/rust/README.md +++ b/sdk/rust/README.md @@ -169,8 +169,6 @@ only if it changed. An unchanged token or a second rejection ends authentication retries. Fixed API keys are not refreshed. These rules apply to the async and blocking clients and to routes outside the op registry. -See the [stored login example](examples/README.md#renew_loginrs). - ### Identity and request defaults Builder identity values apply to declared caller and authorship fields. @@ -569,9 +567,10 @@ a route takes the org, namespace and other fields it needs from them. `request` returns the whole response of a status below 400 with its status and headers; a redirect is returned, not followed. `request_json` decodes the body as the requested type; an empty body decodes as an empty object and an invalid -one is `Error::Protocol`. A status of 400 or higher is `Error::Api`. The SDK -resends only on a 429, after the server's hint and within the client's pacing -budget. The HTTP transport does not retry requests. A refused HTTP/2 stream +one is `Error::Protocol`. A status of 400 or higher is `Error::Api`. On a 429, +the SDK resends after the server's hint and within the client's pacing budget. +On a 401, it can resend once with a changed token as described in +[Authentication](#authentication). The HTTP transport does not retry requests. A refused HTTP/2 stream returns `Error::Transport`. `request_with_options` and `request_json_with_options` accept `CallOptions` diff --git a/sdk/rust/examples/README.md b/sdk/rust/examples/README.md index d7f2284bdde..727e9568416 100644 --- a/sdk/rust/examples/README.md +++ b/sdk/rust/examples/README.md @@ -6,12 +6,11 @@ package. Cargo includes these examples in the distributable crate. The three basic examples below write, read and delete their own memory keys and knowledge URIs. Installation and client configuration are covered in the [SDK README](../README.md#install). -| Example | Client | Demonstrates | -| -------------------------------- | -------- | -------------------------------------------------------------------------------------- | -| [memory.rs](memory.rs) | Async | Memory save, key lookup, lexical search, deletion and absence check | -| [operations.rs](operations.rs) | Async | Capabilities, memory and knowledge calls, request options, metadata and request `send` | -| [blocking.rs](blocking.rs) | Blocking | The same memory, knowledge and context flow from a synchronous `main` | -| [renew_login.rs](renew_login.rs) | Async | Stored login credentials and automatic renewal | +| Example | Client | Demonstrates | +| ------------------------------ | -------- | -------------------------------------------------------------------------------------- | +| [memory.rs](memory.rs) | Async | Memory save, key lookup, lexical search, deletion and absence check | +| [operations.rs](operations.rs) | Async | Capabilities, memory and knowledge calls, request options, metadata and request `send` | +| [blocking.rs](blocking.rs) | Blocking | The same memory, knowledge and context flow from a synchronous `main` | ## Configure and run @@ -129,26 +128,6 @@ context: truncated= request= A health-enabled run also prints `health: ` after the schema version. Successful memory and knowledge lookups and cleanup do not print separate lines. -## renew_login.rs - -The [renew_login.rs](renew_login.rs) example reads the `preference` memory using -a stored login. Sign in through the Loom CLI first: - -```bash -loom login --profile team -cargo run --manifest-path sdk/rust/Cargo.toml --example renew_login -- team -``` - -The example passes `StoredLogin::profile("team")` to `.credential_provider(...)`. -That profile supplies the server and rotating tokens; environment tokens do not -override it. Omitting the example's profile argument selects `default`. -The server resolves the org and namespace from the token. The example prints -`found: false` when the memory is absent. - -Stored login renews expiring tokens and can replace a token rejected with HTTP 401. It does not start a login itself. A missing or revoked login must be -restored with `loom login`; temporary renewal failures follow the -[authentication contract](../README.md#authentication). - ## blocking.rs The [blocking.rs](blocking.rs) example calls `Client::probe` and prints the build, From 506628c6f52bc503f508ad5422ffd34f6168e8e4 Mon Sep 17 00:00:00 2001 From: "zhangxiaoyu.york" Date: Fri, 4 Dec 2026 09:44:28 +0800 Subject: [PATCH 3/4] Stored login example requires an explicit namespace Authenticated memory.get requires a namespace; the token resolves only the org. Read LOOM_NAMESPACE and reject missing or blank values before loading credentials. Regression tests check the outgoing request and configuration errors. Signed-off-by: zhangxiaoyu.york (cherry picked from commit a6878610fedbdaed7ffa37a797080918735612e2) Signed-off-by: zhangxiaoyu.york --- sdk/rust/examples/renew_login.rs | 27 ++++- sdk/rust/tests/renew_login_example/mod.rs | 119 ++++++++++++++++++++++ 2 files changed, 142 insertions(+), 4 deletions(-) create mode 100644 sdk/rust/tests/renew_login_example/mod.rs diff --git a/sdk/rust/examples/renew_login.rs b/sdk/rust/examples/renew_login.rs index e20e0b7b861..9aeac3007b1 100644 --- a/sdk/rust/examples/renew_login.rs +++ b/sdk/rust/examples/renew_login.rs @@ -3,10 +3,29 @@ use clickhouse_loom::{Client, StoredLogin}; #[tokio::main] async fn main() -> Result<(), Box> { let profile = std::env::args().nth(1).unwrap_or_else(|| "default".into()); - let client = Client::builder("", "", "profile-example") - .credential_provider(StoredLogin::profile(profile)?) + let namespace = required_namespace(std::env::var("LOOM_NAMESPACE").ok())?; + let found = read_preference(StoredLogin::profile(profile)?, namespace).await?; + println!("found: {found}"); + Ok(()) +} + +fn required_namespace(namespace: Option) -> Result { + namespace + .filter(|value| !value.trim().is_empty()) + .ok_or("set LOOM_NAMESPACE to a namespace your login can access") +} + +async fn read_preference( + login: StoredLogin, + namespace: String, +) -> Result> { + let client = Client::builder("", namespace, "profile-example") + .credential_provider(login) .build()?; let memory = client.get("preference").await?; - println!("found: {}", memory.found); - Ok(()) + Ok(memory.found) } + +#[cfg(test)] +#[path = "../tests/renew_login_example/mod.rs"] +mod tests; diff --git a/sdk/rust/tests/renew_login_example/mod.rs b/sdk/rust/tests/renew_login_example/mod.rs new file mode 100644 index 00000000000..95454ef35a5 --- /dev/null +++ b/sdk/rust/tests/renew_login_example/mod.rs @@ -0,0 +1,119 @@ +use super::*; +use std::{ + io::{BufRead, BufReader, Read, Write}, + net::TcpListener, + thread, + time::{Duration, Instant, SystemTime, UNIX_EPOCH}, +}; + +#[tokio::test] +async fn stored_login_read_sends_the_selected_namespace() { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let server = format!("http://{}", listener.local_addr().unwrap()); + listener.set_nonblocking(true).unwrap(); + let worker = thread::spawn(move || { + let deadline = Instant::now() + Duration::from_secs(5); + let mut stream = loop { + assert!(Instant::now() < deadline, "example did not send a request"); + match listener.accept() { + Ok((stream, _)) => break stream, + Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => { + thread::park_timeout(Duration::from_millis(5)); + } + Err(error) => panic!("accept: {error}"), + } + }; + stream.set_nonblocking(false).unwrap(); + stream + .set_read_timeout(Some(Duration::from_secs(5))) + .unwrap(); + stream + .set_write_timeout(Some(Duration::from_secs(5))) + .unwrap(); + let mut reader = BufReader::new(&mut stream); + let mut line = String::new(); + reader.read_line(&mut line).unwrap(); + assert!(line.starts_with("POST /v1/memory.get ")); + let mut length = 0; + let mut authorized = false; + loop { + line.clear(); + assert!(reader.read_line(&mut line).unwrap() > 0); + if line == "\r\n" { + break; + } + let (name, value) = line.split_once(':').unwrap(); + if name.eq_ignore_ascii_case("content-length") { + length = value.trim().parse().unwrap(); + } + if name.eq_ignore_ascii_case("authorization") { + authorized = value.trim() == "Bearer stored-token"; + } + } + let mut bytes = vec![0; length]; + reader.read_exact(&mut bytes).unwrap(); + let body: serde_json::Value = serde_json::from_slice(&bytes).unwrap(); + let (status, response) = if body.get("namespace").is_some() { + ("200 OK", r#"{"found":false}"#) + } else { + ( + "422 Unprocessable Entity", + r#"{"detail":"namespace is required"}"#, + ) + }; + write!( + stream, + "HTTP/1.1 {status}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{response}", + response.len() + ) + .unwrap(); + (authorized, body) + }); + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("credentials"); + let expires = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_secs() + + 3600; + std::fs::write( + &path, + serde_json::json!({ + "profiles": { + "team": { + "server": server, + "access_token": "stored-token", + "refresh_token": "refresh-token", + "expires_at": expires, + "session": "example-test", + "marked": true + } + } + }) + .to_string(), + ) + .unwrap(); + let login = StoredLogin::from_file(path, "team").unwrap(); + let result = read_preference(login, "team-memory".into()).await; + let (authorized, body) = worker.join().unwrap(); + assert!(!result.unwrap()); + assert!(authorized); + assert_eq!(body["namespace"], "team-memory"); + assert_eq!(body["memory_key"], "preference"); + assert_eq!(body["org"], ""); +} + +#[test] +fn missing_or_blank_namespace_is_rejected() { + for namespace in [None, Some(String::new()), Some(" \t ".into())] { + let error = required_namespace(namespace).unwrap_err(); + assert_eq!( + error, + "set LOOM_NAMESPACE to a namespace your login can access" + ); + } + assert_eq!( + required_namespace(Some("team-memory".into())).unwrap(), + "team-memory" + ); +} From afaf45f1332e5c98e662542fb6087465f515b22b Mon Sep 17 00:00:00 2001 From: "zhangxiaoyu.york" Date: Fri, 4 Dec 2026 10:16:41 +0800 Subject: [PATCH 4/4] Document the namespace required by the stored-login example The profile supplies the server and tokens; the memory lookup still needs an addressed namespace. Signed-off-by: zhangxiaoyu.york --- sdk/rust/examples/README.md | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/sdk/rust/examples/README.md b/sdk/rust/examples/README.md index 727e9568416..8d745abb9d7 100644 --- a/sdk/rust/examples/README.md +++ b/sdk/rust/examples/README.md @@ -57,6 +57,20 @@ Writes use the server's configured embedding provider. Indexing may still be pending when a search runs. `operations.rs` and `blocking.rs` print search results without requiring an immediate hit; `memory.rs` requires its saved key to appear. +## renew_login.rs + +The [renew_login.rs](renew_login.rs) example uses a stored login profile to read +the `preference` memory key. Select a namespace that the login can access: + +```bash +loom login --profile team +LOOM_NAMESPACE=my-namespace cargo run --manifest-path sdk/rust/Cargo.toml --example renew_login -- team +``` + +The profile supplies the server and tokens. The profile argument defaults to +`default`; `LOOM_NAMESPACE` has no default and must be nonblank. The example +prints `found: true` or `found: false`. + ## memory.rs The [memory.rs](memory.rs) example saves a value under an agent identity, reads