From 903f14efb2981dfb92f856384a5994b8ffdaf2da Mon Sep 17 00:00:00 2001 From: rong Date: Sun, 1 Nov 2026 19:49:16 +0800 Subject: [PATCH] =?UTF-8?q?feat(sql):=20GROUP=20BY=20=E8=B5=B0=E6=95=B4?= =?UTF-8?q?=E6=95=B0=E7=A0=81=E5=89=8D=E7=BC=80=E5=92=8C=EF=BC=8C8=20?= =?UTF-8?q?=E7=BB=84=20162=20=E2=86=92=2092=20=E8=BD=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 影响:`secure_group_by` 新增 `GroupMode::IntegerCode` 路径,每组相等判断 (`bit_eq` = 两次 `bit_lt`,18 轮/组、串行累加)换成 `N+1` 个单调前缀 「码 ≤ g」,`COUNT` 取前缀位之和、`SUM` 取 `mul_raw(前缀位, 列)`,所有 `open` 落在同一阶段合成一次,**组内值在明文侧差分**,没有第二段图。默认仍是 `GroupMode::Exact`,语义不变。 实测(`nax sql-plan --rows 8 --aggs count,sum`):2 组 42→32、4 组 82→52、 8 组 162→92;每组建图成本约 20 → 11 轮。带 WHERE 的增量是「一次比较 + 一次 搬家乘」10~11 轮。 新增: - `secure_graph::build_prefix_stage` —— 谓词 → 码搬家 → N+1 个前缀 → 累积和 - `secure_group_by_coded` / `secure_group_by_pred_coded`,`query_rounds` 收 `GroupMode`,`nax sql-plan --group-mode coded`、`nax sql --group-mode coded` - `crates/nax-sql/tests/coded.rs` 12 条:与 Exact 对拍(`COUNT`/`SUM` 逐位、 `AVG` 相对 1e-4)、复合谓词、越界/非整数码契约、空组、k-匿名、单组、轮数钉值 三条契约(写进 `docs/IR.md` §3.3,不隐藏代价):分组码必须是整数(非整数落 到上方最近一组);不支持 MIN/MAX(前缀和还原不出极值,直接报错不降级); 越界码丢弃(与逐组比较一致,两端边界 `−0.5` / `N−0.5` 就是为它留的)。 WHERE 未命中行不逐组乘 `base`(`2N` 轮),而是把码搬到 `−1000·2^fxp` 让它在 差分中自动抵消。**第一版把 `−1000` 当 raw 用**:分组码列是 fxp 编码, `0.5` 编出来是 `131072`,于是 `−1000` 比每个边界都小,全部行被算进每个前缀 (行数变全表、SUM 变全表之和且不报错)。改为按 `2^fxp` 缩放,`fxp > 40` 拒绝。 变异验证 4 条全部按预期变红后还原:停放值不缩放(2 红)、边界少 `−0.5` (只有非整数码契约那条红,整数码下 ` ExitCode { "lr-vertical" => cmd_lr_vertical(&args[1..]), "fl" => cmd_fl(&args[1..]), #[cfg(feature = "secure")] - "sql" => sql_demo::run(), + "sql" => sql_demo::run(&args[1..]), #[cfg(feature = "secure")] "sql-plan" => cmd_sql_plan(&args[1..]), #[cfg(feature = "secure")] @@ -121,6 +121,10 @@ fn usage() { nax sql in-process 2 方密态 SQL 演示(编译需 --features secure) nax sql-plan 把一条聚合查询编译成执行计划,报出交互轮数(不联网,需 --features secure) nax sql-join 真两进程 TCP 的 JOIN×PSI×密态 SQL(编译需 --features secure) + + nax sql / nax sql-plan 都支持 --group-mode exact|coded(默认 exact): + coded 走整数分组码前缀和,8 组时 162 → 92 轮;要求分组码是 0..n-1 的整数, + 且不支持 MIN/MAX(前缀和还原不出分组极值) nax pg 连一条 PostgreSQL 跑一条 SQL,把列类型摊开(排障用,需 --features secure) nax version 打印版本 nax help 显示本帮助 @@ -878,15 +882,35 @@ fn cmd_sql_plan(args: &[String]) -> Result<(), String> { Some(s) => Some(parse_simple_pred(&s)?), None => None, }; + let mode = match parse_flag(args, "--group-mode").as_deref() { + None | Some("exact") => nax_sql::secure::GroupMode::Exact, + Some("coded") => nax_sql::secure::GroupMode::IntegerCode, + Some(other) => { + return Err(format!( + "--group-mode {other:?} 不认识(可选 exact / coded)" + )) + } + }; - let plan = nax_sql::secure::query_rounds(rows, FXP, 1, pred.as_ref(), groups, &aggs) + let plan = nax_sql::secure::query_rounds(rows, FXP, 1, pred.as_ref(), groups, &aggs, mode) .map_err(|e| e.to_string())?; - for (title, p) in [ - ("掩码段(谓词 → 0/1 位 → 掩码后列 → 命中数)", &plan.mask), - ("聚合段(SUM / AVG / MIN / MAX)", &plan.aggs), - ] { - report::table(title, &["起始轮", "交互算子", "本地算子", "交互数"], &stage_rows(p)); + let coded = mode == nax_sql::secure::GroupMode::IntegerCode && groups.is_some(); + report::table( + if coded { + "前缀段(谓词 → 分组码搬家 → N+1 个单调前缀 → 累积和)" + } else { + "掩码段(谓词 → 0/1 位 → 掩码后列 → 命中数)" + }, + &["起始轮", "交互算子", "本地算子", "交互数"], + &stage_rows(&plan.mask), + ); + if let Some(a) = &plan.aggs { + report::table( + "聚合段(SUM / AVG / MIN / MAX)", + &["起始轮", "交互算子", "本地算子", "交互数"], + &stage_rows(a), + ); } let agg_names: Vec<&str> = aggs @@ -910,6 +934,14 @@ fn cmd_sql_plan(args: &[String]) -> Result<(), String> { None => report::Cell::txt("无(整表)"), }, ), + ( + "分组模式", + report::Cell::txt(if coded { + "整数码(前缀和)" + } else { + "逐组比较" + }), + ), ("聚合", report::Cell::txt(agg_names.join(", "))), ( "谓词", @@ -919,7 +951,7 @@ fn cmd_sql_plan(args: &[String]) -> Result<(), String> { }, ), ("掩码段往返", report::Cell::int(plan.mask.rounds() as i64)), - ("聚合段往返", report::Cell::int(plan.aggs.rounds() as i64)), + ("聚合段往返", report::Cell::int(plan.agg_rounds() as i64)), ("总往返", report::Cell::int(plan.rounds() as i64)), ( "口径", @@ -1147,7 +1179,7 @@ fn json_str(s: &str) -> String { // nax node // --------------------------------------------------------------------------- -fn parse_flag<'a>(args: &'a [String], name: &str) -> Option<&'a str> { +pub(crate) fn parse_flag<'a>(args: &'a [String], name: &str) -> Option<&'a str> { args.iter() .position(|a| a == name) .and_then(|i| args.get(i + 1)) diff --git a/crates/nax-cli/src/sql_demo.rs b/crates/nax-cli/src/sql_demo.rs index aadee5b..6842c4e 100644 --- a/crates/nax-cli/src/sql_demo.rs +++ b/crates/nax-cli/src/sql_demo.rs @@ -5,7 +5,7 @@ use crate::report::Cell; use nax_core::ring; -use nax_sql::secure::{secure_group_by, Agg}; +use nax_sql::secure::{secure_group_by, secure_group_by_coded, Agg, GroupMode}; use nax_vault::{Pipe, Vault}; use std::thread; @@ -16,7 +16,16 @@ fn split_on(va: &mut Vault, vals: &[f64], fxp: u32) -> (Vec, Vec (all[0..len].to_vec(), all[len..2 * len].to_vec()) } -pub fn run() -> Result<(), String> { +pub fn run(args: &[String]) -> Result<(), String> { + let mode = match crate::parse_flag(args, "--group-mode").as_deref() { + None | Some("exact") => GroupMode::Exact, + Some("coded") => GroupMode::IntegerCode, + Some(other) => { + return Err(format!( + "--group-mode {other:?} 不认识(可选 exact / coded)" + )) + } + }; let fxp = 18u32; let seed = [5u8; 32]; let sites = ["alice", "bob"]; @@ -34,11 +43,25 @@ pub fn run() -> Result<(), String> { note!("nax sql · in-process 2 方密态 GROUP BY(无网络、无可信第三方)"); note!(" 查询: SELECT region, COUNT(*), SUM(amount), AVG(amount) FROM t GROUP BY region"); - note!(" 说明: WHERE/GROUP BY 是 0/1 掩码,聚合乘掩码;比较用 edaBit+BitLT,乘法走 Beaver\n"); + note!(" 说明: WHERE/GROUP BY 是 0/1 掩码,聚合乘掩码;比较用 edaBit+BitLT,乘法走 Beaver"); + note!( + " 分组: {}\n", + match mode { + GroupMode::Exact => "逐组比较(每组一次 ==)", + GroupMode::IntegerCode => "整数码前缀和(region 码就是 0/1 整数)", + } + ); - let ha = thread::spawn(move || secure_group_by(&mut va, &a0, &g0, 2, None, &aggs, 0)); + let ha = thread::spawn(move || match mode { + GroupMode::Exact => secure_group_by(&mut va, &a0, &g0, 2, None, &aggs, 0), + GroupMode::IntegerCode => secure_group_by_coded(&mut va, &a0, &g0, 2, None, &aggs, 0), + }); let hb = thread::spawn(move || { - let _ = secure_group_by(&mut vb, &a1, &g1, 2, None, &aggs, 0); + let r = match mode { + GroupMode::Exact => secure_group_by(&mut vb, &a1, &g1, 2, None, &aggs, 0), + GroupMode::IntegerCode => secure_group_by_coded(&mut vb, &a1, &g1, 2, None, &aggs, 0), + }; + let _ = r; }); let rows = ha .join() diff --git a/crates/nax-sql/Cargo.toml b/crates/nax-sql/Cargo.toml index 990ad42..83a6615 100644 --- a/crates/nax-sql/Cargo.toml +++ b/crates/nax-sql/Cargo.toml @@ -34,3 +34,7 @@ required-features = ["secure"] [[test]] name = "migration" required-features = ["secure"] + +[[test]] +name = "coded" +required-features = ["secure"] diff --git a/crates/nax-sql/src/secure.rs b/crates/nax-sql/src/secure.rs index 1afee88..68b1394 100644 --- a/crates/nax-sql/src/secure.rs +++ b/crates/nax-sql/src/secure.rs @@ -34,7 +34,10 @@ use nax_core::ring; use nax_ir::{run, Graph, IrError, Val}; use nax_vault::{Transport, Vault, VaultError}; -use crate::secure_graph::{build_agg_stage, build_count_stage, ir, run_mask_only, AggOut, Ctx, Feed}; +use crate::secure_graph::{ + build_agg_stage, build_count_stage, build_prefix_stage, ir, run_mask_only, AggOut, Ctx, Feed, + PrefixStage, +}; /// 比较运算符。 #[derive(Clone, Copy, PartialEq, Eq, Debug)] @@ -57,6 +60,43 @@ pub enum Agg { Max, } +/// 分组掩码怎么算 —— 决定 `GROUP BY` 的**协议形状**,不改变语义。 +/// +/// 两种模式的返回值在整数分组码下相同(`COUNT` / `SUM` 逐位相同,`AVG` 差 +/// 在浮点末位),差别只在要几个往返。 +#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)] +pub enum GroupMode { + /// 每组一次 `gcol == g`:`bit_eq` 是两次比较,**每组 18 轮**。 + /// + /// 对任意编码都成立(分组码是字符串哈希、浮点数、越界值都没问题),是默认值。 + #[default] + Exact, + /// 假定分组码是**整数** `0..n_groups-1`:`N` 个组共享 `N+1` 个单调前缀, + /// **每组约 11 轮**,而且所有组的聚合值在一次批量 `open` 里就都出来了。 + /// + /// 代价是两条契约,都由调用方保证(密态下无法校验): + /// + /// 1. 码必须是整数。**非整数码会落到它上方最近的一组**(`1.5 → 2 号组`), + /// 而不是「哪组都不算」; + /// 2. 越界码(负数、`≥ n_groups`)会被丢掉 —— 这点与 [`GroupMode::Exact`] 一致。 + /// + /// 不支持 `MIN` / `MAX`:分组极值不能由前缀和还原(前缀和只知道「和」, + /// 不知道「谁最大」)。请求它们会直接报错,不会悄悄退化成别的结果。 + IntegerCode, +} + +/// 整数分组码路径能用哪些聚合;不支持的当场拒,不做静默降级。 +fn check_coded_aggs(aggs: &[Agg]) -> Result<(), VaultError> { + if aggs.iter().any(|a| matches!(a, Agg::Min | Agg::Max)) { + return Err(VaultError::Protocol( + "整数分组码(GroupMode::IntegerCode)不支持 MIN / MAX:\ + 分组极值无法由前缀和还原。请改用 GroupMode::Exact" + .into(), + )); + } + Ok(()) +} + /// 计算比较掩码(共享原始 0/1 位)。 /// /// 两侧都吃分片 —— 公开阈值请调用方自己 `vault.constant` 之后传进来, @@ -310,6 +350,128 @@ pub fn secure_group_by_pred( .collect()) } +// --------------------------------------------------------------------------- // +// 整数分组码:前缀和路径 +// --------------------------------------------------------------------------- // + +/// 密态 GROUP BY(整数分组码):语义同 [`secure_group_by`],协议形状不同。 +/// +/// 逐组 `gcol == g` 换成 `N+1` 个单调前缀(`码 ≤ g`),组内值在明文侧由累积和 +/// 相减得到。每组建图成本从 20 轮降到约 11 轮,且**所有组的输出在一次批量 +/// `open` 里**就都出来了 —— 没有第二段图。 +/// +/// 契约(密态下无法校验,由调用方保证)见 [`GroupMode::IntegerCode`]: +/// `gcol` 必须是 `0..n_groups-1` 的**整数**码;不支持 `MIN` / `MAX`。 +pub fn secure_group_by_coded( + vault: &mut Vault, + col: &[u64], + gcol: &[u64], + n_groups: usize, + pred: Option<(f64, CmpOp)>, + aggs: &[Agg], + min_group_size: usize, +) -> Result>, VaultError> { + if gcol.len() != col.len() { + return Err(VaultError::Protocol("col 与 gcol 长度不一致".into())); + } + if col.is_empty() { + return Ok(vec![empty_answer(aggs); n_groups]); + } + check_coded_aggs(aggs)?; + + let ctx = Ctx::new(col.len(), vault.fxp()); + let st = build_prefix_stage(ctx, 2, 0, 1, n_groups, |g, cs| match pred { + Some((t, op)) => Ok(Some(ctx.mask_cmp(g, cs[0], t, op)?)), + None => Ok(None), + })?; + let vals = run(&st.plan, vault, &[col, gcol], ctx.fxp).map_err(ir)?; + assemble_coded(ctx, aggs, n_groups, &vals, &st, min_group_size) +} + +/// 密态 GROUP BY(整数分组码 + 复合谓词):`secure_group_by_pred` 的前缀和版本。 +pub fn secure_group_by_pred_coded( + vault: &mut Vault, + cols: &[Vec], + agg_col: usize, + gcol: &[u64], + n_groups: usize, + pred: Option<&Pred>, + aggs: &[Agg], + min_group_size: usize, +) -> Result>, VaultError> { + let col = cols + .get(agg_col) + .ok_or_else(|| VaultError::Protocol(format!("聚合列 {agg_col} 不存在")))?; + if gcol.len() != col.len() { + return Err(VaultError::Protocol(format!( + "聚合列有 {} 行、分组列有 {} 行 —— 行对齐没做干净", + col.len(), + gcol.len() + ))); + } + let len = check_aligned(cols)?; + if len == 0 { + return Ok(vec![empty_answer(aggs); n_groups]); + } + check_coded_aggs(aggs)?; + + let ctx = Ctx::new(len, vault.fxp()); + let n_cols = cols.len(); + let mut given: Vec<&[u64]> = cols.iter().map(|c| c.as_slice()).collect(); + given.push(gcol); + let st = build_prefix_stage(ctx, n_cols + 1, agg_col, n_cols, n_groups, |g, cs| match pred { + Some(p) => Ok(Some(ctx.pred(g, &cs[..n_cols], p)?)), + None => Ok(None), + })?; + let vals = run(&st.plan, vault, &given, ctx.fxp).map_err(ir)?; + assemble_coded(ctx, aggs, n_groups, &vals, &st, min_group_size) +} + +/// 累积和 → 各组的值。全部在**明文**上做,不过网络。 +fn assemble_coded( + ctx: Ctx, + aggs: &[Agg], + n_groups: usize, + vals: &nax_ir::Values, + st: &PrefixStage, + min_group_size: usize, +) -> Result>, VaultError> { + let mut out = Vec::with_capacity(n_groups); + for i in 0..n_groups { + let c_lo = vals.raw(st.cum_count[i]).map_err(ir)?[0]; + let c_hi = vals.raw(st.cum_count[i + 1]).map_err(ir)?[0]; + let count = c_hi.wrapping_sub(c_lo) as usize; + + let s_lo = vals.raw(st.cum_sum[i]).map_err(ir)?[0]; + let s_hi = vals.raw(st.cum_sum[i + 1]).map_err(ir)?[0]; + let sum_raw = (s_hi as i64).wrapping_sub(s_lo as i64) as u64; + + if min_group_size > 0 && count < min_group_size { + out.push(vec![f64::NAN; aggs.len()]); + continue; + } + + let mut row = Vec::with_capacity(aggs.len()); + for &a in aggs { + row.push(match a { + Agg::Count => count as f64, + Agg::Sum => ring::decode(sum_raw, ctx.fxp), + // 空组没有平均值:与 Exact 路径一样给 NaN(不是 0/0 得到的 NaN + // 就算巧合,这里显式写出来,免得以后改成 IEEE 之外的语义)。 + Agg::Avg if count == 0 => f64::NAN, + Agg::Avg => ring::decode(sum_raw, ctx.fxp) / count as f64, + Agg::Min | Agg::Max => { + return Err(VaultError::Protocol( + "整数分组码不支持 MIN / MAX".into(), + )) + } + }); + } + out.push(row); + } + Ok(out) +} + /// 复合谓词:列与字面量的比较,用 AND / OR / NOT 组合。 /// /// 对应明文引擎 `_eval_binop` 里 AND/OR/NOT 的位运算;`col` 是 `cols` 切片的下标。 @@ -394,33 +556,49 @@ pub fn secure_aggregate_all( Ok(vals.pop().expect("单分支")) } -/// 一条聚合查询的两段计划(已编译,**没有执行**)。 +/// 一条聚合查询的计划(已编译,**没有执行**)。 /// /// 报出来的轮数是 [`nax_ir::Plan::rounds`] 那个口径:**上界**。同阶段的 `open` /// 合成一次往返,但 `mul` / `cmp` 这些自带内部往返的算子不与 `open` 搭车。 pub struct QueryPlan { /// 第一段:掩码 + 掩码后列 + 命中数。 + /// + /// 整数分组码模式下这一段是**前缀段**(分组码搬家 + `N+1` 个单调前缀 + /// + 累积和),且**没有**第二段 —— 所有组的输出在同一次批量 `open` 里出来。 pub mask: nax_ir::Plan, - /// 第二段:`SUM` / `AVG` / `MIN` / `MAX`。 - pub aggs: nax_ir::Plan, + /// 第二段:`SUM` / `AVG` / `MIN` / `MAX`。整数分组码模式下是 `None`。 + pub aggs: Option, } impl QueryPlan { /// 总往返数。 pub fn rounds(&self) -> usize { - self.mask.rounds() + self.aggs.rounds() + self.mask.rounds() + self.agg_rounds() + } + + /// 第二段的往返数(没有第二段时是 0)。 + pub fn agg_rounds(&self) -> usize { + self.aggs.as_ref().map_or(0, |p| p.rounds()) } /// 人读摘要。`nax sql-plan` 直接打它。 pub fn summary(&self) -> String { - format!( - "总往返 {} 轮 = 掩码段 {} + 聚合段 {}\n--- 掩码段 ---\n{}--- 聚合段 ---\n{}", - self.rounds(), - self.mask.rounds(), - self.aggs.rounds(), - self.mask.summary(), - self.aggs.summary() - ) + match &self.aggs { + Some(a) => format!( + "总往返 {} 轮 = 掩码段 {} + 聚合段 {}\n--- 掩码段 ---\n{}--- 聚合段 ---\n{}", + self.rounds(), + self.mask.rounds(), + a.rounds(), + self.mask.summary(), + a.summary() + ), + None => format!( + "总往返 {} 轮(整数分组码:只有前缀段,各组输出在一次批量 open 里)\n\ + --- 前缀段 ---\n{}", + self.rounds(), + self.mask.summary() + ), + } } } @@ -430,6 +608,9 @@ impl QueryPlan { /// 图只依赖**形状**,所以只需要行数,不需要真数据 —— 这是「轮数能报出来」 /// 最直接的用处:不必先有数据、不必联网。 /// +/// `mode` 只影响 `GROUP BY`:`Exact` 逐组比较(每组 18 轮),`IntegerCode` +/// 走前缀和(每组约 11 轮,且没有第二段图)。两者报出来的数都是**上界**。 +/// /// # 两处估计(返回值是上界,不是精确值) /// /// * `AVG` 的除数 `COUNT` 要执行后才知道。这里按**非整数**系数算,也就是 @@ -445,12 +626,26 @@ pub fn query_rounds( pred: Option<&Pred>, groups: Option, aggs: &[Agg], + mode: GroupMode, ) -> Result { let ctx = Ctx::new(rows, fxp); if n_cols == 0 { return Err(VaultError::Protocol("至少要有一列".into())); } + // 整数分组码走另一张图:前缀段,没有第二段(所有输出一次 open 出来)。 + if let Some(n) = groups.filter(|_| mode == GroupMode::IntegerCode) { + check_coded_aggs(aggs)?; + let st = build_prefix_stage(ctx, n_cols + 1, 0, n_cols, n, |g, cols| match pred { + Some(p) => Ok(Some(ctx.pred(g, &cols[..n_cols], p)?)), + None => Ok(None), + })?; + return Ok(QueryPlan { + mask: st.plan, + aggs: None, + }); + } + let cs = build_count_stage(ctx, n_cols, 0, aggs, |g, cols| { let base = match pred { Some(p) => { @@ -483,7 +678,7 @@ pub fn query_rounds( Ok(QueryPlan { mask: cs.plan, - aggs: st.plan, + aggs: Some(st.plan), }) } @@ -513,7 +708,8 @@ pub fn query_rounds( /// 缓冲时会双向死锁。n 方时更要命:每方都在等下一方,环上全卡住。 pub fn exchange_split_columns_multi( vault: &mut Vault, - my_cols: &[Vec], counts: &[usize], + my_cols: &[Vec], + counts: &[usize], ) -> Result>>, VaultError> { let n = vault.parties(); let me = vault.my_index(); diff --git a/crates/nax-sql/src/secure_graph.rs b/crates/nax-sql/src/secure_graph.rs index 7b25eb4..d141a77 100644 --- a/crates/nax-sql/src/secure_graph.rs +++ b/crates/nax-sql/src/secure_graph.rs @@ -40,29 +40,33 @@ //! //! # 分组 //! -//! `GROUP BY` 的每个组是一个独立分支,全部塞进**同一张图**。各组掩码互不依赖, -//! 于是各组的 `open` 合到同一轮 —— 迁移前是逐组串行,`N` 个组就是 `2N` 次 -//! `reveal`,现在只要 2 次。 +//! `GROUP BY` 有两条建图路径,语义相同、协议形状不同,由 +//! [`crate::secure::GroupMode`] 选: //! -//! 省下多少,实测(`--rows 6 --aggs count,sum`,见 `tests/migration.rs`): +//! **逐组比较(`Exact`,默认)**:每个组是一个独立分支,全部塞进**同一张图**。 +//! 各组掩码互不依赖,于是各组的 `open` 合到同一轮 —— 迁移前是逐组串行,`N` 个组 +//! 就是 `2N` 次 `reveal`,现在只要 2 次。省下 `2N − 2` 轮(8~9%),**不是数量级**: +//! 主导成本是每组的 `bit_eq`(两次比较 = 18 轮),它按组累加。 //! -//! | 组数 | 迁移前 | 迁移后 | +//! **整数分组码前缀和(`IntegerCode`,`--group-mode coded`)**:把「`N` 个组的 +//! 相等判断」换成「`N+1` 个单调前缀 `码 ≤ g`」,组内值由累积和相减得到,全程只有 +//! 一次批量 `open`、**没有第二段图**。实测(`--rows 8 --aggs count,sum`): +//! +//! | 组数 | Exact | IntegerCode | //! |---|---|---| -//! | 2 | 44 | 42 | -//! | 4 | 88 | 82 | -//! | 8 | 176 | 162 | +//! | 2 | 42 | 32 | +//! | 4 | 82 | 52 | +//! | 8 | 162 | **92** | //! -//! 也就是 `2N − 2` 轮、**8%~9%**,不是数量级。原因写在下面:主导成本不是 `open`。 +//! 每组的建图成本从 20 轮降到约 11 轮(`9` 一次比较 + `2` 一次掩码乘)。 +//! 代价是两条**契约**(密态下无法校验,由调用方保证):分组码必须是整数、 +//! 且不支持 `MIN`/`MAX`(分组极值不能由前缀和还原)。见 +//! [`crate::secure::GroupMode::IntegerCode`] 与 `tests/coded.rs`。 //! -//! **主导成本是每组的 `bit_eq`**:`gcol == g` 要两次比较(18 轮),它是重交互 -//! 算子,按组累加(见 [`nax_ir::compile`] 里「跨算子类别不共享尾部轮」那条边界)。 -//! `N` 个组光比较就要 `18N` 轮。 -//! -//! 真正的数量级优化在另一处:对**整数**分组码,`gcol == g` 可以换成 -//! `lt(gcol, g + 0.5) − lt(gcol, g − 0.5)`,而 `N` 个组的 `N+1` 个阈值可以共用 -//! 一遍比较 —— `18N` 变 `9(N+1)`。这是**语义变更**(非整数分组码会落到相邻组, -//! 现在会落到「哪个组都不算」),所以不混在搬家这一次里做。 - +//! WHERE 未命中的行不逐组乘 `base`,而是**把码搬到 −1000**:这些行会出现在 +//! 每一个前缀里,差分时自动抵消,省掉 `2N` 轮。搬迁值必须按 `2^fxp` 缩放 —— +//! 第一版拿真值 `−1000` 当 raw 用,它比 `0.5·2^18` 还大,被算进了每一个前缀, +//! 行数变成全表。**尺度不统一不会报错,只会算错。** //! //! # 命中数为 0 的分支 //! @@ -357,6 +361,18 @@ where Ok(CountStage { plan, branches }) } +/// `−PARKED_CODE` 的 raw 编码(即 `−PARKED_CODE · 2^fxp`)。 +/// +/// 一个 i64 装得下:`1000 · 2^40 ≈ 1.1e15`,离 `i64::MAX` 还有三个数量级。 +fn parked_raw(fxp: u32) -> Result { + if fxp > 40 { + return Err(IrError::Op(format!( + "fxp={fxp} 太大:整数分组码的停放值 −{PARKED_CODE}·2^{fxp} 会溢出 i64" + ))); + } + Ok(-(PARKED_CODE << fxp)) +} + /// `±SENTINEL` 的 fxp 编码,作为 `scale_int` 的整数系数。 /// /// 哨兵取 `2^30`:远大于常规业务值(几十万就到顶了),又远小于定点溢出上限。 @@ -478,8 +494,124 @@ fn minmax( Ok(g.open(best)) } +// ── 整数分组码:前缀段 ───────────────────────────────────────────────── // + +/// WHERE 未命中的行,分组码被搬到 `−PARKED_CODE` 上(远小于任何合法码)。 +/// +/// 为什么要「搬码」而不是逐组再乘一次 `base`:前缀和天然会**抵消** —— 这些行 +/// 出现在**每一个**前缀集合里,任意两个前缀相减时它们就被减掉了。于是每组的 +/// 建图不用再乘一次 `base`,省下 `2N` 轮。 +/// +/// 注意这是**真值**,要乘 `2^fxp` 才是 raw 值:分组码列是 fxp 编码的, +/// 边界 `g+0.5` 编出来是 `(g+0.5)·2^fxp`。第一版直接拿 `−1000` 当 raw 起步, +/// 结果它比 `0.5·2^18` 还大,被算进了每一个前缀 —— 行数变成全表,`SUM` 也跟着 +/// 变成全表之和。**尺度不统一不会报错,只会算错。** +const PARKED_CODE: i64 = 1000; + +/// 整数分组码的前缀段:`N+1` 个单调前缀,各组的值由累积和差分得到。 +/// +/// 与 [`CountStage`] 的区别是**没有「每分支一份掩码」**:这里只有前缀, +/// 组内值在明文侧相减。因此它不需要第二段图 —— 所有输出在一次批量 `open` +/// 里就都是公开的了。 +pub(crate) struct PrefixStage { + /// 编译好的计划。 + pub plan: Plan, + /// `cum_count[i]` = 码 `≤ i−1` 的行数(已 open,原始整数)。`i ∈ 0..=N`。 + pub cum_count: Vec, + /// `cum_sum[i]` = 码 `≤ i−1` 的列和(已 open,fxp 原始值)。`i ∈ 0..=N`。 + pub cum_sum: Vec, +} + +/// 建前缀段图。 +/// +/// `code_col` 是分组码在输入里的下标、`agg_col` 是聚合列的下标。 +/// `base_of` 返回 WHERE 掩码;返回 `None` 表示没有 WHERE(掩码是公开全 1)。 +/// +/// # 为什么是 `N+1` 个边界 +/// +/// 组的边界在 `g + 0.5`(`g = −1 ..= N−1`):`码 < g + 0.5` 等价于 `码 ≤ g`, +/// 且对**整数**码没有歧义。两端的 `−1` / `N−1` 不是多余的 —— 有它们, +/// 越界码(负数、`≥ N`)会自然落在所有分组之外,与逐组 `==` 的语义一致。 +/// +/// # 为什么要求 `fxp ≥ 1` +/// +/// `g + 0.5` 要能被定点表示。`fxp == 0` 时它会被舍成整数,边界全错一位且 +/// **不报错**,所以这里直接拒。 +pub(crate) fn build_prefix_stage( + ctx: Ctx, + cols: usize, + agg_col: usize, + code_col: usize, + n_groups: usize, + base_of: F, +) -> Result +where + F: FnOnce(&mut Graph, &[Val]) -> Result, IrError>, +{ + if cols == 0 || agg_col >= cols || code_col >= cols { + return Err(VaultError::Protocol(format!( + "前缀段:列下标越界(cols={cols}, agg={agg_col}, code={code_col})" + ))); + } + if n_groups == 0 { + return Err(VaultError::Protocol("分组数必须大于 0".into())); + } + if ctx.fxp == 0 { + return Err(VaultError::Protocol( + "整数分组码要求 fxp ≥ 1(边界取 g+0.5,fxp=0 会把它舍掉)".into(), + )); + } + + let mut g = Graph::new(); + let inputs: Vec = (0..cols).map(|_| g.input(col_shape(ctx.len))).collect(); + let col = inputs[agg_col]; + let code = inputs[code_col]; + + let base = match base_of(&mut g, &inputs).map_err(ir)? { + Some(m) => m, + None => ctx.ones(&mut g).map_err(ir)?, + }; + + // WHERE 未命中 → 码搬到 −1000。`base·code + (1−base)·(−1000)`: + // 前一项要一次 Beaver 乘(2 轮),后一项是裸整数乘(0 轮)。 + let code_w = if g.vis(base).is_public() { + code + } else { + let kept = g.mul_raw(base, code).map_err(ir)?; + let not_base = g.bit_not(base); + let park = parked_raw(ctx.fxp).map_err(ir)?; + let off = g.scale_int(not_base, park).map_err(ir)?; + g.add(kept, off).map_err(ir)? + }; + + let mut prefixes = Vec::with_capacity(n_groups + 1); + for i in 0..=n_groups { + // 第 i 个前缀 = 码 ≤ i−1 = 码 < (i−1) + 0.5 + let th = ctx.threshold(&mut g, i as f64 - 0.5).map_err(ir)?; + prefixes.push(g.cmp(CmpKind::Lt, code_w, th).map_err(ir)?); + } + + let mut cum_count = Vec::with_capacity(n_groups + 1); + let mut cum_sum = Vec::with_capacity(n_groups + 1); + for c in prefixes { + let cnt = g.sum(c); + cum_count.push(g.open(cnt)); + let masked = g.mul_raw(c, col).map_err(ir)?; + let s = g.sum(masked); + cum_sum.push(g.open(s)); + } + + let plan = Plan::compile(g).map_err(ir)?; + Ok(PrefixStage { + plan, + cum_count, + cum_sum, + }) +} + // ── 掩码单独出口(`mask_for` / `secure_predicate_mask`) ─────────────── // + /// 只算掩码:`cols` 个输入,返回掩码分片。 /// /// 这两个函数是对外 API 的一部分(调用方拿掩码自己用),所以它们不走两段式, diff --git a/crates/nax-sql/tests/coded.rs b/crates/nax-sql/tests/coded.rs new file mode 100644 index 0000000..13cbba5 --- /dev/null +++ b/crates/nax-sql/tests/coded.rs @@ -0,0 +1,364 @@ +//! 整数分组码(`GroupMode::IntegerCode`)的对拍与契约测试。 +//! +//! 这里的每一条都在回答「这条捷径到底能不能用」: +//! +//! * 与逐组比较(`GroupMode::Exact`)**逐位相同** —— 捷径不是新算法,是同一条 +//! 语义的另一条建图路径; +//! * 越界码被丢掉、非整数码落到上方最近一组 —— 这是**契约**,不是 bug,所以 +//! 用测试钉住它,而不是等它在生产里悄悄发生; +//! * 轮数确实更少,且少多少能报出来。 + +use nax_core::ring; +use nax_sql::secure::{ + query_rounds, secure_group_by, secure_group_by_coded, secure_group_by_pred, + secure_group_by_pred_coded, Agg, CmpOp, GroupMode, Pred, +}; +use nax_vault::{Pipe, Vault, VaultError}; + +const FXP: u32 = 18; + +fn enc(v: &[f64]) -> Vec { + v.iter().map(|x| ring::encode(*x, FXP).unwrap()).collect() +} + +/// 把一份明文分成两片(用一个临时 Vault 发牌)。 +fn split(vals: &[f64]) -> (Vec, Vec) { + let mut v = Vault::new(Pipe::pair().0, "alice", &["alice", "bob"], [7u8; 32], FXP).unwrap(); + let all = v.split(&enc(vals)).unwrap(); + let len = vals.len(); + (all[0..len].to_vec(), all[len..2 * len].to_vec()) +} + +/// 两方跑同一段查询,返回 `(alice 侧结果, bob 侧结果)`。 +/// +/// 用 `thread::scope` 而不是 `spawn`:闭包要借本地的 `codes` 切片, +/// `'static` 那条约束是多余的。 +fn run_pair(cols: &[&[f64]], f: F) -> (Vec>, Vec>) +where + F: Fn(usize, &mut Vault, &[Vec]) -> Result>, VaultError> + Sync, +{ + let shares: Vec<(Vec, Vec)> = cols.iter().map(|c| split(c)).collect(); + let sites = ["alice", "bob"]; + let seed = [13u8; 32]; + let (pa, pb) = Pipe::pair(); + let mut va = Vault::new(pa, "alice", &sites, seed, FXP).unwrap(); + let mut vb = Vault::new(pb, "bob", &sites, seed, FXP).unwrap(); + + let a: Vec> = shares.iter().map(|(x, _)| x.clone()).collect(); + let b: Vec> = shares.iter().map(|(_, y)| y.clone()).collect(); + + std::thread::scope(|s| { + let h = s.spawn(|| f(1, &mut vb, &b)); + let out = f(0, &mut va, &a).unwrap(); + (out, h.join().unwrap().unwrap()) + }) +} + +/// 只要 alice 侧结果。 +fn run_one(cols: &[&[f64]], f: F) -> Vec> +where + F: Fn(usize, &mut Vault, &[Vec]) -> Result>, VaultError> + Sync, +{ + run_pair(cols, f).0 +} + +/// 两方都要拿到的错误(只在一侧报错说明建图不一致)。 +fn run_err(cols: &[&[f64]], f: F) -> VaultError +where + F: Fn(usize, &mut Vault, &[Vec]) -> Result>, VaultError> + Sync, +{ + let shares: Vec<(Vec, Vec)> = cols.iter().map(|c| split(c)).collect(); + let sites = ["alice", "bob"]; + let seed = [17u8; 32]; + let (pa, pb) = Pipe::pair(); + let mut va = Vault::new(pa, "alice", &sites, seed, FXP).unwrap(); + let mut vb = Vault::new(pb, "bob", &sites, seed, FXP).unwrap(); + + let a: Vec> = shares.iter().map(|(x, _)| x.clone()).collect(); + let b: Vec> = shares.iter().map(|(_, y)| y.clone()).collect(); + + std::thread::scope(|s| { + let h = s.spawn(|| f(1, &mut vb, &b)); + let out = f(0, &mut va, &a); + let other = h.join().unwrap(); + match (out, other) { + (Err(e), Err(_)) => e, + (Err(e), Ok(_)) => e, + (Ok(_), Err(e)) => e, + (Ok(_), Ok(_)) => panic!("期望两侧都报错,实际都成功了"), + } + }) +} + +// --------------------------------------------------------------------------- // +// 1. 与逐组比较对拍 +// --------------------------------------------------------------------------- // + +const AMOUNTS: [f64; 5] = [100.0, 500.0, 250.0, 600.0, 300.0]; +const CODES_3: [f64; 5] = [0.0, 1.0, 0.0, 2.0, 1.0]; +const AGGS: [Agg; 3] = [Agg::Count, Agg::Sum, Agg::Avg]; + +fn both_modes(pred: Option<(f64, CmpOp)>, n_groups: usize, codes: &[f64]) -> (Vec>, Vec>) { + let exact = run_one(&[&AMOUNTS, codes], |_, v, cs| { + secure_group_by(v, &cs[0], &cs[1], n_groups, pred, &AGGS, 0) + }); + let coded = run_one(&[&AMOUNTS, codes], |_, v, cs| { + secure_group_by_coded(v, &cs[0], &cs[1], n_groups, pred, &AGGS, 0) + }); + (exact, coded) +} + +fn assert_same(exact: &[Vec], coded: &[Vec], what: &str) { + assert_eq!(exact.len(), coded.len(), "{what}:组数不同"); + for (g, (e, c)) in exact.iter().zip(coded.iter()).enumerate() { + for (k, (a, b)) in e.iter().zip(c.iter()).enumerate() { + match AGGS[k] { + // COUNT / SUM 是整数,两条路径必须**逐位相同**。 + Agg::Count | Agg::Sum => assert_eq!( + a, b, + "{what}:组 {g} 的 {:?} 不同(exact={a} coded={b})", + AGGS[k] + ), + // AVG 的两条路径除法不一样,这是**唯一**会有差的地方: + // Exact 走 `scale(sum, 1/count)`,系数被量化到 `2^-fxp` + // (`1/5` 这种除不尽的最多差 `sum·2^-fxp`);coded 拿到精确整数和 + // 之后在明文侧除,没有这层量化。所以按**相对**误差比。 + Agg::Avg => { + if a.is_nan() { + assert!(b.is_nan(), "{what}:组 {g} 空组语义不同"); + } else { + let tol = 1e-4 * a.abs().max(1.0); + assert!( + (a - b).abs() <= tol, + "{what}:组 {g} 的 AVG 差太多(exact={a} coded={b},容差 {tol})" + ); + } + } + Agg::Min | Agg::Max => unreachable!("这组测试不请求 MIN/MAX"), + } + } + } +} + +#[test] +fn coded_matches_exact_without_where() { + let (exact, coded) = both_modes(None, 3, &CODES_3); + assert_same(&exact, &coded, "无 WHERE"); + // 顺手把期望值钉住:组 0 两行(100+250)、组 1 两行(500+300)、组 2 一行。 + assert_eq!(coded[0][0], 2.0); + assert_eq!(coded[0][1], 350.0); + assert_eq!(coded[1][1], 800.0); + assert_eq!(coded[2][1], 600.0); + assert_eq!(coded[2][2], 600.0); +} + +#[test] +fn coded_matches_exact_with_where() { + let (exact, coded) = both_modes(Some((300.0, CmpOp::Lt)), 3, &CODES_3); + assert_same(&exact, &coded, "带 WHERE"); + // col < 300 只剩 100、250,都在 0 号组。 + assert_eq!(coded[0][0], 2.0); + assert_eq!(coded[0][1], 350.0); + assert_eq!(coded[1][0], 0.0, "1 号组应当被 WHERE 清空"); +} + +/// 复合谓词版(`secure_group_by_pred_coded`):与 `secure_group_by_pred` 对拍。 +/// +/// 这条路径多了两件事:谓词作用在**多列**上、聚合列在下标 `agg_col` 而不是 0。 +/// 前缀段的输入布局是「用户列 ++ 分组码」,这两点任一处错位都只表现为数值不对 +/// (不会崩),所以必须对着 Exact 跑一遍。 +#[test] +fn coded_pred_matches_exact() { + let spend: [f64; 5] = [50.0, 100.0, 10.0, 700.0, 20.0]; + let cols: [&[f64]; 3] = [&AMOUNTS, &spend, &CODES_3]; + // WHERE amount < 400 AND spend > 5 + let pred = Pred::And( + Box::new(Pred::Cmp { + col: 0, + op: CmpOp::Lt, + threshold: 400.0, + }), + Box::new(Pred::Cmp { + col: 1, + op: CmpOp::Gt, + threshold: 5.0, + }), + ); + + let exact = run_one(&cols, |_, v, cs| { + secure_group_by_pred(v, cs, 0, &cs[2], 3, Some(&pred), &AGGS, 0) + }); + let coded = run_one(&cols, |_, v, cs| { + secure_group_by_pred_coded(v, cs, 0, &cs[2], 3, Some(&pred), &AGGS, 0) + }); + assert_same(&exact, &coded, "复合谓词"); + // 命中第 0/2/4 行(100、250、300),码分别是 0、0、1: + // 组 0 两行 350,组 1 一行 300,组 2 空。 + assert_eq!(coded[0][0], 2.0); + assert_eq!(coded[0][1], 350.0); + assert_eq!(coded[1][0], 1.0); + assert_eq!(coded[1][1], 300.0); + assert_eq!(coded[2][0], 0.0); + assert!(coded[2][2].is_nan(), "空组的 AVG 是 NaN"); +} + +// --------------------------------------------------------------------------- // +// 2. 契约:越界码与非整数码 +// --------------------------------------------------------------------------- // + +/// 越界码(`< 0` 或 `>= n_groups`)被丢掉 —— 与逐组比较一致。 +#[test] +fn coded_drops_out_of_range_codes() { + let codes = [0.0, 1.0, 5.0, -1.0, 2.0]; + let (exact, coded) = both_modes(None, 2, &codes); + assert_same(&exact, &coded, "越界码"); + // `5` 和 `−1` 都越界(`5` ≥ N=2、`−1` < 0),只剩码 0 和 1 两行。 + assert_eq!(coded[0][0], 1.0); + assert_eq!(coded[1][0], 1.0); + let total: f64 = coded.iter().map(|r| r[0]).sum(); + assert_eq!(total, 2.0, "5 行里只有 2 行的码落在 0..2 内"); +} + +/// **非整数码落到上方最近的一组**(`1.5 → 2 号组`)。 +/// +/// 这是 `GroupMode::IntegerCode` 与 `Exact` 唯一会给出不同数字的地方,属于契约, +/// 不是缺陷:浮点码当分组码用,本来就该先用 `binning` 落成整数码再进密态。 +#[test] +fn coded_treats_non_integer_code_as_ceiling() { + let codes = [0.0, 1.5, 2.0, 0.4, 0.6]; + let (exact, coded) = both_modes(None, 3, &codes); + // 逐组比较:1.5 / 0.4 / 0.6 谁都不属于,只有 0.0 与 2.0 两行有组。 + assert_eq!(exact[0][0], 1.0); + assert_eq!(exact[1][0], 0.0); + assert_eq!(exact[2][0], 1.0); + // 前缀和:它们被吸到上方最近的整数组。 + assert_eq!(coded[0][0], 2.0, "0.0 和 0.4 都算 0 号组"); + assert_eq!(coded[1][0], 1.0, "0.6 落到 1 号组"); + assert_eq!(coded[2][0], 2.0, "1.5 和 2.0 落到 2 号组"); +} + +/// `MIN` / `MAX` 不能用前缀和还原 —— 直接拒,不静默降级。 +#[test] +fn coded_rejects_min_max() { + let err = run_err(&[&AMOUNTS, &CODES_3], |_, v, cs| { + secure_group_by_coded(v, &cs[0], &cs[1], 3, None, &[Agg::Min], 0) + }); + let msg = err.to_string(); + assert!( + msg.contains("MIN") && msg.contains("Exact"), + "报错该说清「不支持 MIN/MAX,请改用 Exact」,实际:{msg}" + ); +} + +/// 空组的语义与 `Exact` 一致:`COUNT`/`SUM` 是 0,`AVG` 是 `NaN`。 +#[test] +fn coded_empty_group_keeps_exact_semantics() { + let codes = [0.0, 0.0, 0.0, 0.0, 0.0]; + let (exact, coded) = both_modes(None, 2, &codes); + assert_same(&exact, &coded, "空组"); + assert_eq!(coded[1][0], 0.0); + assert_eq!(coded[1][1], 0.0); + assert!(coded[1][2].is_nan()); +} + +/// k-匿名抑制:组太小整行 `NaN`,与 `Exact` 一致。 +#[test] +fn coded_respects_k_anonymity() { + let rows = run_one(&[&AMOUNTS, &CODES_3], |_, v, cs| { + secure_group_by_coded(v, &cs[0], &cs[1], 3, None, &AGGS, 3) + }); + // 每组最多 2 行,阈值 3 → 全部抑制。 + for (g, row) in rows.iter().enumerate() { + assert!( + row.iter().all(|v| v.is_nan()), + "组 {g} 应当被抑制,实际 {row:?}" + ); + } +} + +/// 单组(`n_groups == 1`)时前缀只剩两个边界,结果应与整表聚合完全一致。 +/// +/// 注意 `n_groups == 1` 只认码 `0`:码 `1`、`2` 都算越界(`≥ N`)被丢掉 —— +/// 边界值就是 `−0.5` 与 `0.5`,没有第三个边界可给它们。 +#[test] +fn coded_single_group_equals_whole_table() { + let all_zero = [0.0; 5]; + let rows = run_one(&[&AMOUNTS, &all_zero], |_, v, cs| { + secure_group_by_coded(v, &cs[0], &cs[1], 1, None, &AGGS, 0) + }); + assert_eq!(rows.len(), 1); + assert_eq!(rows[0][0], 5.0, "5 行全在唯一的一组里"); + assert_eq!(rows[0][1], 1750.0); + assert!((rows[0][2] - 350.0).abs() < 1e-9); +} + +// --------------------------------------------------------------------------- // +// 3. 轮数:确实更少,且能报出来 +// --------------------------------------------------------------------------- // + +#[test] +fn coded_costs_fewer_rounds_and_the_number_is_reported() { + let agg = [Agg::Count, Agg::Sum]; + let mut prev = 0; + for n in [2usize, 4, 8] { + let exact = query_rounds(8, FXP, 1, None, Some(n), &agg, GroupMode::Exact).unwrap(); + let coded = query_rounds(8, FXP, 1, None, Some(n), &agg, GroupMode::IntegerCode).unwrap(); + assert!( + coded.rounds() < exact.rounds(), + "{n} 组时整数码模式应当更少:exact {} vs coded {}", + exact.rounds(), + coded.rounds() + ); + // 整数码模式下没有第二段:所有组的输出在一次批量 open 里出来。 + assert_eq!(coded.agg_rounds(), 0); + assert!(coded.aggs.is_none()); + assert!(coded.rounds() > prev, "组数翻倍,轮数应当上升"); + prev = coded.rounds(); + } + // 钉住实测值:8 组 162 → 92 轮。 + let exact = query_rounds(8, FXP, 1, None, Some(8), &agg, GroupMode::Exact).unwrap(); + let coded = query_rounds(8, FXP, 1, None, Some(8), &agg, GroupMode::IntegerCode).unwrap(); + assert_eq!(exact.rounds(), 162); + assert_eq!(coded.rounds(), 92); +} + +/// 带 WHERE 只多「一次比较 + 一次码搬家乘」。 +#[test] +fn coded_where_costs_only_the_park_mul() { + let agg = [Agg::Count, Agg::Sum]; + let free = query_rounds(8, FXP, 1, None, Some(4), &agg, GroupMode::IntegerCode).unwrap(); + let pred = Pred::Cmp { + col: 0, + op: CmpOp::Lt, + threshold: 300.0, + }; + let with_where = query_rounds( + 8, + FXP, + 1, + Some(&pred), + Some(4), + &agg, + GroupMode::IntegerCode, + ) + .unwrap(); + // WHERE 本身一次比较(9 轮)+ 码搬家一次 mul_raw(2 轮)= 11 轮; + // 实测 10,因为有一轮 `open` 恰好并进了搬家那个阶段。 + let extra = with_where.rounds() - free.rounds(); + assert!( + (9..=11).contains(&extra), + "带 WHERE 只该多「一次比较 + 一次搬家乘」(9~11 轮),实际 {extra}:{} → {}", + free.rounds(), + with_where.rounds() + ); +} + +/// 整数码模式下 `fxp == 0` 必须报错:`g + 0.5` 会被舍成整数,边界全错一位。 +#[test] +fn coded_rejects_fxp_zero() { + let err = match query_rounds(8, 0, 1, None, Some(4), &[Agg::Count], GroupMode::IntegerCode) { + Ok(_) => panic!("fxp=0 必须报错"), + Err(e) => e, + }; + assert!(err.to_string().contains("fxp"), "实际:{err}"); +} diff --git a/crates/nax-sql/tests/migration.rs b/crates/nax-sql/tests/migration.rs index d9ba190..60b05a9 100644 --- a/crates/nax-sql/tests/migration.rs +++ b/crates/nax-sql/tests/migration.rs @@ -33,7 +33,8 @@ use nax_core::ring; use nax_proto::Frame; use nax_sql::secure::{ - query_rounds, secure_group_by, secure_predicate_mask, secure_where_aggregate, Agg, CmpOp, Pred, + query_rounds, secure_group_by, secure_predicate_mask, secure_where_aggregate, Agg, CmpOp, + GroupMode, Pred, }; use nax_vault::{Pipe, Transport, Vault, VaultError}; use std::sync::{Arc, Mutex}; @@ -621,7 +622,7 @@ fn query_rounds_matches_the_measured_protocol() { threshold: 400.0, }; // 命中 3 个(100/250/300),与 `query_rounds` 里的假设一致 - let planned = query_rounds(data.len(), FXP, 1, Some(&pred), None, &ALL_AGGS).unwrap(); + let planned = query_rounds(data.len(), FXP, 1, Some(&pred), None, &ALL_AGGS, GroupMode::Exact).unwrap(); let (_, measured) = { let sh = shares_of(&[&data]); @@ -649,8 +650,8 @@ fn query_rounds_matches_the_measured_protocol() { #[test] fn group_opens_are_batched_across_groups() { let agg = [Agg::Count]; - let one = query_rounds(8, FXP, 1, None, Some(1), &agg).unwrap(); - let four = query_rounds(8, FXP, 1, None, Some(4), &agg).unwrap(); + let one = query_rounds(8, FXP, 1, None, Some(1), &agg, GroupMode::Exact).unwrap(); + let four = query_rounds(8, FXP, 1, None, Some(4), &agg, GroupMode::Exact).unwrap(); // 每组多 18 轮比较 + 1 轮 and + 1 轮 mul_raw;open 只多 0 轮 assert_eq!( four.rounds() - one.rounds(), diff --git a/docs/IR.md b/docs/IR.md index 761ee79..92b4397 100644 --- a/docs/IR.md +++ b/docs/IR.md @@ -212,6 +212,55 @@ $ nax sql-plan --rows 6 --where "0<400" --aggs count,sum,avg,min,max > 「跨类别不共享尾部轮」那条边界一致。真要并行化,得把 Beaver 的收发摊到 > IR 层,那是另一件事。 +### 3.3 分组:相等判断换单调前缀 + +`GROUP BY` 的默认路径是「每组一次 `gcol == g`」,而 `bit_eq` 是两次比较 +(18 轮/组),按组累加 —— `N` 个组光比较就要 `18N` 轮。 + +如果分组码是**整数**,同一件事可以换个问法:不问「这行是不是第 g 组」, +而问「这行码 ≤ g 吗」。这 `N+1` 个单调前缀一次建完,组内值由**累积和相减** +得到,`COUNT` 甚至不用乘掩码(前缀是位,求和就是计数),所有 `open` 合并成 +一次,`SUM`/`AVG` 直接落在明文上 —— 没有第二段图。 + +``` +$ nax sql-plan --rows 8 --groups 8 --aggs count,sum --group-mode coded +前缀段(谓词 → 分组码搬家 → N+1 个单调前缀 → 累积和) +起始轮 | 交互算子 | 本地算子 | 交互数 +-------+------------------------------------------------+---------------------------------+------- + 1 | cmp × 9 | input, const, lift × 9 | 9 + 82 | open, mul_raw 交替 × 9 对 | sum × 9 | 18 + 92 | open × 9 | — | 9 +掩码段往返 | 92 +聚合段往返 | 0 +总往返 | 92 +``` + +第二行那 9 对 `open`/`mul_raw` 就是「累积计数」和「累积和」:计数只要 +`sum(前缀位)`(本地),和要一次 `mul_raw(前缀位, 列)`。第三行是它们的 `open` +全部落在同一阶段 —— 9 个组的输出一起出来。 + +| 组数 | 逐组比较 | 整数码前缀和 | 倍数 | +|---|---|---|---| +| 2 | 42 | 32 | 1.3× | +| 4 | 82 | 52 | 1.6× | +| 8 | 162 | **92** | **1.8×** | + +两处代价都写在这里,不藏: + +* **分组码必须是整数**。非整数码会落到它上方最近的一组(`1.5 → 2 号组`), + 而不是「哪组都不算」—— `tests/coded.rs` 里有一条测试专门钉这个语义; +* **不支持 `MIN`/`MAX`**。前缀和只知道「和」,不知道「谁最大」,所以请求它们 + 直接报错,不会静默降级。 + +越界码(负数、`≥ N`)被丢掉,这点与逐组比较一致:两端的边界 `−0.5` / `N−0.5` +就是为它留的。 + +`WHERE` 未命中的行不逐组乘 `base`,而是**把码搬到 −1000**(按 `2^fxp` 缩放的 +raw 值)。这些行会出现在每一个前缀里,差分时自动抵消 —— 省掉 `2N` 轮。 +第一版拿真值 `−1000` 直接当 raw 用,它比 `0.5·2^18` 还大,结果被算进了每一个 +前缀:行数变成全表、`SUM` 变成全表之和,**且不报错**。这条坑写在 +`secure_graph.rs` 的源码注释里。 + ## 4. 谁在用这一层 到目前为止两个消费者,迁移方式一样:**手写协议序列搬上图,轮数改由编译器报**。 @@ -223,6 +272,11 @@ $ nax sql-plan --rows 6 --where "0<400" --aggs count,sum,avg,min,max | 报出来的数 | `nax plan`:**17 轮/迭代**(degree 7),degree 3 是 11 轮 | `nax sql-plan`:见上,`[COUNT,SUM,AVG,MIN,MAX]` 共 **115 轮** | | 回归判据 | 帧序列逐帧相同 + ≤64 ULP | `COUNT`/`SUM`/`MIN`/`MAX` **逐位相同**、`AVG` ≤1e-4、轮数不增 | +SQL 侧还有第三条路径不在上表里,因为它是**换算法**而不是搬家: +`--group-mode coded` 把逐组 `==` 换成整数码前缀和(§3.3),8 组从 162 轮降到 +92 轮。它自带两条契约(码是整数、不支持 `MIN`/`MAX`),所以是显式开关, +默认仍是逐组比较。 + 两边的「为什么不是逐位相同」都指向同一处:`nax-vault::truncate` 是随机舍入 (`c = x + r`,`out = (c >> fxp) − (r >> fxp)`),只有 `x` 的低 `fxp` 位全 0 才 精确。所以**同一段手写代码换个 seed 结果都会变**(`nax-ml` 的