Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
119 changes: 98 additions & 21 deletions pkgs/atlas-search/crates/atlas-core/src/aggregate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,15 +19,21 @@
//! pipeline's own contract is that the embedder only ever sees
//! in-context inputs, and atlas-embed refuses longer ones. The
//! pieces partition the chunk text exactly and become separate
//! shard chunks under the same source pointer, in order.
//! shard chunks under the same source pointer, in order. Pieces
//! split within one staged chunk, so a piece never crosses the
//! classification boundary its chunk was cut on (#12628), and
//! each distinct piece text is embedded once per run: identical
//! texts share the one computed vector.
//! 3. Write one new local core scan shard in `shard_dir` —
//! `atlas-core-<tier>-<topic>-<nn>.db` carrying exactly the shard
//! schema shard discovery and the fan-out scan read (`chunks`, the
//! [`DEFAULT_VEC_TABLE`] vector table, `atlas_manifest`), so the
//! promoted entries are searchable by the existing fan-out with no
//! new read path. The shard's tier is the unit's recorded
//! sensitivity; each chunk's `sensitivity` is written in the scan
//! vocabulary (see [`tier_sensitivity_name`]).
//! vocabulary (see [`tier_sensitivity_name`]) — for an item staged
//! with classification records (#12628), the chunk's own persisted
//! effective sensitivity; otherwise its item's tier.
//! 4. Stamp the unit DB's `atlas_manifest` `embedding_model` with the
//! mandated model — the provenance record [`Registry::promote`]'s
//! M6 gate (#7648) reads. Stamping adds the manifest table to the
Expand Down Expand Up @@ -58,8 +64,9 @@ use rusqlite::{Connection, params};

use crate::embed::DocEmbedder;
use crate::error::{Error, Result};
use crate::filters::Sensitivity;
use crate::shards::{EMBEDDING_MODEL_ID, Tier};
use crate::stage::{Registry, UnitState};
use crate::stage::{Registry, UnitState, chunk_classifications};
use crate::types::DEFAULT_VEC_TABLE;

/// The scan-vocabulary sensitivity name a chunk of this tier carries
Expand Down Expand Up @@ -96,6 +103,13 @@ struct StagedChunk {
item_sensitivity: String,
text: String,
content_hash: String,
/// The chunk's persisted effective sensitivity (#12628), for
/// items staged with classification records: `Some` whenever the
/// item carries records — a chunk whose record is missing from a
/// classified item resolves to `secret-bearing` here, never to
/// the item's tier — and `None` for legacy items staged without
/// records, whose chunks keep the item-tier behaviour.
effective_sensitivity: Option<Sensitivity>,
}

