mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-11-24 05:07:10 +01:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1c779c4731 |
No files matched your search
@@ -33,7 +33,7 @@ jobs:
|
||||
|
||||
# Initializes the CodeQL tools for scanning.
|
||||
- name: Initialize CodeQL
|
||||
uses: github/codeql-action/init@v4.39.3
|
||||
uses: github/codeql-action/init@v4.39.4
|
||||
# Override language selection by uncommenting this and choosing your languages
|
||||
with:
|
||||
languages: go
|
||||
@@ -41,7 +41,7 @@ jobs:
|
||||
# Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
|
||||
# If this step fails, then you should remove it and run the build manually (see below).
|
||||
- name: Autobuild
|
||||
uses: github/codeql-action/autobuild@v4.39.3
|
||||
uses: github/codeql-action/autobuild@v4.39.4
|
||||
|
||||
# ℹ️ Command-line programs to run using the OS shell.
|
||||
# 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun
|
||||
@@ -55,4 +55,4 @@ jobs:
|
||||
# make release
|
||||
|
||||
- name: Perform CodeQL Analysis
|
||||
uses: github/codeql-action/analyze@v4.39.3
|
||||
uses: github/codeql-action/analyze@v4.39.4
|
||||
@@ -434,7 +434,7 @@ jobs:
|
||||
output: trivy-results.sarif
|
||||
exit-code: '0'
|
||||
- name: Upload Trivy scan results to GitHub Security
|
||||
uses: github/codeql-action/upload-sarif@v4.39.3
|
||||
uses: github/codeql-action/upload-sarif@v4.39.4
|
||||
if: always()
|
||||
with:
|
||||
sarif_file: trivy-results.sarif
|
||||
|
||||
@@ -515,7 +515,7 @@ jobs:
|
||||
|
||||
- name: Upload Trivy scan results to GitHub Security
|
||||
if: always()
|
||||
uses: github/codeql-action/upload-sarif@v4.39.3
|
||||
uses: github/codeql-action/upload-sarif@v4.39.4
|
||||
with:
|
||||
sarif_file: trivy-results.sarif
|
||||
category: trivy-${{ matrix.variant }}
|
||||
|
||||
@@ -38,46 +38,3 @@ For mutual TLS, configure `[grpc.vector]` for the engine's server certificate, `
|
||||
Run the Lance maintenance worker against the cluster's admin to build and update ANN indexes. Queries can scan data that has not been indexed yet. See the [maintenance worker documentation](../seaweed-worker/README.md) and [Helm chart](../k8s/charts/seaweedfs/README.md) for deployment settings.
|
||||
|
||||
The integration suite at `test/s3vectors` runs the same API and observability checks against both Go and Rust volume servers, including mutual TLS, signed volume reads, and encrypted volume data.
|
||||
|
||||
## Search indexed data only
|
||||
|
||||
The default search includes recent writes by scanning data that indexes do not
|
||||
cover yet. To exclude that data, send `x-seaweedfs-vector-search-mode: indexed-only`
|
||||
on `QueryVectors`. Omit the header, or set it to `all`, for the default behavior.
|
||||
This is a SeaweedFS extension. With SigV4, the header must be signed.
|
||||
|
||||
For example, inject it before boto3 signs the request:
|
||||
|
||||
```python
|
||||
def indexed_only(request, **kwargs):
|
||||
request.headers["x-seaweedfs-vector-search-mode"] = "indexed-only"
|
||||
|
||||
client.meta.events.register("before-sign.s3vectors.QueryVectors", indexed_only)
|
||||
try:
|
||||
result = client.query_vectors(
|
||||
vectorBucketName="embeddings", indexName="articles",
|
||||
queryVector={"float32": embedding}, topK=10,
|
||||
)
|
||||
finally:
|
||||
client.meta.events.unregister("before-sign.s3vectors.QueryVectors", indexed_only)
|
||||
```
|
||||
|
||||
Indexed-only searches use the intersection of vector index coverage and the
|
||||
coverage of each metadata index the filter requires, at one table version. Filters
|
||||
must be conjunctions of string equality or `$in` predicates on ready indexed
|
||||
metadata keys. An unavailable index or unsupported filter returns
|
||||
`ValidationException`. A valid index with no eligible data returns an empty list.
|
||||
A vector engine predating this extension returns `ServiceUnavailableException`;
|
||||
the gateway never falls back to a full search.
|
||||
|
||||
The response includes `x-seaweedfs-vector-search-mode: indexed-only`,
|
||||
`x-seaweedfs-vector-data-excluded: true|false`, and
|
||||
`x-seaweedfs-vector-excluded-fragments`. The exclusion count describes coverage,
|
||||
not the number of matching vectors. New writes, updates, and rewritten fragments
|
||||
from compaction can be omitted until indexing catches up. Current deletions still
|
||||
apply. Exact-search fallbacks stay within the eligible data; this option does not
|
||||
guarantee a fixed latency.
|
||||
|
||||
Enterprise gateways send this mode to the shared single-engine backend using
|
||||
`QueryIndexedVectors`; ordinary searches retain distributed routing. The shared
|
||||
`Query` structure and existing query request/response messages are unchanged.
|
||||
@@ -149,52 +149,6 @@ mod tests {
|
||||
assert!(hits[0].distance < 1e-6);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn indexed_only_skips_new_rows_until_indexed_and_honors_deletes() {
|
||||
let dir = TempDir::new().unwrap();
|
||||
let mut dataset = indexed_dataset(&dir, &["a"; 64]).await;
|
||||
append_dataset(&mut dataset, &[vec![9.0; DIM]], &["b"]).await;
|
||||
let table = VectorTable::resolve(&dataset, None, None).unwrap();
|
||||
let query = Query {
|
||||
vector: vec![9.0; DIM],
|
||||
k: 100,
|
||||
filter: None,
|
||||
postfilter: false,
|
||||
distance: DistanceType::L2,
|
||||
nprobes: Some(4),
|
||||
index_segments: None,
|
||||
fragments: None,
|
||||
exact_match_limit: None,
|
||||
};
|
||||
let (hits, excluded) = crate::query::indexed_only(&dataset, &table, &query)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(excluded, 1);
|
||||
assert_eq!(hits.len(), 64);
|
||||
assert!(hits.iter().all(|h| h.key != "k64"));
|
||||
dataset
|
||||
.optimize_indices(&lance_index::optimize::OptimizeOptions::append())
|
||||
.await
|
||||
.unwrap();
|
||||
let (hits, excluded) = crate::query::indexed_only(&dataset, &table, &query)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(excluded, 0);
|
||||
assert_eq!(hits[0].key, "k64");
|
||||
dataset.delete("key = 'k64'").await.unwrap();
|
||||
let (hits, _) = crate::query::indexed_only(&dataset, &table, &query)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(hits.iter().all(|h| h.key != "k64"));
|
||||
let missing = write_dataset(&TempDir::new().unwrap(), &vectors(4, DIM), &["a"; 4]).await;
|
||||
assert!(
|
||||
crate::query::indexed_only(&missing, &table, &query)
|
||||
.await
|
||||
.unwrap_err()
|
||||
.is::<crate::query::IndexedOnlyError>()
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn prefiltered_ann_matches_filtered_flat() {
|
||||
let dir = TempDir::new().unwrap();
|
||||
|
||||
@@ -84,20 +84,6 @@ pub(crate) fn rewrite(filter: Expr, ready: &HashMap<String, String>) -> (Expr, V
|
||||
(rewritten.unwrap_or(lit(true)), indexed)
|
||||
}
|
||||
|
||||
pub(crate) fn columns(dataset: &Dataset, filter: &str) -> Result<Vec<String>> {
|
||||
let mut scanner = dataset.scan();
|
||||
scanner.filter(filter)?;
|
||||
let expr = scanner.get_expr_filter()?.ok_or_else(|| {
|
||||
crate::query::IndexedOnlyError("indexed-only requires an indexed metadata filter".into())
|
||||
})?;
|
||||
let count = split_conjunction_owned(expr.clone()).len();
|
||||
let (_, indexed) = rewrite(expr, &ready_columns(dataset));
|
||||
if indexed.len() != count {
|
||||
return Err(crate::query::IndexedOnlyError("indexed-only supports conjunctions of string $eq/$in filters on ready metadata indexes".into()).into());
|
||||
}
|
||||
Ok(indexed.into_iter().map(|i| i.column).collect())
|
||||
}
|
||||
|
||||
fn and(left: Option<Expr>, right: Expr) -> Expr {
|
||||
match left {
|
||||
Some(left) => Expr::BinaryExpr(BinaryExpr::new(
|
||||
@@ -638,7 +624,7 @@ mod tests {
|
||||
let few = |q: Query| {
|
||||
let (dataset, table) = (&dataset, &table);
|
||||
async move {
|
||||
query::few_indexed_matches(dataset, table, &q, None)
|
||||
query::few_indexed_matches(dataset, table, &q)
|
||||
.await
|
||||
.unwrap()
|
||||
}
|
||||
@@ -671,99 +657,6 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn indexed_only_intersects_metadata_and_vector_coverage() {
|
||||
use futures::TryStreamExt;
|
||||
let dir = TempDir::new().unwrap();
|
||||
let mut dataset = dataset(&dir, 300).await;
|
||||
let batches = dataset
|
||||
.scan()
|
||||
.try_into_stream()
|
||||
.await
|
||||
.unwrap()
|
||||
.try_collect::<Vec<_>>()
|
||||
.await
|
||||
.unwrap();
|
||||
let batch = &batches[0];
|
||||
let mut columns = batch.columns().to_vec();
|
||||
let key = batch.schema().index_of("key").unwrap();
|
||||
columns[key] = Arc::new(StringArray::from(
|
||||
(0..batch.num_rows())
|
||||
.map(|i| format!("new{i}"))
|
||||
.collect::<Vec<_>>(),
|
||||
));
|
||||
let batch = RecordBatch::try_new(batch.schema(), columns).unwrap();
|
||||
let reader = RecordBatchIterator::new(vec![Ok(batch.clone())], batch.schema());
|
||||
dataset.append(reader, None).await.unwrap();
|
||||
dataset
|
||||
.optimize_indices(&lance_index::optimize::OptimizeOptions::append())
|
||||
.await
|
||||
.unwrap();
|
||||
let table = VectorTable::resolve(&dataset, None, None).unwrap();
|
||||
let query = Query {
|
||||
vector: vec![1.0, 2.0, 3.0, 4.0],
|
||||
k: 1000,
|
||||
filter: Some(eq("author", "\"rare\"")),
|
||||
postfilter: false,
|
||||
distance: DistanceType::L2,
|
||||
nprobes: Some(4),
|
||||
index_segments: None,
|
||||
fragments: None,
|
||||
exact_match_limit: None,
|
||||
};
|
||||
let reader = RecordBatchIterator::new(vec![Ok(batch.clone())], batch.schema());
|
||||
dataset.append(reader, None).await.unwrap();
|
||||
crate::index::build(&mut dataset, "vector", crate::index::INDEX_NAME, 4, true)
|
||||
.await
|
||||
.unwrap();
|
||||
let tail = Query {
|
||||
fragments: Some(vec![dataset.fragments().last().unwrap().id]),
|
||||
..query.clone()
|
||||
};
|
||||
let (hits, excluded) = query::indexed_only(&dataset, &table, &tail).await.unwrap();
|
||||
assert!(hits.is_empty());
|
||||
assert_eq!(excluded, 1);
|
||||
for limit in [None, Some(0)] {
|
||||
let query = Query {
|
||||
exact_match_limit: limit,
|
||||
..query.clone()
|
||||
};
|
||||
let all = query::ann(&dataset, &table, &query).await.unwrap();
|
||||
let (indexed, excluded) = query::indexed_only(&dataset, &table, &query).await.unwrap();
|
||||
assert_eq!(excluded, 1);
|
||||
assert!(all.len() > indexed.len());
|
||||
assert!(indexed.len() >= 30);
|
||||
}
|
||||
for file in &dataset.fragments().last().unwrap().files {
|
||||
std::fs::remove_file(dir.path().join("data").join(&file.path)).unwrap();
|
||||
}
|
||||
let dataset = Dataset::open(dir.path().to_str().unwrap()).await.unwrap();
|
||||
assert!(query::ann(&dataset, &table, &query).await.is_err());
|
||||
for limit in [None, Some(0)] {
|
||||
let query = Query {
|
||||
exact_match_limit: limit,
|
||||
..query.clone()
|
||||
};
|
||||
assert!(query::indexed_only(&dataset, &table, &query).await.is_ok());
|
||||
}
|
||||
for filter in [
|
||||
eq("other", "\"rare\""),
|
||||
eq("author", "true"),
|
||||
format!("NOT {}", eq("author", "\"rare\"")),
|
||||
] {
|
||||
let query = Query {
|
||||
filter: Some(filter),
|
||||
..query.clone()
|
||||
};
|
||||
assert!(
|
||||
query::indexed_only(&dataset, &table, &query)
|
||||
.await
|
||||
.unwrap_err()
|
||||
.is::<query::IndexedOnlyError>()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn the_plan_reads_the_scalar_index() {
|
||||
let dir = TempDir::new().unwrap();
|
||||
|
||||
@@ -6,11 +6,8 @@ use arrow_array::{Array, Float32Array, RecordBatch, StringArray, UInt64Array};
|
||||
use futures::TryStreamExt;
|
||||
use lance::Dataset;
|
||||
use lance::dataset::scanner::Scanner;
|
||||
use lance::index::DatasetIndexExt;
|
||||
use lance_linalg::distance::DistanceType;
|
||||
use lance_table::format::Fragment;
|
||||
use roaring::RoaringBitmap;
|
||||
use std::collections::HashSet;
|
||||
|
||||
use crate::table::VectorTable;
|
||||
|
||||
@@ -63,7 +60,7 @@ pub struct Hit {
|
||||
|
||||
/// Exact top-K over every fragment, ignoring any index.
|
||||
pub async fn flat(dataset: &Dataset, table: &VectorTable, query: &Query) -> Result<Vec<Hit>> {
|
||||
run(scanner(dataset, table, query, false, None).await?.0, table).await
|
||||
run(scanner(dataset, table, query, false).await?.0, table).await
|
||||
}
|
||||
|
||||
/// Top-K with the ANN index where it covers the fragment and a flat pass over
|
||||
@@ -78,152 +75,35 @@ pub async fn flat(dataset: &Dataset, table: &VectorTable, query: &Query) -> Resu
|
||||
/// they are scored exactly to begin with. The decision is per scope, so
|
||||
/// exact answers of several scopes merge into the exact answer.
|
||||
pub async fn ann(dataset: &Dataset, table: &VectorTable, query: &Query) -> Result<Vec<Hit>> {
|
||||
ann_with_scope(dataset, table, query, None).await
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct IndexedOnlyError(pub String);
|
||||
|
||||
impl std::fmt::Display for IndexedOnlyError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_str(&self.0)
|
||||
if few_indexed_matches(dataset, table, query).await? {
|
||||
return exact_in_scope(dataset, table, query).await;
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for IndexedOnlyError {}
|
||||
|
||||
pub async fn indexed_only(
|
||||
dataset: &Dataset,
|
||||
table: &VectorTable,
|
||||
query: &Query,
|
||||
) -> Result<(Vec<Hit>, usize)> {
|
||||
if query.postfilter {
|
||||
return Err(IndexedOnlyError("indexed-only requires prefiltering".into()).into());
|
||||
}
|
||||
let mut eligible = indexed_fragments(
|
||||
dataset,
|
||||
&table.vector_column,
|
||||
query.index_segments.as_deref(),
|
||||
)
|
||||
.await?;
|
||||
if let Some(filter) = &query.filter {
|
||||
for column in crate::indexed_filter::columns(dataset, filter)? {
|
||||
eligible &= indexed_fragments(dataset, &column, None).await?;
|
||||
}
|
||||
}
|
||||
let original = scope(dataset, table, query, None).await?;
|
||||
let live: RoaringBitmap = dataset.fragments().iter().map(|f| f.id as u32).collect();
|
||||
let original = original
|
||||
.map(|ids| {
|
||||
ids.into_iter()
|
||||
.map(|id| id as u32)
|
||||
.collect::<RoaringBitmap>()
|
||||
})
|
||||
.unwrap_or(live.clone())
|
||||
& live;
|
||||
eligible &= &original;
|
||||
let excluded = (&original - &eligible).len() as usize;
|
||||
if eligible.is_empty() {
|
||||
return Ok((Vec::new(), excluded));
|
||||
}
|
||||
if excluded == 0
|
||||
&& query.filter.is_none()
|
||||
&& query.index_segments.is_none()
|
||||
&& query.fragments.is_none()
|
||||
{
|
||||
let hits = ann(dataset, table, query).await?;
|
||||
return if hits.len() < query.k {
|
||||
Ok((exact_in_scope(dataset, table, query, None).await?, 0))
|
||||
} else {
|
||||
Ok((hits, 0))
|
||||
};
|
||||
}
|
||||
let eligible: Vec<u64> = eligible.iter().map(u64::from).collect();
|
||||
let hits = ann_with_scope(dataset, table, query, Some(&eligible)).await?;
|
||||
Ok((hits, excluded))
|
||||
}
|
||||
|
||||
async fn indexed_fragments(
|
||||
dataset: &Dataset,
|
||||
column: &str,
|
||||
selected: Option<&[uuid::Uuid]>,
|
||||
) -> Result<RoaringBitmap> {
|
||||
if selected.is_some_and(|ids| ids.is_empty()) {
|
||||
return Ok(RoaringBitmap::new());
|
||||
}
|
||||
let field = dataset
|
||||
.schema()
|
||||
.field(column)
|
||||
.with_context(|| format!("no such field {column}"))?;
|
||||
let mut covered = RoaringBitmap::new();
|
||||
let mut found = Vec::new();
|
||||
for index in dataset
|
||||
.load_indices()
|
||||
.await?
|
||||
.iter()
|
||||
.filter(|i| i.fields == [field.id])
|
||||
{
|
||||
if selected.is_some_and(|ids| !ids.contains(&index.uuid)) {
|
||||
continue;
|
||||
}
|
||||
let bitmap = index
|
||||
.fragment_bitmap
|
||||
.as_ref()
|
||||
.ok_or_else(|| IndexedOnlyError(format!("index coverage is unknown for {column}")))?;
|
||||
covered |= bitmap;
|
||||
found.push(index.uuid);
|
||||
}
|
||||
if found.is_empty() || selected.is_some_and(|ids| ids.iter().any(|id| !found.contains(id))) {
|
||||
return Err(IndexedOnlyError(format!("no usable index for {column}")).into());
|
||||
}
|
||||
Ok(covered)
|
||||
}
|
||||
|
||||
/// ANN and exact fallbacks restricted to the supplied fragments.
|
||||
pub async fn ann_with_scope(
|
||||
dataset: &Dataset,
|
||||
table: &VectorTable,
|
||||
query: &Query,
|
||||
restriction: Option<&[u64]>,
|
||||
) -> Result<Vec<Hit>> {
|
||||
if few_indexed_matches(dataset, table, query, restriction).await? {
|
||||
return exact_in_scope(dataset, table, query, restriction).await;
|
||||
}
|
||||
let (scanner, indexed) = scanner(dataset, table, query, true, restriction).await?;
|
||||
let (scanner, indexed) = scanner(dataset, table, query, true).await?;
|
||||
let hits = run(scanner, table).await?;
|
||||
let short_prefilter = (query.filter.is_some() || restriction.is_some())
|
||||
if indexed
|
||||
&& query.filter.is_some()
|
||||
&& !query.postfilter
|
||||
&& hits.len() < query.k;
|
||||
if indexed && (short_prefilter || hits.iter().any(|h| !h.distance.is_finite())) {
|
||||
return exact_in_scope(dataset, table, query, restriction).await;
|
||||
&& (hits.len() < query.k || hits.iter().any(|h| !h.distance.is_finite()))
|
||||
{
|
||||
return exact_in_scope(dataset, table, query).await;
|
||||
}
|
||||
Ok(hits)
|
||||
}
|
||||
|
||||
/// [`flat`] over what [`ann`] searches for `query`: the listed fragments plus
|
||||
/// the live coverage of the listed index segments, or the whole table.
|
||||
async fn exact_in_scope(
|
||||
dataset: &Dataset,
|
||||
table: &VectorTable,
|
||||
query: &Query,
|
||||
restriction: Option<&[u64]>,
|
||||
) -> Result<Vec<Hit>> {
|
||||
async fn exact_in_scope(dataset: &Dataset, table: &VectorTable, query: &Query) -> Result<Vec<Hit>> {
|
||||
let exact = Query {
|
||||
index_segments: None,
|
||||
fragments: scope(dataset, table, query, restriction).await?,
|
||||
fragments: scope(dataset, table, query).await?,
|
||||
..query.clone()
|
||||
};
|
||||
run(scanner(dataset, table, &exact, false, None).await?.0, table).await
|
||||
run(scanner(dataset, table, &exact, false).await?.0, table).await
|
||||
}
|
||||
|
||||
/// The fragments [`ann`] searches for `query`, or None for the whole table.
|
||||
async fn scope(
|
||||
dataset: &Dataset,
|
||||
table: &VectorTable,
|
||||
query: &Query,
|
||||
restriction: Option<&[u64]>,
|
||||
) -> Result<Option<Vec<u64>>> {
|
||||
let scope = match &query.index_segments {
|
||||
async fn scope(dataset: &Dataset, table: &VectorTable, query: &Query) -> Result<Option<Vec<u64>>> {
|
||||
Ok(match &query.index_segments {
|
||||
Some(segments) if !segments.is_empty() => {
|
||||
let mut ids = query.fragments.clone().unwrap_or_default();
|
||||
ids.extend(
|
||||
@@ -231,25 +111,8 @@ async fn scope(
|
||||
);
|
||||
Some(ids)
|
||||
}
|
||||
Some(_) => Some(query.fragments.clone().unwrap_or_default()),
|
||||
None => query.fragments.clone(),
|
||||
};
|
||||
Ok(restrict(scope, restriction))
|
||||
}
|
||||
|
||||
fn restrict(scope: Option<Vec<u64>>, restriction: Option<&[u64]>) -> Option<Vec<u64>> {
|
||||
match restriction {
|
||||
Some(ids) => {
|
||||
let scope = scope.map(|ids| ids.into_iter().collect::<HashSet<_>>());
|
||||
Some(
|
||||
ids.iter()
|
||||
.copied()
|
||||
.filter(|id| scope.as_ref().is_none_or(|scope| scope.contains(id)))
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
None => scope,
|
||||
}
|
||||
_ => query.fragments.clone(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether the rows of [`ann`]'s scope matching the filter's indexed
|
||||
@@ -259,7 +122,6 @@ pub(crate) async fn few_indexed_matches(
|
||||
dataset: &Dataset,
|
||||
table: &VectorTable,
|
||||
query: &Query,
|
||||
restriction: Option<&[u64]>,
|
||||
) -> Result<bool> {
|
||||
let limit = query.exact_match_limit.unwrap_or(DEFAULT_EXACT_MATCH_LIMIT);
|
||||
let Some(filter) = &query.filter else {
|
||||
@@ -281,7 +143,7 @@ pub(crate) async fn few_indexed_matches(
|
||||
if indexed.is_empty() {
|
||||
return Ok(false);
|
||||
}
|
||||
let scope = scope(dataset, table, query, restriction).await?;
|
||||
let scope = scope(dataset, table, query).await?;
|
||||
// An AND matches at most what its most selective indexed conjunct does.
|
||||
for conjunct in &indexed {
|
||||
let count =
|
||||
@@ -333,7 +195,6 @@ async fn scanner(
|
||||
table: &VectorTable,
|
||||
query: &Query,
|
||||
use_index: bool,
|
||||
restriction: Option<&[u64]>,
|
||||
) -> Result<(Scanner, bool)> {
|
||||
if query.vector.len() != table.dimension {
|
||||
bail!(
|
||||
@@ -386,13 +247,22 @@ async fn scanner(
|
||||
if use_index && !segments.is_empty() {
|
||||
scanner.with_index_segments(segments.to_vec())?;
|
||||
}
|
||||
let fragments = if use_index {
|
||||
scope(dataset, table, query, restriction).await?
|
||||
} else {
|
||||
restrict(query.fragments.clone(), restriction)
|
||||
};
|
||||
if let Some(ids) = fragments {
|
||||
let ids: HashSet<_> = ids.into_iter().collect();
|
||||
// Lance intersects the fragment list with the selected segments, so a
|
||||
// scoped scan must name the segment-covered fragments itself: the universe
|
||||
// is the listed ids plus the live coverage of the selected segments. An
|
||||
// empty universe (or an empty-segment, fragment-less assignment) scopes to
|
||||
// nothing — `with_fragments` with an empty list scans nothing.
|
||||
let mut wanted: Option<Vec<u64>> = query.fragments.clone();
|
||||
if let Some(ids) = &mut wanted {
|
||||
if use_index && !segments.is_empty() {
|
||||
ids.extend(
|
||||
crate::segments::covered_fragments(dataset, &table.vector_column, segments).await?,
|
||||
);
|
||||
}
|
||||
} else if use_index && query.index_segments.as_ref().is_some_and(|s| s.is_empty()) {
|
||||
wanted = Some(Vec::new());
|
||||
}
|
||||
if let Some(ids) = wanted {
|
||||
let frags: Vec<Fragment> = dataset
|
||||
.fragments()
|
||||
.iter()
|
||||
@@ -470,65 +340,6 @@ mod tests {
|
||||
a.iter().zip(b).map(|(x, y)| (x - y) * (x - y)).sum()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn indexed_only_scores_all_returned_distances() {
|
||||
let dir = TempDir::new().unwrap();
|
||||
let vectors: Vec<_> = (0..1024)
|
||||
.map(|i| {
|
||||
vec![
|
||||
(i / 64) as f32 * 100.0 + (i % 64) as f32 * 0.01,
|
||||
0.0,
|
||||
0.0,
|
||||
0.0,
|
||||
]
|
||||
})
|
||||
.collect();
|
||||
let mut dataset = write_dataset(&dir, &vectors, &vec!["a"; vectors.len()]).await;
|
||||
dataset
|
||||
.create_index(
|
||||
&["vector"],
|
||||
lance_index::IndexType::Vector,
|
||||
Some("vidx".into()),
|
||||
&lance::index::vector::VectorIndexParams::ivf_flat(16, DistanceType::L2),
|
||||
true,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
crate::testing::append_dataset(&mut dataset, &[vec![0.0; DIM]], &["late"]).await;
|
||||
let table = VectorTable::resolve(&dataset, None, None).unwrap();
|
||||
let mut query = Query {
|
||||
vector: vec![0.0; DIM],
|
||||
k: vectors.len(),
|
||||
filter: None,
|
||||
postfilter: false,
|
||||
distance: DistanceType::L2,
|
||||
nprobes: None,
|
||||
index_segments: None,
|
||||
fragments: None,
|
||||
exact_match_limit: None,
|
||||
};
|
||||
for nprobes in [None, Some(1)] {
|
||||
query.nprobes = nprobes;
|
||||
let (hits, excluded) = indexed_only(&dataset, &table, &query).await.unwrap();
|
||||
assert_eq!(excluded, 1);
|
||||
assert_eq!(hits.len(), vectors.len());
|
||||
for hit in hits {
|
||||
let index: usize = hit.key[1..].parse().unwrap();
|
||||
assert_eq!(hit.distance, l2(&query.vector, &vectors[index]));
|
||||
}
|
||||
}
|
||||
|
||||
dataset
|
||||
.optimize_indices(&lance_index::optimize::OptimizeOptions::append())
|
||||
.await
|
||||
.unwrap();
|
||||
query.k += 1;
|
||||
let (hits, excluded) = indexed_only(&dataset, &table, &query).await.unwrap();
|
||||
assert_eq!(excluded, 0);
|
||||
assert_eq!(hits.len(), query.k);
|
||||
assert!(hits.iter().all(|hit| hit.distance.is_finite()));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn flat_returns_exact_top_k() {
|
||||
let dir = TempDir::new().unwrap();
|
||||
@@ -829,12 +640,7 @@ mod tests {
|
||||
fragments: None,
|
||||
exact_match_limit: None,
|
||||
};
|
||||
assert!(
|
||||
!scanner(&dataset, &table, &query, true, None)
|
||||
.await
|
||||
.unwrap()
|
||||
.1
|
||||
);
|
||||
assert!(!scanner(&dataset, &table, &query, true).await.unwrap().1);
|
||||
crate::index::build(
|
||||
&mut dataset,
|
||||
&table.vector_column,
|
||||
@@ -844,11 +650,6 @@ mod tests {
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(
|
||||
scanner(&dataset, &table, &query, true, None)
|
||||
.await
|
||||
.unwrap()
|
||||
.1
|
||||
);
|
||||
assert!(scanner(&dataset, &table, &query, true).await.unwrap().1);
|
||||
}
|
||||
}
|
||||
@@ -195,46 +195,6 @@ mod tests {
|
||||
assert_eq!(got, want);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn indexed_only_keeps_assigned_segments_and_excludes_tail_work() {
|
||||
let dir = TempDir::new().unwrap();
|
||||
let mut dataset = testing::write_dataset(&dir, &testing::vectors(64, 4), &["a"; 64]).await;
|
||||
crate::index::build(&mut dataset, "vector", crate::index::INDEX_NAME, 4, false)
|
||||
.await
|
||||
.unwrap();
|
||||
testing::append_dataset(&mut dataset, &testing::vectors(4, 4), &["b"; 4]).await;
|
||||
let table = VectorTable::resolve(&dataset, None, None).unwrap();
|
||||
let segments = index_segments(&dataset, "vector").await.unwrap();
|
||||
let query = Query {
|
||||
vector: vec![0.0; 4],
|
||||
k: 100,
|
||||
filter: None,
|
||||
postfilter: false,
|
||||
distance: DistanceType::L2,
|
||||
nprobes: Some(4),
|
||||
index_segments: Some(segments),
|
||||
fragments: Some(vec![1]),
|
||||
exact_match_limit: None,
|
||||
};
|
||||
let (hits, excluded) = query::indexed_only(&dataset, &table, &query).await.unwrap();
|
||||
assert_eq!(excluded, 1);
|
||||
assert_eq!(hits.len(), 64);
|
||||
let tail = Query {
|
||||
index_segments: Some(Vec::new()),
|
||||
..query.clone()
|
||||
};
|
||||
let (hits, excluded) = query::indexed_only(&dataset, &table, &tail).await.unwrap();
|
||||
assert!(hits.is_empty());
|
||||
assert_eq!(excluded, 1);
|
||||
let empty = Query {
|
||||
fragments: None,
|
||||
..tail
|
||||
};
|
||||
let (hits, excluded) = query::indexed_only(&dataset, &table, &empty).await.unwrap();
|
||||
assert!(hits.is_empty());
|
||||
assert_eq!(excluded, 0);
|
||||
}
|
||||
|
||||
/// named_segment_fragments must carry the logical index name through —
|
||||
/// a fanout planner groups tasks by name.
|
||||
#[tokio::test]
|
||||
|
||||
@@ -815,96 +815,3 @@ async fn a_dropped_and_recreated_index_serves_nothing_old() {
|
||||
let author = stats().await.unwrap().into_inner().keys;
|
||||
assert_eq!((author.len(), author[0].queries), (1, 1));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn indexed_queries_acknowledge_coverage_and_skip_recent_writes() {
|
||||
let fixture = Fixture::new().await;
|
||||
fixture
|
||||
.put(
|
||||
(0..64)
|
||||
.map(|i| row(i, Some(serde_json::json!("alice"))))
|
||||
.collect(),
|
||||
)
|
||||
.await;
|
||||
fixture.index_author().await;
|
||||
let mut dataset = fixture.dataset(0).await;
|
||||
weed_vector_core::index::build(
|
||||
&mut dataset,
|
||||
"vector",
|
||||
weed_vector_core::index::INDEX_NAME,
|
||||
4,
|
||||
false,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
fixture
|
||||
.put(vec![row(100, Some(serde_json::json!("alice")))])
|
||||
.await;
|
||||
let request = pb::QueryVectorsRequest {
|
||||
table: Some(fixture.table.clone()),
|
||||
query_vector: vector_of(100),
|
||||
top_k: 10,
|
||||
filter: FILTERS[0].1.to_string(),
|
||||
return_distance: true,
|
||||
return_metadata: true,
|
||||
..Default::default()
|
||||
};
|
||||
let all = fixture
|
||||
.server
|
||||
.query_vectors(Request::new(request.clone()))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(all.get_ref().vectors[0].key, "k100");
|
||||
let indexed = fixture
|
||||
.server
|
||||
.query_indexed_vectors(Request::new(request.clone()))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
indexed
|
||||
.metadata()
|
||||
.get("x-seaweedfs-vector-search-mode")
|
||||
.unwrap(),
|
||||
"indexed-only"
|
||||
);
|
||||
assert_eq!(
|
||||
indexed
|
||||
.metadata()
|
||||
.get("x-seaweedfs-vector-excluded-fragments")
|
||||
.unwrap(),
|
||||
"1"
|
||||
);
|
||||
assert_eq!(indexed.get_ref().vectors.len(), 10);
|
||||
assert!(
|
||||
indexed
|
||||
.get_ref()
|
||||
.vectors
|
||||
.iter()
|
||||
.all(|v| v.key != "k100" && v.metadata.is_some())
|
||||
);
|
||||
let mut dataset = fixture.dataset(0).await;
|
||||
dataset
|
||||
.optimize_indices(&lance_index::optimize::OptimizeOptions::append())
|
||||
.await
|
||||
.unwrap();
|
||||
let indexed = fixture
|
||||
.server
|
||||
.query_indexed_vectors(Request::new(request.clone()))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(indexed.get_ref().vectors[0].key, "k100");
|
||||
assert_eq!(
|
||||
indexed
|
||||
.metadata()
|
||||
.get("x-seaweedfs-vector-excluded-fragments")
|
||||
.unwrap(),
|
||||
"0"
|
||||
);
|
||||
fixture.set_state(State::Building).await;
|
||||
let err = fixture
|
||||
.server
|
||||
.query_indexed_vectors(Request::new(request))
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_eq!(err.code(), tonic::Code::InvalidArgument);
|
||||
}
|
||||
@@ -78,20 +78,6 @@ impl VectorService for ObservedService {
|
||||
}
|
||||
result
|
||||
}
|
||||
async fn query_indexed_vectors(
|
||||
&self,
|
||||
request: Request<pb::QueryVectorsRequest>,
|
||||
) -> Result<Response<pb::QueryVectorsResponse>, Status> {
|
||||
let mut in_flight = self.metrics.start("QueryVectors");
|
||||
let result = self.inner.query_indexed_vectors(request).await;
|
||||
in_flight.complete(result.as_ref().err().map(|e| e.code()));
|
||||
if let Ok(response) = &result {
|
||||
self.metrics
|
||||
.query_results
|
||||
.inc_by(response.get_ref().vectors.len() as u64);
|
||||
}
|
||||
result
|
||||
}
|
||||
async fn metadata_keys(
|
||||
&self,
|
||||
request: Request<pb::MetadataKeysRequest>,
|
||||
|
||||
@@ -1136,71 +1136,6 @@ impl VectorService for VectorServer {
|
||||
async fn query_vectors(
|
||||
&self,
|
||||
request: Request<pb::QueryVectorsRequest>,
|
||||
) -> Result<Response<pb::QueryVectorsResponse>, Status> {
|
||||
self.query(request, false).await
|
||||
}
|
||||
|
||||
async fn query_indexed_vectors(
|
||||
&self,
|
||||
request: Request<pb::QueryVectorsRequest>,
|
||||
) -> Result<Response<pb::QueryVectorsResponse>, Status> {
|
||||
self.query(request, true).await
|
||||
}
|
||||
|
||||
async fn metadata_keys(
|
||||
&self,
|
||||
request: Request<pb::MetadataKeysRequest>,
|
||||
) -> Result<Response<pb::MetadataKeysResponse>, Status> {
|
||||
let table = request
|
||||
.into_inner()
|
||||
.table
|
||||
.ok_or_else(|| Status::invalid_argument("missing table"))?;
|
||||
let dataset = self.open_to_read(&table).await?;
|
||||
let _lease = self.leases.try_pin(&dataset).await.map_err(internal)?;
|
||||
Ok(Response::new(
|
||||
metadata_keys(&dataset).await.map_err(internal)?,
|
||||
))
|
||||
}
|
||||
|
||||
async fn update_metadata_key(
|
||||
&self,
|
||||
request: Request<pb::UpdateMetadataKeyRequest>,
|
||||
) -> Result<Response<pb::MetadataKeysResponse>, Status> {
|
||||
let req = request.into_inner();
|
||||
let table = req
|
||||
.table
|
||||
.ok_or_else(|| Status::invalid_argument("missing table"))?;
|
||||
let mut dataset = self.open(&table).await?;
|
||||
let updated = if req.remove {
|
||||
metadata_index::request_removal(&mut dataset, &req.key).await
|
||||
} else {
|
||||
metadata_index::request(&mut dataset, &req.key).await
|
||||
};
|
||||
updated.map_err(|e| Status::failed_precondition(format!("{e:#}")))?;
|
||||
Ok(Response::new(
|
||||
metadata_keys(&dataset).await.map_err(internal)?,
|
||||
))
|
||||
}
|
||||
|
||||
async fn filter_stats(
|
||||
&self,
|
||||
request: Request<pb::FilterStatsRequest>,
|
||||
) -> Result<Response<pb::FilterStatsResponse>, Status> {
|
||||
let table = request
|
||||
.into_inner()
|
||||
.table
|
||||
.ok_or_else(|| Status::invalid_argument("missing table"))?;
|
||||
Ok(Response::new(
|
||||
self.filter_stats.snapshot(&table.id.join("/")),
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
impl VectorServer {
|
||||
async fn query(
|
||||
&self,
|
||||
request: Request<pb::QueryVectorsRequest>,
|
||||
indexed_only: bool,
|
||||
) -> Result<Response<pb::QueryVectorsResponse>, Status> {
|
||||
let started = std::time::Instant::now();
|
||||
let req = request.into_inner();
|
||||
@@ -1243,24 +1178,9 @@ impl VectorServer {
|
||||
fragments: None,
|
||||
exact_match_limit: self.exact_match_limit,
|
||||
};
|
||||
let (hits, excluded) = if indexed_only {
|
||||
query::indexed_only(&dataset, &resolved, &query)
|
||||
.await
|
||||
.map_err(|err| {
|
||||
if err.is::<query::IndexedOnlyError>() {
|
||||
invalid(err)
|
||||
} else {
|
||||
internal(err)
|
||||
}
|
||||
})?
|
||||
} else {
|
||||
(
|
||||
query::ann(&dataset, &resolved, &query)
|
||||
.await
|
||||
.map_err(internal)?,
|
||||
0,
|
||||
)
|
||||
};
|
||||
let hits = query::ann(&dataset, &resolved, &query)
|
||||
.await
|
||||
.map_err(internal)?;
|
||||
// One batched read for every hit's columns; keyed by the hit key so
|
||||
// row order does not matter.
|
||||
let mut metas: std::collections::HashMap<String, Option<Struct>> =
|
||||
@@ -1335,18 +1255,55 @@ impl VectorServer {
|
||||
let index = table.id.join("/");
|
||||
self.filter_stats
|
||||
.record(&index, table_id(&dataset), &filter_keys, started.elapsed());
|
||||
let mut response = Response::new(pb::QueryVectorsResponse { vectors });
|
||||
if indexed_only {
|
||||
response.metadata_mut().insert(
|
||||
"x-seaweedfs-vector-search-mode",
|
||||
"indexed-only".parse().unwrap(),
|
||||
);
|
||||
response.metadata_mut().insert(
|
||||
"x-seaweedfs-vector-excluded-fragments",
|
||||
excluded.to_string().parse().unwrap(),
|
||||
);
|
||||
}
|
||||
Ok(response)
|
||||
Ok(Response::new(pb::QueryVectorsResponse { vectors }))
|
||||
}
|
||||
|
||||
async fn metadata_keys(
|
||||
&self,
|
||||
request: Request<pb::MetadataKeysRequest>,
|
||||
) -> Result<Response<pb::MetadataKeysResponse>, Status> {
|
||||
let table = request
|
||||
.into_inner()
|
||||
.table
|
||||
.ok_or_else(|| Status::invalid_argument("missing table"))?;
|
||||
let dataset = self.open_to_read(&table).await?;
|
||||
let _lease = self.leases.try_pin(&dataset).await.map_err(internal)?;
|
||||
Ok(Response::new(
|
||||
metadata_keys(&dataset).await.map_err(internal)?,
|
||||
))
|
||||
}
|
||||
|
||||
async fn update_metadata_key(
|
||||
&self,
|
||||
request: Request<pb::UpdateMetadataKeyRequest>,
|
||||
) -> Result<Response<pb::MetadataKeysResponse>, Status> {
|
||||
let req = request.into_inner();
|
||||
let table = req
|
||||
.table
|
||||
.ok_or_else(|| Status::invalid_argument("missing table"))?;
|
||||
let mut dataset = self.open(&table).await?;
|
||||
let updated = if req.remove {
|
||||
metadata_index::request_removal(&mut dataset, &req.key).await
|
||||
} else {
|
||||
metadata_index::request(&mut dataset, &req.key).await
|
||||
};
|
||||
updated.map_err(|e| Status::failed_precondition(format!("{e:#}")))?;
|
||||
Ok(Response::new(
|
||||
metadata_keys(&dataset).await.map_err(internal)?,
|
||||
))
|
||||
}
|
||||
|
||||
async fn filter_stats(
|
||||
&self,
|
||||
request: Request<pb::FilterStatsRequest>,
|
||||
) -> Result<Response<pb::FilterStatsResponse>, Status> {
|
||||
let table = request
|
||||
.into_inner()
|
||||
.table
|
||||
.ok_or_else(|| Status::invalid_argument("missing table"))?;
|
||||
Ok(Response::new(
|
||||
self.filter_stats.snapshot(&table.id.join("/")),
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -15,35 +15,6 @@ BUCKET = "vectors-bucket"
|
||||
INDEX = "idx"
|
||||
|
||||
|
||||
def query_indexed_vectors(client, **kwargs):
|
||||
def before_sign(request, **_):
|
||||
request.headers["x-seaweedfs-vector-search-mode"] = "indexed-only"
|
||||
|
||||
event = "before-sign.s3vectors.QueryVectors"
|
||||
client.meta.events.register(event, before_sign)
|
||||
try:
|
||||
return client.query_vectors(**kwargs)
|
||||
finally:
|
||||
client.meta.events.unregister(event, before_sign)
|
||||
|
||||
|
||||
def test_indexed_only_requires_a_built_index(vectors):
|
||||
bucket = "indexed-only-" + uuid.uuid4().hex[:12]
|
||||
target = {"vectorBucketName": bucket, "indexName": "idx"}
|
||||
vectors.create_vector_bucket(vectorBucketName=bucket)
|
||||
try:
|
||||
vectors.create_index(**target, dataType="float32", dimension=3, distanceMetric="cosine")
|
||||
vectors.put_vectors(**target, vectors=[{"key": "new", "data": {"float32": [1, 0, 0]}}])
|
||||
query = {**target, "queryVector": {"float32": [1, 0, 0]}, "topK": 1}
|
||||
assert vectors.query_vectors(**query)["vectors"][0]["key"] == "new"
|
||||
with pytest.raises(ClientError, match="no usable index for vector") as exc:
|
||||
query_indexed_vectors(vectors, **query)
|
||||
assert exc.value.response["Error"]["Code"] == "ValidationException"
|
||||
finally:
|
||||
vectors.delete_index(**target)
|
||||
vectors.delete_vector_bucket(vectorBucketName=bucket)
|
||||
|
||||
|
||||
def test_vector_lifecycle(vectors):
|
||||
vectors.create_vector_bucket(vectorBucketName=BUCKET)
|
||||
buckets = [b["vectorBucketName"] for b in vectors.list_vector_buckets()["vectorBuckets"]]
|
||||
@@ -712,13 +683,6 @@ def test_vector_index_job(vectors, cluster):
|
||||
hits = vectors.query_vectors(vectorBucketName=bucket, indexName=index, queryVector={"float32": late}, topK=1)
|
||||
assert [h["key"] for h in hits["vectors"]] == ["late"]
|
||||
|
||||
indexed = query_indexed_vectors(vectors, vectorBucketName=bucket, indexName=index,
|
||||
queryVector={"float32": late}, topK=10)
|
||||
assert all(h["key"] != "late" for h in indexed["vectors"])
|
||||
headers = indexed["ResponseMetadata"]["HTTPHeaders"]
|
||||
assert headers["x-seaweedfs-vector-search-mode"] == "indexed-only"
|
||||
assert headers["x-seaweedfs-vector-data-excluded"] == "true"
|
||||
|
||||
again = call("/run", "POST", {"timeout_seconds": 60})
|
||||
assert again["detected_count"] == 0, again
|
||||
|
||||
@@ -745,11 +709,6 @@ def test_vector_index_job(vectors, cluster):
|
||||
after = coverage_now()
|
||||
assert after["unindexed_rows"] == 0 and after["segments"] == 2, after
|
||||
|
||||
indexed = query_indexed_vectors(vectors, vectorBucketName=bucket, indexName=index,
|
||||
queryVector={"float32": late}, topK=1)
|
||||
assert indexed["vectors"][0]["key"] == "late"
|
||||
assert indexed["ResponseMetadata"]["HTTPHeaders"]["x-seaweedfs-vector-data-excluded"] == "false"
|
||||
|
||||
# Five times the rows the index was sized for: the job trains it again
|
||||
# instead of extending it, and the partitions follow the new row count.
|
||||
rows.update(more)
|
||||
|
||||
+6
-13
@@ -1,7 +1,6 @@
|
||||
package command
|
||||
|
||||
import (
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
@@ -57,22 +56,16 @@ func runCompact(cmd *Command, args []string) bool {
|
||||
}
|
||||
switch strings.ToLower(*compactMethod) {
|
||||
case "data":
|
||||
err = v.CompactByVolumeData(opts)
|
||||
if err = v.CompactByVolumeData(opts); err != nil {
|
||||
glog.Fatalf("Compact Volume [ERROR] %s\n", err)
|
||||
}
|
||||
case "index":
|
||||
err = v.CompactByIndex(opts)
|
||||
if err = v.CompactByIndex(opts); err != nil {
|
||||
glog.Fatalf("Compact Volume [ERROR] %s\n", err)
|
||||
}
|
||||
default:
|
||||
glog.Fatalf("unsupported compaction method %q", *compactMethod)
|
||||
}
|
||||
if err != nil {
|
||||
v.Close()
|
||||
for _, ext := range []string{".cpd", ".cpx"} {
|
||||
if rmErr := os.Remove(v.FileName(ext)); rmErr != nil && !os.IsNotExist(rmErr) {
|
||||
glog.Errorf("remove %s: %v", v.FileName(ext), rmErr)
|
||||
}
|
||||
}
|
||||
glog.Errorf("Compact Volume [ERROR] %s", err)
|
||||
SetCommandExitStatus(1)
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
package command
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"os"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestCompactDataMethodBadHeaderLeavesNoOutput(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
base, offsets := writeFixTestVolume(t, dir, 5)
|
||||
doFixOneVolume(dir, "fix_7", "fix", 7, true)
|
||||
overwriteAt(t, base+".dat", offsets[2], bytes.Repeat([]byte{0xa5}, 16))
|
||||
|
||||
savedDir, savedCollection, savedId, savedMethod, savedStatus := *compactVolumePath, *compactVolumeCollection, *compactVolumeId, *compactMethod, commandExitStatus
|
||||
defer func() {
|
||||
*compactVolumePath, *compactVolumeCollection, *compactVolumeId, *compactMethod, commandExitStatus = savedDir, savedCollection, savedId, savedMethod, savedStatus
|
||||
}()
|
||||
*compactVolumePath, *compactVolumeCollection, *compactVolumeId, *compactMethod, commandExitStatus = dir, "fix", 7, "data", 0
|
||||
|
||||
runCompact(cmdCompact, nil)
|
||||
|
||||
if CommandExitStatus() == 0 {
|
||||
t.Error("expected a non-zero exit status")
|
||||
}
|
||||
for _, ext := range []string{".cpd", ".cpx"} {
|
||||
if _, err := os.Stat(base + ext); !os.IsNotExist(err) {
|
||||
t.Errorf("%s left behind: %v", ext, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
+4
-39
@@ -33,8 +33,6 @@ var cmdFix = &Command{
|
||||
Long: `Fix runs the SeaweedFS fix command on local dat files ( or remote files) or whole folders to re-create the index .idx file. If fixing remote files, you need to synchronize master.toml to the same directory on the current node as on the master node.
|
||||
You Need to stop the volume server when running this command.
|
||||
Use -ecx to rebuild a lost EC index (.ecx) — and the .vif when missing — from the local .ec## shards.
|
||||
On a damaged .dat, fix indexes only the needles before the first unreadable header or a record cut off by the end of the file, and exits non-zero; repair from a replica, or run fix on a copy, before compacting or loading the volume.
|
||||
With -ignoreError, fix keeps going and writes what it could index, but still exits non-zero if any volume failed.
|
||||
`,
|
||||
}
|
||||
|
||||
@@ -52,7 +50,6 @@ var (
|
||||
|
||||
type VolumeFileScanner4Fix struct {
|
||||
version needle.Version
|
||||
datSize int64
|
||||
nm *needle_map.MemDb
|
||||
nmDeleted *needle_map.MemDb
|
||||
includeDeleted bool
|
||||
@@ -69,15 +66,6 @@ func (scanner *VolumeFileScanner4Fix) ReadNeedleBody() bool {
|
||||
|
||||
func (scanner *VolumeFileScanner4Fix) VisitNeedle(n *needle.Needle, offset int64, needleHeader, needleBody []byte) error {
|
||||
glog.V(2).Infof("key %v offset %d size %d disk_size %d compressed %v", n.Id, offset, n.Size, n.DiskSize(scanner.version), n.IsCompressed())
|
||||
if scanner.datSize > 0 && offset+n.DiskSize(scanner.version) > scanner.datSize {
|
||||
glog.Errorf("needle %v at offset %d needs %d bytes but the .dat ends at %d; not indexing it", n.Id, offset, n.DiskSize(scanner.version), scanner.datSize)
|
||||
SetCommandExitStatus(1)
|
||||
// The key was rewritten or deleted here, so an older record must not become current again.
|
||||
if pe := scanner.nm.Delete(n.Id); pe != nil {
|
||||
return fmt.Errorf("delete %v with error %v", n.Id, pe)
|
||||
}
|
||||
return io.EOF
|
||||
}
|
||||
if n.Size.IsValid() {
|
||||
if pe := scanner.nm.Set(n.Id, types.ToOffset(offset), n.Size); pe != nil {
|
||||
return fmt.Errorf("saved %d with error %v", n.Size, pe)
|
||||
@@ -198,15 +186,10 @@ func fixEcxFromShardsInDir(basePath string, files []fs.DirEntry) bool {
|
||||
func SaveToIdx(scaner *VolumeFileScanner4Fix, idxName string) (ret error) {
|
||||
idxFile, err := os.OpenFile(idxName, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
|
||||
if err != nil {
|
||||
return err
|
||||
return
|
||||
}
|
||||
defer func() {
|
||||
idxFile.Close()
|
||||
if ret != nil && !*fixIgnoreError {
|
||||
if err := os.Remove(idxName); err != nil {
|
||||
glog.Errorf("failed to cleanup file %s:%v", idxName, err)
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
// Emit entries in .dat offset (append) order so the .idx stays the
|
||||
@@ -239,18 +222,6 @@ func SaveToIdx(scaner *VolumeFileScanner4Fix, idxName string) (ret error) {
|
||||
return nil
|
||||
}
|
||||
|
||||
// localDatSize is the length of the .dat the scan reads, or 0 when the volume
|
||||
// is read from a remote tier.
|
||||
func localDatSize(basepath, baseFileName string) int64 {
|
||||
if _, hasRemoteFile, _, _ := volume_info.MaybeLoadVolumeInfo(path.Join(basepath, baseFileName+".vif")); hasRemoteFile {
|
||||
return 0
|
||||
}
|
||||
if info, err := os.Stat(path.Join(basepath, baseFileName+".dat")); err == nil {
|
||||
return info.Size()
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func doFixOneVolume(basepath string, baseFileName string, collection string, volumeId int64, fixIncludeDeleted bool) {
|
||||
indexFileName := path.Join(basepath, baseFileName+".idx")
|
||||
|
||||
@@ -264,7 +235,6 @@ func doFixOneVolume(basepath string, baseFileName string, collection string, vol
|
||||
err := fmt.Errorf("volume ID out of range: %d", volumeId)
|
||||
if *fixIgnoreError {
|
||||
glog.Error(err)
|
||||
SetCommandExitStatus(1)
|
||||
return
|
||||
} else {
|
||||
glog.Fatal(err)
|
||||
@@ -278,17 +248,11 @@ func doFixOneVolume(basepath string, baseFileName string, collection string, vol
|
||||
nmDeleted: nmDeleted,
|
||||
includeDeleted: fixIncludeDeleted,
|
||||
}
|
||||
scanner.datSize = localDatSize(basepath, baseFileName)
|
||||
|
||||
if err := storage.ScanVolumeFile(basepath, collection, vid, storage.NeedleMapInMemory, scanner); err != nil {
|
||||
err := fmt.Errorf("scan .dat File: %w", err)
|
||||
if *fixIgnoreError {
|
||||
glog.Error(err)
|
||||
SetCommandExitStatus(1)
|
||||
// Without a super block nothing was scanned; keep the existing .idx.
|
||||
if scanner.version == 0 {
|
||||
return
|
||||
}
|
||||
} else {
|
||||
glog.Fatal(err)
|
||||
}
|
||||
@@ -298,8 +262,10 @@ func doFixOneVolume(basepath string, baseFileName string, collection string, vol
|
||||
err := fmt.Errorf("save to .idx File: %w", err)
|
||||
if *fixIgnoreError {
|
||||
glog.Error(err)
|
||||
SetCommandExitStatus(1)
|
||||
} else {
|
||||
if err := os.Remove(indexFileName); err != nil {
|
||||
glog.Errorf("failed to cleanup file %s:%v", indexFileName, err)
|
||||
}
|
||||
glog.Fatal(err)
|
||||
}
|
||||
}
|
||||
@@ -320,7 +286,6 @@ func doFixEcxFromShards(basePath, baseFileName, collection string, volumeId int6
|
||||
fail := func(err error) {
|
||||
if *fixIgnoreError {
|
||||
glog.Error(err)
|
||||
SetCommandExitStatus(1)
|
||||
} else {
|
||||
glog.Fatal(err)
|
||||
}
|
||||
|
||||
@@ -1,20 +1,13 @@
|
||||
package command
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/volume_server_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/backend"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/idx"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/needle"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/needle_map"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/super_block"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/types"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/volume_info"
|
||||
)
|
||||
|
||||
// TestSaveToIdxWritesOffsetOrder guards that weed fix rebuilds the .idx as an
|
||||
@@ -80,206 +73,3 @@ func TestSaveToIdxWritesOffsetOrder(t *testing.T) {
|
||||
t.Errorf("last entry should be the .dat-tail tombstone (key 5), got key %v", lastKey)
|
||||
}
|
||||
}
|
||||
|
||||
// writeFixTestVolume writes a .dat holding needles 1..count and returns its
|
||||
// base path and the offset of each needle, in key order.
|
||||
func writeFixTestVolume(t *testing.T, dir string, count int) (string, []int64) {
|
||||
t.Helper()
|
||||
base := filepath.Join(dir, "fix_7")
|
||||
version := needle.GetCurrentVersion()
|
||||
f, err := os.OpenFile(base+".dat", os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0644)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
datBackend := backend.NewDiskFile(f)
|
||||
defer datBackend.Close()
|
||||
sb := super_block.SuperBlock{Version: version, ReplicaPlacement: &super_block.ReplicaPlacement{}, Ttl: &needle.TTL{}}
|
||||
if _, err := datBackend.WriteAt(sb.Bytes(), 0); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var offsets []int64
|
||||
for i := 1; i <= count; i++ {
|
||||
n := &needle.Needle{Id: types.Uint64ToNeedleId(uint64(i)), Data: bytes.Repeat([]byte{byte(i)}, 1000*i)}
|
||||
n.Checksum = needle.NewCRC(n.Data)
|
||||
offset, _, _, err := n.Append(datBackend, version)
|
||||
if err != nil {
|
||||
t.Fatalf("append needle %d: %v", i, err)
|
||||
}
|
||||
offsets = append(offsets, int64(offset))
|
||||
}
|
||||
return base, offsets
|
||||
}
|
||||
|
||||
func indexedKeys(t *testing.T, idxPath string) []uint64 {
|
||||
t.Helper()
|
||||
f, err := os.Open(idxPath)
|
||||
if err != nil {
|
||||
t.Fatalf("open idx: %v", err)
|
||||
}
|
||||
defer f.Close()
|
||||
var keys []uint64
|
||||
if err := idx.WalkIndexFile(f, 0, func(key types.NeedleId, offset types.Offset, size types.Size) error {
|
||||
keys = append(keys, uint64(key))
|
||||
return nil
|
||||
}); err != nil {
|
||||
t.Fatalf("walk idx: %v", err)
|
||||
}
|
||||
return keys
|
||||
}
|
||||
|
||||
func overwriteAt(t *testing.T, path string, offset int64, b []byte) {
|
||||
t.Helper()
|
||||
f, err := os.OpenFile(path, os.O_WRONLY, 0644)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer f.Close()
|
||||
if _, err := f.WriteAt(b, offset); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFixSkipsRecordPastEndOfDat(t *testing.T) {
|
||||
savedStatus := commandExitStatus
|
||||
defer func() { commandExitStatus = savedStatus }()
|
||||
sizeAt := types.NeedleIdSize + types.CookieSize
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
corrupt func(t *testing.T, dat string, off int64)
|
||||
}{
|
||||
{"truncated", func(t *testing.T, dat string, off int64) {
|
||||
if err := os.Truncate(dat, off+100); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}},
|
||||
{"huge size", func(t *testing.T, dat string, off int64) {
|
||||
overwriteAt(t, dat, off+int64(sizeAt), []byte{0x7f, 0xff, 0xff, 0xf0})
|
||||
}},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
base, offsets := writeFixTestVolume(t, dir, 5)
|
||||
tc.corrupt(t, base+".dat", offsets[4])
|
||||
commandExitStatus = 0
|
||||
doFixOneVolume(dir, "fix_7", "fix", 7, true)
|
||||
if CommandExitStatus() == 0 {
|
||||
t.Error("expected a non-zero exit status")
|
||||
}
|
||||
if got := indexedKeys(t, base+".idx"); !slices.Equal(got, []uint64{1, 2, 3, 4}) {
|
||||
t.Errorf("indexed keys %v, want [1 2 3 4]", got)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestFixIgnoreErrorReportsIncompleteScan(t *testing.T) {
|
||||
savedIgnore, savedStatus := *fixIgnoreError, commandExitStatus
|
||||
*fixIgnoreError = true
|
||||
defer func() { *fixIgnoreError, commandExitStatus = savedIgnore, savedStatus }()
|
||||
|
||||
t.Run("bad header", func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
base, offsets := writeFixTestVolume(t, dir, 5)
|
||||
overwriteAt(t, base+".dat", offsets[2], bytes.Repeat([]byte{0xa5}, 16))
|
||||
commandExitStatus = 0
|
||||
doFixOneVolume(dir, "fix_7", "fix", 7, false)
|
||||
if CommandExitStatus() == 0 {
|
||||
t.Error("expected a non-zero exit status for a scan that stopped before the end of the .dat")
|
||||
}
|
||||
if got := indexedKeys(t, base+".idx"); !slices.Equal(got, []uint64{1, 2}) {
|
||||
t.Errorf("indexed keys %v, want [1 2]", got)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("bad super block keeps the existing index", func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
base, _ := writeFixTestVolume(t, dir, 3)
|
||||
overwriteAt(t, base+".dat", 0, bytes.Repeat([]byte{0xa5}, 8))
|
||||
if err := os.WriteFile(base+".idx", []byte("previous index"), 0644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
commandExitStatus = 0
|
||||
doFixOneVolume(dir, "fix_7", "fix", 7, true)
|
||||
if CommandExitStatus() == 0 {
|
||||
t.Error("expected a non-zero exit status for an unreadable super block")
|
||||
}
|
||||
if b, err := os.ReadFile(base + ".idx"); err != nil || string(b) != "previous index" {
|
||||
t.Errorf("existing .idx changed: %q, %v", b, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestLocalDatSizeIgnoresRemoteTier(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
base, _ := writeFixTestVolume(t, dir, 2)
|
||||
info, err := os.Stat(base + ".dat")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := localDatSize(dir, "fix_7"); got != info.Size() {
|
||||
t.Fatalf("localDatSize = %d, want %d", got, info.Size())
|
||||
}
|
||||
vi := &volume_server_pb.VolumeInfo{Files: []*volume_server_pb.RemoteFile{{BackendType: "s3", Key: "fix_7.dat", FileSize: uint64(info.Size()) * 2}}}
|
||||
if err := volume_info.SaveVolumeInfo(base+".vif", vi); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := localDatSize(dir, "fix_7"); got != 0 {
|
||||
t.Errorf("localDatSize with a remote .dat = %d, want 0", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFixTruncatedDeleteKeepsKeyDeleted(t *testing.T) {
|
||||
savedStatus := commandExitStatus
|
||||
defer func() { commandExitStatus = savedStatus }()
|
||||
dir := t.TempDir()
|
||||
base, _ := writeFixTestVolume(t, dir, 3)
|
||||
f, err := os.OpenFile(base+".dat", os.O_RDWR, 0644)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
datBackend := backend.NewDiskFile(f)
|
||||
deletion := &needle.Needle{Id: types.Uint64ToNeedleId(2)}
|
||||
offset, _, _, err := deletion.Append(datBackend, needle.GetCurrentVersion())
|
||||
datBackend.Close()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Truncate(base+".dat", int64(offset)+types.NeedleHeaderSize+2); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
for _, includeDeleted := range []bool{true, false} {
|
||||
doFixOneVolume(dir, "fix_7", "fix", 7, includeDeleted)
|
||||
f, err := os.Open(base + ".idx")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
live := map[uint64]bool{}
|
||||
err = idx.WalkIndexFile(f, 0, func(key types.NeedleId, offset types.Offset, size types.Size) error {
|
||||
live[uint64(key)] = !offset.IsZero() && size.IsValid()
|
||||
return nil
|
||||
})
|
||||
f.Close()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if live[2] || !live[1] || !live[3] {
|
||||
t.Errorf("includeDeleted=%v: live keys %v, want 1 and 3 only", includeDeleted, live)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSaveToIdxReportsOpenError(t *testing.T) {
|
||||
nm := needle_map.NewMemDb()
|
||||
defer nm.Close()
|
||||
idxPath := filepath.Join(t.TempDir(), "fix_7.idx")
|
||||
if err := os.Mkdir(idxPath, 0755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := SaveToIdx(&VolumeFileScanner4Fix{nm: nm}, idxPath); err == nil {
|
||||
t.Error("expected an error when the .idx path cannot be opened")
|
||||
}
|
||||
if _, err := os.Stat(idxPath); err != nil {
|
||||
t.Errorf("a failed open must leave the existing .idx path alone: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -144,10 +144,6 @@ func (rc *ReaderCache) fetchChunkRange(ctx context.Context, buffer []byte, chunk
|
||||
glog.ErrorfCtx(ctx, "operation LookupFileId %s failed, err: %v", chunkView.FileId, err)
|
||||
return 0, err
|
||||
}
|
||||
if rc.budget != nil {
|
||||
// the buffers of hedged requests count against the budget too
|
||||
ctx = util_http.WithScratchBudget(ctx, rc.budget)
|
||||
}
|
||||
return rc.fetchChunkDataFn(ctx, buffer, urlStrings, chunkView.CipherKey, chunkView.IsGzipped, false, offset, chunkView.FileId,
|
||||
refreshUrls(ctx, rc.cacheInvalidator, rc.lookupFileIdFn, chunkView.FileId))
|
||||
}
|
||||
@@ -523,10 +519,6 @@ func (s *SingleChunkCacher) fetchChunkData(ctx context.Context, urlStrings []str
|
||||
// Allocate buffer and download without holding the lock.
|
||||
// This allows multiple downloads to proceed in parallel.
|
||||
data := mem.Allocate(s.chunkSize)
|
||||
if s.parent.budget != nil {
|
||||
// the buffers of hedged requests count against the budget too
|
||||
ctx = util_http.WithScratchBudget(ctx, s.parent.budget)
|
||||
}
|
||||
_, fetchErr := s.parent.fetchChunkDataFn(ctx, data, urlStrings, s.cipherKey, s.isGzipped, true, 0, s.chunkFileId, refreshUrls(ctx, s.parent.cacheInvalidator, s.lookupFileId, s.chunkFileId))
|
||||
if fetchErr != nil {
|
||||
mem.Free(data)
|
||||
|
||||
@@ -109,65 +109,6 @@ func (b *ReaderCacheBudget) canFit(size int) bool {
|
||||
return b == nil || int64(mem.AllocationSize(size)) <= b.limit
|
||||
}
|
||||
|
||||
// TryReserveScratch takes size bytes for a buffer that a hedged chunk read
|
||||
// borrows while it races the download holding the chunk's own reservation.
|
||||
// Like a download it evicts idle chunks no stream is positioned in, but it
|
||||
// never waits and never evicts a pinned chunk: a hedge that does not fit is
|
||||
// simply not sent. A nil budget has room for anything.
|
||||
func (b *ReaderCacheBudget) TryReserveScratch(size int) bool {
|
||||
if b == nil {
|
||||
return true
|
||||
}
|
||||
n := int64(mem.AllocationSize(size))
|
||||
if n > b.limit {
|
||||
return false
|
||||
}
|
||||
for {
|
||||
b.Lock()
|
||||
if n <= b.limit-b.used {
|
||||
b.used += n
|
||||
b.Unlock()
|
||||
return true
|
||||
}
|
||||
var victim *SingleChunkCacher
|
||||
var entry *list.Element
|
||||
for e := b.idle.Front(); e != nil; e = e.Next() {
|
||||
if c := e.Value.(*SingleChunkCacher); atomic.LoadInt32(&c.pins) == 0 {
|
||||
victim, entry = c, e
|
||||
break
|
||||
}
|
||||
}
|
||||
if entry == nil {
|
||||
b.Unlock()
|
||||
return false
|
||||
}
|
||||
b.idle.Remove(entry)
|
||||
delete(b.idleEntries, victim)
|
||||
b.Unlock()
|
||||
if !victim.parent.removeUnpinned(victim) {
|
||||
// pinned meanwhile: keep it evictable, as reserve does, and give up
|
||||
b.Lock()
|
||||
if _, ok := b.reservations[victim]; ok && b.idleEntries[victim] == nil {
|
||||
b.idleEntries[victim] = b.idle.PushBack(victim)
|
||||
}
|
||||
b.Unlock()
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ReleaseScratch returns what TryReserveScratch took.
|
||||
func (b *ReaderCacheBudget) ReleaseScratch(size int) {
|
||||
if b == nil {
|
||||
return
|
||||
}
|
||||
b.Lock()
|
||||
defer b.Unlock()
|
||||
b.used -= int64(mem.AllocationSize(size))
|
||||
close(b.changed)
|
||||
b.changed = make(chan struct{})
|
||||
}
|
||||
|
||||
func (b *ReaderCacheBudget) complete(s *SingleChunkCacher) {
|
||||
if b == nil {
|
||||
return
|
||||
|
||||
@@ -486,69 +486,3 @@ func TestReaderCacheBudgetWaitStopsWithItsLastStream(t *testing.T) {
|
||||
t.Fatal("releasing the stream waited for budget nobody needs")
|
||||
}
|
||||
}
|
||||
|
||||
// TestReaderCacheBudgetLendsScratchToHedges: a hedged download borrows its
|
||||
// buffer from the budget. It may evict idle chunks for it, as a download
|
||||
// does, but it neither waits nor touches downloads in flight.
|
||||
func TestReaderCacheBudgetLendsScratchToHedges(t *testing.T) {
|
||||
budget := NewReaderCacheBudget(8 << 10)
|
||||
gate := make(chan struct{})
|
||||
rc := NewReaderCache(256, newMockChunkCacheForReaderCache(), func(context.Context, string) ([]string, error) { return []string{"unused"}, nil }, nil, budget)
|
||||
defer rc.destroy()
|
||||
defer close(gate) // before destroy, which waits for the download held at the gate
|
||||
var sawBudget atomic.Bool
|
||||
rc.fetchChunkDataFn = func(ctx context.Context, buffer []byte, _ []string, _ []byte, _ bool, _ bool, _ int64, fileId string, _ util_http.RefreshUrlsFunc) (int, error) {
|
||||
if util_http.ScratchBudgetFrom(ctx) == budget {
|
||||
sawBudget.Store(true)
|
||||
}
|
||||
if fileId == "inflight" {
|
||||
<-gate
|
||||
}
|
||||
buffer[0] = 42
|
||||
return len(buffer), nil
|
||||
}
|
||||
used := func() int64 {
|
||||
budget.Lock()
|
||||
defer budget.Unlock()
|
||||
return budget.used
|
||||
}
|
||||
|
||||
// two idle chunks fill the budget
|
||||
for _, fid := range []string{"a", "b"} {
|
||||
buffer := make([]byte, 1)
|
||||
if n, err := rc.ReadChunkAt(context.Background(), buffer, fid, nil, false, 0, 3<<10, false); err != nil || n != 1 {
|
||||
t.Fatalf("read %s: n=%d err=%v", fid, n, err)
|
||||
}
|
||||
}
|
||||
if !sawBudget.Load() {
|
||||
t.Fatal("the download's context does not carry the budget for its hedges")
|
||||
}
|
||||
if used() != 8<<10 {
|
||||
t.Fatalf("used %d, want the budget full of idle chunks", used())
|
||||
}
|
||||
if !budget.TryReserveScratch(3<<10) || !budget.TryReserveScratch(3<<10) {
|
||||
t.Fatal("hedge buffers did not evict the idle chunks")
|
||||
}
|
||||
if budget.TryReserveScratch(3 << 10) {
|
||||
t.Fatal("a third hedge buffer fit into a full budget")
|
||||
}
|
||||
budget.ReleaseScratch(3 << 10)
|
||||
budget.ReleaseScratch(3 << 10)
|
||||
if used() != 0 {
|
||||
t.Fatalf("used %d after returning the hedge buffers, want 0", used())
|
||||
}
|
||||
|
||||
// downloads in flight are not evicted, and the hedge does not wait for them
|
||||
rc.MaybeCache(&Interval[*ChunkView]{Value: &ChunkView{FileId: "inflight", ViewSize: 6 << 10, ChunkSize: 6 << 10}}, 1)
|
||||
deadline := time.Now().Add(5 * time.Second)
|
||||
for used() == 0 && time.Now().Before(deadline) {
|
||||
time.Sleep(time.Millisecond)
|
||||
}
|
||||
start := time.Now()
|
||||
if budget.TryReserveScratch(3 << 10) {
|
||||
t.Fatal("a hedge buffer evicted a download in flight")
|
||||
}
|
||||
if took := time.Since(start); took > time.Second {
|
||||
t.Fatalf("a hedge waited %v for room", took)
|
||||
}
|
||||
}
|
||||
@@ -607,22 +607,6 @@ func (i *InodeToPath) AddPath(inode uint64, path util.FullPath) {
|
||||
}
|
||||
}
|
||||
|
||||
// RemovePathOf takes path away from inode when the path is still the inode's,
|
||||
// and reports whether it was. Checked and removed under one lock: a rename on
|
||||
// this mount may have given the path to another inode since the caller looked,
|
||||
// and that mapping is not the caller's to drop.
|
||||
func (i *InodeToPath) RemovePathOf(inode uint64, path util.FullPath) bool {
|
||||
i.Lock()
|
||||
defer i.Unlock()
|
||||
if current, found := i.path2inode[path]; !found || current != inode {
|
||||
return false
|
||||
}
|
||||
delete(i.path2inode, path)
|
||||
i.dropDirPath(inode)
|
||||
i.removePathFromInode2Path(inode, path)
|
||||
return true
|
||||
}
|
||||
|
||||
// RemovePath drops the name. onStillReferenced, if given, runs under the
|
||||
// table's lock when the kernel still holds lookup references to the inode:
|
||||
// such an inode keeps receiving requests until the final forget, and holding
|
||||
@@ -655,22 +639,6 @@ func (i *InodeToPath) RemoveAlias(path util.FullPath) (util.FullPath, bool) {
|
||||
if !found {
|
||||
return "", false
|
||||
}
|
||||
return i.removeAlias(inode, path)
|
||||
}
|
||||
|
||||
// RemoveAliasOf drops path only while it still names inode and the inode
|
||||
// keeps another name. Ownership is checked under the same lock as removal.
|
||||
func (i *InodeToPath) RemoveAliasOf(inode uint64, path util.FullPath) (util.FullPath, bool) {
|
||||
i.Lock()
|
||||
defer i.Unlock()
|
||||
if current, found := i.path2inode[path]; !found || current != inode {
|
||||
return "", false
|
||||
}
|
||||
return i.removeAlias(inode, path)
|
||||
}
|
||||
|
||||
// removeAlias requires the table lock and a path that belongs to inode.
|
||||
func (i *InodeToPath) removeAlias(inode uint64, path util.FullPath) (util.FullPath, bool) {
|
||||
ie := i.inode2path[inode]
|
||||
if ie == nil {
|
||||
return "", false
|
||||
|
||||
@@ -231,33 +231,6 @@ func TestLookupRecordsHardLinkNames(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestRemoveAliasOfChecksOwnership(t *testing.T) {
|
||||
table := NewInodeToPath(util.FullPath("/"), 0)
|
||||
inode := table.Lookup("/a", 1, false, true, 42, true)
|
||||
if survivor, ok := table.RemoveAliasOf(inode, "/a"); ok || survivor != "" || !table.HasPath("/a") {
|
||||
t.Fatal("removed the only name")
|
||||
}
|
||||
table.AddPath(inode, "/b")
|
||||
if survivor, ok := table.RemoveAliasOf(inode+1, "/a"); ok || survivor != "" {
|
||||
t.Fatalf("removed another inode's name: survivor %q", survivor)
|
||||
}
|
||||
if paths := table.GetAllPaths(inode); len(paths) != 2 || paths[0] != "/a" || paths[1] != "/b" {
|
||||
t.Fatalf("ownership mismatch changed inode paths: %v", paths)
|
||||
}
|
||||
if got, found := table.GetInode("/a"); !found || got != inode {
|
||||
t.Fatalf("ownership mismatch changed /a mapping: %d (found %v)", got, found)
|
||||
}
|
||||
if survivor, ok := table.RemoveAliasOf(inode, "/a"); !ok || survivor != "/b" || table.HasPath("/a") {
|
||||
t.Fatalf("RemoveAliasOf(/a) = %q, %v, want /b", survivor, ok)
|
||||
}
|
||||
if survivor, ok := table.RemoveAliasOf(inode, "/a"); ok || survivor != "" {
|
||||
t.Fatal("removed an absent name")
|
||||
}
|
||||
if got, status := table.GetPath(inode); status != fuse.OK || got != "/b" {
|
||||
t.Fatalf("surviving path %q (%v), want /b", got, status)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRemoveAliasKeepsSoleName(t *testing.T) {
|
||||
table := NewInodeToPath(util.FullPath("/"), 0)
|
||||
inode := table.Lookup("/a", 1, false, true, 42, true)
|
||||
|
||||
+10
-84
@@ -1007,7 +1007,7 @@ func (wfs *WFS) onEntryInvalidation(invalidation meta_cache.EntryInvalidation) {
|
||||
// the handle's own path bookkeeping. This is for the rest: the kernel goes
|
||||
// on addressing a moved inode by nodeid whether or not anything holds it
|
||||
// open.
|
||||
handled, replacedInode, detached := wfs.invalidateOpenFileHandle(invalidation)
|
||||
handled, replacedInode := wfs.invalidateOpenFileHandle(invalidation)
|
||||
if !handled && invalidation.RenamedTo != "" {
|
||||
_, replacedInode = wfs.inodeToPath.MovePath(invalidation.Path, invalidation.RenamedTo)
|
||||
} else if !handled && invalidation.Deleted && len(invalidation.LiveHardLinkId) > 0 {
|
||||
@@ -1023,32 +1023,6 @@ func (wfs *WFS) onEntryInvalidation(invalidation meta_cache.EntryInvalidation) {
|
||||
if replacedInode != 0 {
|
||||
wfs.markHandleDeleted(replacedInode)
|
||||
}
|
||||
// The kernel still resolves the name to the inode whose handle just lost
|
||||
// it, for as long as it trusts its lookup. With that lookup dropped, a
|
||||
// call by path reaches the file that has the name now.
|
||||
if detached {
|
||||
wfs.invalidateKernelEntry(invalidation.Path)
|
||||
}
|
||||
}
|
||||
|
||||
// invalidateKernelEntry drops the kernel's cached lookup of path, so its next
|
||||
// use of the name asks again. Called from the invalidation worker with no
|
||||
// handle lock held, for the reasons invalidateKernelDirListing gives: the
|
||||
// kernel takes the parent directory's lock for it, and waits there for any
|
||||
// request on that directory this mount is still serving.
|
||||
func (wfs *WFS) invalidateKernelEntry(path util.FullPath) {
|
||||
server := wfs.fuseServer
|
||||
if server == nil {
|
||||
return
|
||||
}
|
||||
dir, name := path.DirAndName()
|
||||
dirInode, found := wfs.inodeToPath.GetInode(util.FullPath(dir))
|
||||
if !found {
|
||||
return
|
||||
}
|
||||
if status := server.EntryNotify(dirInode, name); status != fuse.OK && status != fuse.ENOENT && status != fuse.ENOSYS {
|
||||
glog.V(4).Infof("invalidate kernel lookup of %s: %v", path, status)
|
||||
}
|
||||
}
|
||||
|
||||
// invalidateKernelDirListing drops the kernel's cached listing of the directory
|
||||
@@ -1085,10 +1059,8 @@ func (wfs *WFS) MountRoot() util.FullPath {
|
||||
// open, reporting whether it found one: a handle owns its inode's rename
|
||||
// bookkeeping, and the caller moves the table only for inodes without one. Any
|
||||
// inode a rename destroyed comes back for the caller to mark, since marking it
|
||||
// here would hold two handle locks at once. detached reports that the handle's
|
||||
// inode gave the event's path up to another file, for the caller to tell the
|
||||
// kernel once the handle's locks are released.
|
||||
func (wfs *WFS) invalidateOpenFileHandle(invalidation meta_cache.EntryInvalidation) (handled bool, replacedInode uint64, detached bool) {
|
||||
// here would hold two handle locks at once.
|
||||
func (wfs *WFS) invalidateOpenFileHandle(invalidation meta_cache.EntryInvalidation) (handled bool, replacedInode uint64) {
|
||||
filePath, eventEntry, eventTsNs := invalidation.Path, invalidation.Entry, invalidation.TsNs
|
||||
inode, inodeFound := wfs.inodeToPath.GetInode(filePath)
|
||||
if !inodeFound {
|
||||
@@ -1109,10 +1081,8 @@ func (wfs *WFS) invalidateOpenFileHandle(invalidation meta_cache.EntryInvalidati
|
||||
// below - a fence that skipped it would strand the inode and the handle on
|
||||
// a name the filer has vacated. MovePath reports whether the source was
|
||||
// still ours to move, which is what makes a replayed rename a no-op here.
|
||||
moved := false
|
||||
if invalidation.RenamedTo != "" {
|
||||
if sourceInode, replaced := wfs.inodeToPath.MovePath(filePath, invalidation.RenamedTo); sourceInode != 0 {
|
||||
moved = true
|
||||
if replaced != inode {
|
||||
replacedInode = replaced
|
||||
}
|
||||
@@ -1144,17 +1114,11 @@ func (wfs *WFS) invalidateOpenFileHandle(invalidation meta_cache.EntryInvalidati
|
||||
// A cached parent's store entry is the ordered merge of this event and
|
||||
// anything applied since. An uncached parent takes no store writes, so a
|
||||
// hit there is a stale leftover — use the event entry instead.
|
||||
//
|
||||
// A handle that just followed its file to another name has nothing to
|
||||
// learn at the path it left: whatever the cache holds there by now is
|
||||
// another file's. The rename's event for the new path brings the entry.
|
||||
var candidate *filer_pb.Entry
|
||||
candidateTsNs := eventTsNs
|
||||
if !moved {
|
||||
if storeEntry, storeVersionTsNs, found := wfs.cachedEntrySince(filePath, eventTsNs); found {
|
||||
candidate = storeEntry.ToProtoEntry()
|
||||
candidateTsNs = storeVersionTsNs
|
||||
}
|
||||
if storeEntry, storeVersionTsNs, found := wfs.cachedEntrySince(filePath, eventTsNs); found {
|
||||
candidate = storeEntry.ToProtoEntry()
|
||||
candidateTsNs = storeVersionTsNs
|
||||
}
|
||||
if candidate == nil && eventEntry != nil {
|
||||
candidate = proto.Clone(eventEntry).(*filer_pb.Entry)
|
||||
@@ -1175,7 +1139,7 @@ func (wfs *WFS) invalidateOpenFileHandle(invalidation meta_cache.EntryInvalidati
|
||||
if invalidation.Deleted {
|
||||
// The next flush reads the survivor's stored entry before
|
||||
// publishing, so the version stays where it was.
|
||||
if len(invalidation.LiveHardLinkId) > 0 && wfs.followSurvivingLink(fh, inode, filePath) {
|
||||
if len(invalidation.LiveHardLinkId) > 0 && wfs.followSurvivingLink(fh, filePath) {
|
||||
fh.linkRefresh = invalidation.LiveHardLinkId
|
||||
return
|
||||
}
|
||||
@@ -1210,35 +1174,6 @@ func (wfs *WFS) invalidateOpenFileHandle(invalidation meta_cache.EntryInvalidati
|
||||
}
|
||||
return
|
||||
}
|
||||
// Another file has the name: a peer renamed it over the one this handle
|
||||
// has open, from a source this mount never looked up, so no MovePath
|
||||
// reported the handle's inode as replaced. Installing the newcomer would
|
||||
// send every later write, truncate and chmod through this descriptor to
|
||||
// it. The inode gives the name up instead, as a replaced rename target
|
||||
// does: the kernel walks the path again and reaches the newcomer under an
|
||||
// inode of its own.
|
||||
if replacedByAnotherFile(candidate, base) {
|
||||
// A hard-linked file lives on under its other names, and the handle
|
||||
// with it under one this mount knows, as after a peer's unlink of
|
||||
// one name. The next flush reads the survivor's stored entry before
|
||||
// publishing, so the version stays where it was.
|
||||
if len(base.HardLinkId) > 0 && wfs.followSurvivingLink(fh, inode, filePath) {
|
||||
detached = true
|
||||
fh.linkRefresh = base.HardLinkId
|
||||
return
|
||||
}
|
||||
// A local rename may have moved the inode off the name since it was
|
||||
// looked up; the file then lives on under its new one.
|
||||
if !wfs.inodeToPath.RemovePathOf(inode, filePath) {
|
||||
return
|
||||
}
|
||||
// No name left here: the handle's file is gone, as after a delete.
|
||||
detached = true
|
||||
fh.isDeleted = true
|
||||
fh.deleteEpoch++
|
||||
fh.advanceEntryVersion(candidateTsNs, 0)
|
||||
return
|
||||
}
|
||||
// Dirty pages overlay content, so only a content change invalidates them:
|
||||
// a metadata-only event (chmod, touch, or a committed copy's own event
|
||||
// against an approximate base) leaves them valid.
|
||||
@@ -1252,15 +1187,6 @@ func (wfs *WFS) invalidateOpenFileHandle(invalidation meta_cache.EntryInvalidati
|
||||
return
|
||||
}
|
||||
|
||||
// replacedByAnotherFile reports whether stored is provably not the file base
|
||||
// was: both carry an inode and the two differ. An update in place keeps the
|
||||
// inode, so does a hard link made of the file; an entry without one cannot
|
||||
// tell, and is not taken for another file.
|
||||
func replacedByAnotherFile(stored, base *filer_pb.Entry) bool {
|
||||
storedInode, baseInode := stored.GetAttributes().GetInode(), base.GetAttributes().GetInode()
|
||||
return storedInode != 0 && baseInode != 0 && storedInode != baseInode
|
||||
}
|
||||
|
||||
// cachedEntrySince returns the meta cache's entry at path when its directory is
|
||||
// cached and the entry is no older than tsNs.
|
||||
func (wfs *WFS) cachedEntrySince(path util.FullPath, tsNs int64) (*filer.Entry, int64, bool) {
|
||||
@@ -1277,9 +1203,9 @@ func (wfs *WFS) cachedEntrySince(path util.FullPath, tsNs int64) (*filer.Entry,
|
||||
|
||||
// followSurvivingLink drops a hard link name another client deleted and
|
||||
// keeps the handle on a name of the inode this mount still knows, reporting
|
||||
// false when it knows none or the removed name no longer belongs to owner.
|
||||
func (wfs *WFS) followSurvivingLink(fh *FileHandle, owner uint64, removed util.FullPath) bool {
|
||||
survivor, ok := wfs.inodeToPath.RemoveAliasOf(owner, removed)
|
||||
// false when it knows none.
|
||||
func (wfs *WFS) followSurvivingLink(fh *FileHandle, removed util.FullPath) bool {
|
||||
survivor, ok := wfs.inodeToPath.RemoveAlias(removed)
|
||||
if ok {
|
||||
fh.RememberPath(survivor)
|
||||
wfs.readAuth.TrackHandle(survivor, fh)
|
||||
|
||||
@@ -4,12 +4,8 @@ import (
|
||||
"context"
|
||||
"net"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"syscall"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -2238,362 +2234,6 @@ func TestPeerTruncateWaitsForBufferedWrites(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// A peer putting another file (another inode) at the path of a clean handle
|
||||
// must not hand the handle the newcomer: what the descriptor writes,
|
||||
// truncates or chmods next would land in it. This mount never looked the
|
||||
// rename's source up, so nothing reports the handle's inode as replaced. The
|
||||
// handle's file is gone, and its inode gives the name up.
|
||||
func TestPeerReplacementDetachesCleanHandle(t *testing.T) {
|
||||
for _, name := range []string{"renamed-over", "replaced-in-place"} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
wfs := newInvalidateTestWFS(t)
|
||||
|
||||
path := util.FullPath("/dir/file")
|
||||
inode := wfs.inodeToPath.Lookup(path, time.Now().Unix(), false, false, 0, true)
|
||||
base := flushConditionEntry(1)
|
||||
wfs.mapPbIdFromFilerToLocal(base)
|
||||
fh, _, _, _ := wfs.fhMap.AcquireFileHandle(wfs, inode, base, 0, 0)
|
||||
|
||||
replacement := flushConditionEntry(7)
|
||||
replacement.Attributes.Inode = 99
|
||||
old := flushConditionEntry(1)
|
||||
if name == "renamed-over" {
|
||||
old = proto.Clone(replacement).(*filer_pb.Entry)
|
||||
old.Name = "file.new"
|
||||
}
|
||||
resp := &filer_pb.SubscribeMetadataResponse{
|
||||
Directory: "/dir",
|
||||
TsNs: 1500,
|
||||
EventNotification: &filer_pb.EventNotification{
|
||||
OldEntry: old,
|
||||
NewEntry: replacement,
|
||||
NewParentPath: "/dir",
|
||||
},
|
||||
}
|
||||
if err := wfs.metaCache.ApplyMetadataResponse(context.Background(), resp, meta_cache.SubscriberMetadataResponseApplyOptions); err != nil {
|
||||
t.Fatalf("apply: %v", err)
|
||||
}
|
||||
wfs.metaCache.WaitForEntryInvalidations()
|
||||
|
||||
if !fh.isDeleted {
|
||||
t.Fatal("handle of the replaced file not marked deleted; its next write would go into the replacement")
|
||||
}
|
||||
if got := chunkFileKeys(fh.GetEntry().GetEntry()); len(got) != 1 || got[0] != 1 {
|
||||
t.Fatalf("handle chunks %v, want its own", got)
|
||||
}
|
||||
if got := fh.baseEntry.Load().GetAttributes().GetInode(); got != 42 {
|
||||
t.Fatalf("base inode %d, want the handle's own 42", got)
|
||||
}
|
||||
if got, found := wfs.inodeToPath.GetInode(path); found && got == inode {
|
||||
t.Fatal("the name still answers to the replaced inode")
|
||||
}
|
||||
if runtime.GOOS == "linux" {
|
||||
if status := wfs.pathlessInodeStatus(inode, fuse.ENOENT); status != fuse.Status(syscall.ESTALE) {
|
||||
t.Fatalf("replaced inode answers %v, want ESTALE so the kernel walks the path again", status)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// The worker looks the inode up by name before it takes the handle's lock. A
|
||||
// rename on this mount can move the inode off that name in between: the file
|
||||
// lives on under its new name, so the handle is not the replaced file's.
|
||||
func TestPeerReplacementAfterALocalRenameKeepsTheHandle(t *testing.T) {
|
||||
wfs := newInvalidateTestWFS(t)
|
||||
|
||||
path, renamed := util.FullPath("/dir/file"), util.FullPath("/dir/renamed")
|
||||
inode := wfs.inodeToPath.Lookup(path, time.Now().Unix(), false, false, 0, true)
|
||||
base := flushConditionEntry(1)
|
||||
wfs.mapPbIdFromFilerToLocal(base)
|
||||
fh, _, _, _ := wfs.fhMap.AcquireFileHandle(wfs, inode, base, 0, 0)
|
||||
|
||||
testLock := wfs.fhLockTable.AcquireLock("test", fh.fh, util.ExclusiveLock)
|
||||
var releaseOnce sync.Once
|
||||
release := func() { releaseOnce.Do(func() { wfs.fhLockTable.ReleaseLock(fh.fh, testLock) }) }
|
||||
t.Cleanup(release)
|
||||
|
||||
replacement := flushConditionEntry(7)
|
||||
replacement.Attributes.Inode = 99
|
||||
resp := &filer_pb.SubscribeMetadataResponse{
|
||||
Directory: "/dir",
|
||||
TsNs: 1500,
|
||||
EventNotification: &filer_pb.EventNotification{NewEntry: replacement, NewParentPath: "/dir"},
|
||||
}
|
||||
if err := wfs.metaCache.ApplyMetadataResponse(context.Background(), resp, meta_cache.SubscriberMetadataResponseApplyOptions); err != nil {
|
||||
t.Fatalf("apply: %v", err)
|
||||
}
|
||||
waitForHandleLockWaiter(t, "invalidateOpenFileHandle")
|
||||
wfs.inodeToPath.MovePath(path, renamed)
|
||||
release()
|
||||
wfs.metaCache.WaitForEntryInvalidations()
|
||||
|
||||
if fh.isDeleted {
|
||||
t.Fatal("handle marked deleted while its file lives on under the name it was renamed to")
|
||||
}
|
||||
if got, found := wfs.inodeToPath.GetInode(renamed); !found || got != inode {
|
||||
t.Fatalf("renamed name answers to %d (found %v), want %d", got, found, inode)
|
||||
}
|
||||
}
|
||||
|
||||
// A queued invalidation must not take a surviving name from a different
|
||||
// hard-linked inode that local renames moved onto the invalidated path.
|
||||
func TestPeerInvalidationLeavesAnotherInodesHardLinks(t *testing.T) {
|
||||
for _, event := range []string{"replacement", "delete"} {
|
||||
t.Run(event, func(t *testing.T) {
|
||||
wfs := newInvalidateTestWFS(t)
|
||||
path, renamed := util.FullPath("/dir/file"), util.FullPath("/dir/renamed")
|
||||
incoming, alias := util.FullPath("/dir/incoming"), util.FullPath("/dir/alias")
|
||||
inode := wfs.inodeToPath.Lookup(path, 1, false, true, 42, true)
|
||||
other := wfs.inodeToPath.Lookup(incoming, 1, false, true, 99, true)
|
||||
wfs.inodeToPath.AddPath(other, alias)
|
||||
base := flushConditionEntry(1)
|
||||
base.HardLinkId, base.HardLinkCounter = []byte{7, 7, 7}, 2
|
||||
wfs.mapPbIdFromFilerToLocal(base)
|
||||
fh, _, _, _ := wfs.fhMap.AcquireFileHandle(wfs, inode, base, 0, 0)
|
||||
|
||||
testLock := wfs.fhLockTable.AcquireLock("test", fh.fh, util.ExclusiveLock)
|
||||
var releaseOnce sync.Once
|
||||
release := func() { releaseOnce.Do(func() { wfs.fhLockTable.ReleaseLock(fh.fh, testLock) }) }
|
||||
t.Cleanup(release)
|
||||
|
||||
message := &filer_pb.EventNotification{OldEntry: proto.Clone(base).(*filer_pb.Entry)}
|
||||
if event == "replacement" {
|
||||
message.NewEntry = flushConditionEntry(7)
|
||||
message.NewEntry.Attributes.Inode = 99
|
||||
message.NewParentPath = "/dir"
|
||||
}
|
||||
resp := &filer_pb.SubscribeMetadataResponse{Directory: "/dir", TsNs: 1500, EventNotification: message}
|
||||
if err := wfs.metaCache.ApplyMetadataResponse(context.Background(), resp, meta_cache.SubscriberMetadataResponseApplyOptions); err != nil {
|
||||
t.Fatalf("apply: %v", err)
|
||||
}
|
||||
waitForHandleLockWaiter(t, "invalidateOpenFileHandle")
|
||||
wfs.inodeToPath.MovePath(path, renamed)
|
||||
wfs.inodeToPath.MovePath(incoming, path)
|
||||
fh.RememberPath(renamed)
|
||||
release()
|
||||
wfs.metaCache.WaitForEntryInvalidations()
|
||||
|
||||
for _, name := range []util.FullPath{path, alias} {
|
||||
if got, found := wfs.inodeToPath.GetInode(name); !found || got != other {
|
||||
t.Errorf("%s maps to %d (found %v), want %d", name, got, found, other)
|
||||
}
|
||||
}
|
||||
if paths := wfs.inodeToPath.GetAllPaths(other); len(paths) != 2 {
|
||||
t.Errorf("other inode's paths %v, want both hard links", paths)
|
||||
}
|
||||
if fh.savedDir != "/dir" || fh.savedName != "renamed" || len(fh.linkRefresh) != 0 {
|
||||
t.Errorf("handle followed another inode's alias: saved path %s/%s, linkRefresh %v", fh.savedDir, fh.savedName, fh.linkRefresh)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// waitForHandleLockWaiter returns once a goroutine in caller waits for a
|
||||
// handle lock.
|
||||
func waitForHandleLockWaiter(t *testing.T, caller string) {
|
||||
t.Helper()
|
||||
deadline := time.Now().Add(10 * time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
buf := make([]byte, 1<<20)
|
||||
n := runtime.Stack(buf, true)
|
||||
for _, stack := range strings.Split(string(buf[:n]), "\n\n") {
|
||||
header, _, _ := strings.Cut(stack, "\n")
|
||||
if strings.Contains(header, "[sync.Cond.Wait") && strings.Contains(stack, "."+caller+"(") {
|
||||
return
|
||||
}
|
||||
}
|
||||
runtime.Gosched()
|
||||
}
|
||||
t.Fatalf("%s never waited for the handle lock", caller)
|
||||
}
|
||||
|
||||
// A hard-linked file a peer replaced under one of its names lives on under
|
||||
// the others. The handle stays with it, under a name this mount knows, as
|
||||
// after a peer's unlink of one name: marking it deleted would drop what the
|
||||
// descriptor, or a later open of the other name, writes next.
|
||||
func TestPeerReplacementOfOneHardLinkNameKeepsTheHandle(t *testing.T) {
|
||||
wfs := newInvalidateTestWFS(t)
|
||||
|
||||
file, alias := util.FullPath("/dir/file"), util.FullPath("/dir/alias")
|
||||
linkId := []byte{7, 7, 7}
|
||||
inode := wfs.inodeToPath.Lookup(file, time.Now().Unix(), false, true, 42, true)
|
||||
if got := wfs.inodeToPath.Lookup(alias, time.Now().Unix(), false, true, 42, true); got != inode {
|
||||
t.Fatalf("alias inode %d, want the file's %d", got, inode)
|
||||
}
|
||||
base := flushConditionEntry(1)
|
||||
base.HardLinkId, base.HardLinkCounter = linkId, 2
|
||||
wfs.mapPbIdFromFilerToLocal(base)
|
||||
fh, _, _, _ := wfs.fhMap.AcquireFileHandle(wfs, inode, base, 0, 0)
|
||||
|
||||
replacement := flushConditionEntry(7)
|
||||
replacement.Attributes.Inode = 99
|
||||
resp := &filer_pb.SubscribeMetadataResponse{
|
||||
Directory: "/dir",
|
||||
TsNs: 1500,
|
||||
EventNotification: &filer_pb.EventNotification{
|
||||
OldEntry: flushConditionEntry(1),
|
||||
NewEntry: replacement,
|
||||
NewParentPath: "/dir",
|
||||
},
|
||||
}
|
||||
if err := wfs.metaCache.ApplyMetadataResponse(context.Background(), resp, meta_cache.SubscriberMetadataResponseApplyOptions); err != nil {
|
||||
t.Fatalf("apply: %v", err)
|
||||
}
|
||||
wfs.metaCache.WaitForEntryInvalidations()
|
||||
|
||||
if fh.isDeleted {
|
||||
t.Fatal("handle marked deleted although the file lives on under its other name")
|
||||
}
|
||||
if got := chunkFileKeys(fh.GetEntry().GetEntry()); len(got) != 1 || got[0] != 1 {
|
||||
t.Fatalf("handle chunks %v, want its own", got)
|
||||
}
|
||||
if got := fh.FullPath(); got != alias {
|
||||
t.Fatalf("handle path %q, want the surviving name %q", got, alias)
|
||||
}
|
||||
if string(fh.linkRefresh) != string(linkId) {
|
||||
t.Fatalf("linkRefresh %v, want %v so the next flush reads the survivor's entry", fh.linkRefresh, linkId)
|
||||
}
|
||||
if got, found := wfs.inodeToPath.GetInode(file); found && got == inode {
|
||||
t.Fatal("the replaced name still answers to the hard link's inode")
|
||||
}
|
||||
if got, found := wfs.inodeToPath.GetInode(alias); !found || got != inode {
|
||||
t.Fatalf("the surviving name answers to inode %d (found %v), want %d", got, found, inode)
|
||||
}
|
||||
}
|
||||
|
||||
// A peer renames the open file away and another file takes the old name. When
|
||||
// the cache holds both changes before the rename is applied to the handle,
|
||||
// the handle has already followed its file: what sits at the name it left is
|
||||
// not a replacement of it, and not its entry either.
|
||||
func TestRenamedHandleIgnoresWhatTookItsOldName(t *testing.T) {
|
||||
wfs := newInvalidateTestWFS(t)
|
||||
|
||||
dir := util.FullPath("/dir")
|
||||
wfs.inodeToPath.Lookup(dir, time.Now().Unix(), true, false, 0, true)
|
||||
wfs.inodeToPath.MarkChildrenCached(dir)
|
||||
current, archive := dir.Child("current"), dir.Child("archive")
|
||||
inode := wfs.inodeToPath.Lookup(current, time.Now().Unix(), false, false, 0, true)
|
||||
base := flushConditionEntry(1)
|
||||
base.Name = "current"
|
||||
wfs.mapPbIdFromFilerToLocal(base)
|
||||
fh, _, _, _ := wfs.fhMap.AcquireFileHandle(wfs, inode, base, 0, 0)
|
||||
|
||||
// hold the worker at its first invalidation until both events are cached
|
||||
gate := make(chan struct{})
|
||||
var openGate sync.Once
|
||||
release := func() { openGate.Do(func() { close(gate) }) }
|
||||
t.Cleanup(release)
|
||||
var first atomic.Bool
|
||||
wfs.SetEntryChangeListener(func(meta_cache.EntryInvalidation) {
|
||||
if first.CompareAndSwap(false, true) {
|
||||
<-gate
|
||||
}
|
||||
})
|
||||
moved := flushConditionEntry(1)
|
||||
moved.Name = "archive"
|
||||
old := flushConditionEntry(1)
|
||||
old.Name = "current"
|
||||
newcomer := flushConditionEntry(7)
|
||||
newcomer.Name = "current"
|
||||
newcomer.Attributes.Inode = 99
|
||||
for _, resp := range []*filer_pb.SubscribeMetadataResponse{
|
||||
{Directory: "/dir", TsNs: 1500, EventNotification: &filer_pb.EventNotification{OldEntry: old, NewEntry: moved, NewParentPath: "/dir"}},
|
||||
{Directory: "/dir", TsNs: 1600, EventNotification: &filer_pb.EventNotification{NewEntry: newcomer, NewParentPath: "/dir"}},
|
||||
} {
|
||||
if err := wfs.metaCache.ApplyMetadataResponse(context.Background(), resp, meta_cache.SubscriberMetadataResponseApplyOptions); err != nil {
|
||||
t.Fatalf("apply: %v", err)
|
||||
}
|
||||
}
|
||||
release()
|
||||
wfs.metaCache.WaitForEntryInvalidations()
|
||||
|
||||
if fh.isDeleted {
|
||||
t.Fatal("handle marked deleted for the file that took its old name; its writes to the renamed file would be dropped")
|
||||
}
|
||||
if got := fh.FullPath(); got != archive {
|
||||
t.Fatalf("handle path %q, want %q", got, archive)
|
||||
}
|
||||
if got := fh.GetEntry().GetEntry().GetAttributes().GetInode(); got != 42 {
|
||||
t.Fatalf("handle holds the entry of inode %d, want its own 42", got)
|
||||
}
|
||||
if got := chunkFileKeys(fh.GetEntry().GetEntry()); len(got) != 1 || got[0] != 1 {
|
||||
t.Fatalf("handle chunks %v, want its own", got)
|
||||
}
|
||||
}
|
||||
|
||||
// RemovePathOf drops a name only while it is the inode's: a rename on this
|
||||
// mount may have handed it to another inode in between.
|
||||
func TestRemovePathOfLeavesAnotherInodesName(t *testing.T) {
|
||||
table := NewInodeToPath(util.FullPath("/"), 0)
|
||||
path := util.FullPath("/dir/file")
|
||||
inode := table.Lookup(path, time.Now().Unix(), false, false, 0, true)
|
||||
|
||||
if table.RemovePathOf(inode+1, path) {
|
||||
t.Fatal("removed a name that belongs to another inode")
|
||||
}
|
||||
if got, found := table.GetInode(path); !found || got != inode {
|
||||
t.Fatalf("the name answers to %d (found %v), want %d", got, found, inode)
|
||||
}
|
||||
if !table.RemovePathOf(inode, path) {
|
||||
t.Fatal("did not remove the inode's own name")
|
||||
}
|
||||
if _, found := table.GetInode(path); found {
|
||||
t.Fatal("the name is still there")
|
||||
}
|
||||
if !table.HasInode(inode) {
|
||||
t.Fatal("the inode went with its name; its open handle still needs it")
|
||||
}
|
||||
}
|
||||
|
||||
// An update in place keeps the file's inode, and an entry without an inode
|
||||
// cannot tell which file it is: a clean handle installs both, as before.
|
||||
func TestPeerUpdateOfTheSameFileStillInstalls(t *testing.T) {
|
||||
for _, name := range []string{"same-inode", "event-without-inode", "handle-without-inode"} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
wfs := newInvalidateTestWFS(t)
|
||||
|
||||
path := util.FullPath("/dir/file")
|
||||
inode := wfs.inodeToPath.Lookup(path, time.Now().Unix(), false, false, 0, true)
|
||||
base := flushConditionEntry(1)
|
||||
update := flushConditionEntry(7)
|
||||
switch name {
|
||||
case "event-without-inode":
|
||||
update.Attributes.Inode = 0
|
||||
case "handle-without-inode":
|
||||
base.Attributes.Inode = 0
|
||||
update.Attributes.Inode = 99
|
||||
}
|
||||
wfs.mapPbIdFromFilerToLocal(base)
|
||||
fh, _, _, _ := wfs.fhMap.AcquireFileHandle(wfs, inode, base, 0, 0)
|
||||
|
||||
resp := &filer_pb.SubscribeMetadataResponse{
|
||||
Directory: "/dir",
|
||||
TsNs: 1500,
|
||||
EventNotification: &filer_pb.EventNotification{
|
||||
OldEntry: flushConditionEntry(1),
|
||||
NewEntry: update,
|
||||
NewParentPath: "/dir",
|
||||
},
|
||||
}
|
||||
if err := wfs.metaCache.ApplyMetadataResponse(context.Background(), resp, meta_cache.SubscriberMetadataResponseApplyOptions); err != nil {
|
||||
t.Fatalf("apply: %v", err)
|
||||
}
|
||||
wfs.metaCache.WaitForEntryInvalidations()
|
||||
|
||||
if fh.isDeleted {
|
||||
t.Fatal("handle marked deleted by an update of its own file; later writes would be dropped")
|
||||
}
|
||||
if got := chunkFileKeys(fh.GetEntry().GetEntry()); len(got) != 1 || got[0] != 7 {
|
||||
t.Fatalf("handle chunks %v, want the update's", got)
|
||||
}
|
||||
if got, found := wfs.inodeToPath.GetInode(path); !found || got != inode {
|
||||
t.Fatalf("the name answers to inode %d (found %v), want the handle's %d", got, found, inode)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A peer replacing the file at the handle's path (another inode) leaves the
|
||||
// dirty handle's writes and base alone instead of installing the newcomer,
|
||||
// and the handle's flush then fails without touching the replacement.
|
||||
|
||||
@@ -17,7 +17,6 @@ service VectorService {
|
||||
rpc DeleteVectors(DeleteVectorsRequest) returns (DeleteVectorsResponse);
|
||||
rpc ListVectors(ListVectorsRequest) returns (ListVectorsResponse);
|
||||
rpc QueryVectors(QueryVectorsRequest) returns (QueryVectorsResponse);
|
||||
rpc QueryIndexedVectors(QueryVectorsRequest) returns (QueryVectorsResponse);
|
||||
// How this engine's queries of an index filtered on each metadata key
|
||||
// over the last hour.
|
||||
rpc FilterStats(FilterStatsRequest) returns (FilterStatsResponse);
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// Code generated by protoc-gen-go. DO NOT EDIT.
|
||||
// versions:
|
||||
// protoc-gen-go v1.36.6
|
||||
// protoc v7.35.0
|
||||
// protoc v3.21.12
|
||||
// source: vector.proto
|
||||
|
||||
package vector_pb
|
||||
@@ -1654,7 +1654,7 @@ const file_vector_proto_rawDesc = "" +
|
||||
"\x02L2\x10\x01\x12\n" +
|
||||
"\n" +
|
||||
"\x06COSINE\x10\x02\x12\x0f\n" +
|
||||
"\vDOT_PRODUCT\x10\x032\x80\a\n" +
|
||||
"\vDOT_PRODUCT\x10\x032\xa8\x06\n" +
|
||||
"\rVectorService\x12L\n" +
|
||||
"\vCreateIndex\x12\x1d.vector_pb.CreateIndexRequest\x1a\x1e.vector_pb.CreateIndexResponse\x12F\n" +
|
||||
"\tDropIndex\x12\x1b.vector_pb.DropIndexRequest\x1a\x1c.vector_pb.DropIndexResponse\x12I\n" +
|
||||
@@ -1664,8 +1664,7 @@ const file_vector_proto_rawDesc = "" +
|
||||
"GetVectors\x12\x1c.vector_pb.GetVectorsRequest\x1a\x1d.vector_pb.GetVectorsResponse\x12R\n" +
|
||||
"\rDeleteVectors\x12\x1f.vector_pb.DeleteVectorsRequest\x1a .vector_pb.DeleteVectorsResponse\x12L\n" +
|
||||
"\vListVectors\x12\x1d.vector_pb.ListVectorsRequest\x1a\x1e.vector_pb.ListVectorsResponse\x12O\n" +
|
||||
"\fQueryVectors\x12\x1e.vector_pb.QueryVectorsRequest\x1a\x1f.vector_pb.QueryVectorsResponse\x12V\n" +
|
||||
"\x13QueryIndexedVectors\x12\x1e.vector_pb.QueryVectorsRequest\x1a\x1f.vector_pb.QueryVectorsResponse\x12L\n" +
|
||||
"\fQueryVectors\x12\x1e.vector_pb.QueryVectorsRequest\x1a\x1f.vector_pb.QueryVectorsResponse\x12L\n" +
|
||||
"\vFilterStats\x12\x1d.vector_pb.FilterStatsRequest\x1a\x1e.vector_pb.FilterStatsResponse\x12O\n" +
|
||||
"\fMetadataKeys\x12\x1e.vector_pb.MetadataKeysRequest\x1a\x1f.vector_pb.MetadataKeysResponse\x12Y\n" +
|
||||
"\x11UpdateMetadataKey\x12#.vector_pb.UpdateMetadataKeyRequest\x1a\x1f.vector_pb.MetadataKeysResponseB2Z0github.com/seaweedfs/seaweedfs/weed/pb/vector_pbb\x06proto3"
|
||||
@@ -1739,23 +1738,21 @@ var file_vector_proto_depIdxs = []int32{
|
||||
11, // 23: vector_pb.VectorService.DeleteVectors:input_type -> vector_pb.DeleteVectorsRequest
|
||||
13, // 24: vector_pb.VectorService.ListVectors:input_type -> vector_pb.ListVectorsRequest
|
||||
15, // 25: vector_pb.VectorService.QueryVectors:input_type -> vector_pb.QueryVectorsRequest
|
||||
15, // 26: vector_pb.VectorService.QueryIndexedVectors:input_type -> vector_pb.QueryVectorsRequest
|
||||
18, // 27: vector_pb.VectorService.FilterStats:input_type -> vector_pb.FilterStatsRequest
|
||||
21, // 28: vector_pb.VectorService.MetadataKeys:input_type -> vector_pb.MetadataKeysRequest
|
||||
24, // 29: vector_pb.VectorService.UpdateMetadataKey:input_type -> vector_pb.UpdateMetadataKeyRequest
|
||||
3, // 30: vector_pb.VectorService.CreateIndex:output_type -> vector_pb.CreateIndexResponse
|
||||
5, // 31: vector_pb.VectorService.DropIndex:output_type -> vector_pb.DropIndexResponse
|
||||
8, // 32: vector_pb.VectorService.PutVectors:output_type -> vector_pb.PutVectorsResponse
|
||||
10, // 33: vector_pb.VectorService.GetVectors:output_type -> vector_pb.GetVectorsResponse
|
||||
12, // 34: vector_pb.VectorService.DeleteVectors:output_type -> vector_pb.DeleteVectorsResponse
|
||||
14, // 35: vector_pb.VectorService.ListVectors:output_type -> vector_pb.ListVectorsResponse
|
||||
17, // 36: vector_pb.VectorService.QueryVectors:output_type -> vector_pb.QueryVectorsResponse
|
||||
17, // 37: vector_pb.VectorService.QueryIndexedVectors:output_type -> vector_pb.QueryVectorsResponse
|
||||
20, // 38: vector_pb.VectorService.FilterStats:output_type -> vector_pb.FilterStatsResponse
|
||||
23, // 39: vector_pb.VectorService.MetadataKeys:output_type -> vector_pb.MetadataKeysResponse
|
||||
23, // 40: vector_pb.VectorService.UpdateMetadataKey:output_type -> vector_pb.MetadataKeysResponse
|
||||
30, // [30:41] is the sub-list for method output_type
|
||||
19, // [19:30] is the sub-list for method input_type
|
||||
18, // 26: vector_pb.VectorService.FilterStats:input_type -> vector_pb.FilterStatsRequest
|
||||
21, // 27: vector_pb.VectorService.MetadataKeys:input_type -> vector_pb.MetadataKeysRequest
|
||||
24, // 28: vector_pb.VectorService.UpdateMetadataKey:input_type -> vector_pb.UpdateMetadataKeyRequest
|
||||
3, // 29: vector_pb.VectorService.CreateIndex:output_type -> vector_pb.CreateIndexResponse
|
||||
5, // 30: vector_pb.VectorService.DropIndex:output_type -> vector_pb.DropIndexResponse
|
||||
8, // 31: vector_pb.VectorService.PutVectors:output_type -> vector_pb.PutVectorsResponse
|
||||
10, // 32: vector_pb.VectorService.GetVectors:output_type -> vector_pb.GetVectorsResponse
|
||||
12, // 33: vector_pb.VectorService.DeleteVectors:output_type -> vector_pb.DeleteVectorsResponse
|
||||
14, // 34: vector_pb.VectorService.ListVectors:output_type -> vector_pb.ListVectorsResponse
|
||||
17, // 35: vector_pb.VectorService.QueryVectors:output_type -> vector_pb.QueryVectorsResponse
|
||||
20, // 36: vector_pb.VectorService.FilterStats:output_type -> vector_pb.FilterStatsResponse
|
||||
23, // 37: vector_pb.VectorService.MetadataKeys:output_type -> vector_pb.MetadataKeysResponse
|
||||
23, // 38: vector_pb.VectorService.UpdateMetadataKey:output_type -> vector_pb.MetadataKeysResponse
|
||||
29, // [29:39] is the sub-list for method output_type
|
||||
19, // [19:29] is the sub-list for method input_type
|
||||
19, // [19:19] is the sub-list for extension type_name
|
||||
19, // [19:19] is the sub-list for extension extendee
|
||||
0, // [0:19] is the sub-list for field type_name
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// Code generated by protoc-gen-go-grpc. DO NOT EDIT.
|
||||
// versions:
|
||||
// - protoc-gen-go-grpc v1.6.2
|
||||
// - protoc v7.35.0
|
||||
// - protoc v3.21.12
|
||||
// source: vector.proto
|
||||
|
||||
package vector_pb
|
||||
@@ -19,17 +19,16 @@ import (
|
||||
const _ = grpc.SupportPackageIsVersion9
|
||||
|
||||
const (
|
||||
VectorService_CreateIndex_FullMethodName = "/vector_pb.VectorService/CreateIndex"
|
||||
VectorService_DropIndex_FullMethodName = "/vector_pb.VectorService/DropIndex"
|
||||
VectorService_PutVectors_FullMethodName = "/vector_pb.VectorService/PutVectors"
|
||||
VectorService_GetVectors_FullMethodName = "/vector_pb.VectorService/GetVectors"
|
||||
VectorService_DeleteVectors_FullMethodName = "/vector_pb.VectorService/DeleteVectors"
|
||||
VectorService_ListVectors_FullMethodName = "/vector_pb.VectorService/ListVectors"
|
||||
VectorService_QueryVectors_FullMethodName = "/vector_pb.VectorService/QueryVectors"
|
||||
VectorService_QueryIndexedVectors_FullMethodName = "/vector_pb.VectorService/QueryIndexedVectors"
|
||||
VectorService_FilterStats_FullMethodName = "/vector_pb.VectorService/FilterStats"
|
||||
VectorService_MetadataKeys_FullMethodName = "/vector_pb.VectorService/MetadataKeys"
|
||||
VectorService_UpdateMetadataKey_FullMethodName = "/vector_pb.VectorService/UpdateMetadataKey"
|
||||
VectorService_CreateIndex_FullMethodName = "/vector_pb.VectorService/CreateIndex"
|
||||
VectorService_DropIndex_FullMethodName = "/vector_pb.VectorService/DropIndex"
|
||||
VectorService_PutVectors_FullMethodName = "/vector_pb.VectorService/PutVectors"
|
||||
VectorService_GetVectors_FullMethodName = "/vector_pb.VectorService/GetVectors"
|
||||
VectorService_DeleteVectors_FullMethodName = "/vector_pb.VectorService/DeleteVectors"
|
||||
VectorService_ListVectors_FullMethodName = "/vector_pb.VectorService/ListVectors"
|
||||
VectorService_QueryVectors_FullMethodName = "/vector_pb.VectorService/QueryVectors"
|
||||
VectorService_FilterStats_FullMethodName = "/vector_pb.VectorService/FilterStats"
|
||||
VectorService_MetadataKeys_FullMethodName = "/vector_pb.VectorService/MetadataKeys"
|
||||
VectorService_UpdateMetadataKey_FullMethodName = "/vector_pb.VectorService/UpdateMetadataKey"
|
||||
)
|
||||
|
||||
// VectorServiceClient is the client API for VectorService service.
|
||||
@@ -47,7 +46,6 @@ type VectorServiceClient interface {
|
||||
DeleteVectors(ctx context.Context, in *DeleteVectorsRequest, opts ...grpc.CallOption) (*DeleteVectorsResponse, error)
|
||||
ListVectors(ctx context.Context, in *ListVectorsRequest, opts ...grpc.CallOption) (*ListVectorsResponse, error)
|
||||
QueryVectors(ctx context.Context, in *QueryVectorsRequest, opts ...grpc.CallOption) (*QueryVectorsResponse, error)
|
||||
QueryIndexedVectors(ctx context.Context, in *QueryVectorsRequest, opts ...grpc.CallOption) (*QueryVectorsResponse, error)
|
||||
// How this engine's queries of an index filtered on each metadata key
|
||||
// over the last hour.
|
||||
FilterStats(ctx context.Context, in *FilterStatsRequest, opts ...grpc.CallOption) (*FilterStatsResponse, error)
|
||||
@@ -136,16 +134,6 @@ func (c *vectorServiceClient) QueryVectors(ctx context.Context, in *QueryVectors
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *vectorServiceClient) QueryIndexedVectors(ctx context.Context, in *QueryVectorsRequest, opts ...grpc.CallOption) (*QueryVectorsResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(QueryVectorsResponse)
|
||||
err := c.cc.Invoke(ctx, VectorService_QueryIndexedVectors_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *vectorServiceClient) FilterStats(ctx context.Context, in *FilterStatsRequest, opts ...grpc.CallOption) (*FilterStatsResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(FilterStatsResponse)
|
||||
@@ -191,7 +179,6 @@ type VectorServiceServer interface {
|
||||
DeleteVectors(context.Context, *DeleteVectorsRequest) (*DeleteVectorsResponse, error)
|
||||
ListVectors(context.Context, *ListVectorsRequest) (*ListVectorsResponse, error)
|
||||
QueryVectors(context.Context, *QueryVectorsRequest) (*QueryVectorsResponse, error)
|
||||
QueryIndexedVectors(context.Context, *QueryVectorsRequest) (*QueryVectorsResponse, error)
|
||||
// How this engine's queries of an index filtered on each metadata key
|
||||
// over the last hour.
|
||||
FilterStats(context.Context, *FilterStatsRequest) (*FilterStatsResponse, error)
|
||||
@@ -231,9 +218,6 @@ func (UnimplementedVectorServiceServer) ListVectors(context.Context, *ListVector
|
||||
func (UnimplementedVectorServiceServer) QueryVectors(context.Context, *QueryVectorsRequest) (*QueryVectorsResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method QueryVectors not implemented")
|
||||
}
|
||||
func (UnimplementedVectorServiceServer) QueryIndexedVectors(context.Context, *QueryVectorsRequest) (*QueryVectorsResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method QueryIndexedVectors not implemented")
|
||||
}
|
||||
func (UnimplementedVectorServiceServer) FilterStats(context.Context, *FilterStatsRequest) (*FilterStatsResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method FilterStats not implemented")
|
||||
}
|
||||
@@ -390,24 +374,6 @@ func _VectorService_QueryVectors_Handler(srv interface{}, ctx context.Context, d
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _VectorService_QueryIndexedVectors_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(QueryVectorsRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(VectorServiceServer).QueryIndexedVectors(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: VectorService_QueryIndexedVectors_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(VectorServiceServer).QueryIndexedVectors(ctx, req.(*QueryVectorsRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _VectorService_FilterStats_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(FilterStatsRequest)
|
||||
if err := dec(in); err != nil {
|
||||
@@ -497,10 +463,6 @@ var VectorService_ServiceDesc = grpc.ServiceDesc{
|
||||
MethodName: "QueryVectors",
|
||||
Handler: _VectorService_QueryVectors_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "QueryIndexedVectors",
|
||||
Handler: _VectorService_QueryIndexedVectors_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "FilterStats",
|
||||
Handler: _VectorService_FilterStats_Handler,
|
||||
|
||||
@@ -325,7 +325,7 @@ func (iam *IdentityAccessManagement) verifyV4Signature(r *http.Request, shouldCh
|
||||
return nil, nil, "", nil, errCode
|
||||
}
|
||||
|
||||
// 5a. Reject requests with headers that require signing outside of SignedHeaders.
|
||||
// 5a. Reject requests that carry x-amz-* headers outside of SignedHeaders.
|
||||
// Without this check a presigned-URL holder can inject unsigned headers
|
||||
// (x-amz-tagging, x-amz-acl, x-amz-meta-*, x-amz-storage-class, x-amz-object-lock-*,
|
||||
// x-amz-server-side-encryption*, etc.) that downstream handlers still persist.
|
||||
@@ -965,8 +965,8 @@ var presignedUnsignedSSECHeaders = map[string]struct{}{
|
||||
strings.ToLower(s3_constants.AmzCopySourceServerSideEncryptionCustomerKeyMD5): {},
|
||||
}
|
||||
|
||||
// verifySignedHeadersCoverage checks x-amz-* headers and the vector search
|
||||
// mode header against SignedHeaders. AWS SigV4 requires every x-amz-* header
|
||||
// verifySignedHeadersCoverage rejects requests that carry x-amz-* headers
|
||||
// outside of the SignedHeaders list. AWS SigV4 requires every x-amz-* header
|
||||
// present in the request to be covered by the signature; without this check a
|
||||
// presigned-URL holder can add unsigned headers (ACL, tagging, storage class,
|
||||
// user metadata, encryption options, object lock) that the server still
|
||||
@@ -978,7 +978,7 @@ func verifySignedHeadersCoverage(r *http.Request, signedHeaders []string, isPres
|
||||
}
|
||||
for name := range r.Header {
|
||||
lower := strings.ToLower(name)
|
||||
if !strings.HasPrefix(lower, "x-amz-") && lower != s3_constants.SeaweedFSVectorSearchMode {
|
||||
if !strings.HasPrefix(lower, "x-amz-") {
|
||||
continue
|
||||
}
|
||||
if _, ok := signedSet[lower]; ok {
|
||||
|
||||
@@ -8,56 +8,9 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
|
||||
)
|
||||
|
||||
func TestVectorSearchModeRequiresSignatureCoverage(t *testing.T) {
|
||||
const accessKey = "AKIAIOSFODNN7EXAMPLE"
|
||||
const secretKey = "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"
|
||||
const header = s3_constants.SeaweedFSVectorSearchMode
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
presigned, signed bool
|
||||
}{
|
||||
{name: "unsigned header"},
|
||||
{name: "signed header", signed: true},
|
||||
{name: "unsigned presigned header", presigned: true},
|
||||
{name: "signed presigned header", presigned: true, signed: true},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
iam := newTestIAM()
|
||||
req, err := newTestRequest(http.MethodPost, "http://127.0.0.1:9000/QueryVectors", 0, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
signedHeaders := []string{"host"}
|
||||
if tc.signed {
|
||||
req.Header.Set(header, "indexed-only")
|
||||
signedHeaders = append(signedHeaders, header)
|
||||
}
|
||||
if tc.presigned {
|
||||
err = preSignV4WithHeaders(iam, req, accessKey, secretKey, 600, signedHeaders)
|
||||
} else {
|
||||
err = signRequestV4(req, accessKey, secretKey)
|
||||
req.Header.Set("Authorization", strings.Replace(req.Header.Get("Authorization"), signV4Algorithm+" ", signV4Algorithm, 1))
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, got := iam.reqSignatureV4Verify(req); got != s3err.ErrNone {
|
||||
t.Fatalf("expected valid signature, got %v", got)
|
||||
}
|
||||
if !tc.signed {
|
||||
req.Header.Set(header, "indexed-only")
|
||||
if _, got := iam.reqSignatureV4Verify(req); got != s3err.ErrSignatureDoesNotMatch {
|
||||
t.Fatalf("expected unsigned search mode to be rejected, got %v", got)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestVerifySignedHeadersCoverage_Unit exercises the helper directly.
|
||||
func TestVerifySignedHeadersCoverage_Unit(t *testing.T) {
|
||||
tests := []struct {
|
||||
|
||||
@@ -67,7 +67,6 @@ const (
|
||||
SeaweedFSMultipartPartsCount = "X-Seaweedfs-Multipart-Parts-Count"
|
||||
SeaweedFSMultipartPartBoundaries = "X-Seaweedfs-Multipart-Part-Boundaries" // JSON: [{part:1,start:0,end:2,etag:"abc"},{part:2,start:2,end:3,etag:"def"}]
|
||||
SeaweedFSExpiresS3 = "X-Seaweedfs-Expires-S3"
|
||||
SeaweedFSVectorSearchMode = "x-seaweedfs-vector-search-mode"
|
||||
AmzMpPartsCount = "x-amz-mp-parts-count"
|
||||
|
||||
// S3 ACL headers
|
||||
|
||||
@@ -123,13 +123,6 @@ func (c *describedClient) QueryVectors(ctx context.Context, in *vector_pb.QueryV
|
||||
return c.VectorServiceClient.QueryVectors(ctx, in, opts...)
|
||||
}
|
||||
|
||||
func (c *describedClient) QueryIndexedVectors(ctx context.Context, in *vector_pb.QueryVectorsRequest, opts ...grpc.CallOption) (*vector_pb.QueryVectorsResponse, error) {
|
||||
if err := c.resolve(ctx, in.Table); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return c.VectorServiceClient.QueryIndexedVectors(ctx, in, opts...)
|
||||
}
|
||||
|
||||
func (c *describedClient) MetadataKeys(ctx context.Context, in *vector_pb.MetadataKeysRequest, opts ...grpc.CallOption) (*vector_pb.MetadataKeysResponse, error) {
|
||||
if err := c.resolve(ctx, in.Table); err != nil {
|
||||
return nil, err
|
||||
|
||||
@@ -326,27 +326,6 @@ func (d *vectorDiscovery) QueryVectors(ctx context.Context, in *vector_pb.QueryV
|
||||
return nil, err
|
||||
}
|
||||
|
||||
func (d *vectorDiscovery) QueryIndexedVectors(ctx context.Context, in *vector_pb.QueryVectorsRequest, opts ...grpc.CallOption) (resp *vector_pb.QueryVectorsResponse, err error) {
|
||||
for attempt := 0; attempt < 2; attempt++ {
|
||||
var c vector_pb.VectorServiceClient
|
||||
if c, err = d.cli(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
resp, err = c.QueryIndexedVectors(ctx, in, opts...)
|
||||
if isTransportError(err) {
|
||||
d.reset(c)
|
||||
}
|
||||
d.release(c)
|
||||
if err == nil {
|
||||
return resp, nil
|
||||
}
|
||||
if !isTransportError(err) {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
func (d *vectorDiscovery) FilterStats(ctx context.Context, in *vector_pb.FilterStatsRequest, opts ...grpc.CallOption) (resp *vector_pb.FilterStatsResponse, err error) {
|
||||
for attempt := 0; attempt < 2; attempt++ {
|
||||
var c vector_pb.VectorServiceClient
|
||||
|
||||
@@ -2159,11 +2159,6 @@ func sqlLiteral(v interface{}) (string, error) {
|
||||
}
|
||||
|
||||
func (s *Server) handleQueryVectors(w http.ResponseWriter, r *http.Request) {
|
||||
indexedOnly, err := searchMode(r)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusBadRequest, "ValidationException", err.Error())
|
||||
return
|
||||
}
|
||||
var req QueryVectorsRequest
|
||||
if err := readJSON(r, &req); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "ValidationException", err.Error())
|
||||
@@ -2217,14 +2212,14 @@ func (s *Server) handleQueryVectors(w http.ResponseWriter, r *http.Request) {
|
||||
writeError(w, http.StatusBadRequest, "ValidationException", err.Error())
|
||||
return
|
||||
}
|
||||
resp, err := s.queryVectors(w, r, &vector_pb.QueryVectorsRequest{
|
||||
resp, err := s.vectors.QueryVectors(r.Context(), &vector_pb.QueryVectorsRequest{
|
||||
Table: tableID(arns.bucket, arns.index),
|
||||
QueryVector: queryVector,
|
||||
TopK: uint32(req.TopK),
|
||||
Filter: filter,
|
||||
ReturnMetadata: req.ReturnMetadata,
|
||||
ReturnDistance: req.ReturnDistance,
|
||||
}, indexedOnly)
|
||||
})
|
||||
if err != nil {
|
||||
vectorErr(w, r, arns, err)
|
||||
return
|
||||
|
||||
@@ -1,58 +0,0 @@
|
||||
package s3vectors
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/vector_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/metadata"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
const (
|
||||
searchModeHeader = s3_constants.SeaweedFSVectorSearchMode
|
||||
excludedFragmentsHeader = "x-seaweedfs-vector-excluded-fragments"
|
||||
dataExcludedHeader = "x-seaweedfs-vector-data-excluded"
|
||||
)
|
||||
|
||||
func searchMode(r *http.Request) (bool, error) {
|
||||
values := r.Header.Values(searchModeHeader)
|
||||
if len(values) == 0 {
|
||||
return false, nil
|
||||
}
|
||||
if len(values) != 1 || (values[0] != "all" && values[0] != "indexed-only") {
|
||||
return false, fmt.Errorf("%s must be all or indexed-only", searchModeHeader)
|
||||
}
|
||||
return values[0] == "indexed-only", nil
|
||||
}
|
||||
|
||||
func (s *Server) queryVectors(w http.ResponseWriter, r *http.Request, req *vector_pb.QueryVectorsRequest, indexedOnly bool) (*vector_pb.QueryVectorsResponse, error) {
|
||||
if !indexedOnly {
|
||||
return s.vectors.QueryVectors(r.Context(), req)
|
||||
}
|
||||
var headers metadata.MD
|
||||
resp, err := s.vectors.QueryIndexedVectors(r.Context(), req, grpc.Header(&headers))
|
||||
if status.Code(err) == codes.Unimplemented {
|
||||
return nil, status.Error(codes.Unavailable, "indexed-only search requires an updated vector engine")
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
mode := headers.Get(searchModeHeader)
|
||||
excluded := headers.Get(excludedFragmentsHeader)
|
||||
if len(mode) != 1 || mode[0] != "indexed-only" || len(excluded) != 1 {
|
||||
return nil, status.Error(codes.Unavailable, "vector engine did not acknowledge indexed-only search")
|
||||
}
|
||||
count, err := strconv.ParseUint(excluded[0], 10, 64)
|
||||
if err != nil {
|
||||
return nil, status.Error(codes.Internal, "invalid indexed-only coverage response")
|
||||
}
|
||||
w.Header().Set(searchModeHeader, mode[0])
|
||||
w.Header().Set(excludedFragmentsHeader, excluded[0])
|
||||
w.Header().Set(dataExcludedHeader, strconv.FormatBool(count > 0))
|
||||
return resp, nil
|
||||
}
|
||||
@@ -1,151 +0,0 @@
|
||||
package s3vectors
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/vector_pb"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/metadata"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
func TestSearchMode(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name, mode string
|
||||
indexed, invalid bool
|
||||
}{
|
||||
{name: "default"},
|
||||
{name: "all", mode: "all"},
|
||||
{name: "indexed", mode: "indexed-only", indexed: true},
|
||||
{name: "unknown", mode: "fast", invalid: true},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
r := httptest.NewRequest(http.MethodPost, "/QueryVectors", nil)
|
||||
if tc.mode != "" {
|
||||
r.Header.Set(searchModeHeader, tc.mode)
|
||||
}
|
||||
indexed, err := searchMode(r)
|
||||
if indexed != tc.indexed || (err != nil) != tc.invalid {
|
||||
t.Fatalf("indexed=%v err=%v", indexed, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
for _, values := range [][]string{{""}, {"all", "indexed-only"}, {"indexed-only,all"}} {
|
||||
r := httptest.NewRequest(http.MethodPost, "/QueryVectors", nil)
|
||||
r.Header[http.CanonicalHeaderKey(searchModeHeader)] = values
|
||||
if _, err := searchMode(r); err == nil {
|
||||
t.Fatalf("accepted %v", values)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type queryClient struct {
|
||||
*fakeVectors
|
||||
headers metadata.MD
|
||||
err error
|
||||
indexed, ordinary int
|
||||
table *vector_pb.Table
|
||||
}
|
||||
|
||||
func (c *queryClient) QueryVectors(context.Context, *vector_pb.QueryVectorsRequest, ...grpc.CallOption) (*vector_pb.QueryVectorsResponse, error) {
|
||||
c.ordinary++
|
||||
return &vector_pb.QueryVectorsResponse{}, nil
|
||||
}
|
||||
|
||||
func (c *queryClient) QueryIndexedVectors(_ context.Context, req *vector_pb.QueryVectorsRequest, opts ...grpc.CallOption) (*vector_pb.QueryVectorsResponse, error) {
|
||||
c.indexed++
|
||||
c.table = req.Table
|
||||
for _, opt := range opts {
|
||||
if header, ok := opt.(grpc.HeaderCallOption); ok {
|
||||
*header.HeaderAddr = c.headers
|
||||
}
|
||||
}
|
||||
return &vector_pb.QueryVectorsResponse{}, c.err
|
||||
}
|
||||
|
||||
type routedQueryClient struct{ vector_pb.VectorServiceClient }
|
||||
|
||||
func (*routedQueryClient) QueryVectors(context.Context, *vector_pb.QueryVectorsRequest, ...grpc.CallOption) (*vector_pb.QueryVectorsResponse, error) {
|
||||
return nil, status.Error(codes.Internal, "distributed query must not handle indexed-only")
|
||||
}
|
||||
|
||||
func TestQueryVectorsSearchMode(t *testing.T) {
|
||||
s := &Server{}
|
||||
backend := &queryClient{fakeVectors: newFakeVectors(0)}
|
||||
s.vectors = backend
|
||||
body := `{"vectorBucketName":"vec-bucket","indexName":"live-idx","queryVector":{"float32":[1,0,0]},"topK":1}`
|
||||
for _, tc := range []struct {
|
||||
name, mode string
|
||||
headers metadata.MD
|
||||
err error
|
||||
want int
|
||||
}{
|
||||
{name: "default", want: http.StatusOK},
|
||||
{name: "explicit all", mode: "all", want: http.StatusOK},
|
||||
{name: "indexed", mode: "indexed-only", headers: metadata.Pairs(searchModeHeader, "indexed-only", excludedFragmentsHeader, "2"), want: http.StatusOK},
|
||||
{name: "old engine", mode: "indexed-only", err: status.Error(codes.Unimplemented, "old"), want: http.StatusServiceUnavailable},
|
||||
{name: "missing acknowledgement", mode: "indexed-only", want: http.StatusServiceUnavailable},
|
||||
{name: "invalid coverage", mode: "indexed-only", headers: metadata.Pairs(searchModeHeader, "indexed-only", excludedFragmentsHeader, "-1"), want: http.StatusInternalServerError},
|
||||
{name: "unsupported filter", mode: "indexed-only", err: status.Error(codes.InvalidArgument, "filter requires an index"), want: http.StatusBadRequest},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
backend.headers, backend.err = tc.headers, tc.err
|
||||
r := httptest.NewRequest(http.MethodPost, "/QueryVectors", strings.NewReader(body))
|
||||
if tc.mode != "" {
|
||||
r.Header.Set(searchModeHeader, tc.mode)
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
indexed, err := searchMode(r)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, err = s.queryVectors(w, r, &vector_pb.QueryVectorsRequest{TopK: 1}, indexed)
|
||||
if err != nil {
|
||||
vectorErr(w, r, vectorBucketARNs{}, err)
|
||||
}
|
||||
if w.Code != tc.want {
|
||||
t.Fatalf("status=%d body=%s", w.Code, w.Body)
|
||||
}
|
||||
if tc.mode == "indexed-only" && tc.want == http.StatusOK {
|
||||
if w.Header().Get(dataExcludedHeader) != "true" || w.Header().Get(excludedFragmentsHeader) != "2" {
|
||||
t.Fatalf("headers=%v", w.Header())
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
if backend.ordinary != 2 || backend.indexed != 5 {
|
||||
t.Fatalf("ordinary=%d indexed=%d", backend.ordinary, backend.indexed)
|
||||
}
|
||||
s.vectors = &describedClient{
|
||||
VectorServiceClient: &routedQueryClient{VectorServiceClient: backend},
|
||||
describe: func(_ context.Context, id []string) (string, map[string]string, error) {
|
||||
return "s3://" + strings.Join(id, "/"), nil, nil
|
||||
},
|
||||
encrypts: func(context.Context, string) (bool, error) { return true, nil },
|
||||
}
|
||||
backend.headers, backend.err = metadata.Pairs(searchModeHeader, "indexed-only", excludedFragmentsHeader, "0"), nil
|
||||
r := httptest.NewRequest(http.MethodPost, "/QueryVectors", strings.NewReader(body))
|
||||
r.Header.Set(searchModeHeader, "indexed-only")
|
||||
w := httptest.NewRecorder()
|
||||
indexed, err := searchMode(r)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, err = s.queryVectors(w, r, &vector_pb.QueryVectorsRequest{
|
||||
TopK: 1, Table: tableID("vec-bucket", "live-idx"),
|
||||
}, indexed)
|
||||
if err != nil {
|
||||
vectorErr(w, r, vectorBucketARNs{}, err)
|
||||
}
|
||||
if w.Code != http.StatusOK || w.Header().Get(dataExcludedHeader) != "false" {
|
||||
t.Fatalf("status=%d headers=%v body=%s", w.Code, w.Header(), w.Body)
|
||||
}
|
||||
if backend.table.GetLocation() != "s3://vec-bucket/vector/live-idx" || !backend.table.GetSseS3() {
|
||||
t.Fatalf("backend table = %v", backend.table)
|
||||
}
|
||||
}
|
||||
@@ -1,471 +0,0 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util/mem"
|
||||
)
|
||||
|
||||
// A chunk read whose location goes quiet is asked of another location as
|
||||
// well. A volume server sends a chunk without pauses once it has answered, so
|
||||
// a body that stops arriving for chunkReadStallDelay is waiting for a lost TCP
|
||||
// segment: the retransmission timeout is at least 200 ms and doubles with
|
||||
// every further loss, so on a lossy path one chunk can hold up a sequential
|
||||
// reader for seconds, while a fresh request takes milliseconds. Half the
|
||||
// minimum retransmission timeout still gets ahead of every such wait, and
|
||||
// lets the shorter pauses that recover on their own go by without a hedge.
|
||||
// Before the response headers the server is still reading the needle, which
|
||||
// can take a while on a busy disk, so a location gets chunkReadAnswerDelay to
|
||||
// answer; one silent for that long is on a hung or dead host, or its answer
|
||||
// was lost. Tests shorten both.
|
||||
var (
|
||||
chunkReadAnswerDelay = 200 * time.Millisecond
|
||||
chunkReadStallDelay = 100 * time.Millisecond
|
||||
)
|
||||
|
||||
// maxHedgesPerRead caps the extra requests a single chunk read can make.
|
||||
const maxHedgesPerRead = 2
|
||||
|
||||
// errNoAnswer marks a location that had not even sent its response headers by
|
||||
// the time another location delivered the chunk.
|
||||
var errNoAnswer = errors.New("no response headers before another location delivered the chunk")
|
||||
|
||||
// Hedging is budgeted so that a cluster that is slow everywhere is not asked
|
||||
// for every chunk twice: every chunk read earns a tenth of a token, every
|
||||
// hedge spends a whole one, and at most hedgeTokenBurst tokens are saved up.
|
||||
// Hedges therefore stay below a tenth of the reads, apart from a burst of ten.
|
||||
const (
|
||||
hedgeTokenScale = 1000 // tokens are counted in thousandths
|
||||
hedgeTokenEarn = hedgeTokenScale / 10
|
||||
hedgeTokenBurst = 10 * hedgeTokenScale
|
||||
)
|
||||
|
||||
var hedgeTokens = func() *atomic.Int64 {
|
||||
var tokens atomic.Int64
|
||||
tokens.Store(hedgeTokenBurst)
|
||||
return &tokens
|
||||
}()
|
||||
|
||||
func earnHedgeToken() {
|
||||
for {
|
||||
tokens := hedgeTokens.Load()
|
||||
if tokens >= hedgeTokenBurst || hedgeTokens.CompareAndSwap(tokens, min(tokens+hedgeTokenEarn, hedgeTokenBurst)) {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// refundHedgeToken gives back the token of a hedge that was not sent after all.
|
||||
func refundHedgeToken() {
|
||||
for {
|
||||
tokens := hedgeTokens.Load()
|
||||
if hedgeTokens.CompareAndSwap(tokens, min(tokens+hedgeTokenScale, hedgeTokenBurst)) {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func spendHedgeToken() bool {
|
||||
for {
|
||||
tokens := hedgeTokens.Load()
|
||||
if tokens < hedgeTokenScale {
|
||||
return false
|
||||
}
|
||||
if hedgeTokens.CompareAndSwap(tokens, tokens-hedgeTokenScale) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// chunkProgress is what a chunk read reports while it runs: when something
|
||||
// last arrived, and whether the response headers did. A nil one ignores it.
|
||||
type chunkProgress struct {
|
||||
lastArrival atomic.Int64 // unix nanoseconds
|
||||
answered atomic.Bool
|
||||
}
|
||||
|
||||
func (p *chunkProgress) arrived() {
|
||||
if p != nil {
|
||||
p.lastArrival.Store(time.Now().UnixNano())
|
||||
}
|
||||
}
|
||||
|
||||
func (p *chunkProgress) answer() {
|
||||
if p != nil {
|
||||
p.answered.Store(true)
|
||||
p.arrived()
|
||||
}
|
||||
}
|
||||
|
||||
// progressReader reports every piece of a response body that arrives.
|
||||
type progressReader struct {
|
||||
reader io.Reader
|
||||
progress *chunkProgress
|
||||
}
|
||||
|
||||
func (r progressReader) Read(p []byte) (int, error) {
|
||||
n, err := r.reader.Read(p)
|
||||
if n > 0 {
|
||||
r.progress.arrived()
|
||||
}
|
||||
return n, err
|
||||
}
|
||||
|
||||
// chunkAttempt reads a chunk from one location into dst and returns how many
|
||||
// bytes it read. It reports to progress what arrives, and stops when ctx ends.
|
||||
// A failure comes with whether another location is worth asking.
|
||||
type chunkAttempt func(ctx context.Context, url string, dst []byte, progress *chunkProgress) (n int, retryable bool, err error)
|
||||
|
||||
// ScratchBudget accounts for the buffers that hedged chunk reads borrow. A
|
||||
// caller that bounds the memory of its chunk buffers passes one in the
|
||||
// context with WithScratchBudget, and a hedge that does not fit is not sent.
|
||||
type ScratchBudget interface {
|
||||
// TryReserveScratch takes size bytes without waiting, or reports that
|
||||
// they do not fit.
|
||||
TryReserveScratch(size int) bool
|
||||
// ReleaseScratch returns what TryReserveScratch took.
|
||||
ReleaseScratch(size int)
|
||||
}
|
||||
|
||||
type scratchBudgetKey struct{}
|
||||
|
||||
// WithScratchBudget makes the chunk reads under ctx account the buffers of
|
||||
// their hedges to budget.
|
||||
func WithScratchBudget(ctx context.Context, budget ScratchBudget) context.Context {
|
||||
return context.WithValue(ctx, scratchBudgetKey{}, budget)
|
||||
}
|
||||
|
||||
// ScratchBudgetFrom returns the budget WithScratchBudget put in ctx, or nil.
|
||||
func ScratchBudgetFrom(ctx context.Context) ScratchBudget {
|
||||
budget, _ := ctx.Value(scratchBudgetKey{}).(ScratchBudget)
|
||||
return budget
|
||||
}
|
||||
|
||||
// readHedges is what one chunk read has spent on hedges, across the passes of
|
||||
// its retries.
|
||||
type readHedges struct {
|
||||
earned bool // the read has added its share to the hedge budget
|
||||
sent int
|
||||
}
|
||||
|
||||
type hedgedAttempt struct {
|
||||
url string
|
||||
dst []byte
|
||||
scratch bool // dst is not the caller's buffer and is freed when the attempt ends
|
||||
hedge bool // sent because the requests before it went quiet
|
||||
cancel context.CancelFunc
|
||||
started time.Time
|
||||
progress chunkProgress
|
||||
finished bool
|
||||
abandoned bool
|
||||
}
|
||||
|
||||
type attemptResult struct {
|
||||
attempt *hedgedAttempt
|
||||
n int
|
||||
retryable bool
|
||||
err error
|
||||
}
|
||||
|
||||
// hedgedChunkPass makes one pass over urls for a chunk read into buffer.
|
||||
//
|
||||
// Like a plain loop over the locations it asks them in order and moves on to
|
||||
// the next one as soon as one fails. Unlike it, it does not wait out a location
|
||||
// that goes quiet: once every request in flight has been quiet for longer than
|
||||
// it may be (chunkReadAnswerDelay before its response headers arrive,
|
||||
// chunkReadStallDelay after), the read is asked of the next location as well.
|
||||
// Once every location has been asked, a location whose server answered and
|
||||
// then went quiet is asked again over another connection: the server is up,
|
||||
// and only that connection is stuck. A location that has not answered is left
|
||||
// alone then, as it was before. Whichever request delivers the whole chunk
|
||||
// first wins, and the others are cancelled. hedging carries what the read has
|
||||
// spent on hedges over to the passes of its retries.
|
||||
//
|
||||
// Only one request at a time reads into buffer; the others read into buffers
|
||||
// of their own, accounted to the ScratchBudget in ctx if there is one, and a
|
||||
// winner's data is copied over once the request reading into buffer has
|
||||
// ended. buffer is not written after hedgedChunkPass returns.
|
||||
//
|
||||
// It returns the number of bytes read, whether a location failed or did not
|
||||
// answer at all on the way, which says the caller's location list may be
|
||||
// stale, and the error of the pass with whether it is worth another pass. A
|
||||
// failure that another location would not fix stops the asking, though a
|
||||
// request already in flight may still deliver the chunk. A hedge throttled by
|
||||
// its server is not such a failure: that server is only busy.
|
||||
func hedgedChunkPass(ctx context.Context, urls []string, buffer []byte, hedging *readHedges, attempt chunkAttempt) (n int, failed bool, retryable bool, err error) {
|
||||
if len(urls) == 0 {
|
||||
return 0, false, false, nil
|
||||
}
|
||||
if !hedging.earned {
|
||||
earnHedgeToken()
|
||||
hedging.earned = true
|
||||
}
|
||||
budget := ScratchBudgetFrom(ctx)
|
||||
|
||||
results := make(chan attemptResult, len(urls)+maxHedgesPerRead)
|
||||
var (
|
||||
attempts []*hedgedAttempt
|
||||
owner *hedgedAttempt // the request reading into buffer
|
||||
running int
|
||||
next int // the next location not asked yet
|
||||
hedgeOff bool // no budget or memory left for a hedge in this pass
|
||||
stopAsking bool
|
||||
finalErr error
|
||||
throttled error // a hedge's server was too busy to serve it
|
||||
)
|
||||
|
||||
// destination is where a new request reads: the caller's buffer when no
|
||||
// other request reads into it, otherwise a buffer of its own, if the
|
||||
// scratch budget has room for one.
|
||||
destination := func() (dst []byte, scratch bool, ok bool) {
|
||||
if owner == nil {
|
||||
return buffer, false, true
|
||||
}
|
||||
if budget != nil && !budget.TryReserveScratch(len(buffer)) {
|
||||
return nil, false, false
|
||||
}
|
||||
return mem.Allocate(len(buffer)), true, true
|
||||
}
|
||||
size := len(buffer)
|
||||
freeScratch := func(dst []byte) {
|
||||
mem.Free(dst)
|
||||
if budget != nil {
|
||||
budget.ReleaseScratch(size)
|
||||
}
|
||||
}
|
||||
|
||||
start := func(url string, dst []byte, scratch, hedge bool) {
|
||||
a := &hedgedAttempt{url: url, dst: dst, scratch: scratch, hedge: hedge, started: time.Now()}
|
||||
if !scratch {
|
||||
owner = a
|
||||
}
|
||||
attemptCtx, cancel := context.WithCancel(ctx)
|
||||
a.cancel = cancel
|
||||
a.progress.arrived()
|
||||
attempts = append(attempts, a)
|
||||
running++
|
||||
go func() {
|
||||
m, r, e := attempt(attemptCtx, url, a.dst, &a.progress)
|
||||
results <- attemptResult{attempt: a, n: m, retryable: r, err: e}
|
||||
}()
|
||||
}
|
||||
|
||||
// askNext asks the next location not asked yet, as the plain loop did
|
||||
// after a failure. When the request reading into buffer is still running
|
||||
// and there is no room for another buffer, its own failure asks it later.
|
||||
askNext := func() {
|
||||
if stopAsking || next >= len(urls) {
|
||||
return
|
||||
}
|
||||
dst, scratch, ok := destination()
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
start(urls[next], dst, scratch, false)
|
||||
next++
|
||||
}
|
||||
|
||||
// settle takes in the result of a request that ended.
|
||||
settle := func(r attemptResult) {
|
||||
running--
|
||||
r.attempt.finished = true
|
||||
r.attempt.cancel()
|
||||
if r.attempt == owner {
|
||||
owner = nil
|
||||
}
|
||||
}
|
||||
|
||||
// end cancels the requests still running and waits for the one reading
|
||||
// into buffer. The others release their buffers in the background.
|
||||
end := func() {
|
||||
for _, a := range attempts {
|
||||
if !a.finished {
|
||||
a.abandoned = true
|
||||
a.cancel()
|
||||
}
|
||||
}
|
||||
for owner != nil {
|
||||
r := <-results
|
||||
settle(r)
|
||||
if r.attempt.scratch {
|
||||
freeScratch(r.attempt.dst)
|
||||
}
|
||||
}
|
||||
if running > 0 {
|
||||
go func(left int) {
|
||||
for ; left > 0; left-- {
|
||||
if r := <-results; r.attempt.scratch {
|
||||
freeScratch(r.attempt.dst)
|
||||
}
|
||||
}
|
||||
}(running)
|
||||
}
|
||||
}
|
||||
|
||||
// hedgeAt is when every request in flight will have been quiet for longer
|
||||
// than it may be, unless something arrives first.
|
||||
hedgeAt := func() time.Time {
|
||||
var at time.Time
|
||||
for _, a := range attempts {
|
||||
if a.finished {
|
||||
continue
|
||||
}
|
||||
quietLimit := chunkReadAnswerDelay
|
||||
if a.progress.answered.Load() {
|
||||
quietLimit = chunkReadStallDelay
|
||||
}
|
||||
if t := time.Unix(0, a.progress.lastArrival.Load()).Add(quietLimit); t.After(at) {
|
||||
at = t
|
||||
}
|
||||
}
|
||||
return at
|
||||
}
|
||||
|
||||
// stuckAnswered is the request that answered and has been quiet the
|
||||
// longest, if any: its location is worth asking again.
|
||||
stuckAnswered := func() *hedgedAttempt {
|
||||
var pick *hedgedAttempt
|
||||
for _, a := range attempts {
|
||||
if !a.finished && a.progress.answered.Load() &&
|
||||
(pick == nil || a.progress.lastArrival.Load() < pick.progress.lastArrival.Load()) {
|
||||
pick = a
|
||||
}
|
||||
}
|
||||
return pick
|
||||
}
|
||||
|
||||
askNext()
|
||||
|
||||
timer := time.NewTimer(chunkReadAnswerDelay)
|
||||
defer timer.Stop()
|
||||
|
||||
for running > 0 {
|
||||
var hedge <-chan time.Time
|
||||
if !stopAsking && !hedgeOff && hedging.sent < maxHedgesPerRead {
|
||||
// A request that answers meanwhile may be quiet only for the
|
||||
// shorter chunkReadStallDelay from then on: look again by then.
|
||||
wait := chunkReadStallDelay
|
||||
if next < len(urls) || stuckAnswered() != nil {
|
||||
wait = min(time.Until(hedgeAt()), wait)
|
||||
}
|
||||
timer.Reset(max(wait, time.Millisecond))
|
||||
hedge = timer.C
|
||||
}
|
||||
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
end()
|
||||
return 0, failed, false, ctx.Err()
|
||||
|
||||
case <-hedge:
|
||||
if time.Now().Before(hedgeAt()) {
|
||||
continue // something arrived meanwhile
|
||||
}
|
||||
// a location not asked yet, or again one whose answer got stuck
|
||||
var url string
|
||||
unasked := next < len(urls)
|
||||
if unasked {
|
||||
url = urls[next]
|
||||
} else if stuck := stuckAnswered(); stuck != nil {
|
||||
url = stuck.url
|
||||
} else {
|
||||
continue // nowhere worth asking yet
|
||||
}
|
||||
// The token comes first: room for a buffer may evict cached
|
||||
// chunks, which is only worth it for a hedge that is sent.
|
||||
if !spendHedgeToken() {
|
||||
hedgeOff = true
|
||||
continue
|
||||
}
|
||||
dst, scratch, ok := destination()
|
||||
if !ok {
|
||||
refundHedgeToken()
|
||||
hedgeOff = true // no room for another buffer
|
||||
continue
|
||||
}
|
||||
if unasked {
|
||||
next++
|
||||
}
|
||||
hedging.sent++
|
||||
glog.V(1).InfofCtx(ctx, "chunk read went quiet, asking %s as well", url)
|
||||
start(url, dst, scratch, true)
|
||||
|
||||
case r := <-results:
|
||||
settle(r)
|
||||
a := r.attempt
|
||||
if a.abandoned {
|
||||
if a.scratch {
|
||||
freeScratch(a.dst)
|
||||
}
|
||||
continue
|
||||
}
|
||||
if ctxErr := ctx.Err(); ctxErr != nil {
|
||||
if a.scratch {
|
||||
freeScratch(a.dst)
|
||||
}
|
||||
end()
|
||||
return 0, failed, false, ctxErr
|
||||
}
|
||||
if r.err == nil {
|
||||
// The chunk is here. A location that has not even answered by
|
||||
// now is tried last for a while, like one that cannot be
|
||||
// reached, and the location list it came from may be stale.
|
||||
// A request asked again where the server answered is only
|
||||
// waiting for a connection.
|
||||
answered := make(map[string]bool, len(attempts))
|
||||
for _, other := range attempts {
|
||||
if other.progress.answered.Load() {
|
||||
answered[other.url] = true
|
||||
}
|
||||
}
|
||||
for _, other := range attempts {
|
||||
if !other.finished && !answered[other.url] && time.Since(other.started) >= chunkReadAnswerDelay {
|
||||
recordUnreachable(hostOf(other.url), errNoAnswer)
|
||||
failed = true
|
||||
}
|
||||
}
|
||||
end()
|
||||
if a.scratch {
|
||||
copy(buffer, a.dst[:r.n])
|
||||
freeScratch(a.dst)
|
||||
}
|
||||
return r.n, failed, false, nil
|
||||
}
|
||||
if a.scratch {
|
||||
freeScratch(a.dst)
|
||||
}
|
||||
if !r.retryable {
|
||||
if a.hedge && errors.Is(r.err, ErrTooManyRequests) {
|
||||
// that server is busy; another location may still serve it
|
||||
if throttled == nil {
|
||||
throttled = r.err
|
||||
}
|
||||
askNext()
|
||||
continue
|
||||
}
|
||||
if finalErr == nil {
|
||||
finalErr = r.err
|
||||
}
|
||||
stopAsking = true
|
||||
continue
|
||||
}
|
||||
failed = true
|
||||
err, retryable = r.err, true
|
||||
glog.V(0).InfofCtx(ctx, "read %s failed, err: %v", a.url, r.err)
|
||||
askNext()
|
||||
}
|
||||
}
|
||||
|
||||
if finalErr != nil {
|
||||
return 0, failed, false, finalErr
|
||||
}
|
||||
if err == nil && throttled != nil {
|
||||
return 0, failed, false, throttled
|
||||
}
|
||||
return 0, failed, retryable, err
|
||||
}
|
||||
@@ -1,783 +0,0 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"compress/gzip"
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strconv"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
)
|
||||
|
||||
// shortHedgeDelay makes chunk reads hedge after d of quiet, before and after
|
||||
// the response headers alike, and starts the test with a full hedge budget.
|
||||
func shortHedgeDelay(t *testing.T, d time.Duration) {
|
||||
t.Helper()
|
||||
hedgeDelays(t, d, d)
|
||||
}
|
||||
|
||||
func hedgeDelays(t *testing.T, answer, stall time.Duration) {
|
||||
t.Helper()
|
||||
savedAnswer, savedStall, savedTokens := chunkReadAnswerDelay, chunkReadStallDelay, hedgeTokens.Load()
|
||||
chunkReadAnswerDelay, chunkReadStallDelay = answer, stall
|
||||
hedgeTokens.Store(hedgeTokenBurst)
|
||||
t.Cleanup(func() {
|
||||
chunkReadAnswerDelay, chunkReadStallDelay = savedAnswer, savedStall
|
||||
hedgeTokens.Store(savedTokens)
|
||||
})
|
||||
}
|
||||
|
||||
// chunkServer serves one chunk. Each request is answered by behave, which gets
|
||||
// the request's 1-based number at this server.
|
||||
type chunkServer struct {
|
||||
*httptest.Server
|
||||
requests atomic.Int32
|
||||
abandoned atomic.Int32 // requests whose client went away before the end
|
||||
}
|
||||
|
||||
func newChunkServer(t *testing.T, behave func(n int32, w http.ResponseWriter, r *http.Request)) *chunkServer {
|
||||
t.Helper()
|
||||
s := &chunkServer{}
|
||||
s.Server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
behave(s.requests.Add(1), w, r)
|
||||
}))
|
||||
t.Cleanup(s.Close)
|
||||
return s
|
||||
}
|
||||
|
||||
func (s *chunkServer) url() string { return s.URL + "/3,abc" }
|
||||
|
||||
// wait blocks until the client gives up on r, and counts that.
|
||||
func (s *chunkServer) wait(r *http.Request) {
|
||||
<-r.Context().Done()
|
||||
s.abandoned.Add(1)
|
||||
}
|
||||
|
||||
func sendHeaders(w http.ResponseWriter, body []byte, gzipped bool) {
|
||||
if gzipped {
|
||||
w.Header().Set("Content-Encoding", "gzip")
|
||||
}
|
||||
w.Header().Set("Content-Length", strconv.Itoa(len(body)))
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}
|
||||
|
||||
func flush(w http.ResponseWriter) { w.(http.Flusher).Flush() }
|
||||
|
||||
// stallsAfter sends the headers and the first part of body, then sends
|
||||
// nothing more until the client gives up: a response whose next TCP segment
|
||||
// was lost.
|
||||
func stallsAfter(s **chunkServer, body []byte, part int, gzipped bool) func(n int32, w http.ResponseWriter, r *http.Request) {
|
||||
return func(n int32, w http.ResponseWriter, r *http.Request) {
|
||||
sendHeaders(w, body, gzipped)
|
||||
w.Write(body[:part])
|
||||
flush(w)
|
||||
(*s).wait(r)
|
||||
}
|
||||
}
|
||||
|
||||
func answers(body []byte, gzipped bool) func(n int32, w http.ResponseWriter, r *http.Request) {
|
||||
return func(n int32, w http.ResponseWriter, r *http.Request) {
|
||||
sendHeaders(w, body, gzipped)
|
||||
w.Write(body)
|
||||
}
|
||||
}
|
||||
|
||||
func gzipped(t *testing.T, data []byte) []byte {
|
||||
t.Helper()
|
||||
var b bytes.Buffer
|
||||
gz := gzip.NewWriter(&b)
|
||||
if _, err := gz.Write(data); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := gz.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return b.Bytes()
|
||||
}
|
||||
|
||||
// readPath is one of the ways RetriedFetchChunkData reads a chunk.
|
||||
type readPath struct {
|
||||
name string
|
||||
body []byte // what the volume server sends
|
||||
cipherKey []byte
|
||||
isGzipped bool
|
||||
isFullChunk bool
|
||||
}
|
||||
|
||||
func readPaths(t *testing.T, payload []byte) []readPath {
|
||||
cipherKey := util.GenCipherKey()
|
||||
encrypted, err := util.Encrypt(payload, cipherKey)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return []readPath{
|
||||
{name: "direct", body: payload, isFullChunk: true},
|
||||
{name: "range", body: payload},
|
||||
{name: "gzip", body: gzipped(t, payload), isGzipped: true, isFullChunk: true},
|
||||
{name: "encrypted", body: encrypted, cipherKey: cipherKey, isFullChunk: true},
|
||||
}
|
||||
}
|
||||
|
||||
func fetch(ctx context.Context, p readPath, size int, urls []string, refresh RefreshUrlsFunc) ([]byte, time.Duration, error) {
|
||||
buffer := make([]byte, size)
|
||||
start := time.Now()
|
||||
n, err := RetriedFetchChunkData(ctx, buffer, urls, p.cipherKey, p.isGzipped, p.isFullChunk, 0, "3,abc", refresh)
|
||||
return buffer[:n], time.Since(start), err
|
||||
}
|
||||
|
||||
func testPayload(size int) []byte {
|
||||
payload := make([]byte, size)
|
||||
for i := range payload {
|
||||
payload[i] = byte('a' + i%26)
|
||||
}
|
||||
return payload
|
||||
}
|
||||
|
||||
// TestChunkReadHedgesABodyThatStalls is the read the hedge is for: the first
|
||||
// replica sends part of the chunk and then nothing, as a response does while
|
||||
// it waits for a TCP retransmission, and the second replica is fine. The read
|
||||
// must come from the second replica a hedge delay later instead of whenever
|
||||
// the first one recovers, and give up on the first one.
|
||||
func TestChunkReadHedgesABodyThatStalls(t *testing.T) {
|
||||
payload := testPayload(256 * 1024)
|
||||
for _, p := range readPaths(t, payload) {
|
||||
t.Run(p.name, func(t *testing.T) {
|
||||
forgetUnreachable(t)
|
||||
shortHedgeDelay(t, 100*time.Millisecond)
|
||||
var stalling *chunkServer
|
||||
stalling = newChunkServer(t, stallsAfter(&stalling, p.body, len(p.body)/2, p.isGzipped))
|
||||
live := newChunkServer(t, answers(p.body, p.isGzipped))
|
||||
|
||||
refreshed := 0
|
||||
got, took, err := fetch(context.Background(), p, len(payload), []string{stalling.url(), live.url()}, func() []string {
|
||||
refreshed++
|
||||
return nil
|
||||
})
|
||||
if err != nil || !bytes.Equal(got, payload) {
|
||||
t.Fatalf("got %d bytes, %v; want the %d byte chunk", len(got), err, len(payload))
|
||||
}
|
||||
if took < chunkReadStallDelay || took > chunkReadStallDelay+time.Second {
|
||||
t.Fatalf("read took %v, want a little over the %v hedge delay", took, chunkReadStallDelay)
|
||||
}
|
||||
waitFor(t, "the stalled request to be given up", func() bool { return stalling.abandoned.Load() == 1 })
|
||||
if n := live.requests.Load(); n != 1 {
|
||||
t.Fatalf("second location asked %d times, want once", n)
|
||||
}
|
||||
if refreshed != 0 {
|
||||
t.Fatalf("refresh called %d times; a stalled body is no reason to look the chunk up again", refreshed)
|
||||
}
|
||||
// a location that answered and then stalled is not unreachable
|
||||
assertOrder(t, ReachableFirst([]string{stalling.url(), live.url()}), stalling.url(), live.url())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestChunkReadHedgesALocationThatDoesNotAnswer: the first replica accepts the
|
||||
// request and sends nothing, as one on a hung or dead host does. The read moves
|
||||
// on a hedge delay later, the silent location is tried last afterwards, and the
|
||||
// location list is looked up again, as after a failed location.
|
||||
func TestChunkReadHedgesALocationThatDoesNotAnswer(t *testing.T) {
|
||||
forgetUnreachable(t)
|
||||
shortHedgeDelay(t, 100*time.Millisecond)
|
||||
payload := testPayload(64 * 1024)
|
||||
var silent *chunkServer
|
||||
silent = newChunkServer(t, func(n int32, w http.ResponseWriter, r *http.Request) { silent.wait(r) })
|
||||
live := newChunkServer(t, answers(payload, false))
|
||||
p := readPath{name: "direct", body: payload, isFullChunk: true}
|
||||
|
||||
urls := []string{silent.url(), live.url()}
|
||||
refreshed := 0
|
||||
got, took, err := fetch(context.Background(), p, len(payload), urls, func() []string {
|
||||
refreshed++
|
||||
return nil
|
||||
})
|
||||
if err != nil || !bytes.Equal(got, payload) {
|
||||
t.Fatalf("got %d bytes, %v; want the chunk", len(got), err)
|
||||
}
|
||||
if refreshed != 1 {
|
||||
t.Fatalf("refresh called %d times, want once after a location did not answer", refreshed)
|
||||
}
|
||||
if took < chunkReadStallDelay || took > chunkReadStallDelay+time.Second {
|
||||
t.Fatalf("read took %v, want a little over the %v hedge delay", took, chunkReadStallDelay)
|
||||
}
|
||||
assertOrder(t, ReachableFirst(urls), live.url(), silent.url())
|
||||
|
||||
// the next read starts with the location that answers and does not wait
|
||||
got, took, err = fetch(context.Background(), p, len(payload), ReachableFirst(urls), nil)
|
||||
if err != nil || !bytes.Equal(got, payload) || took >= chunkReadStallDelay {
|
||||
t.Fatalf("second read: got %d bytes, %v in %v; want the chunk at once", len(got), err, took)
|
||||
}
|
||||
if n := silent.requests.Load(); n != 1 {
|
||||
t.Fatalf("silent location asked %d times, want once", n)
|
||||
}
|
||||
}
|
||||
|
||||
// TestChunkReadDoesNotHedgeAReadThatKeepsArriving: a slow location that keeps
|
||||
// sending is left alone, however long the whole chunk takes.
|
||||
func TestChunkReadDoesNotHedgeAReadThatKeepsArriving(t *testing.T) {
|
||||
forgetUnreachable(t)
|
||||
shortHedgeDelay(t, 100*time.Millisecond)
|
||||
payload := testPayload(64 * 1024)
|
||||
const pieces = 8
|
||||
slow := newChunkServer(t, func(n int32, w http.ResponseWriter, r *http.Request) {
|
||||
sendHeaders(w, payload, false)
|
||||
piece := len(payload) / pieces
|
||||
for i := 0; i < pieces; i++ {
|
||||
time.Sleep(chunkReadStallDelay / 3)
|
||||
w.Write(payload[i*piece : (i+1)*piece])
|
||||
flush(w)
|
||||
}
|
||||
})
|
||||
other := newChunkServer(t, answers(payload, false))
|
||||
|
||||
for _, p := range readPaths(t, payload)[:2] {
|
||||
got, took, err := fetch(context.Background(), p, len(payload), []string{slow.url(), other.url()}, nil)
|
||||
if err != nil || !bytes.Equal(got, payload) {
|
||||
t.Fatalf("%s: got %d bytes, %v; want the chunk", p.name, len(got), err)
|
||||
}
|
||||
if took < 2*chunkReadStallDelay {
|
||||
t.Fatalf("%s: read took %v; the slow location should have been read to the end", p.name, took)
|
||||
}
|
||||
}
|
||||
if n := other.requests.Load(); n != 0 {
|
||||
t.Fatalf("second location asked %d times, want never", n)
|
||||
}
|
||||
}
|
||||
|
||||
// TestChunkReadKeepsTheFirstAnswerToArrive: once a hedge is under way, the
|
||||
// first location may still win, and then the hedge is the one given up.
|
||||
func TestChunkReadKeepsTheFirstAnswerToArrive(t *testing.T) {
|
||||
forgetUnreachable(t)
|
||||
shortHedgeDelay(t, 100*time.Millisecond)
|
||||
payload := testPayload(64 * 1024)
|
||||
recovering := newChunkServer(t, func(n int32, w http.ResponseWriter, r *http.Request) {
|
||||
sendHeaders(w, payload, false)
|
||||
w.Write(payload[:len(payload)/2])
|
||||
flush(w)
|
||||
time.Sleep(chunkReadStallDelay * 3 / 2)
|
||||
w.Write(payload[len(payload)/2:])
|
||||
})
|
||||
var late *chunkServer
|
||||
late = newChunkServer(t, func(n int32, w http.ResponseWriter, r *http.Request) {
|
||||
select {
|
||||
case <-time.After(10 * chunkReadStallDelay):
|
||||
answers(payload, false)(n, w, r)
|
||||
case <-r.Context().Done():
|
||||
late.abandoned.Add(1)
|
||||
}
|
||||
})
|
||||
|
||||
p := readPath{name: "direct", body: payload, isFullChunk: true}
|
||||
got, took, err := fetch(context.Background(), p, len(payload), []string{recovering.url(), late.url()}, nil)
|
||||
if err != nil || !bytes.Equal(got, payload) {
|
||||
t.Fatalf("got %d bytes, %v; want the chunk", len(got), err)
|
||||
}
|
||||
if took > 5*chunkReadStallDelay {
|
||||
t.Fatalf("read took %v; it should have ended when the first location recovered", took)
|
||||
}
|
||||
if n := late.requests.Load(); n != 1 {
|
||||
t.Fatalf("second location asked %d times, want once", n)
|
||||
}
|
||||
waitFor(t, "the hedge to be given up", func() bool { return late.abandoned.Load() == 1 })
|
||||
}
|
||||
|
||||
// TestChunkReadHedgeWinnerReplacesThePartialRead: the first location wrote part
|
||||
// of the chunk into the caller's buffer before it stalled. The chunk the hedge
|
||||
// delivered must replace all of it, and the stalled request must not write the
|
||||
// buffer again once the read returned.
|
||||
func TestChunkReadHedgeWinnerReplacesThePartialRead(t *testing.T) {
|
||||
forgetUnreachable(t)
|
||||
shortHedgeDelay(t, 100*time.Millisecond)
|
||||
payload := testPayload(128 * 1024)
|
||||
stale := bytes.Repeat([]byte{'x'}, len(payload))
|
||||
release := make(chan struct{})
|
||||
stalling := newChunkServer(t, func(n int32, w http.ResponseWriter, r *http.Request) {
|
||||
sendHeaders(w, stale, false)
|
||||
w.Write(stale[:len(stale)/2])
|
||||
flush(w)
|
||||
select {
|
||||
case <-release:
|
||||
w.Write(stale[len(stale)/2:])
|
||||
case <-r.Context().Done():
|
||||
}
|
||||
})
|
||||
live := newChunkServer(t, answers(payload, false))
|
||||
|
||||
buffer := make([]byte, len(payload))
|
||||
n, err := RetriedFetchChunkData(context.Background(), buffer, []string{stalling.url(), live.url()}, nil, false, true, 0, "3,abc", nil)
|
||||
if err != nil || n != len(payload) || !bytes.Equal(buffer, payload) {
|
||||
t.Fatalf("got %d bytes, %v; want the chunk from the second location", n, err)
|
||||
}
|
||||
close(release)
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
if !bytes.Equal(buffer, payload) {
|
||||
t.Fatal("the buffer changed after the read returned")
|
||||
}
|
||||
}
|
||||
|
||||
// TestChunkReadAsksTheOnlyLocationAgain: a chunk with a single location is
|
||||
// asked again over another connection when its response stalls, since the
|
||||
// stall belongs to that connection rather than to the server.
|
||||
func TestChunkReadAsksTheOnlyLocationAgain(t *testing.T) {
|
||||
forgetUnreachable(t)
|
||||
shortHedgeDelay(t, 100*time.Millisecond)
|
||||
payload := testPayload(64 * 1024)
|
||||
var only *chunkServer
|
||||
only = newChunkServer(t, func(n int32, w http.ResponseWriter, r *http.Request) {
|
||||
if n == 1 {
|
||||
stallsAfter(&only, payload, len(payload)/4, false)(n, w, r)
|
||||
return
|
||||
}
|
||||
answers(payload, false)(n, w, r)
|
||||
})
|
||||
|
||||
for _, p := range readPaths(t, payload)[:2] {
|
||||
only.requests.Store(0)
|
||||
got, took, err := fetch(context.Background(), p, len(payload), []string{only.url()}, nil)
|
||||
if err != nil || !bytes.Equal(got, payload) {
|
||||
t.Fatalf("%s: got %d bytes, %v; want the chunk", p.name, len(got), err)
|
||||
}
|
||||
if took > chunkReadStallDelay+time.Second {
|
||||
t.Fatalf("%s: read took %v, want a little over the %v hedge delay", p.name, took, chunkReadStallDelay)
|
||||
}
|
||||
if n := only.requests.Load(); n != 2 {
|
||||
t.Fatalf("%s: location asked %d times, want twice", p.name, n)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestChunkReadHedgesOnlyWithinBudget: with the budget spent, a stalled read is
|
||||
// waited out as before instead of being asked elsewhere.
|
||||
func TestChunkReadHedgesOnlyWithinBudget(t *testing.T) {
|
||||
forgetUnreachable(t)
|
||||
shortHedgeDelay(t, 50*time.Millisecond)
|
||||
hedgeTokens.Store(0)
|
||||
payload := testPayload(64 * 1024)
|
||||
recovering := newChunkServer(t, func(n int32, w http.ResponseWriter, r *http.Request) {
|
||||
sendHeaders(w, payload, false)
|
||||
w.Write(payload[:len(payload)/2])
|
||||
flush(w)
|
||||
time.Sleep(4 * chunkReadStallDelay)
|
||||
w.Write(payload[len(payload)/2:])
|
||||
})
|
||||
other := newChunkServer(t, answers(payload, false))
|
||||
|
||||
p := readPath{name: "direct", body: payload, isFullChunk: true}
|
||||
got, took, err := fetch(context.Background(), p, len(payload), []string{recovering.url(), other.url()}, nil)
|
||||
if err != nil || !bytes.Equal(got, payload) {
|
||||
t.Fatalf("got %d bytes, %v; want the chunk", len(got), err)
|
||||
}
|
||||
if took < 4*chunkReadStallDelay {
|
||||
t.Fatalf("read took %v; without budget it should have waited for the first location", took)
|
||||
}
|
||||
if n := other.requests.Load(); n != 0 {
|
||||
t.Fatalf("second location asked %d times without budget, want never", n)
|
||||
}
|
||||
}
|
||||
|
||||
// TestChunkReadHedgeBudgetIsATenthOfTheReads checks the budget arithmetic: the
|
||||
// burst is available at once, after that every ten reads pay for one hedge.
|
||||
func TestChunkReadHedgeBudgetIsATenthOfTheReads(t *testing.T) {
|
||||
shortHedgeDelay(t, time.Second)
|
||||
hedges := 0
|
||||
for spendHedgeToken() {
|
||||
hedges++
|
||||
}
|
||||
if hedges != hedgeTokenBurst/hedgeTokenScale {
|
||||
t.Fatalf("burst allowed %d hedges, want %d", hedges, hedgeTokenBurst/hedgeTokenScale)
|
||||
}
|
||||
for i := 0; i < 9; i++ {
|
||||
earnHedgeToken()
|
||||
}
|
||||
if spendHedgeToken() {
|
||||
t.Fatal("nine reads paid for a hedge")
|
||||
}
|
||||
earnHedgeToken()
|
||||
if !spendHedgeToken() {
|
||||
t.Fatal("ten reads did not pay for a hedge")
|
||||
}
|
||||
for i := 0; i < 1000; i++ {
|
||||
earnHedgeToken()
|
||||
}
|
||||
if got := hedgeTokens.Load(); got != hedgeTokenBurst {
|
||||
t.Fatalf("saved %d tokens, want at most the burst %d", got, hedgeTokenBurst)
|
||||
}
|
||||
}
|
||||
|
||||
// TestChunkReadCancelledDuringAHedge: when the caller gives up while both the
|
||||
// first request and its hedge are stalled, the read returns at once and no
|
||||
// request writes the buffer afterwards.
|
||||
func TestChunkReadCancelledDuringAHedge(t *testing.T) {
|
||||
forgetUnreachable(t)
|
||||
shortHedgeDelay(t, 50*time.Millisecond)
|
||||
payload := testPayload(64 * 1024)
|
||||
release := make(chan struct{})
|
||||
stall := func(n int32, w http.ResponseWriter, r *http.Request) {
|
||||
sendHeaders(w, payload, false)
|
||||
w.Write(payload[:1024])
|
||||
flush(w)
|
||||
select {
|
||||
case <-release:
|
||||
w.Write(payload[1024:])
|
||||
case <-r.Context().Done():
|
||||
}
|
||||
}
|
||||
first := newChunkServer(t, stall)
|
||||
second := newChunkServer(t, stall)
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
time.AfterFunc(4*chunkReadStallDelay, cancel)
|
||||
buffer := make([]byte, len(payload))
|
||||
start := time.Now()
|
||||
_, err := RetriedFetchChunkData(ctx, buffer, []string{first.url(), second.url()}, nil, false, true, 0, "3,abc", nil)
|
||||
if !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("got %v, want the cancellation", err)
|
||||
}
|
||||
if took := time.Since(start); took > 4*chunkReadStallDelay+time.Second {
|
||||
t.Fatalf("returned %v after the start, long after the cancellation", took)
|
||||
}
|
||||
if second.requests.Load() == 0 {
|
||||
t.Fatal("the stalled read was never hedged")
|
||||
}
|
||||
clear(buffer)
|
||||
close(release)
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
if !bytes.Equal(buffer, make([]byte, len(payload))) {
|
||||
t.Fatal("the buffer changed after the read returned")
|
||||
}
|
||||
}
|
||||
|
||||
// TestChunkReadStillMovesOnAtOnceAfterAFailure: a location that fails outright
|
||||
// is not waited on for the hedge delay, and the failure still refreshes the
|
||||
// location list as before.
|
||||
func TestChunkReadStillMovesOnAtOnceAfterAFailure(t *testing.T) {
|
||||
forgetUnreachable(t)
|
||||
shortHedgeDelay(t, time.Second)
|
||||
payload := testPayload(64 * 1024)
|
||||
failing := newChunkServer(t, func(n int32, w http.ResponseWriter, r *http.Request) {
|
||||
http.Error(w, "disk error", http.StatusInternalServerError)
|
||||
})
|
||||
live := newChunkServer(t, answers(payload, false))
|
||||
|
||||
for _, p := range readPaths(t, payload)[:2] {
|
||||
refreshed := 0
|
||||
got, took, err := fetch(context.Background(), p, len(payload), []string{failing.url(), live.url()}, func() []string {
|
||||
refreshed++
|
||||
return nil
|
||||
})
|
||||
if err != nil || !bytes.Equal(got, payload) {
|
||||
t.Fatalf("%s: got %d bytes, %v; want the chunk", p.name, len(got), err)
|
||||
}
|
||||
if took >= chunkReadStallDelay {
|
||||
t.Fatalf("%s: read took %v; a failure should move on at once", p.name, took)
|
||||
}
|
||||
if refreshed != 1 {
|
||||
t.Fatalf("%s: refresh called %d times after a failure, want once", p.name, refreshed)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func waitFor(t *testing.T, what string, cond func() bool) {
|
||||
t.Helper()
|
||||
deadline := time.Now().Add(5 * time.Second)
|
||||
for !cond() {
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatalf("timed out waiting for %s", what)
|
||||
}
|
||||
time.Sleep(5 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
|
||||
// TestChunkReadGivesAnAnswerLongerThanABodyThatStops: before its response
|
||||
// headers a server may still be reading the needle from a busy disk, so a
|
||||
// location gets chunkReadAnswerDelay to answer, while a body that stops
|
||||
// arriving is hedged after the shorter chunkReadStallDelay.
|
||||
func TestChunkReadGivesAnAnswerLongerThanABodyThatStops(t *testing.T) {
|
||||
forgetUnreachable(t)
|
||||
hedgeDelays(t, 400*time.Millisecond, 50*time.Millisecond)
|
||||
payload := testPayload(64 * 1024)
|
||||
slowDisk := newChunkServer(t, func(n int32, w http.ResponseWriter, r *http.Request) {
|
||||
time.Sleep(150 * time.Millisecond)
|
||||
answers(payload, false)(n, w, r)
|
||||
})
|
||||
var stalling *chunkServer
|
||||
stalling = newChunkServer(t, stallsAfter(&stalling, payload, len(payload)/2, false))
|
||||
other := newChunkServer(t, answers(payload, false))
|
||||
p := readPath{name: "direct", body: payload, isFullChunk: true}
|
||||
|
||||
got, took, err := fetch(context.Background(), p, len(payload), []string{slowDisk.url(), other.url()}, nil)
|
||||
if err != nil || !bytes.Equal(got, payload) {
|
||||
t.Fatalf("slow answer: got %d bytes, %v; want the chunk", len(got), err)
|
||||
}
|
||||
if took < 150*time.Millisecond || other.requests.Load() != 0 {
|
||||
t.Fatalf("slow answer: read took %v and asked the other location %d times; want it waited for", took, other.requests.Load())
|
||||
}
|
||||
|
||||
got, took, err = fetch(context.Background(), p, len(payload), []string{stalling.url(), other.url()}, nil)
|
||||
if err != nil || !bytes.Equal(got, payload) {
|
||||
t.Fatalf("stalled body: got %d bytes, %v; want the chunk", len(got), err)
|
||||
}
|
||||
if took >= chunkReadAnswerDelay || other.requests.Load() != 1 {
|
||||
t.Fatalf("stalled body: read took %v and asked the other location %d times; want it hedged after %v", took, other.requests.Load(), chunkReadStallDelay)
|
||||
}
|
||||
}
|
||||
|
||||
// TestChunkReadAsksAgainWhereTheServerAnswered: once every location has been
|
||||
// asked, a stalled read is asked again of a location whose server answered,
|
||||
// not of one that never did.
|
||||
func TestChunkReadAsksAgainWhereTheServerAnswered(t *testing.T) {
|
||||
forgetUnreachable(t)
|
||||
hedgeDelays(t, 100*time.Millisecond, 50*time.Millisecond)
|
||||
payload := testPayload(64 * 1024)
|
||||
var silent, flaky *chunkServer
|
||||
silent = newChunkServer(t, func(n int32, w http.ResponseWriter, r *http.Request) { silent.wait(r) })
|
||||
flaky = newChunkServer(t, func(n int32, w http.ResponseWriter, r *http.Request) {
|
||||
if n == 1 {
|
||||
stallsAfter(&flaky, payload, len(payload)/2, false)(n, w, r)
|
||||
return
|
||||
}
|
||||
answers(payload, false)(n, w, r)
|
||||
})
|
||||
p := readPath{name: "direct", body: payload, isFullChunk: true}
|
||||
|
||||
urls := []string{silent.url(), flaky.url()}
|
||||
got, _, err := fetch(context.Background(), p, len(payload), urls, nil)
|
||||
if err != nil || !bytes.Equal(got, payload) {
|
||||
t.Fatalf("got %d bytes, %v; want the chunk", len(got), err)
|
||||
}
|
||||
if s, f := silent.requests.Load(), flaky.requests.Load(); s != 1 || f != 2 {
|
||||
t.Fatalf("asked the silent location %d and the stalling one %d times, want 1 and 2", s, f)
|
||||
}
|
||||
assertOrder(t, ReachableFirst(urls), flaky.url(), silent.url())
|
||||
}
|
||||
|
||||
// TestChunkReadAskedAgainIsNotUnreachable: the requests that asked a stalled
|
||||
// location again over new connections had not answered when the first one
|
||||
// recovered and delivered the chunk. That server answered, so it is not taken
|
||||
// for one that cannot be reached.
|
||||
func TestChunkReadAskedAgainIsNotUnreachable(t *testing.T) {
|
||||
forgetUnreachable(t)
|
||||
shortHedgeDelay(t, 50*time.Millisecond)
|
||||
payload := testPayload(64 * 1024)
|
||||
var only *chunkServer
|
||||
only = newChunkServer(t, func(n int32, w http.ResponseWriter, r *http.Request) {
|
||||
if n > 1 {
|
||||
only.wait(r)
|
||||
return
|
||||
}
|
||||
sendHeaders(w, payload, false)
|
||||
w.Write(payload[:len(payload)/2])
|
||||
flush(w)
|
||||
time.Sleep(5 * chunkReadStallDelay)
|
||||
w.Write(payload[len(payload)/2:])
|
||||
})
|
||||
p := readPath{name: "direct", body: payload, isFullChunk: true}
|
||||
refreshed := 0
|
||||
got, _, err := fetch(context.Background(), p, len(payload), []string{only.url()}, func() []string {
|
||||
refreshed++
|
||||
return nil
|
||||
})
|
||||
if err != nil || !bytes.Equal(got, payload) {
|
||||
t.Fatalf("got %d bytes, %v; want the chunk", len(got), err)
|
||||
}
|
||||
if n := only.requests.Load(); n < 2 {
|
||||
t.Fatalf("asked %d times, want it asked again", n)
|
||||
}
|
||||
if refreshed != 0 {
|
||||
t.Fatalf("refresh called %d times; the location answered", refreshed)
|
||||
}
|
||||
other := "http://127.0.0.1:1/3,abc"
|
||||
assertOrder(t, ReachableFirst([]string{only.url(), other}), only.url(), other)
|
||||
}
|
||||
|
||||
// TestChunkReadWaitsForTheOnlyLocationToAnswer: with nowhere else to go, a
|
||||
// location that has not answered yet is waited for, as before: asking its
|
||||
// server again would only add to whatever keeps it busy.
|
||||
func TestChunkReadWaitsForTheOnlyLocationToAnswer(t *testing.T) {
|
||||
forgetUnreachable(t)
|
||||
shortHedgeDelay(t, 50*time.Millisecond)
|
||||
payload := testPayload(64 * 1024)
|
||||
slow := newChunkServer(t, func(n int32, w http.ResponseWriter, r *http.Request) {
|
||||
time.Sleep(300 * time.Millisecond)
|
||||
answers(payload, false)(n, w, r)
|
||||
})
|
||||
p := readPath{name: "direct", body: payload, isFullChunk: true}
|
||||
got, _, err := fetch(context.Background(), p, len(payload), []string{slow.url()}, nil)
|
||||
if err != nil || !bytes.Equal(got, payload) {
|
||||
t.Fatalf("got %d bytes, %v; want the chunk", len(got), err)
|
||||
}
|
||||
if n := slow.requests.Load(); n != 1 {
|
||||
t.Fatalf("asked %d times, want once", n)
|
||||
}
|
||||
}
|
||||
|
||||
// fakeScratchBudget has room for a hedge buffer while room is set, and
|
||||
// counts what is reserved and returned.
|
||||
type fakeScratchBudget struct {
|
||||
room atomic.Bool
|
||||
reserved, released atomic.Int32
|
||||
}
|
||||
|
||||
func (b *fakeScratchBudget) TryReserveScratch(size int) bool {
|
||||
if !b.room.Load() {
|
||||
return false
|
||||
}
|
||||
b.reserved.Add(1)
|
||||
return true
|
||||
}
|
||||
|
||||
func (b *fakeScratchBudget) ReleaseScratch(size int) { b.released.Add(1) }
|
||||
|
||||
// TestChunkReadHedgeNeedsRoomInTheScratchBudget: a hedge reads into a buffer
|
||||
// of its own, which counts against the caller's memory budget. Without room
|
||||
// in it the stalled read is waited out as before; with room, every buffer
|
||||
// taken is returned once its request has ended, abandoned ones included.
|
||||
func TestChunkReadHedgeNeedsRoomInTheScratchBudget(t *testing.T) {
|
||||
forgetUnreachable(t)
|
||||
shortHedgeDelay(t, 50*time.Millisecond)
|
||||
payload := testPayload(64 * 1024)
|
||||
recovering := newChunkServer(t, func(n int32, w http.ResponseWriter, r *http.Request) {
|
||||
sendHeaders(w, payload, false)
|
||||
w.Write(payload[:len(payload)/2])
|
||||
flush(w)
|
||||
select {
|
||||
case <-time.After(4 * chunkReadStallDelay):
|
||||
w.Write(payload[len(payload)/2:])
|
||||
case <-r.Context().Done():
|
||||
}
|
||||
})
|
||||
other := newChunkServer(t, answers(payload, false))
|
||||
p := readPath{name: "direct", body: payload, isFullChunk: true}
|
||||
budget := &fakeScratchBudget{}
|
||||
ctx := WithScratchBudget(context.Background(), budget)
|
||||
|
||||
// without a hedge token, no room is taken: taking it can evict cached chunks
|
||||
budget.room.Store(true)
|
||||
hedgeTokens.Store(0)
|
||||
got, _, err := fetch(ctx, p, len(payload), []string{recovering.url(), other.url()}, nil)
|
||||
if err != nil || !bytes.Equal(got, payload) {
|
||||
t.Fatalf("no token: got %d bytes, %v; want the chunk", len(got), err)
|
||||
}
|
||||
if r, o := budget.reserved.Load(), other.requests.Load(); r != 0 || o != 0 {
|
||||
t.Fatalf("no token: took room %d times and asked the other location %d times, want neither", r, o)
|
||||
}
|
||||
|
||||
// without room, the token is given back
|
||||
budget.room.Store(false)
|
||||
hedgeTokens.Store(5 * hedgeTokenScale)
|
||||
got, took, err := fetch(ctx, p, len(payload), []string{recovering.url(), other.url()}, nil)
|
||||
if err != nil || !bytes.Equal(got, payload) {
|
||||
t.Fatalf("no room: got %d bytes, %v; want the chunk", len(got), err)
|
||||
}
|
||||
if took < 4*chunkReadStallDelay || other.requests.Load() != 0 {
|
||||
t.Fatalf("no room: read took %v and asked the other location %d times; want it waited out", took, other.requests.Load())
|
||||
}
|
||||
if got, want := hedgeTokens.Load(), int64(5*hedgeTokenScale+hedgeTokenEarn); got != want {
|
||||
t.Fatalf("no room: %d thousandths of a token left, want %d: the hedge not sent keeps its token", got, want)
|
||||
}
|
||||
|
||||
budget.room.Store(true)
|
||||
got, took, err = fetch(ctx, p, len(payload), []string{recovering.url(), other.url()}, nil)
|
||||
if err != nil || !bytes.Equal(got, payload) {
|
||||
t.Fatalf("room: got %d bytes, %v; want the chunk", len(got), err)
|
||||
}
|
||||
if took >= 4*chunkReadStallDelay || other.requests.Load() != 1 {
|
||||
t.Fatalf("room: read took %v and asked the other location %d times; want it hedged", took, other.requests.Load())
|
||||
}
|
||||
waitFor(t, "every hedge buffer to be returned", func() bool {
|
||||
return budget.reserved.Load() == 1 && budget.released.Load() == 1
|
||||
})
|
||||
}
|
||||
|
||||
// TestChunkReadThrottledHedgeAsksTheNextLocation: a hedge whose server is too
|
||||
// busy to serve it (429) says nothing about the other locations, so the read
|
||||
// goes on to the next one instead of waiting out the stalled request.
|
||||
func TestChunkReadThrottledHedgeAsksTheNextLocation(t *testing.T) {
|
||||
forgetUnreachable(t)
|
||||
shortHedgeDelay(t, 50*time.Millisecond)
|
||||
payload := testPayload(64 * 1024)
|
||||
var stalling *chunkServer
|
||||
stalling = newChunkServer(t, stallsAfter(&stalling, payload, len(payload)/2, false))
|
||||
busy := newChunkServer(t, func(n int32, w http.ResponseWriter, r *http.Request) {
|
||||
http.Error(w, "too many requests", http.StatusTooManyRequests)
|
||||
})
|
||||
live := newChunkServer(t, answers(payload, false))
|
||||
p := readPath{name: "direct", body: payload, isFullChunk: true}
|
||||
|
||||
got, took, err := fetch(context.Background(), p, len(payload), []string{stalling.url(), busy.url(), live.url()}, nil)
|
||||
if err != nil || !bytes.Equal(got, payload) {
|
||||
t.Fatalf("got %d bytes, %v; want the chunk from the third location", len(got), err)
|
||||
}
|
||||
if took > chunkReadStallDelay+time.Second {
|
||||
t.Fatalf("read took %v; it should not have waited for the stalled location", took)
|
||||
}
|
||||
if b, l := busy.requests.Load(), live.requests.Load(); b != 1 || l != 1 {
|
||||
t.Fatalf("asked the busy location %d and the live one %d times, want once each", b, l)
|
||||
}
|
||||
}
|
||||
|
||||
// TestChunkReadHedgeCapCoversRetries: the hedges of one read are capped across
|
||||
// the passes of its retries, not per pass.
|
||||
func TestChunkReadHedgeCapCoversRetries(t *testing.T) {
|
||||
shortHedgeDelay(t, 20*time.Millisecond)
|
||||
var attempts atomic.Int32
|
||||
stallThenFail := func(ctx context.Context, url string, dst []byte, progress *chunkProgress) (int, bool, error) {
|
||||
attempts.Add(1)
|
||||
progress.answer()
|
||||
select {
|
||||
case <-time.After(10 * chunkReadStallDelay):
|
||||
return 0, true, errors.New("connection reset")
|
||||
case <-ctx.Done():
|
||||
return 0, false, ctx.Err()
|
||||
}
|
||||
}
|
||||
hedging := &readHedges{}
|
||||
buffer := make([]byte, 16)
|
||||
hedgeTokens.Store(5 * hedgeTokenScale)
|
||||
for pass := 0; pass < 2; pass++ {
|
||||
if _, _, _, err := hedgedChunkPass(context.Background(), []string{"http://volume:8080/3,abc"}, buffer, hedging, stallThenFail); err == nil {
|
||||
t.Fatalf("pass %d: want the failure", pass)
|
||||
}
|
||||
}
|
||||
if n := attempts.Load(); n != 1+maxHedgesPerRead+1 {
|
||||
t.Fatalf("%d requests over two passes, want %d: the first pass's request and hedges, then one", n, 1+maxHedgesPerRead+1)
|
||||
}
|
||||
if got, want := hedgeTokens.Load(), int64(5*hedgeTokenScale+hedgeTokenEarn-maxHedgesPerRead*hedgeTokenScale); got != want {
|
||||
t.Fatalf("%d thousandths of a token left, want %d: one share earned for the read, not one per pass", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
// TestChunkReadErrorThatAnsweredIsNotUnreachable: a location that sent the
|
||||
// response headers of an error and then stalled its body did answer. When
|
||||
// another location delivers the chunk first, it is not taken for one that
|
||||
// cannot be reached.
|
||||
func TestChunkReadErrorThatAnsweredIsNotUnreachable(t *testing.T) {
|
||||
forgetUnreachable(t)
|
||||
shortHedgeDelay(t, 100*time.Millisecond)
|
||||
payload := testPayload(64 * 1024)
|
||||
failing := stalledBodyServer(t, http.StatusInternalServerError, "disk ")
|
||||
live := newChunkServer(t, answers(payload, false))
|
||||
|
||||
for _, p := range readPaths(t, payload)[:2] {
|
||||
forgetUnreachable(t)
|
||||
urls := []string{failing.URL + "/3,abc", live.url()}
|
||||
refreshed := 0
|
||||
got, _, err := fetch(context.Background(), p, len(payload), urls, func() []string {
|
||||
refreshed++
|
||||
return nil
|
||||
})
|
||||
if err != nil || !bytes.Equal(got, payload) {
|
||||
t.Fatalf("%s: got %d bytes, %v; want the chunk from the second location", p.name, len(got), err)
|
||||
}
|
||||
if refreshed != 0 {
|
||||
t.Fatalf("%s: refresh called %d times; the first location answered", p.name, refreshed)
|
||||
}
|
||||
assertOrder(t, ReachableFirst(urls), urls...)
|
||||
}
|
||||
}
|
||||
@@ -102,10 +102,6 @@ func Get(url string) ([]byte, bool, error) {
|
||||
}
|
||||
|
||||
func GetAuthenticated(ctx context.Context, url, jwt string) ([]byte, bool, error) {
|
||||
return getAuthenticated(ctx, url, jwt, nil)
|
||||
}
|
||||
|
||||
func getAuthenticated(ctx context.Context, url, jwt string, progress *chunkProgress) ([]byte, bool, error) {
|
||||
request, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
|
||||
if err != nil {
|
||||
return nil, true, err
|
||||
@@ -122,28 +118,22 @@ func getAuthenticated(ctx context.Context, url, jwt string, progress *chunkProgr
|
||||
}
|
||||
recordReachable(request.URL.Host)
|
||||
defer CloseResponse(response)
|
||||
progress.answer()
|
||||
|
||||
if response.StatusCode >= 400 {
|
||||
retryable := response.StatusCode >= 500
|
||||
return nil, retryable, StatusError(url, response)
|
||||
}
|
||||
|
||||
var body io.Reader = response.Body
|
||||
if progress != nil {
|
||||
body = progressReader{reader: response.Body, progress: progress}
|
||||
}
|
||||
var reader io.Reader
|
||||
var reader io.ReadCloser
|
||||
switch response.Header.Get("Content-Encoding") {
|
||||
case "gzip":
|
||||
gz, gzErr := gzip.NewReader(body)
|
||||
if gzErr != nil {
|
||||
return nil, true, gzErr
|
||||
reader, err = gzip.NewReader(response.Body)
|
||||
if err != nil {
|
||||
return nil, true, err
|
||||
}
|
||||
defer gz.Close()
|
||||
reader = gz
|
||||
defer reader.Close()
|
||||
default:
|
||||
reader = body
|
||||
reader = response.Body
|
||||
}
|
||||
|
||||
b, err := io.ReadAll(reader)
|
||||
@@ -327,7 +317,7 @@ func ReadUrl(ctx context.Context, fileUrl string, cipherKey []byte, isContentCom
|
||||
var n int
|
||||
_, err := readEncryptedUrl(ctx, fileUrl, "", cipherKey, isContentCompressed, isFullChunk, offset, size, func(data []byte) {
|
||||
n = copy(buf, data)
|
||||
}, nil)
|
||||
})
|
||||
return int64(n), err
|
||||
}
|
||||
|
||||
@@ -394,13 +384,8 @@ func ReadUrl(ctx context.Context, fileUrl string, cipherKey []byte, isContentCom
|
||||
}
|
||||
|
||||
func ReadUrlAsStream(ctx context.Context, fileUrl, jwt string, cipherKey []byte, isContentGzipped bool, isFullChunk bool, offset int64, size int, fn func(data []byte)) (retryable bool, err error) {
|
||||
return readUrlAsStream(ctx, fileUrl, jwt, cipherKey, isContentGzipped, isFullChunk, offset, size, fn, nil)
|
||||
}
|
||||
|
||||
// readUrlAsStream is ReadUrlAsStream reporting to progress what arrives.
|
||||
func readUrlAsStream(ctx context.Context, fileUrl, jwt string, cipherKey []byte, isContentGzipped bool, isFullChunk bool, offset int64, size int, fn func(data []byte), progress *chunkProgress) (retryable bool, err error) {
|
||||
if cipherKey != nil {
|
||||
return readEncryptedUrl(ctx, fileUrl, jwt, cipherKey, isContentGzipped, isFullChunk, offset, size, fn, progress)
|
||||
return readEncryptedUrl(ctx, fileUrl, jwt, cipherKey, isContentGzipped, isFullChunk, offset, size, fn)
|
||||
}
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, fileUrl, nil)
|
||||
@@ -425,7 +410,6 @@ func readUrlAsStream(ctx context.Context, fileUrl, jwt string, cipherKey []byte,
|
||||
}
|
||||
recordReachable(req.URL.Host)
|
||||
defer CloseResponse(r)
|
||||
progress.answer()
|
||||
if r.StatusCode >= 400 {
|
||||
if r.StatusCode == http.StatusNotFound {
|
||||
return true, fmt.Errorf("%s: %s: %w", fileUrl, r.Status, ErrNotFound)
|
||||
@@ -437,22 +421,17 @@ func readUrlAsStream(ctx context.Context, fileUrl, jwt string, cipherKey []byte,
|
||||
return retryable, StatusError(fileUrl, r)
|
||||
}
|
||||
|
||||
var raw io.Reader = r.Body
|
||||
if progress != nil {
|
||||
raw = progressReader{reader: r.Body, progress: progress}
|
||||
}
|
||||
var reader io.Reader
|
||||
var reader io.ReadCloser
|
||||
contentEncoding := r.Header.Get("Content-Encoding")
|
||||
switch contentEncoding {
|
||||
case "gzip":
|
||||
gz, gzErr := gzip.NewReader(raw)
|
||||
if gzErr != nil {
|
||||
return true, gzErr
|
||||
reader, err = gzip.NewReader(r.Body)
|
||||
if err != nil {
|
||||
return true, err
|
||||
}
|
||||
defer gz.Close()
|
||||
reader = gz
|
||||
defer reader.Close()
|
||||
default:
|
||||
reader = raw
|
||||
reader = r.Body
|
||||
}
|
||||
var body io.Reader = reader
|
||||
if size > 0 {
|
||||
@@ -492,8 +471,8 @@ func readUrlAsStream(ctx context.Context, fileUrl, jwt string, cipherKey []byte,
|
||||
|
||||
}
|
||||
|
||||
func readEncryptedUrl(ctx context.Context, fileUrl, jwt string, cipherKey []byte, isContentCompressed bool, isFullChunk bool, offset int64, size int, fn func(data []byte), progress *chunkProgress) (bool, error) {
|
||||
encryptedData, retryable, err := getAuthenticated(ctx, fileUrl, jwt, progress)
|
||||
func readEncryptedUrl(ctx context.Context, fileUrl, jwt string, cipherKey []byte, isContentCompressed bool, isFullChunk bool, offset int64, size int, fn func(data []byte)) (bool, error) {
|
||||
encryptedData, retryable, err := GetAuthenticated(ctx, fileUrl, jwt)
|
||||
if err != nil {
|
||||
return retryable, fmt.Errorf("fetch %s: %v", fileUrl, err)
|
||||
}
|
||||
@@ -744,7 +723,6 @@ func RetriedFetchChunkData(ctx context.Context, buffer []byte, urlStrings []stri
|
||||
}
|
||||
|
||||
var shouldRetry bool
|
||||
hedging := &readHedges{}
|
||||
|
||||
for waitTime := time.Second; waitTime < util.RetryWaitTime; waitTime += waitTime / 2 {
|
||||
// Check for context cancellation before starting retry loop
|
||||
@@ -755,19 +733,34 @@ func RetriedFetchChunkData(ctx context.Context, buffer []byte, urlStrings []stri
|
||||
}
|
||||
|
||||
var failed bool
|
||||
n, failed, shouldRetry, err = hedgedChunkPass(ctx, ReachableFirst(urlStrings), buffer, hedging,
|
||||
func(attemptCtx context.Context, urlString string, dst []byte, progress *chunkProgress) (int, bool, error) {
|
||||
if strings.Contains(urlString, "%") {
|
||||
urlString = url.PathEscape(urlString)
|
||||
for _, urlString := range ReachableFirst(urlStrings) {
|
||||
// Check for context cancellation before each volume server request
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return n, ctx.Err()
|
||||
default:
|
||||
}
|
||||
|
||||
n = 0
|
||||
if strings.Contains(urlString, "%") {
|
||||
urlString = url.PathEscape(urlString)
|
||||
}
|
||||
shouldRetry, err = ReadUrlAsStream(ctx, AppendQueryParameter(urlString, "readDeleted", "true"), string(selectJwt()), cipherKey, isGzipped, isFullChunk, offset, len(buffer), func(data []byte) {
|
||||
if n < len(buffer) {
|
||||
x := copy(buffer[n:], data)
|
||||
n += x
|
||||
}
|
||||
m := 0
|
||||
retryable, readErr := readUrlAsStream(attemptCtx, AppendQueryParameter(urlString, "readDeleted", "true"), string(selectJwt()), cipherKey, isGzipped, isFullChunk, offset, len(dst), func(data []byte) {
|
||||
if m < len(dst) {
|
||||
m += copy(dst[m:], data)
|
||||
}
|
||||
}, progress)
|
||||
return m, retryable, readErr
|
||||
})
|
||||
if !shouldRetry {
|
||||
break
|
||||
}
|
||||
if err != nil {
|
||||
failed = true
|
||||
glog.V(0).InfofCtx(ctx, "read %s failed, err: %v", urlString, err)
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
if err == nil && failed && refreshUrls != nil {
|
||||
refreshUrls()
|
||||
}
|
||||
@@ -801,7 +794,6 @@ func RetriedFetchChunkData(ctx context.Context, buffer []byte, urlStrings []stri
|
||||
// for large chunk reads.
|
||||
func retriedFetchChunkDataDirect(ctx context.Context, buffer []byte, urlStrings []string, selectJwt func() security.EncodedJwt, fileId string, refreshUrls RefreshUrlsFunc) (n int, err error) {
|
||||
var shouldRetry bool
|
||||
hedging := &readHedges{}
|
||||
|
||||
for waitTime := time.Second; waitTime < util.RetryWaitTime; waitTime += waitTime / 2 {
|
||||
select {
|
||||
@@ -811,15 +803,25 @@ func retriedFetchChunkDataDirect(ctx context.Context, buffer []byte, urlStrings
|
||||
}
|
||||
|
||||
var failed bool
|
||||
n, failed, shouldRetry, err = hedgedChunkPass(ctx, ReachableFirst(urlStrings), buffer, hedging,
|
||||
func(attemptCtx context.Context, urlString string, dst []byte, progress *chunkProgress) (int, bool, error) {
|
||||
return readUrlDirectToBuffer(attemptCtx, AppendQueryParameter(urlString, "readDeleted", "true"), string(selectJwt()), dst, progress)
|
||||
})
|
||||
if err == nil {
|
||||
if failed && refreshUrls != nil {
|
||||
refreshUrls()
|
||||
for _, urlString := range ReachableFirst(urlStrings) {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return 0, ctx.Err()
|
||||
default:
|
||||
}
|
||||
return n, nil
|
||||
|
||||
n, shouldRetry, err = readUrlDirectToBuffer(ctx, AppendQueryParameter(urlString, "readDeleted", "true"), string(selectJwt()), buffer)
|
||||
if err == nil {
|
||||
if failed && refreshUrls != nil {
|
||||
refreshUrls()
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
if !shouldRetry {
|
||||
break
|
||||
}
|
||||
failed = true
|
||||
glog.V(0).InfofCtx(ctx, "read %s failed, err: %v", urlString, err)
|
||||
}
|
||||
|
||||
if err != nil && shouldRetry {
|
||||
@@ -846,7 +848,7 @@ func retriedFetchChunkDataDirect(ctx context.Context, buffer []byte, urlStrings
|
||||
|
||||
// readUrlDirectToBuffer reads HTTP response directly into the provided buffer,
|
||||
// avoiding intermediate buffer allocations and copies.
|
||||
func readUrlDirectToBuffer(ctx context.Context, fileUrl, jwt string, buffer []byte, progress *chunkProgress) (n int, retryable bool, err error) {
|
||||
func readUrlDirectToBuffer(ctx context.Context, fileUrl, jwt string, buffer []byte) (n int, retryable bool, err error) {
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, fileUrl, nil)
|
||||
if err != nil {
|
||||
return 0, false, err
|
||||
@@ -863,7 +865,6 @@ func readUrlDirectToBuffer(ctx context.Context, fileUrl, jwt string, buffer []by
|
||||
}
|
||||
recordReachable(req.URL.Host)
|
||||
defer CloseResponse(r)
|
||||
progress.answer()
|
||||
|
||||
if r.StatusCode >= 400 {
|
||||
if r.StatusCode == http.StatusNotFound {
|
||||
@@ -888,9 +889,6 @@ func readUrlDirectToBuffer(ctx context.Context, fileUrl, jwt string, buffer []by
|
||||
|
||||
m, readErr := r.Body.Read(buffer[totalRead:])
|
||||
totalRead += m
|
||||
if m > 0 {
|
||||
progress.arrived()
|
||||
}
|
||||
if readErr != nil {
|
||||
if readErr == io.EOF {
|
||||
// Return io.ErrUnexpectedEOF if we haven't filled the buffer
|
||||
|
||||
@@ -200,7 +200,7 @@ func TestReadErrorsCarryTheServerMessage(t *testing.T) {
|
||||
if _, _, err := ReadUrlAsReaderCloser(server.URL, "", ""); err == nil || err.Error() != want {
|
||||
t.Errorf("ReadUrlAsReaderCloser: got %v, want %q", err, want)
|
||||
}
|
||||
if _, _, err := readUrlDirectToBuffer(context.Background(), server.URL, "", make([]byte, 16), nil); err == nil || err.Error() != want {
|
||||
if _, _, err := readUrlDirectToBuffer(context.Background(), server.URL, "", make([]byte, 16)); err == nil || err.Error() != want {
|
||||
t.Errorf("readUrlDirectToBuffer: got %v, want %q", err, want)
|
||||
}
|
||||
if _, _, err := GetAuthenticated(context.Background(), server.URL, ""); err == nil || err.Error() != want {
|
||||
|
||||
Reference in new issue
Block a user