Merge main CI prerequisites into Lance beta19 update

This commit is contained in:
Xuanwo
2026-11-12 16:26:00 +00:00
15 changed files with 282 additions and 45 deletions
+9 -4
View File
@@ -154,6 +154,8 @@ jobs:
- uses: actions-rust-lang/setup-rust-toolchain@v1
with:
toolchain: "stable"
# The explicit cache below runs after lock removal and only saves on main.
cache: false
# Remove cargo.lock to force a fresh build
- name: Remove Cargo.lock
run: rm -f Cargo.lock
@@ -295,10 +297,12 @@ jobs:
run: CARGO_ARGS="--profile ci" make -C ./lancedb remote-tests
macos:
name: ${{ matrix.phase == 'tests' && format('macos ({0})', matrix.mac-runner) || format('macos-doc ({0})', matrix.mac-runner) }}
timeout-minutes: 60
strategy:
matrix:
mac-runner: ["macos-15", "macos-26"]
phase: [tests, doc]
runs-on: "${{ matrix.mac-runner }}"
defaults:
run:
@@ -320,16 +324,17 @@ jobs:
- name: Install dependencies
run: brew install protobuf
- name: Run tests
env:
CARGO_TEST_TARGETS: ${{ matrix.phase == 'doc' && '--doc' || '--lib --tests' }}
run: |
# Don't run the s3 integration tests since docker isn't available
# on this image.
ALL_FEATURES=`cargo metadata --format-version=1 --no-deps \
| jq -r '.packages[] | .features | keys | .[]' \
| grep -v s3-test | sort | uniq | paste -s -d "," -`
# Run doctests before test binaries fill the runner disk. Examples are
# already built by the Linux job, so avoid retaining them here.
cargo test --profile ci --features $ALL_FEATURES --locked --doc
cargo test --profile ci --features $ALL_FEATURES --locked --lib --tests
# Separate jobs give each phase its own time and disk budget. Examples
# are already built by the Linux job, so avoid retaining them here.
cargo test --profile ci --features $ALL_FEATURES --locked $CARGO_TEST_TARGETS
windows:
strategy:
+2 -1
View File
@@ -54,6 +54,7 @@ def main() -> int:
["cargo", "metadata", "--format-version=1", "--no-deps", "--all-features"],
stdout=subprocess.PIPE,
text=True,
check=False,
)
if metadata.returncode:
return metadata.returncode
@@ -68,7 +69,7 @@ def main() -> int:
"--tests",
# Bound simultaneous compiler/linker temporary outputs as well as retained files.
"--jobs",
"1",
"2",
"--message-format=json,json-diagnostic-rendered-ansi",
]
cleanup_failed = False
+2 -2
View File
@@ -282,7 +282,7 @@ maybeDescribe("DynamoDB Lock", () => {
});
it("can be used to configure a DynamoDB table for commit log", async () => {
const uri = `s3+ddb://${bucket.name}/test?ddbTableName=${commitTable.name}`;
const uri = `s3+ddb://${bucket.name}/concurrent-appends?ddbTableName=${commitTable.name}`;
const db = await connect(uri, {
storageOptions: CONFIG,
readConsistencyInterval: 0,
@@ -307,7 +307,7 @@ maybeDescribe("DynamoDB Lock", () => {
});
it("clears dynamodb state after dropping all tables", async () => {
const uri = `s3+ddb://${bucket.name}/test?ddbTableName=${commitTable.name}`;
const uri = `s3+ddb://${bucket.name}/drop-all-tables?ddbTableName=${commitTable.name}`;
const db = await connect(uri, {
storageOptions: CONFIG,
readConsistencyInterval: 0,
+6 -1
View File
@@ -228,7 +228,12 @@ class Connection(object):
self, name: str, namespace_path: Optional[List[str]] = None
) -> None: ...
async def create_secret(
self, name: str, value: str, namespace_path: Optional[List[str]] = None
self,
name: str,
value: str,
namespace_path: Optional[List[str]] = None,
*,
exist_ok: bool = False,
) -> None: ...
async def alter_secret(
self, name: str, value: str, namespace_path: Optional[List[str]] = None
+40 -8
View File
@@ -1158,14 +1158,24 @@ class DBConnection(EnforceOverrides):
)
def create_secret(
self, name: str, value: str, *, namespace_path: Optional[List[str]] = None
self,
name: str,
value: str,
*,
exist_ok: bool = False,
namespace_path: Optional[List[str]] = None,
) -> None:
"""Create a named Secret in this database.
Fails if the name is taken, so a create never silently becomes a
rotation. Nothing reads the value back: it is bound to a Function by
Fails if the name is taken unless ``exist_ok=True``, which leaves the
existing value unchanged. Use :meth:`alter_secret` to rotate a Secret.
Nothing reads the value back: it is bound to a Function by
name and resolved by the service when that Function runs. Local
connections raise ``NotImplementedError``.
Examples
--------
>>> db.create_secret("api-key", "credential", exist_ok=True) # doctest: +SKIP
"""
raise NotImplementedError(
_append_doc_url(
@@ -2492,9 +2502,18 @@ class LanceDBConnection(DBConnection):
@override
def create_secret(
self, name: str, value: str, *, namespace_path: Optional[List[str]] = None
self,
name: str,
value: str,
*,
exist_ok: bool = False,
namespace_path: Optional[List[str]] = None,
) -> None:
LOOP.run(self._conn.create_secret(name, value, namespace_path=namespace_path))
LOOP.run(
self._conn.create_secret(
name, value, exist_ok=exist_ok, namespace_path=namespace_path
)
)
@override
def alter_secret(
@@ -3949,17 +3968,30 @@ class AsyncConnection(object):
)
async def create_secret(
self, name: str, value: str, *, namespace_path: Optional[List[str]] = None
self,
name: str,
value: str,
*,
exist_ok: bool = False,
namespace_path: Optional[List[str]] = None,
) -> None:
"""Create a named Secret in this database.
Fails if the name is taken, so a create never silently becomes a
rotation. Nothing reads the value back.
Fails if the name is taken unless ``exist_ok=True``, which leaves the
existing value unchanged. Use :meth:`alter_secret` to rotate a Secret.
Nothing reads the value back.
Examples
--------
>>> await db.create_secret( # doctest: +SKIP
... "api-key", "credential", exist_ok=True
... )
"""
await self._inner.create_secret(
validate_secret_name(name),
value,
list(validate_namespace_path(namespace_path)),
exist_ok=exist_ok,
)
async def alter_secret(
+11 -2
View File
@@ -1129,9 +1129,18 @@ class RemoteDBConnection(DBConnection):
@override
def create_secret(
self, name: str, value: str, *, namespace_path: Optional[List[str]] = None
self,
name: str,
value: str,
*,
exist_ok: bool = False,
namespace_path: Optional[List[str]] = None,
) -> None:
LOOP.run(self._conn.create_secret(name, value, namespace_path=namespace_path))
LOOP.run(
self._conn.create_secret(
name, value, exist_ok=exist_ok, namespace_path=namespace_path
)
)
@override
def alter_secret(
+50
View File
@@ -293,6 +293,56 @@ def test_parameters_reach_the_server_as_the_values_that_were_sent():
assert echoed.column("k").to_pylist() == [10]
@pytest.mark.asyncio
@pytest.mark.parametrize("asynchronous", [False, True])
@pytest.mark.parametrize(
("exist_ok", "status"),
[
(None, "created"),
(False, "created"),
(True, "created"),
(True, "already_exists"),
],
)
async def test_create_secret_exist_ok_reaches_sql(asynchronous, exist_ok, status):
flight = pytest.importorskip("pyarrow.flight")
class SecretServer(flight.FlightServerBase):
def __init__(self):
super().__init__("grpc://127.0.0.1:0")
self.writes = []
def do_exchange(self, context, descriptor, reader, writer):
self.writes.append((descriptor.command, reader.read_all()))
result = pa.table({"status": [status]})
writer.begin(result.schema)
writer.write_table(result)
writer.close()
with SecretServer() as server:
options = {
"api_key": "test-key",
"host_override": "http://localhost:10024",
"sql_host_override": f"grpc://127.0.0.1:{server.port}",
}
kwargs = {"namespace_path": ["team", "production"]}
if exist_ok is not None:
kwargs["exist_ok"] = exist_ok
if asynchronous:
db = await lancedb.connect_async("db://analytics", **options)
await db.create_secret("api-key", "credential's value", **kwargs)
else:
db = lancedb.connect("db://analytics", **options)
db.create_secret("api-key", "credential's value", **kwargs)
((command, parameters),) = server.writes
prefix = "CREATE SECRET IF NOT EXISTS" if exist_ok else "CREATE SECRET"
sql = f'{prefix} "api-key" TYPE = GENERIC_STRING SECRET_STRING = $1'
assert sql.encode() in command
assert b"credential's value" not in command
assert parameters.column(0).to_pylist() == ["credential's value"]
@pytest.mark.parametrize("job_id", [None, "sql-job-1"])
def test_sql_input_error_metadata_crosses_native_boundary(job_id):
flight = pytest.importorskip("pyarrow.flight")
+3 -1
View File
@@ -1036,18 +1036,20 @@ impl Connection {
})
}
#[pyo3(signature = (name, value, namespace_path=None))]
#[pyo3(signature = (name, value, namespace_path=None, *, exist_ok=false))]
pub fn create_secret(
self_: PyRef<'_, Self>,
name: String,
value: String,
namespace_path: Option<Vec<String>>,
exist_ok: bool,
) -> PyResult<Bound<'_, PyAny>> {
let inner = self_.get_inner()?.clone();
let namespace_path = namespace_path.unwrap_or_default();
future_into_py(self_.py(), async move {
inner
.create_secret(name, value, &namespace_path)
.exist_ok(exist_ok)
.await
.infer_error()
})
+21 -8
View File
@@ -51,8 +51,11 @@ pub use lance_file::version::LanceFileVersion;
use lance_io::object_store::StorageOptions;
use lance_io::object_store::{StorageOptionsAccessor, StorageOptionsProvider};
mod create_secret;
mod create_table;
pub use create_secret::CreateSecretBuilder;
pub(crate) fn merge_storage_options(
store_params: &mut ObjectStoreParams,
pairs: impl IntoIterator<Item = (String, String)>,
@@ -853,20 +856,30 @@ impl Connection {
/// Create a named Secret in this database.
///
/// Fails if the name is taken, so a create can never silently become a
/// rotation. There is no API that reads a stored credential back; the only
/// Fails if the name is taken unless [`CreateSecretBuilder::exist_ok`] is true,
/// in which case the existing value is left unchanged. There is no API that
/// reads a stored credential back; the only
/// consumer is a Function that binds the Secret by name. LanceDB Embedded databases
/// return [`Error::NotSupported`].
pub async fn create_secret(
///
/// ```
/// # async fn example(connection: &lancedb::Connection) -> lancedb::Result<()> {
/// connection.create_secret("api-key", "credential", &[]).exist_ok(true).await?;
/// # Ok(())
/// # }
/// ```
pub fn create_secret(
&self,
name: impl AsRef<str>,
value: impl AsRef<str>,
namespace_path: &[String],
) -> Result<()> {
validate_secret_reference(name.as_ref(), namespace_path)?;
self.internal
.create_secret(name.as_ref(), value.as_ref(), namespace_path)
.await
) -> CreateSecretBuilder {
CreateSecretBuilder::new(
self.internal.clone(),
name.as_ref().to_owned(),
value.as_ref().to_owned(),
namespace_path.to_vec(),
)
}
/// Replace the credential behind an existing Secret.
@@ -0,0 +1,61 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
use std::future::{Future, IntoFuture};
use std::pin::Pin;
use std::sync::Arc;
use crate::Result;
use crate::database::Database;
use crate::utils::validate_secret_reference;
/// Configure creation of a named Secret with [`super::Connection::create_secret`].
#[must_use]
pub struct CreateSecretBuilder {
database: Arc<dyn Database>,
name: String,
value: String,
namespace_path: Vec<String>,
exist_ok: bool,
}
impl CreateSecretBuilder {
pub(super) fn new(
database: Arc<dyn Database>,
name: String,
value: String,
namespace_path: Vec<String>,
) -> Self {
Self {
database,
name,
value,
namespace_path,
exist_ok: false,
}
}
/// Succeed without changing the stored value when the Secret already exists.
/// Defaults to false, which reports an error for an existing name.
pub fn exist_ok(mut self, exist_ok: bool) -> Self {
self.exist_ok = exist_ok;
self
}
/// Create the Secret, preserving any existing value when `exist_ok` is true.
pub async fn execute(self) -> Result<()> {
validate_secret_reference(&self.name, &self.namespace_path)?;
self.database
.create_secret(&self.name, &self.value, &self.namespace_path, self.exist_ok)
.await
}
}
impl IntoFuture for CreateSecretBuilder {
type Output = Result<()>;
type IntoFuture = Pin<Box<dyn Future<Output = Self::Output> + Send>>;
fn into_future(self) -> Self::IntoFuture {
Box::pin(self.execute())
}
}
+3 -2
View File
@@ -635,13 +635,14 @@ pub trait Database:
secret_catalog_not_supported()
}
/// Create a named Secret in this database. Fails if the name is taken, so
/// a create can never silently become a rotation.
/// Create a named Secret in this database. If the name is taken, fail unless
/// `exist_ok` is true, in which case the stored value is left unchanged.
async fn create_secret(
&self,
_name: &str,
_value: &str,
_namespace_path: &[String],
_exist_ok: bool,
) -> Result<()> {
secret_catalog_not_supported()
}
+9 -3
View File
@@ -44,8 +44,8 @@ use super::client::{
ClientConfig, HeaderProvider, HttpSend, ID_DELIMITER, RequestResultExt, RestfulLanceDbClient,
Sender,
};
use super::sql::SqlClient;
use super::sql::materialized_view::quote_identifier;
use super::sql::{SecretWriteOperation, SqlClient};
use super::storage_integration as integration_sql;
use super::table::RemoteTable;
use super::util::parse_server_version;
@@ -1044,11 +1044,17 @@ impl<S: HttpSend> Database for RemoteDatabase<S> {
name: &str,
value: &str,
namespace_path: &[String],
exist_ok: bool,
) -> Result<()> {
crate::utils::validate_secret_name(name)?;
validate_namespace(namespace_path)?;
self.sql_client()?
.write_secret(name, value, namespace_path, true)
.write_secret(
name,
value,
namespace_path,
SecretWriteOperation::Create { exist_ok },
)
.await
.map_err(direct_catalog_resource_error)
}
@@ -1056,7 +1062,7 @@ impl<S: HttpSend> Database for RemoteDatabase<S> {
crate::utils::validate_secret_name(name)?;
validate_namespace(namespace_path)?;
self.sql_client()?
.write_secret(name, value, namespace_path, false)
.write_secret(name, value, namespace_path, SecretWriteOperation::Alter)
.await
.map_err(direct_catalog_resource_error)
}
+1
View File
@@ -40,6 +40,7 @@ mod function;
pub(super) mod materialized_view;
mod objects;
mod secret;
pub(super) use secret::SecretWriteOperation;
mod stream;
mod view;
+21 -8
View File
@@ -13,6 +13,12 @@ use arrow_array::{Array, Int64Array, RecordBatch, StringArray};
use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};
use futures::TryStreamExt;
use std::sync::Arc;
pub(in crate::remote) enum SecretWriteOperation {
Create { exist_ok: bool },
Alter,
}
fn secret_info(batches: Vec<RecordBatch>) -> Result<SecretInfo> {
if batches.iter().map(RecordBatch::num_rows).sum::<usize>() != 1 {
return Err(Error::Runtime {
@@ -47,10 +53,21 @@ impl SqlClient {
name: &str,
value: &str,
namespace: &[String],
create: bool,
operation: SecretWriteOperation,
) -> Result<()> {
validate_secret_name(name)?;
validate_namespace(namespace)?;
let (prefix, assignment) = match operation {
SecretWriteOperation::Create { exist_ok } => (
if exist_ok {
"CREATE SECRET IF NOT EXISTS"
} else {
"CREATE SECRET"
},
"TYPE = GENERIC_STRING ",
),
SecretWriteOperation::Alter => ("ALTER SECRET", "SET "),
};
let parameters = RecordBatch::try_from_iter(vec![(
"",
Arc::new(StringArray::from(vec![value])) as arrow_array::ArrayRef,
@@ -61,14 +78,10 @@ impl SqlClient {
self.object_job(
ExecuteQueryRequest {
query: format!(
"{} SECRET {} {}SECRET_STRING = $1",
if create { "CREATE" } else { "ALTER" },
"{} {} {}SECRET_STRING = $1",
prefix,
quote_identifier(name),
if create {
"TYPE = GENERIC_STRING "
} else {
"SET "
}
assignment
),
default_namespace_path: namespace.to_vec(),
parameters: Some(parameters),
+43 -5
View File
@@ -3214,29 +3214,55 @@ async fn secret_writes_bind_credentials_and_never_put_them_in_sql() {
};
let exchanges = service.exchanges.clone();
let statements = service.statements.clone();
let headers = service.headers.clone();
let (client, shutdown) = start_sql_service(service, ClientConfig::default()).await;
let db = RemoteDatabase::new_mock(|request| -> http::Response<String> {
panic!("unexpected REST request: {}", request.url().path());
})
.with_sql_client(client);
db.create_secret("api-key", "credential's value", &["team".into()])
let connection = Connection::new(
Arc::new(db),
Arc::new(crate::embeddings::MemoryRegistry::new()),
);
connection
.create_secret("api-key", "credential's value", &["team".into()])
.await
.unwrap();
db.alter_secret("api-key", "rotated-value", &["team".into()])
connection
.create_secret("api-key", "ignored-value", &["team".into()])
.exist_ok(true)
.await
.unwrap();
connection
.alter_secret("api-key", "rotated-value", &["team".into()])
.await
.unwrap();
connection
.drop_secret("api-key", &["team".into()])
.await
.unwrap();
db.drop_secret("api-key", &["team".into()]).await.unwrap();
assert_eq!(
statements.lock().unwrap().as_slice(),
["DROP SECRET IF EXISTS \"api-key\""]
);
let seen = exchanges.lock().unwrap();
assert_eq!(seen.len(), 2);
assert_eq!(seen.len(), 3);
assert_eq!(
seen[0].0,
"CREATE SECRET \"api-key\" TYPE = GENERIC_STRING SECRET_STRING = $1"
);
assert_eq!(seen[1].0, "ALTER SECRET \"api-key\" SET SECRET_STRING = $1");
assert_eq!(
seen[1].0,
"CREATE SECRET IF NOT EXISTS \"api-key\" TYPE = GENERIC_STRING SECRET_STRING = $1"
);
assert_eq!(seen[2].0, "ALTER SECRET \"api-key\" SET SECRET_STRING = $1");
assert!(
headers
.lock()
.unwrap()
.iter()
.all(|header| header.namespace_path == "team")
);
assert_eq!(
seen[0]
.1
@@ -3259,6 +3285,18 @@ async fn secret_writes_bind_credentials_and_never_put_them_in_sql() {
.downcast_ref::<StringArray>()
.unwrap()
.value(0),
"ignored-value"
);
assert_eq!(
seen[2]
.1
.as_ref()
.unwrap()
.column(0)
.as_any()
.downcast_ref::<StringArray>()
.unwrap()
.value(0),
"rotated-value"
);
shutdown.send(()).unwrap();