/// Read one unit's staged chunks in staging order (item id, then
Expand All @@ -107,29 +121,64 @@ fn read_staged_chunks(db_path: &Path, unit_id: &str) -> Result<Vec<StagedChunk>>
db_path.display()
))
})?;
// The unit's per-item classification records, resolved once per
// item: item id -> (records present?, per-chunk classifications).
let mut classifications: std::collections::HashMap<
i64,
Option<Vec<crate::stage::ChunkClassification>>,
> = std::collections::HashMap::new();
{
let mut stmt = conn
.prepare("SELECT id FROM items WHERE unit_id = ?1")
.map_err(|e| Error::backend(format!("aggregator: reading staged items: {e}")))?;
let ids = stmt
.query_map(params![unit_id], |r| r.get::<_, i64>(0))
.map_err(|e| Error::backend(format!("aggregator: reading staged items: {e}")))?;
for id in ids {
let id =
id.map_err(|e| Error::backend(format!("aggregator: reading staged items: {e}")))?;
classifications.insert(id, chunk_classifications(&conn, id)?);
}
}
let mut stmt = conn
.prepare(
"SELECT i.id, i.source, i.sensitivity, c.text, c.content_hash \
"SELECT i.id, i.source, i.sensitivity, c.text, c.content_hash, c.idx \
FROM chunks_raw c JOIN items i ON i.id = c.item_id \
WHERE i.unit_id = ?1 ORDER BY i.id, c.idx",
)
.map_err(|e| Error::backend(format!("aggregator: reading staged chunks: {e}")))?;
let rows = stmt
.query_map(params![unit_id], |r| {
Ok(StagedChunk {
item_id: r.get(0)?,
item_source: r.get(1)?,
item_sensitivity: r.get(2)?,
text: r.get(3)?,
content_hash: r.get(4)?,
})
Ok((
StagedChunk {
item_id: r.get(0)?,
item_source: r.get(1)?,
item_sensitivity: r.get(2)?,
text: r.get(3)?,
content_hash: r.get(4)?,
effective_sensitivity: None,
},
r.get::<_, i64>(5)?,
))
})
.map_err(|e| Error::backend(format!("aggregator: reading staged chunks: {e}")))?;
let mut out = Vec::new();
for row in rows {
out.push(
row.map_err(|e| Error::backend(format!("aggregator: reading staged chunks: {e}")))?,
);
let (mut chunk, idx) =
row.map_err(|e| Error::backend(format!("aggregator: reading staged chunks: {e}")))?;
chunk.effective_sensitivity = match classifications.get(&chunk.item_id) {
// Classified item: the chunk's own record governs; a
// chunk with no record in a classified item fails closed.
Some(Some(records)) => Some(
records
.get(idx as usize)
.map(|record| record.sensitivity)
.unwrap_or(Sensitivity::SecretBearing),
),
// Legacy item (or item not seen above): no records.
_ => None,
};
out.push(chunk);
}
Ok(out)
}
Expand Down Expand Up @@ -170,6 +219,11 @@ fn next_shard_part(shard_dir: &Path, tier: Tier, topic: &str) -> Result<u32> {
struct ShardChunk {
item_source: Option<String>,
item_sensitivity: String,
/// The staged chunk's persisted effective sensitivity (#12628),
/// inherited by every embed-time piece of that chunk: pieces are
/// split *within* one staged chunk, so they never cross the
/// boundary the chunk was cut on and keep its classification.
effective_sensitivity: Option<Sensitivity>,
chunk_idx: i64,
text: String,
content_hash: String,
Expand Down Expand Up @@ -366,15 +420,31 @@ pub fn embed_unit_into_shard(
pieces.push(ShardChunk {
item_source: c.item_source.clone(),
item_sensitivity: c.item_sensitivity.clone(),
effective_sensitivity: c.effective_sensitivity,
chunk_idx,
content_hash,
text: piece,
});
}
}
// Embed each distinct text once (#12628): a document vector is a
// pure function of (text, model), and this run uses one model,
// so identical pieces — repeated blocks, identical items, and
// chunks a boundary revision left unchanged — share the single
// computed vector instead of being re-embedded. Only a text that
// actually changed is embedded anew.
let mut vecs: Vec<Vec<f32>> = Vec::with_capacity(pieces.len());
let mut vec_by_text: std::collections::HashMap<String, Vec<f32>> =
std::collections::HashMap::new();
for piece in &pieces {
vecs.push(embedder.embed_doc(&piece.text)?);
let key = sha256_hex(&piece.text);
if let Some(vec) = vec_by_text.get(&key) {
vecs.push(vec.clone());
continue;
}
let vec = embedder.embed_doc(&piece.text)?;
vec_by_text.insert(key, vec.clone());
vecs.push(vec);
}
let dims = vecs[0].len();
if dims == 0 || vecs.iter().any(|v| v.len() != dims) {
Expand Down Expand Up @@ -423,12 +493,19 @@ pub fn embed_unit_into_shard(
.map_err(|e| Error::backend(format!("aggregator: shard begin: {e}")))?;
for (i, (c, v)) in pieces.iter().zip(vecs.iter()).enumerate() {
let id = (i + 1) as i64;
// The chunk's sensitivity is its item's recorded tier,
// in scan vocabulary; an unparseable record falls back
// to the unit's tier rather than widening access.
let sens = Tier::parse(&c.item_sensitivity)
.map(tier_sensitivity_name)
.unwrap_or_else(|| tier_sensitivity_name(unit.sensitivity));
// The chunk's sensitivity: for a classified item, its
// persisted effective sensitivity, whose name is already
// scan vocabulary (the fan-out filters chunk sensitivity
// against the Sensitivity ladder). Otherwise its item's
// recorded tier, in scan vocabulary; an unparseable
// record falls back to the unit's tier rather than
// widening access.
let sens = match c.effective_sensitivity {
Some(sensitivity) => sensitivity.name(),
None => Tier::parse(&c.item_sensitivity)
.map(tier_sensitivity_name)
.unwrap_or_else(|| tier_sensitivity_name(unit.sensitivity)),
};
let message_id = c
.item_source
.clone()
Expand Down
12 changes: 8 additions & 4 deletions pkgs/atlas-search/crates/atlas-core/src/boundary.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,14 @@
//! other chunk keeps its exact byte range and text, so its
//! classification and vector stay valid (design §3, #6038).
//!
//! This is the splitting primitive only. Wiring declared boundaries
//! into staging (`stage`) and promotion (`aggregate`) is the next
//! slice; until then the staging path keeps its current behaviour
//! and this module is exercised by its own tests.
//! This module is the splitting primitive. Declared boundaries are
//! wired into staging by [`crate::stage::stage_classified_artifact`]
//! (boundary-safe `chunks_raw` plus one persisted classification
//! record per chunk) and into promotion by [`crate::aggregate`],
//! which writes each chunk's effective sensitivity into the shard
//! and embeds identical texts once (#12628). The legacy staging
//! path ([`crate::stage::stage_artifact`]) keeps its current
//! behaviour for producers that declare no segments.

use crate::filters::Sensitivity;

Expand Down
6 changes: 4 additions & 2 deletions pkgs/atlas-search/crates/atlas-core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -112,8 +112,10 @@ pub use search::{
run_search_with_executor_traced,
};
pub use stage::{
REGISTRY_V1_DDL, Registry, STAGE_SCHEMA_VERSION, STAGE_V1_DDL, STAGE_V1_TABLES, StagingUnit,
UnitState, check_stage_schema, provision_staging_db, schema_version,
ChunkClassification, REGISTRY_V1_DDL, Registry, STAGE_SCHEMA_VERSION, STAGE_V1_DDL,
STAGE_V1_TABLES, StagingUnit, UnitState, check_stage_schema, chunk_classifications,
provision_staging_db, schema_version, stage_classified_artifact,
stage_classified_artifact_in_db,
};
pub use trace::{JsonlTraceSink, TRACE_SCHEMA, TraceContext, TraceSink};
pub use trace_ingest::{
Expand Down
Loading