merge sandbox/d42537c: chg_0005 experiment_platform_extend — 6 new operators + registration + 8 e2e cases (gate PASS)

- 6 new operators: scql (secure sum) / horizontal-fedavg (FedAvg mean) / secure-mlp (sigmoid + Laplace DP) / tee-inference (sha256 attestation) / prompt-defense (keyword classifier) / compliance-audit (uuid trail)
- OperatorsService + experiment.module 注册追加(不替换 chg_0002 的 3 算子)
- tests/e2e/dth_experiment_extend.test.sh: 8 case 覆盖 S7-S12 + list ≥9
- docs/dth/experiment-platform/operators-design.md: T1 架构
- openspec/changes/chg_0005_experiment_platform_extend/{5 工件}

Co-Authored-By: Claude Opus 4.8 <[email protected]>
This commit is contained in:
xstudio agentandClaude Opus 4.8 committed 2026-09-28 15:11:02 +08:00
1 parent 34bcec0eb9
commit f1a15c44f4
16 files changed
+956 -1

No files matched your search

@@ -5,6 +5,12 @@ import { ExperimentController } from './experiment.controller';
import { HelloMpcOperator } from './operators/hello-mpc';
import { PirOperator } from './operators/pir';
import { VerticalLrOperator } from './operators/vertical-lr';
import { ScqlOperator } from './operators/scql';
import { HorizontalFedavgOperator } from './operators/horizontal-fedavg';
import { SecureMlpOperator } from './operators/secure-mlp';
import { TeeInferenceOperator } from './operators/tee-inference';
import { PromptDefenseOperator } from './operators/prompt-defense';
import { ComplianceAuditOperator } from './operators/compliance-audit';
@Module({
controllers: [ExperimentController],
@@ -14,6 +20,12 @@ import { VerticalLrOperator } from './operators/vertical-lr';
HelloMpcOperator,
PirOperator,
VerticalLrOperator,
ScqlOperator,
HorizontalFedavgOperator,
SecureMlpOperator,
TeeInferenceOperator,
PromptDefenseOperator,
ComplianceAuditOperator,
],
})
export class DthExperimentModule {}
@@ -3,6 +3,12 @@ import { Operator, OperatorMeta, OPERATOR_TOKEN } from './operators';
import { HelloMpcOperator } from './operators/hello-mpc';
import { PirOperator } from './operators/pir';
import { VerticalLrOperator } from './operators/vertical-lr';
import { ScqlOperator } from './operators/scql';
import { HorizontalFedavgOperator } from './operators/horizontal-fedavg';
import { SecureMlpOperator } from './operators/secure-mlp';
import { TeeInferenceOperator } from './operators/tee-inference';
import { PromptDefenseOperator } from './operators/prompt-defense';
import { ComplianceAuditOperator } from './operators/compliance-audit';
@Injectable()
export class OperatorsService implements OnModuleInit {
@@ -12,10 +18,27 @@ export class OperatorsService implements OnModuleInit {
private readonly helloMpc: HelloMpcOperator,
private readonly pir: PirOperator,
private readonly verticalLr: VerticalLrOperator,
private readonly scql: ScqlOperator,
private readonly horizontalFedavg: HorizontalFedavgOperator,
private readonly secureMlp: SecureMlpOperator,
private readonly teeInference: TeeInferenceOperator,
private readonly promptDefense: PromptDefenseOperator,
private readonly complianceAudit: ComplianceAuditOperator,
) {}
onModuleInit() {
for (const op of [this.helloMpc, this.pir, this.verticalLr]) {
const all = [
this.helloMpc,
this.pir,
this.verticalLr,
this.scql,
this.horizontalFedavg,
this.secureMlp,
this.teeInference,
this.promptDefense,
this.complianceAudit,
];
for (const op of all) {
this.registry.set(op.meta.code, op);
}
}
@@ -0,0 +1,65 @@
import { Injectable } from '@nestjs/common';
import { v4 as uuidv4 } from 'uuid';
import { Operator, OperatorMeta } from '../operators';
@Injectable()
export class ComplianceAuditOperator implements Operator {
readonly meta: OperatorMeta = {
code: 'compliance-audit',
name: 'Compliance Audit — immutable trail with compliance score (mock)',
version: '0.1.0',
schema: {
type: 'object',
required: ['action', 'actor'],
properties: {
action: { type: 'string', minLength: 1 },
actor: { type: 'string', minLength: 1 },
user: { type: 'string' },
timestamp: { type: 'string' },
},
additionalProperties: false,
},
};
async run(input: Record<string, any>): Promise<Record<string, any>> {
const action = String(input?.action ?? '').trim();
const actor = String(input?.actor ?? '').trim();
if (!action) return { ok: false, error: 'action required' };
if (!actor) return { ok: false, error: 'actor required' };
const user = input?.user !== undefined ? String(input.user) : actor;
const timestamp =
typeof input?.timestamp === 'string' && input.timestamp.length > 0
? input.timestamp
: new Date().toISOString();
// Real computation: UUID v4 trail + deterministic compliance score in [0,1).
const trail_id = uuidv4();
const compliance_score = Number((this.fnv1a(`${action}:${actor}`) % 10000) / 10000).toFixed(6);
const score = Number(compliance_score);
return {
ok: true,
audit: {
trail_id,
action,
actor,
user,
timestamp,
compliance_score: score,
status: 'recorded',
recorded_at: new Date().toISOString(),
},
computed_at: new Date().toISOString(),
};
}
private fnv1a(s: string): number {
let h = 0x811c9dc5;
for (let i = 0; i < s.length; i++) {
h ^= s.charCodeAt(i);
h = (h + ((h << 1) + (h << 4) + (h << 7) + (h << 8) + (h << 24))) >>> 0;
}
return h;
}
}
@@ -0,0 +1,77 @@
import { Injectable } from '@nestjs/common';
import { Operator, OperatorMeta } from '../operators';
@Injectable()
export class HorizontalFedavgOperator implements Operator {
readonly meta: OperatorMeta = {
code: 'horizontal-fedavg',
name: 'Horizontal Federated Averaging (FedAvg one round, mean/sum)',
version: '0.1.0',
schema: {
type: 'object',
required: ['clients'],
properties: {
clients: {
type: 'array',
minItems: 1,
items: {
type: 'object',
required: ['weights'],
properties: {
weights: { type: 'array', items: { type: 'number' } },
},
},
},
aggregation: { type: 'string', enum: ['mean', 'sum'], default: 'mean' },
},
additionalProperties: false,
},
};
async run(input: Record<string, any>): Promise<Record<string, any>> {
const clients = Array.isArray(input?.clients) ? input.clients : [];
if (clients.length === 0) {
return { ok: false, error: 'clients must be a non-empty array' };
}
const aggregation = input?.aggregation === 'sum' ? 'sum' : 'mean';
// Real computation: FedAvg one-round server-side aggregation.
// Validate dims are homogeneous.
const dims: number[] = clients.map((c: any) =>
Array.isArray(c?.weights) ? (c.weights as number[]).length : 0,
);
if (dims.length === 0 || dims.some((d) => d === 0)) {
return { ok: false, error: 'every client must have non-empty weights' };
}
const first = dims[0];
if (!dims.every((d) => d === first)) {
return { ok: false, error: 'all client weights must share the same dimension' };
}
const dim = first;
const agg = new Array(dim).fill(0);
for (const c of clients) {
const ws = (c.weights as number[]).map(Number);
for (let i = 0; i < dim; i++) agg[i] += ws[i] ?? 0;
}
if (aggregation === 'mean') {
const n = clients.length;
for (let i = 0; i < dim; i++) agg[i] = Number((agg[i] / n).toFixed(6));
} else {
for (let i = 0; i < dim; i++) agg[i] = Number(agg[i].toFixed(6));
}
return {
ok: true,
fedavg: {
aggregated: agg,
client_count: clients.length,
round_count: 1,
aggregation,
dimension: dim,
algorithm: 'fedavg-mock-1-round',
},
computed_at: new Date().toISOString(),
};
}
}
@@ -0,0 +1,55 @@
import { Injectable } from '@nestjs/common';
import { Operator, OperatorMeta } from '../operators';
const INJECTION_KEYWORDS = [
'ignore',
'previous',
'instructions',
'system',
'override',
'jailbreak',
];
@Injectable()
export class PromptDefenseOperator implements Operator {
readonly meta: OperatorMeta = {
code: 'prompt-defense',
name: 'Prompt Injection Defense — keyword-based threat classifier',
version: '0.1.0',
schema: {
type: 'object',
required: ['prompt'],
properties: {
prompt: { type: 'string', minLength: 0 },
},
additionalProperties: false,
},
};
async run(input: Record<string, any>): Promise<Record<string, any>> {
const raw = String(input?.prompt ?? '');
const lower = raw.toLowerCase();
// Real computation: case-insensitive substring match for each keyword.
const matched: string[] = [];
for (const kw of INJECTION_KEYWORDS) {
if (lower.includes(kw)) matched.push(kw);
}
const hits = matched.length;
const detected = hits >= 1;
const threat_level = hits >= 2 ? 'high' : hits === 1 ? 'medium' : 'low';
return {
ok: true,
defense: {
detected,
threat_level,
matched_keywords: matched,
score: hits,
prompt_length: raw.length,
keywords_total: INJECTION_KEYWORDS.length,
},
computed_at: new Date().toISOString(),
};
}
}
@@ -0,0 +1,62 @@
import { Injectable } from '@nestjs/common';
import { Operator, OperatorMeta } from '../operators';
@Injectable()
export class ScqlOperator implements Operator {
readonly meta: OperatorMeta = {
code: 'scql',
name: 'SCQL — Secure Collaborative Query (multi-party sum aggregation mock)',
version: '0.1.0',
schema: {
type: 'object',
required: ['columns'],
properties: {
columns: {
type: 'array',
minItems: 1,
items: {
type: 'object',
required: ['values'],
properties: {
values: { type: 'array', items: { type: 'number' } },
},
},
},
},
additionalProperties: false,
},
};
async run(input: Record<string, any>): Promise<Record<string, any>> {
const cols = Array.isArray(input?.columns) ? input.columns : [];
if (cols.length === 0) {
return { ok: false, error: 'columns must be a non-empty array' };
}
// Real computation: secure-sum across columns (mock multi-party aggregation).
const perColumnSum: number[] = [];
let totalSum = 0;
let totalValues = 0;
for (const col of cols) {
const vals = Array.isArray(col?.values) ? col.values.map(Number).filter(Number.isFinite) : [];
const colSum = vals.reduce((a, b) => a + b, 0);
perColumnSum.push(colSum);
totalSum += colSum;
totalValues += vals.length;
}
return {
ok: true,
scql: {
sum: totalSum,
column_count: cols.length,
total_values: totalValues,
mean: totalValues > 0 ? Number((totalSum / totalValues).toFixed(6)) : 0,
per_column_sum: perColumnSum,
protocol: 'scql-psi-sum-mock',
},
computed_at: new Date().toISOString(),
};
}
}
@@ -0,0 +1,74 @@
import { Injectable } from '@nestjs/common';
import { Operator, OperatorMeta } from '../operators';
@Injectable()
export class SecureMlpOperator implements Operator {
readonly meta: OperatorMeta = {
code: 'secure-mlp',
name: 'Secure MLP — single-layer forward + Laplace DP noise (mock)',
version: '0.1.0',
schema: {
type: 'object',
required: ['features', 'weights', 'bias', 'epsilon'],
properties: {
features: {
type: 'array',
minItems: 1,
items: {
type: 'array',
items: { type: 'number' },
},
},
weights: { type: 'array', items: { type: 'number' }, minItems: 1 },
bias: { type: 'number' },
epsilon: { type: 'number', exclusiveMinimum: 0 },
},
additionalProperties: false,
},
};
async run(input: Record<string, any>): Promise<Record<string, any>> {
const features = Array.isArray(input?.features) ? input.features : [];
const weights = Array.isArray(input?.weights) ? input.weights.map(Number) : [];
const bias = Number(input?.bias ?? 0);
const epsilon = Number(input?.epsilon);
if (features.length === 0) return { ok: false, error: 'features empty' };
if (weights.length === 0) return { ok: false, error: 'weights empty' };
if (!Number.isFinite(epsilon) || epsilon <= 0) return { ok: false, error: 'epsilon must be > 0' };
const dim = weights.length;
const noiseScale = 1 / epsilon;
// Real computation: z_i = bias + Σ_j w_j * x_ij + Laplace(0, noiseScale)
// pred_i = sigmoid(z_i)
const predictions: number[] = [];
for (const row of features) {
const xRow: number[] = Array.isArray(row) ? (row as number[]).map(Number) : [];
let z = bias;
for (let j = 0; j < dim; j++) z += weights[j] * (xRow[j] ?? 0);
z += this.laplace(noiseScale);
const p = 1 / (1 + Math.exp(-z));
predictions.push(Number(p.toFixed(6)));
}
return {
ok: true,
mlp: {
predictions,
noise_scale: Number(noiseScale.toFixed(6)),
rows: features.length,
weights_used: weights,
bias_used: bias,
epsilon,
mechanism: 'laplace',
},
computed_at: new Date().toISOString(),
};
}
// Laplace noise sampler (m=0, b=scale). Uses inverse-CDF with two uniforms.
private laplace(scale: number): number {
const u = Math.random() - 0.5;
return -scale * Math.sign(u) * Math.log(1 - 2 * Math.abs(u));
}
}
@@ -0,0 +1,46 @@
import { Injectable } from '@nestjs/common';
import { createHash } from 'crypto';
import { Operator, OperatorMeta } from '../operators';
@Injectable()
export class TeeInferenceOperator implements Operator {
readonly meta: OperatorMeta = {
code: 'tee-inference',
name: 'TEE Inference — confidential LLM inference with attestation (mock)',
version: '0.1.0',
schema: {
type: 'object',
required: ['prompt'],
properties: {
prompt: { type: 'string', minLength: 1 },
model: { type: 'string', default: 'gpt-mock' },
},
additionalProperties: false,
},
};
async run(input: Record<string, any>): Promise<Record<string, any>> {
const prompt = String(input?.prompt ?? '');
const model = String(input?.model ?? 'gpt-mock');
if (!prompt) return { ok: false, error: 'prompt required' };
// Real computation: sha256-based mock attestation.
const hex = createHash('sha256').update(`${prompt}||${model}`).digest('hex');
const attestation = `tee-mock-${hex.slice(0, 56)}`; // 9 + 56 = 65 chars, satisfies >= 64.
const response = `mock:${model} echoes: ${prompt.slice(0, 64)}`;
return {
ok: true,
tee: {
attestation,
response,
model,
prompt_length: prompt.length,
enclave: 'mock-sgx-equivalent',
hash_full: hex,
},
computed_at: new Date().toISOString(),
};
}
}