Freeze minimal SYSTEM nonstart 221 closure and reproducible Windows source
Rust development slice / linux (push) Failing after 6s

This commit is contained in:
2026-11-16 21:07:24 +01:00
parent 510c069838
commit 559c4cb292
16 changed files with 2222 additions and 37 deletions
+122 -7
View File
@@ -752,6 +752,12 @@ impl<V: Ed25519Verifier> HelperSync<V> {
validate_decision(row, local, d)?;
if d.unlock {
let bytes = unlock_outcome(row, d, current_boot)?;
let preserve = crate::windows_system_nonstart::preserve_original_unlock(
&tx,
&self.binding,
row.grant_id,
&bytes,
)?;
ensure!(
tx.execute(
"UPDATE consumed SET result=?2 WHERE grant_id=?1",
@@ -759,10 +765,12 @@ impl<V: Ed25519Verifier> HelperSync<V> {
)? == 1,
"ROOT_CONSUMPTION_MISSING"
);
tx.execute(
"UPDATE execution_evidence SET outcome=?2 WHERE grant_id=?1",
params![row.grant_id.to_string(), bytes],
)?;
if !preserve {
tx.execute(
"UPDATE execution_evidence SET outcome=?2 WHERE grant_id=?1",
params![row.grant_id.to_string(), bytes],
)?;
}
unlocked.push(row.grant_id);
} else {
safe &= definitive(row)
@@ -1401,12 +1409,16 @@ fn load_rows(
&& attempt_id == job.attempt_id.to_string(),
"LOCAL_REQUEST_BINDING"
);
if let (Some(a), Some(b)) = (&finished, &last) {
let resolved =
crate::windows_system_nonstart::effective_outcome(db, Some(binding), permit.grant_id)?;
if resolved.is_none()
&& let (Some(a), Some(b)) = (&finished, &last)
{
ensure!(canonical(a)? == canonical(b)?, "LOCAL_OUTCOME_CONFLICT");
}
let mut outcome_bytes = last
let mut outcome_bytes = resolved
.as_deref()
.or(finished.as_deref())
.or(last.as_deref().or(finished.as_deref()))
.map(canonical)
.transpose()?
.unwrap_or_default();
@@ -1890,3 +1902,106 @@ fn unique_summaries(rows: &[AttemptView]) -> Result<BTreeMap<(Uuid, Uuid), &Atte
}
Ok(map)
}
/// Exact closed administrative nonstart221 cache materialization. This does not
/// capture, apply a Sync, advance a checkpoint, or create an execution lease.
pub(crate) fn refresh_closed_nonstart_221(db: &Connection, binding: &Binding) -> Result<()> {
use rmm_domain::windows_system_nonstart as closed;
let expected =
crate::windows_system_nonstart::effective_outcome(db, Some(binding), closed::GRANT)?
.context("NONSTART_REFRESH_AUTHENTICATED_COMPLETION_REQUIRED")?;
let raw: Vec<u8> = db.query_row(
"SELECT snapshot FROM helper_sync_captures WHERE checkpoint=413",
[],
|r| r.get(0),
)?;
let snapshot: Snapshot = serde_json::from_slice(&raw)?;
ensure!(
snapshot.checkpoint == 413
&& snapshot.boot_id == closed::BOOT
&& snapshot.attempts.len() == 1,
"NONSTART_REFRESH_ORIGINAL_CAPTURE"
);
let mut original = snapshot.attempts[0].clone();
ensure!(
original.grant_id == closed::GRANT
&& original.job_id == closed::JOB
&& original.attempt_id == closed::ATTEMPT
&& original.state == "unknown"
&& original.outcome_sha256 == closed::UNKNOWN_SHA256,
"NONSTART_REFRESH_ORIGINAL_ATTEMPT"
);
let prior_revision = original.revision;
original.revision = 0;
let prior_fingerprint = hash(&serde_json::to_vec(&original)?);
let (count,revision,fingerprint):(u64,u64,String)=db.query_row("SELECT (SELECT count(*) FROM helper_sync_rows),revision,fingerprint FROM helper_sync_rows WHERE grant_id=?1",[closed::GRANT.to_string()],|r|Ok((r.get(0)?,r.get(1)?,r.get(2)?)))?;
ensure!(
count == 1 && revision == prior_revision && fingerprint == prior_fingerprint,
"NONSTART_REFRESH_EXACT_OLD_CACHE"
);
let rows = load_rows(
db,
binding,
true,
HelperIdentity::System,
&crate::crypto::DalekVerifier,
None,
)?;
ensure!(
rows.len() == 1
&& rows[0].grant_id == closed::GRANT
&& rows[0].state == "failed"
&& rows[0].outcome_bytes == expected
&& rows[0].outcome_sha256 == hash(&expected)
&& rows[0].revision == revision.checked_add(1).context("REVISION_OVERFLOW")?,
"NONSTART_REFRESH_EXACT_DERIVED_CACHE"
);
let checked = load_rows(
db,
binding,
false,
HelperIdentity::System,
&crate::crypto::DalekVerifier,
None,
)?;
ensure!(
checked.len() == 1
&& checked[0].grant_id == closed::GRANT
&& checked[0].outcome_bytes == expected
&& checked[0].revision == rows[0].revision,
"NONSTART_REFRESH_READ_ONLY_VALIDATOR"
);
Ok(())
}
/// SDK-only no-effect fixture surface: actual materialization/read validation,
/// strictly an in-memory database with the single original incident grant.
pub(crate) fn nonstart221_memory_rows(
db: &Connection,
binding: &Binding,
refresh: bool,
) -> Result<Vec<LocalAttempt>> {
let path: String = db.query_row(
"SELECT file FROM pragma_database_list WHERE name='main'",
[],
|r| r.get(0),
)?;
ensure!(
path.is_empty()
&& db.query_row("SELECT count(*) FROM consumed", [], |r| r.get::<_, u64>(0))? == 1
&& db.query_row(
"SELECT EXISTS(SELECT 1 FROM consumed WHERE grant_id=?1)",
[rmm_domain::windows_system_nonstart::GRANT.to_string()],
|r| r.get::<_, bool>(0)
)?,
"NONSTART_CONTRACT_MEMORY_ONLY"
);
load_rows(
db,
binding,
refresh,
HelperIdentity::System,
&crate::crypto::DalekVerifier,
None,
)
}
+8 -4
View File
@@ -284,10 +284,14 @@ pub fn events(db: &Connection) -> Result<Vec<Envelope>> {
let bytes = statement
.query_map([], |r| r.get::<_, Vec<u8>>(0))?
.collect::<rusqlite::Result<Vec<_>>>()?;
bytes
.into_iter()
.map(|b| Ok(Envelope::decode(b.as_slice())?))
.collect()
let mut active = vec![];
for bytes in bytes {
let envelope = Envelope::decode(bytes.as_slice())?;
if !crate::windows_system_nonstart::retired_event(db, &envelope)? {
active.push(envelope);
}
}
Ok(active)
}
pub fn ack(db: &mut Connection, id: &str) -> Result<()> {
let tx = db.transaction()?;
+8
View File
@@ -265,6 +265,14 @@ pub(crate) fn persist_outcome_in(
validate_start_request(p, &request)?;
let bytes = serde_json::to_vec(outcome)?;
let expected = canonical(&bytes)?;
if let Some(resolved) = crate::windows_system_nonstart::effective_outcome(db, None, p.grant_id)?
{
ensure!(
canonical(&resolved)? == expected,
"STORED_COMPLETION_CONFLICT"
);
return Ok(resolved);
}
for previous in [&prior, &finished].into_iter().flatten() {
ensure!(
canonical(previous)? == expected,
+2
View File
@@ -14,3 +14,5 @@ pub mod update_health_sync;
pub mod windows_sync_history;
pub mod windows_sync_alignment;
pub mod windows_system_nonstart;
+67 -21
View File
@@ -40,10 +40,10 @@ pub trait SyncClock {
}
/// Full trusted UTC interval for crypto validity. Existing point-clock
/// providers retain their contract; interval providers override atomically.
fn bounds(&self) -> Result<(DateTime<Utc>,DateTime<Utc>)> {
let reading=self.reading()?;
ensure!(reading.own_wall<=reading.upper,"CLOCK_INTERVAL_ORDER");
Ok((reading.own_wall,reading.upper))
fn bounds(&self) -> Result<(DateTime<Utc>, DateTime<Utc>)> {
let reading = self.reading()?;
ensure!(reading.own_wall <= reading.upper, "CLOCK_INTERVAL_ORDER");
Ok((reading.own_wall, reading.upper))
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
@@ -80,8 +80,12 @@ pub struct Applied {
pub reason: String,
}
/// Diagnostics only; never accepted as an authorization or reusable lease.
#[derive(Clone,Copy)]
pub struct GateObservation {pub signed_ready:bool,pub local_applied:bool,pub helper_ack_pending:bool}
#[derive(Clone, Copy)]
pub struct GateObservation {
pub signed_ready: bool,
pub local_applied: bool,
pub helper_ack_pending: bool,
}
struct Gate {
channel: Channel,
until: DateTime<Utc>,
@@ -129,8 +133,12 @@ impl<V: Ed25519Verifier> ClientSync<V> {
self.channel = None;
self.pending = None;
}
pub fn gate_observation(&self)->Option<GateObservation> {
self.gate.as_ref().map(|g|GateObservation{signed_ready:g.ready,local_applied:g.local_applied,helper_ack_pending:g.helper.is_some()})
pub fn gate_observation(&self) -> Option<GateObservation> {
self.gate.as_ref().map(|g| GateObservation {
signed_ready: g.ready,
local_applied: g.local_applied,
helper_ack_pending: g.helper.is_some(),
})
}
pub fn validity_deadline(&self) -> Option<DateTime<Utc>> {
self.gate.as_ref().map(|gate| gate.until)
@@ -696,7 +704,14 @@ impl<V: Ed25519Verifier> ClientSync<V> {
&& attempt == d.attempt_id.to_string(),
"LOCAL_UNLOCK_CONSUMPTION_BINDING"
);
let previous = previous.context("LOCAL_UNLOCK_PREVIOUS_OUTCOME_MISSING")?;
let resolved = crate::windows_system_nonstart::effective_outcome(
&tx,
Some(&self.binding),
grant,
)?;
let previous = resolved
.or(previous)
.context("LOCAL_UNLOCK_PREVIOUS_OUTCOME_MISSING")?;
let prior = canonical_outcome_bytes(&serde_json::from_slice::<ReconciledOutcome>(
&previous,
)?)?;
@@ -717,14 +732,22 @@ impl<V: Ed25519Verifier> ClientSync<V> {
&& d.outcome_sha256.as_deref() == Some(hash(&bytes).as_str()),
"LOCAL_UNLOCK_CANONICAL_OUTCOME"
);
let preserve = crate::windows_system_nonstart::preserve_original_unlock(
&tx,
&self.binding,
grant,
&bytes,
)?;
tx.execute(
"UPDATE consumed SET result=?2 WHERE grant_id=?1",
params![grant.to_string(), bytes],
)?;
tx.execute(
"UPDATE execution_evidence SET outcome=?2 WHERE grant_id=?1",
params![grant.to_string(), bytes],
)?;
if !preserve {
tx.execute(
"UPDATE execution_evidence SET outcome=?2 WHERE grant_id=?1",
params![grant.to_string(), bytes],
)?;
}
}
tx.execute(
"INSERT INTO reconcile_consumption(decision_id,response) VALUES(?1,?2)",
@@ -820,16 +843,27 @@ pub fn archive_events(db: &Connection) -> Result<()> {
Ok(())
}
fn pending_ids(db: &Connection) -> Result<Vec<String>> {
let mut statement = db.prepare("SELECT id FROM job_events ORDER BY id")?;
let ids = statement
.query_map([], |r| r.get::<_, String>(0))?
let mut statement = db.prepare("SELECT id,payload FROM job_events ORDER BY id")?;
let rows = statement
.query_map([], |r| {
Ok((r.get::<_, String>(0)?, r.get::<_, Vec<u8>>(1)?))
})?
.collect::<rusqlite::Result<Vec<_>>>()?;
for id in &ids {
ensure!(!Uuid::parse_str(id)?.is_nil(), "INVALID_DURABLE_MESSAGE_ID");
let mut ids = vec![];
for (id, bytes) in rows {
ensure!(
!Uuid::parse_str(&id)?.is_nil(),
"INVALID_DURABLE_MESSAGE_ID"
);
let envelope = Envelope::decode(bytes.as_slice())?;
ensure!(envelope.message_id == id, "EVENT_IDENTITY_CONFLICT");
if !crate::windows_system_nonstart::retired_event(db, &envelope)? {
ids.push(id);
}
}
Ok(ids)
}
fn outcome(r: &JobResult) -> Result<ReconciledOutcome> {
pub(crate) fn outcome(r: &JobResult) -> Result<ReconciledOutcome> {
Ok(ReconciledOutcome {
state: r.state.clone(),
stdout: r.stdout.clone(),
@@ -950,7 +984,13 @@ fn attempts(db: &Connection, ledger: &Connection, binding: &Binding) -> Result<V
&& request.authorization_id.to_string() == offer.authorization_id,
"START_EVIDENCE_BINDING"
);
if last.is_some() {
if let Some(resolved) = crate::windows_system_nonstart::effective_outcome(
ledger,
Some(binding),
Uuid::parse_str(&grant_id)?,
)? {
stored = Some(resolved);
} else if last.is_some() {
stored = last;
}
}
@@ -1163,8 +1203,14 @@ fn ingest_helper(
)
.optional()?
.flatten();
let same = existing
let resolved = crate::windows_system_nonstart::effective_outcome(
ledger,
Some(binding),
Uuid::parse_str(&h.grant_id)?,
)?;
let same = resolved
.as_ref()
.or(existing.as_ref())
.map(|b| {
serde_json::from_slice::<ReconciledOutcome>(b)
.and_then(|o| canonical_outcome_bytes(&o))
@@ -0,0 +1,791 @@
//! Exact operator-approved nonstart221. Historical receipt never grants execution.
pub use crate::windows_sync_alignment::{ClosedPairGuard, Local, inventory};
use crate::{
auth::{Binding, Request},
crypto::{DalekVerifier, Ed25519Verifier},
helper_reconcile::Snapshot,
reconcile::{Channel, verify_response_with},
};
use anyhow::{Result, ensure};
use chrono::{DateTime, Utc};
use prost::Message;
use rmm_domain::{
checkpoint_repair::{SignedDecision, SignedReceipt},
jobs::{ExecutionPermitPayload, hash},
windows_system_nonstart as dto,
};
use rmm_protocol::{Envelope, Payload, SyncRequest, SyncResponse};
use rusqlite::{Connection, OptionalExtension, params};
use serde_json::Value;
use uuid::Uuid;
pub const TABLE: &str = "windows_system_nonstart_221_resolution";
const AGENT_START: &str = "f6134c00143b0939a92d2690b8c3a034d332d47241c65a812dcf8f78ead9cfcc";
const HELPER_START: &str = "cf83fc9acbfc1429cca452498c44282f7748d852d73b8221bc0721af60e276d9";
fn canonical(raw: &[u8]) -> Result<Vec<u8>> {
Ok(rmm_domain::reconciliation::canonical_outcome_bytes(
&serde_json::from_slice(raw)?,
)?)
}
fn binding(w: &dto::Witness) -> Binding {
Binding {
tenant_id: w.tenant_id,
asset_id: w.asset_id,
agent_id: w.agent_id,
enrollment_generation: w.enrollment_generation,
assignment_version: w.assignment_version,
public_key_hex: w.verification_public_key_hex.clone(),
}
}
fn receipt(raw: &[u8], local: Option<&Binding>) -> Result<(SignedReceipt, dto::Receipt, String)> {
ensure!(raw.len() <= 4 * 1024 * 1024, "NONSTART_RECEIPT_BOUND");
let signed: SignedReceipt = serde_json::from_slice(raw)?;
let value: dto::Receipt = serde_json::from_slice(&signed.payload)?;
ensure!(
value.valid(value.issued_at),
"NONSTART_RECEIPT_CLOSED_PROFILE"
);
let expected = binding(&value.witness);
if let Some(local) = local {
ensure!(
hash(&serde_json::to_vec(local)?) == hash(&serde_json::to_vec(&expected)?),
"NONSTART_CURRENT_BINDING"
);
}
let key = hex::decode(&expected.public_key_hex)?;
ensure!(
key.len() == 32
&& signed.signature.len() == 64
&& DalekVerifier.verify(&key, &signed.payload, &signed.signature)?,
"NONSTART_RECEIPT_SIGNATURE"
);
// The actual original immutable starts authenticate this historical server key.
for (start, digest) in [
(&value.witness.agent_start, AGENT_START),
(&value.witness.helper_start, HELPER_START),
] {
ensure!(hash(start) == digest, "NONSTART_ORIGINAL_START_HASH");
let saved: Value = serde_json::from_slice(start)?;
let request: Request = serde_json::from_value(saved["request"].clone())?;
let p: ExecutionPermitPayload = serde_json::from_slice(&request.permit_bytes)?;
let (job, p) = expected.verify_with(&request, p.not_before, &DalekVerifier)?;
ensure!(
job.job_id == dto::JOB
&& job.attempt_id == dto::ATTEMPT
&& p.grant_id == dto::GRANT
&& job.execution_identity == "system"
&& hash(&serde_json::to_vec(&request)?)
== "09aa6be3617017e4169f9d83fbfc4cbef43712513a02229a8360dd6a708ee69c",
"NONSTART_ORIGINAL_SIGNED_REQUEST"
);
}
let digest = hash(&serde_json::to_vec(&signed)?);
Ok((signed, value, digest))
}
/// Per-grant historical read only: deliberately no current global count/inventory,
/// clock, code-image or lease assumption. Old unknown bytes remain immutable.
pub fn effective_outcome(
db: &Connection,
local: Option<&Binding>,
grant: Uuid,
) -> Result<Option<Vec<u8>>> {
if grant != dto::GRANT {
return Ok(None);
}
let exists: bool = db.query_row(
"SELECT EXISTS(SELECT 1 FROM sqlite_master WHERE type='table' AND name=?1)",
[TABLE],
|r| r.get(0),
)?;
if !exists {
return Ok(None);
}
type Row = (String, Vec<u8>, String, Vec<u8>);
let row:Option<Row>=db.query_row("SELECT role,receipt,receipt_sha256,derived_outcome FROM windows_system_nonstart_221_resolution WHERE grant_id=?1",[grant.to_string()],|r|Ok((r.get(0)?,r.get(1)?,r.get(2)?,r.get(3)?))).optional()?;
let Some((role, raw, digest, derived)) = row else {
return Ok(None);
};
let (_, value, verified_digest) = receipt(&raw, local)?;
ensure!(
digest == verified_digest && matches!(role.as_str(), "agent" | "helper"),
"NONSTART_RESOLUTION_BINDING"
);
let(start,last,finished):(Vec<u8>,Vec<u8>,Vec<u8>)=db.query_row("SELECT e.start,e.outcome,c.result FROM consumed c JOIN execution_evidence e USING(grant_id) WHERE c.grant_id=?1 AND c.agent=?2 AND c.generation=1 AND c.job=?3 AND c.attempt=?4",params![grant.to_string(),value.witness.agent_id.to_string(),dto::JOB.to_string(),dto::ATTEMPT.to_string()],|r|Ok((r.get(0)?,r.get(1)?,r.get(2)?)))?;
let expected_start = if role == "agent" {
&value.witness.agent_start
} else {
&value.witness.helper_start
};
let expected = rmm_domain::reconciliation::canonical_outcome_bytes(&dto::failed_outcome(
value.receipt_id,
&digest,
))?;
ensure!(
start == *expected_start
&& hash(&last) == dto::UNKNOWN_SHA256
&& last == value.witness.agent_outcome
&& derived == expected
&& canonical(&finished)? == expected,
"NONSTART_IMMUTABLE_ORIGINAL_AND_DERIVED_RESULT"
);
Ok(Some(expected))
}
/// Storage guard only, called AFTER normal fresh signed-unlock verification.
/// A historical receipt never provides that authority. Its derived completion
/// must be byte-identical; the original Unknown evidence is never overwritten.
pub(crate) fn preserve_original_unlock(
db: &Connection,
binding: &Binding,
grant: Uuid,
bytes: &[u8],
) -> Result<bool> {
let Some(resolved) = effective_outcome(db, Some(binding), grant)? else {
return Ok(false);
};
ensure!(
resolved == bytes,
"NONSTART_SIGNED_UNLOCK_CHANGED_DERIVED_COMPLETION"
);
Ok(true)
}
/// Suppresses only the exact original closed delegation placeholder from delivery.
/// The physical event and original reconciliation archive are never deleted/ACKed.
pub fn retired_event(db: &Connection, envelope: &Envelope) -> Result<bool> {
let Some(Payload::JobResult(result)) = &envelope.payload else {
return Ok(false);
};
if result.job_id != dto::JOB.to_string()
|| result.attempt_id != dto::ATTEMPT.to_string()
|| result.grant_id != dto::GRANT.to_string()
|| result.state != "unknown"
|| result.revision != 1
|| result.error_code != "SYSTEM_DELEGATION_REQUIRES_HELPER_SNAPSHOT"
|| envelope.message_id != "6844ae6d-1f0f-4177-9fdd-9d9ed14b9ff5"
|| hash(&envelope.encode_to_vec())
!= "6907fdbbcd1c287c2545fde2f9ebae54fd3b6629b10b61dc5d3884584d8c74c9"
{
return Ok(false);
}
let exists: bool = db.query_row(
"SELECT EXISTS(SELECT 1 FROM sqlite_master WHERE type='table' AND name=?1)",
[TABLE],
|r| r.get(0),
)?;
if !exists {
return Ok(false);
}
let row: Option<(String,Vec<u8>,String,Vec<u8>)> = db.query_row("SELECT role,receipt,receipt_sha256,derived_outcome FROM windows_system_nonstart_221_resolution WHERE grant_id=?1",[dto::GRANT.to_string()],|r|Ok((r.get(0)?,r.get(1)?,r.get(2)?,r.get(3)?))).optional()?;
let Some((role, raw, digest, derived)) = row else {
return Ok(false);
};
let (_, r, actual) = receipt(&raw, None)?;
ensure!(
role == "journal"
&& digest == actual
&& envelope.agent_id == r.witness.agent_id.to_string()
&& envelope.enrollment_generation == r.witness.enrollment_generation
&& envelope.boot_id == dto::BOOT.to_string()
&& envelope.connection_generation == 221
&& r.witness.agent_inventory_sha256
== "124c9318bb5d71572bdde5af34e9c35d83b00b8cfc506cdd6e3157aa6f6bd8da"
&& hash(&rmm_domain::reconciliation::canonical_outcome_bytes(
&crate::reconcile::outcome(result)?
)?) == "a626d3118132b8db525cb3f792f7f278e95833cc3ffe38d34ed7696e7219ab08"
&& derived
== rmm_domain::reconciliation::canonical_outcome_bytes(&dto::failed_outcome(
r.receipt_id,
&digest
))?,
"NONSTART_RETIRED_ORIGINAL_EVENT"
);
Ok(true)
}
fn original(
local: &Local<'_>,
id: Uuid,
decision: Uuid,
cp: u64,
hcp: u64,
) -> Result<(Vec<u8>, SignedDecision)> {
let (raw, env, resp): (Vec<u8>, Vec<u8>, Vec<u8>) = local.agent.query_row(
"SELECT request,envelope,response FROM reconcile_requests WHERE id=?1 AND generation=221",
[id.to_string()],
|r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
)?;
ensure!(
raw.len() <= 65536 && resp.len() <= 131072 && env.len() <= 131072,
"NONSTART_ORIGINAL_BOUND"
);
let request = SyncRequest::decode(raw.as_slice())?;
let envelope = Envelope::decode(env.as_slice())?;
let response = SyncResponse::decode(resp.as_slice())?;
let historical: rmm_domain::reconciliation::ReconcileDecisionPayload =
serde_json::from_slice(&response.decision_bytes)?;
ensure!(
request.encode_to_vec() == raw
&& envelope.payload == Some(Payload::SyncRequest(request.clone()))
&& envelope.sequence == cp
&& envelope.boot_id == dto::BOOT.to_string(),
"NONSTART_ORIGINAL_ENVELOPE"
);
for binding in [local.binding, local.helper_binding] {
let d = verify_response_with(
&DalekVerifier,
binding,
&request,
&Channel {
connection_generation: 221,
boot_id: dto::BOOT,
},
&response,
historical.issued_at,
)?;
ensure!(
d.decision_id == decision
&& d.request_id == id
&& d.checkpoint == cp
&& d.helper_checkpoint == hcp,
"NONSTART_ORIGINAL_RESPONSE"
);
}
let consumed: Vec<u8> = local.consumption.query_row(
"SELECT response FROM reconcile_consumption WHERE decision_id=?1",
[decision.to_string()],
|r| r.get(0),
)?;
ensure!(consumed == resp, "NONSTART_ORIGINAL_CONSUMPTION_RESPONSE");
let capture: Vec<u8> = local.helper.query_row(
"SELECT snapshot FROM helper_sync_captures WHERE checkpoint=?1",
[hcp],
|r| r.get(0),
)?;
let capture: Snapshot = serde_json::from_slice(&capture)?;
ensure!(
capture.boot_id == dto::BOOT
&& capture.checkpoint == hcp
&& capture.attempts.len() == 1
&& capture.attempts[0].job_id == dto::JOB
&& capture.attempts[0].grant_id == dto::GRANT
&& capture.attempts[0].state == "unknown"
&& capture.attempts[0].outcome_sha256 == dto::UNKNOWN_SHA256,
"NONSTART_ORIGINAL_HELPER_CAPTURE"
);
Ok((
raw,
SignedDecision {
decision_bytes: response.decision_bytes,
signature: response.signature,
},
))
}
pub fn witness(
local: &Local<'_>,
guard: &impl ClosedPairGuard,
nonstart: dto::NonstartProof,
) -> Result<dto::Witness> {
guard.check()?;
ensure!(
guard.boot()? == dto::BOOT && nonstart.valid(),
"NONSTART_NATIVE_CONTEXT"
);
let(aj,ac,ag,al,ap):(String,u64,u64,String,Option<String>)=local.agent.query_row("SELECT journal_id,checkpoint,generation,last_decision,pending_request FROM reconcile_meta WHERE id=1 AND fault IS NULL",[],|r|Ok((r.get(0)?,r.get(1)?,r.get(2)?,r.get(3)?,r.get(4)?)))?;
let(hj,hc,hg,hl,hac):(String,u64,u64,String,u64)=local.helper.query_row("SELECT journal_id,checkpoint,generation,last_decision,agent_checkpoint FROM helper_sync_meta WHERE id=1 AND fault IS NULL",[],|r|Ok((r.get(0)?,r.get(1)?,r.get(2)?,r.get(3)?,r.get(4)?)))?;
ensure!(
ac == 10784
&& ag == 221
&& hg == 221
&& hc >= 413
&& hac == 10783
&& al == dto::SECOND.to_string()
&& hl == dto::FIRST.to_string()
&& ap.is_none(),
"NONSTART_ORIGINAL_CONTROL_HEADS"
);
let count = |db: &Connection, table: &str| -> Result<u64> {
Ok(db.query_row(&format!("SELECT count(*) FROM {table}"), [], |r| r.get(0))?)
};
let counts = dto::Counts {
agent_jobs: count(local.agent, "job_attempts")?,
agent_consumed: count(local.consumption, "consumed")?,
agent_starts: count(local.consumption, "execution_evidence")?,
agent_outcomes: local.consumption.query_row(
"SELECT count(*) FROM execution_evidence WHERE outcome IS NOT NULL",
[],
|r| r.get(0),
)?,
helper_consumed: count(local.helper, "consumed")?,
helper_starts: count(local.helper, "execution_evidence")?,
helper_outcomes: local.helper.query_row(
"SELECT count(*) FROM execution_evidence WHERE outcome IS NOT NULL",
[],
|r| r.get(0),
)?,
system_intents: count(local.intents, "system_intents")?,
};
let offer:Vec<u8>=local.agent.query_row("SELECT offer FROM job_attempts WHERE job=?1 AND attempt=?2 AND state='unknown' AND revision=2 AND grant_id=?3",params![dto::JOB.to_string(),dto::ATTEMPT.to_string(),dto::GRANT.to_string()],|r|r.get(0))?;
let row = |db: &Connection| -> Result<(Vec<u8>, Vec<u8>)> {
Ok(db.query_row("SELECT e.start,e.outcome FROM consumed c JOIN execution_evidence e USING(grant_id) WHERE c.grant_id=?1 AND c.result IS NULL",[dto::GRANT.to_string()],|r|Ok((r.get(0)?,r.get(1)?)))?)
};
let (agent_start, agent_outcome) = row(local.consumption)?;
let (helper_start, helper_outcome) = row(local.helper)?;
ensure!(
hash(&agent_start) == AGENT_START
&& hash(&helper_start) == HELPER_START
&& hash(&agent_outcome) == dto::UNKNOWN_SHA256
&& agent_outcome == helper_outcome,
"NONSTART_IMMUTABLE_ORIGINALS"
);
let(intent,digest,phase,mirror):(Vec<u8>,String,String,String)=local.intents.query_row("SELECT i.body,i.digest,i.phase,m.outcome_sha256 FROM system_intents i JOIN system_intent_mirrors m USING(id) WHERE i.grant_id=?1 AND i.cancel_requested=0",[dto::GRANT.to_string()],|r|Ok((r.get(0)?,r.get(1)?,r.get(2)?,r.get(3)?)))?;
ensure!(
hash(&intent) == digest
&& digest == "31c9ddc35a7c09de9e8ec75c835e3dca9e8a816bc031b4b1c1396bd3a2ea46df"
&& phase == "may_have_dispatched"
&& mirror == dto::UNKNOWN_SHA256,
"NONSTART_ORIGINAL_INTENT"
);
let (first_req, first) = original(local, dto::FIRST_REQUEST, dto::FIRST, 10783, 412)?;
let (second_req, second) = original(local, dto::SECOND_REQUEST, dto::SECOND, 10784, 413)?;
let bs = hash(&serde_json::to_vec(local.binding)?);
let hs = hash(&serde_json::to_vec(local.helper_binding)?);
ensure!(bs == hs, "NONSTART_BINDINGS_EQUAL");
let w = dto::Witness {
schema_version: 1,
tenant_id: local.binding.tenant_id,
asset_id: local.binding.asset_id,
agent_id: local.binding.agent_id,
enrollment_generation: 1,
assignment_version: 1,
boot_id: guard.boot()?,
connection_generation: 221,
agent_journal_id: Uuid::parse_str(&aj)?,
helper_journal_id: Uuid::parse_str(&hj)?,
agent_checkpoint: ac,
helper_checkpoint: hc,
agent_last_decision: dto::SECOND,
helper_last_decision: dto::FIRST,
verification_key_id: hash(&hex::decode(&local.binding.public_key_hex)?),
verification_public_key_hex: local.binding.public_key_hex.clone(),
binding_sha256: bs,
helper_binding_sha256: hs,
files: guard.files()?,
agent_inventory_sha256: inventory(local.agent, &[])?,
consumption_inventory_sha256: inventory(local.consumption, &[])?,
helper_inventory_sha256: inventory(local.helper, &[])?,
intent_inventory_sha256: inventory(local.intents, &[])?,
counts,
original_requests: [first_req, second_req],
original_responses: [first, second],
target_job_offer: offer,
agent_start,
helper_start,
agent_outcome,
helper_outcome,
intent,
nonstart,
};
ensure!(w.valid(), "NONSTART_WITNESS_PROFILE");
guard.check()?;
Ok(w)
}
const DDL: &str = "CREATE TABLE windows_system_nonstart_221_resolution(id INTEGER PRIMARY KEY CHECK(id=1),grant_id TEXT NOT NULL UNIQUE,role TEXT NOT NULL CHECK(role IN ('agent','helper','journal')),receipt BLOB NOT NULL,receipt_sha256 TEXT NOT NULL,derived_outcome BLOB NOT NULL,actual_applied_at TEXT NOT NULL,ready INTEGER NOT NULL CHECK(ready=0),helper_ready INTEGER NOT NULL CHECK(helper_ready=0),unlock INTEGER NOT NULL CHECK(unlock=0))";
fn append(
db: &Connection,
role: &str,
raw: &[u8],
r: &dto::Receipt,
digest: &str,
derived: &[u8],
now: DateTime<Utc>,
) -> Result<()> {
db.execute_batch(DDL)?;
for (name, kind) in [
("no_replace", "INSERT"),
("no_update", "UPDATE"),
("no_delete", "DELETE"),
] {
let condition = if kind == "INSERT" {
" WHEN EXISTS(SELECT 1 FROM windows_system_nonstart_221_resolution)"
} else {
""
};
db.execute_batch(&format!("CREATE TRIGGER windows_nonstart_221_{name} BEFORE {kind} ON {TABLE}{condition} BEGIN SELECT RAISE(ABORT,'WINDOWS_NONSTART_221_IMMUTABLE'); END"))?;
}
db.execute(
"INSERT INTO windows_system_nonstart_221_resolution VALUES(1,?1,?2,?3,?4,?5,?6,0,0,0)",
params![
dto::GRANT.to_string(),
role,
raw,
digest,
derived,
now.to_rfc3339()
],
)?;
ensure!(r.valid(now), "NONSTART_FRESH_ADMIN_RECEIPT");
Ok(())
}
/// Exact stopped-pair administrative closure, never an execution grant. Three
/// independently durable journals remain closed on any partial storage failure;
/// callers must not restart either role until verify_applied succeeds.
pub fn apply(
local: &Local<'_>,
guard: &impl ClosedPairGuard,
raw: &[u8],
now: DateTime<Utc>,
) -> Result<()> {
let (_, r, digest) = receipt(raw, Some(local.binding))?;
receipt(raw, Some(local.helper_binding))?;
ensure!(r.valid(now), "NONSTART_FRESH_ADMIN_RECEIPT");
guard.check()?;
for db in [local.agent, local.consumption, local.helper] {
db.execute_batch("BEGIN IMMEDIATE")?;
}
let result = (|| -> Result<()> {
ensure!(
witness(local, guard, r.witness.nonstart.clone())? == r.witness,
"NONSTART_UI_WITNESS_CHANGED"
);
crate::helper_reconcile::verify_checkpoint_repair_history_with(
local.helper,
local.helper_binding,
None,
crate::auth::HelperIdentity::System,
&DalekVerifier,
)?;
let before_agent = inventory(local.agent, &[TABLE, "job_attempts"])?;
let before_consumption = inventory(local.consumption, &[TABLE, "consumed"])?;
let before_helper = inventory(
local.helper,
&[
TABLE,
"consumed",
"helper_sync_decisions",
"helper_sync_meta",
"helper_sync_rows",
],
)?;
let fingerprint: String = local.helper.query_row(
"SELECT fingerprint FROM helper_sync_captures WHERE checkpoint=413",
[],
|r| r.get(0),
)?;
ensure!(
fingerprint == crate::helper_reconcile::ledger_fingerprint(local.helper)?,
"NONSTART_ORIGINAL_LEDGER_FINGERPRINT"
);
let response = &r.witness.original_responses[1];
local.helper.execute("INSERT INTO helper_sync_decisions(decision_id,checkpoint,response,request,fingerprint) VALUES(?1,413,?2,?3,?4)",params![dto::SECOND.to_string(),serde_json::to_vec(&crate::helper_reconcile::SignedResponse{decision_bytes:response.decision_bytes.clone(),signature:response.signature.clone()})?,r.witness.original_requests[1],fingerprint])?;
ensure!(local.helper.execute("UPDATE helper_sync_meta SET last_decision=?1,agent_checkpoint=10784 WHERE id=1 AND checkpoint=?2 AND generation=221 AND last_decision=?3 AND agent_checkpoint=10783 AND fault IS NULL",params![dto::SECOND.to_string(),r.witness.helper_checkpoint,dto::FIRST.to_string()])?==1,"NONSTART_FORWARD_CONTROL_CAS");
let derived = rmm_domain::reconciliation::canonical_outcome_bytes(&dto::failed_outcome(
r.receipt_id,
&digest,
))?;
for (db, role) in [(local.helper, "helper"), (local.consumption, "agent")] {
append(db, role, raw, &r, &digest, &derived, now)?;
ensure!(
db.execute(
"UPDATE consumed SET result=?1 WHERE grant_id=?2 AND result IS NULL",
params![derived, dto::GRANT.to_string()]
)? == 1,
"NONSTART_NULL_COMPLETION_CAS"
);
ensure!(
effective_outcome(db, Some(local.binding), dto::GRANT)?.as_deref()
== Some(derived.as_slice()),
"NONSTART_EFFECTIVE_COMPLETION"
);
}
crate::helper_reconcile::refresh_closed_nonstart_221(local.helper, local.helper_binding)?;
append(local.agent, "journal", raw, &r, &digest, &derived, now)?;
ensure!(local.agent.execute("UPDATE job_attempts SET state='failed',revision=3 WHERE job=?1 AND attempt=?2 AND grant_id=?3 AND state='unknown' AND revision=2",params![dto::JOB.to_string(),dto::ATTEMPT.to_string(),dto::GRANT.to_string()])?==1,"NONSTART_JOB_STATE_CAS");
ensure!(
before_agent == inventory(local.agent, &[TABLE, "job_attempts"])?
&& before_consumption == inventory(local.consumption, &[TABLE, "consumed"])?
&& before_helper
== inventory(
local.helper,
&[
TABLE,
"consumed",
"helper_sync_decisions",
"helper_sync_meta",
"helper_sync_rows"
]
)?
&& inventory(local.intents, &[])? == r.witness.intent_inventory_sha256,
"NONSTART_UNRELATED_HISTORY_UNCHANGED"
);
crate::helper_reconcile::verify_checkpoint_repair_history_with(
local.helper,
local.helper_binding,
None,
crate::auth::HelperIdentity::System,
&DalekVerifier,
)?;
verify_applied(local, guard, raw)?;
guard.check()?;
ensure!(
r.valid(Utc::now()),
"NONSTART_RECEIPT_EXPIRED_BEFORE_COMMIT"
);
Ok(())
})();
if result.is_err() {
for db in [local.agent, local.consumption, local.helper] {
let _ = db.execute_batch("ROLLBACK");
}
return result;
}
// No role can run under the lifetime locks. A commit error is not retried.
// Original rows and receipts remain available for explicit readback.
for db in [local.helper, local.consumption, local.agent] {
db.execute_batch("COMMIT")?;
}
verify_applied(local, guard, raw)?;
Ok(())
}
/// Independent readback: historical evidence only, no receipt freshness/lease.
pub fn verify_applied(
local: &Local<'_>,
guard: &impl ClosedPairGuard,
raw: &[u8],
) -> Result<Value> {
guard.check()?;
let (_, r, digest) = receipt(raw, Some(local.binding))?;
ensure!(guard.boot()? == dto::BOOT, "NONSTART_APPLIED_BOOT");
let expected = rmm_domain::reconciliation::canonical_outcome_bytes(&dto::failed_outcome(
r.receipt_id,
&digest,
))?;
for (db, role) in [
(local.agent, "journal"),
(local.consumption, "agent"),
(local.helper, "helper"),
] {
let (actual_role,actual_raw,actual_digest,derived,applied):(String,Vec<u8>,String,Vec<u8>,String)=db.query_row("SELECT role,receipt,receipt_sha256,derived_outcome,actual_applied_at FROM windows_system_nonstart_221_resolution WHERE id=1 AND grant_id=?1 AND ready=0 AND helper_ready=0 AND unlock=0",[dto::GRANT.to_string()],|r|Ok((r.get(0)?,r.get(1)?,r.get(2)?,r.get(3)?,r.get(4)?)))?;
let at = DateTime::parse_from_rfc3339(&applied)?.with_timezone(&Utc);
ensure!(
actual_role == role
&& actual_raw == raw
&& actual_digest == digest
&& derived == expected
&& r.valid(at),
"NONSTART_APPLIED_ORIGINAL_ADMIN_RECORD"
);
if role != "journal" {
ensure!(
effective_outcome(db, Some(local.binding), dto::GRANT)?.as_deref()
== Some(expected.as_slice()),
"NONSTART_APPLIED_ORIGINAL_OUTCOME"
);
}
}
ensure!(local.agent.query_row("SELECT EXISTS(SELECT 1 FROM job_attempts WHERE job=?1 AND attempt=?2 AND grant_id=?3 AND state='failed' AND revision=3)",params![dto::JOB.to_string(),dto::ATTEMPT.to_string(),dto::GRANT.to_string()],|r|r.get::<_,bool>(0))?,"NONSTART_APPLIED_FAILED_REVISION");
ensure!(local.helper.query_row("SELECT EXISTS(SELECT 1 FROM helper_sync_meta WHERE id=1 AND checkpoint=?1 AND generation=221 AND last_decision=?2 AND agent_checkpoint=10784 AND fault IS NULL)",params![r.witness.helper_checkpoint,dto::SECOND.to_string()],|r|r.get::<_,bool>(0))?,"NONSTART_APPLIED_FORWARD_ONLY_HEAD");
ensure!(
inventory(local.intents, &[])? == r.witness.intent_inventory_sha256,
"NONSTART_APPLIED_IMMUTABLE_INTENTS"
);
for (index, (a, b)) in guard.files()?.iter().zip(&r.witness.files).enumerate() {
ensure!(
a.role == b.role
&& a.file_id == b.file_id
&& (matches!(index, 0 | 1 | 3) || a.sha256 == b.sha256),
"NONSTART_APPLIED_FILE_IDENTITIES"
);
}
crate::helper_reconcile::verify_checkpoint_repair_history_with(
local.helper,
local.helper_binding,
None,
crate::auth::HelperIdentity::System,
&DalekVerifier,
)?;
guard.check()?;
let retained_events: u64 =
local
.agent
.query_row("SELECT count(*) FROM job_events", [], |r| r.get(0))?;
let active_pending = crate::jobs::events(local.agent)?.len();
ensure!(
retained_events == 1 && active_pending == 0,
"NONSTART_APPLIED_RETAINED_EVENT_PROJECTION"
);
Ok(
serde_json::json!({"incident":221,"grant_id":dto::GRANT,"receipt_id":r.receipt_id,"receipt_sha256":digest,"original_unknown_sha256":dto::UNKNOWN_SHA256,"state":"failed","revision":3,"not_started":true,"original_unknown_preserved":true,"old_grant_executed_again":false,"raw_retained_job_events":retained_events,"active_pending_job_events":active_pending,"ready":false,"helper_ready":false,"unlock":false}),
)
}
/// No-effect contract against the actual UI-signed public receipt. Uses the same
/// historical authenticator as the running readers; never opens a product DB.
pub fn receipt_contract(raw: &[u8], original_event: &[u8]) -> Result<Value> {
let (signed, r, _) = receipt(raw, None)?;
let local = binding(&r.witness);
receipt(raw, Some(&local))?;
let mut wrong_signature = signed.clone();
wrong_signature.signature[0] ^= 1;
ensure!(
receipt(&serde_json::to_vec(&wrong_signature)?, Some(&local)).is_err(),
"NONSTART_SIGNATURE_NEGATIVE_FAILED"
);
let db = Connection::open_in_memory()?;
db.execute_batch("CREATE TABLE consumed(grant_id TEXT,agent TEXT,generation INTEGER,job TEXT,attempt TEXT,result BLOB); CREATE TABLE execution_evidence(grant_id TEXT,start BLOB,outcome BLOB)")?;
let digest = hash(&serde_json::to_vec(&signed)?);
let derived = rmm_domain::reconciliation::canonical_outcome_bytes(&dto::failed_outcome(
r.receipt_id,
&digest,
))?;
append(&db, "helper", raw, &r, &digest, &derived, r.issued_at)?;
db.execute(
"INSERT INTO consumed VALUES(?1,?2,1,?3,?4,?5)",
params![
dto::GRANT.to_string(),
r.witness.agent_id.to_string(),
dto::JOB.to_string(),
dto::ATTEMPT.to_string(),
derived
],
)?;
db.execute(
"INSERT INTO execution_evidence VALUES(?1,?2,?3)",
params![
dto::GRANT.to_string(),
r.witness.helper_start,
r.witness.helper_outcome
],
)?;
ensure!(
effective_outcome(&db, Some(&local), dto::GRANT)?.as_deref() == Some(derived.as_slice()),
"NONSTART_REAL_RECEIPT_LOCAL_SCOPE_POSITIVE"
);
// Reproduce the concrete SQL cache bug using only actual signed originals
// in a separate in-memory HELPER ledger. No fabricated server signature.
let cache = Connection::open_in_memory()?;
cache.execute_batch("CREATE TABLE consumed(grant_id TEXT,agent TEXT,generation INTEGER,job TEXT,attempt TEXT,result BLOB); CREATE TABLE execution_evidence(grant_id TEXT,start BLOB,outcome BLOB); CREATE TABLE helper_sync_captures(checkpoint INTEGER,snapshot BLOB); CREATE TABLE helper_sync_rows(grant_id TEXT PRIMARY KEY,revision INTEGER,fingerprint TEXT)")?;
cache.execute(
"INSERT INTO consumed VALUES(?1,?2,1,?3,?4,NULL)",
params![
dto::GRANT.to_string(),
r.witness.agent_id.to_string(),
dto::JOB.to_string(),
dto::ATTEMPT.to_string()
],
)?;
cache.execute(
"INSERT INTO execution_evidence VALUES(?1,?2,?3)",
params![
dto::GRANT.to_string(),
r.witness.helper_start,
r.witness.helper_outcome
],
)?;
let old = crate::helper_reconcile::nonstart221_memory_rows(&cache, &local, true)?;
ensure!(
old.len() == 1 && old[0].state == "unknown",
"NONSTART_CONTRACT_ORIGINAL_CACHE"
);
let prior_revision = old[0].revision;
let snapshot = Snapshot {
journal_id: r.witness.helper_journal_id,
checkpoint: 413,
previous_decision_id: Some(dto::FIRST),
boot_id: dto::BOOT,
captured_at: r.issued_at,
attempts: old,
};
cache.execute(
"INSERT INTO helper_sync_captures VALUES(413,?1)",
[serde_json::to_vec(&snapshot)?],
)?;
append(&cache, "helper", raw, &r, &digest, &derived, r.issued_at)?;
cache.execute(
"UPDATE consumed SET result=?1 WHERE grant_id=?2",
params![derived, dto::GRANT.to_string()],
)?;
let stale = crate::helper_reconcile::nonstart221_memory_rows(&cache, &local, false)
.err()
.ok_or_else(|| anyhow::anyhow!("NONSTART_CONTRACT_STALE_CACHE_NOT_REJECTED"))?;
ensure!(
stale.to_string() == "ROOT_ROW_CHANGED_WITHOUT_SNAPSHOT",
"NONSTART_CONTRACT_EXACT_STALE_FAILURE"
);
crate::helper_reconcile::refresh_closed_nonstart_221(&cache, &local)?;
let fresh = crate::helper_reconcile::nonstart221_memory_rows(&cache, &local, false)?;
ensure!(
fresh.len() == 1
&& fresh[0].revision == prior_revision + 1
&& fresh[0].state == "failed"
&& fresh[0].outcome_bytes == derived,
"NONSTART_CONTRACT_DERIVED_CACHE"
);
let preserve = preserve_original_unlock(&cache, &local, dto::GRANT, &derived)?;
ensure!(preserve, "NONSTART_CONTRACT_UNLOCK_STORAGE_GUARD");
ensure!(
preserve_original_unlock(&cache, &local, dto::GRANT, &r.witness.helper_outcome).is_err(),
"NONSTART_CONTRACT_UNLOCK_CANNOT_RESTORE_UNKNOWN"
);
let original: Vec<u8> = cache.query_row(
"SELECT outcome FROM execution_evidence WHERE grant_id=?1",
[dto::GRANT.to_string()],
|r| r.get(0),
)?;
ensure!(
original == r.witness.helper_outcome,
"NONSTART_CONTRACT_ORIGINAL_PRESERVED"
);
ensure!(
original_event.len() <= 16384
&& hash(original_event)
== "6907fdbbcd1c287c2545fde2f9ebae54fd3b6629b10b61dc5d3884584d8c74c9",
"NONSTART_CONTRACT_EXACT_ORIGINAL_PLACEHOLDER"
);
let event = Envelope::decode(original_event)?;
let journal = Connection::open_in_memory()?;
journal.execute_batch("CREATE TABLE job_events(id TEXT PRIMARY KEY,payload BLOB)")?;
append(&journal, "journal", raw, &r, &digest, &derived, r.issued_at)?;
journal.execute(
"INSERT INTO job_events VALUES(?1,?2)",
params![event.message_id, original_event],
)?;
ensure!(
retired_event(&journal, &event)?
&& crate::jobs::events(&journal)?.is_empty()
&& journal.query_row("SELECT count(*) FROM job_events", [], |r| r
.get::<_, u64>(0))?
== 1,
"NONSTART_CONTRACT_EXACT_RETAINED_PLACEHOLDER"
);
let mut other = event.clone();
other.message_id = Uuid::from_u128(1).to_string();
ensure!(
!retired_event(&journal, &other)?,
"NONSTART_CONTRACT_OTHER_MESSAGE_MUST_REMAIN_ACTIVE"
);
other = event;
other.observed_at += 1;
ensure!(
!retired_event(&journal, &other)?,
"NONSTART_CONTRACT_OTHER_RAW_MUST_REMAIN_ACTIVE"
);
// Keep the valid signed receipt byte-identical. Change only local originals,
// so these failures exercise semantic binding after signature validation.
db.execute(
"UPDATE consumed SET grant_id=?1",
[Uuid::from_u128(1).to_string()],
)?;
ensure!(
effective_outcome(&db, Some(&local), dto::GRANT).is_err(),
"NONSTART_GRANT_NEGATIVE_FAILED"
);
db.execute("UPDATE consumed SET grant_id=?1", [dto::GRANT.to_string()])?;
let mut wrong_unknown = r.witness.agent_outcome.clone();
wrong_unknown[0] ^= 1;
db.execute("UPDATE execution_evidence SET outcome=?1", [wrong_unknown])?;
ensure!(
effective_outcome(&db, Some(&local), dto::GRANT).is_err(),
"NONSTART_ORIGINAL_NEGATIVE_FAILED"
);
Ok(
serde_json::json!({"valid_actual_signed_receipt":true,"original_placeholder_retired":true,"other_message_not_retired":true,"other_raw_not_retired":true,"physical_placeholder_preserved":true,"original_helper_cache_refreshed_once":true,"stale_cache_failure_reproduced":true,"resolved_unlock_storage_guard_preserves_original":true,"wrong_signature_rejected":true,"wrong_grant_rejected":true,"wrong_original_hash_rejected":true,"product_databases_opened":false,"effects":false}),
)
}