fix(mcp,vault,store): the tax-id vault is inside the transaction; a read never sees an open call; the commit outcome is told truthfully (P15 T1 review)

The vault wrote a tax id before its journal line, so a call that failed or
was cut left the new tax id (and lost the old) with no line to say so. A
vault write made for a call is now staged under a name no reader opens
(.staged-TAG, .purging-TAG) and is made final, or dropped, only when the
call closes: a purge is set aside and put back if the call fails. A crash
between the closing line and the settle is finished at the next start by
what the journal says of the call. The readers that check a vault record
against the party's committed vault_record hash (the 1099 and CPA package
paths) therefore only ever see committed records; the filing scan reads
every final record on purpose (more tax ids scanned is safer).

close_call(Done) told the caller none of a call counted when its closing
line was on disk and only SQLite failed. It counted: the store now heals
from the journal where it can, and otherwise says the call counts, stops
taking writes and rebuilds at the next open.

A call whose begin line the projection refused left its frame open, so the
next call began inside it (a corrupt journal): the frame is now closed
failed.

A read arriving between a call's return and its closing line waits for the
close (a call that has written no line leaves reads free), so no read shows
what a call did before it committed.

Tests added through the tools: a call that writes lines and fails, a repeat
arriving while its original runs, the same key under two tokens, a crash
with the ok close on disk and SQLite behind, the vault under a failed and a
crashed call, a key reused for another tax id. The helpers that drop frame
lines no longer back the checks that a refusal or a preview wrote nothing.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude Fable 5.2 committed 2026-11-21 10:19:26 -07:00
1 parent d4c0036599
commit 98cbabde8e
22 files changed
+1516 -169

No files matched your search

+163 -1
View File
@@ -25,6 +25,15 @@
//! 5. `record_hash` is the SHA-256 of a record's bytes on disk, so the
//! journal can prove a record existed without holding it.
//! 6. Purging deletes the record's file; nothing else keeps a copy.
//! 7. A write made for a call that may yet fail is staged, never final:
//! `stage_tin`, `stage_w9` and `stage_purge` write a file of another
//! name (`.staged-TAG`, `.purging-TAG`) that no reader opens, and
//! `settle` makes the call's staged files final, or drops them,
//! once it is known whether the call committed. A record is
//! therefore never replaced, and never destroyed, by a call that did
//! not commit; a crash between the commit and the settle is finished
//! by the next `settle`, which the caller asks of every tag left in
//! `pending_tags`.
//! SCENARIOS:
//! 1. IF the key file is missing: `open` creates one (mode 0600) only when
//! asked to (`create_key`), else the vault is locked (Error::NoKey).
@@ -268,6 +277,16 @@ impl Vault {
}
fn seal(&self, party: u64, kind: Kind, plain: &[u8]) -> Result<String, Error> {
self.seal_to(&self.path(party, kind), party, kind, plain)
}
fn seal_to(
&self,
target: &Path,
party: u64,
kind: Kind,
plain: &[u8],
) -> Result<String, Error> {
let mut nonce = [0u8; NONCE_LEN];
getrandom::getrandom(&mut nonce).map_err(|e| Error::Io(std::io::Error::other(e)))?;
let aad = Self::aad(party, kind);
@@ -286,7 +305,7 @@ impl Vault {
out.extend_from_slice(&nonce);
out.extend_from_slice(&ct);
std::fs::create_dir_all(&self.dir)?;
write_private(&self.path(party, kind), &out)?;
write_private(target, &out)?;
Ok(hex::encode(Sha256::digest(&out)))
}
@@ -323,6 +342,30 @@ impl Vault {
self.seal(party, Kind::Tin, &plain)
}
/// [`Vault::put_tin`] staged for the call `tag` (INVARIANT 7): the
/// record is written, and its hash returned, but under a name no
/// reader opens until [`settle`] makes it final.
pub fn stage_tin(&self, party: u64, tin: &Tin, tag: &str) -> Result<String, Error> {
let plain = Zeroizing::new(serde_json::to_vec(tin).expect("serializes"));
self.seal_to(
&staged_path(&self.dir, party, Kind::Tin, tag)?,
party,
Kind::Tin,
&plain,
)
}
/// [`Vault::put_w9`] staged for the call `tag` (INVARIANT 7).
pub fn stage_w9(&self, party: u64, file: &W9File, tag: &str) -> Result<String, Error> {
let plain = Zeroizing::new(serde_json::to_vec(file).expect("serializes"));
self.seal_to(
&staged_path(&self.dir, party, Kind::W9, tag)?,
party,
Kind::W9,
&plain,
)
}
/// A party's TIN, if the vault holds one.
pub fn tin(&self, party: u64) -> Result<Option<Tin>, Error> {
match self.open_record(party, Kind::Tin)? {
@@ -369,6 +412,125 @@ fn record_path(dir: &Path, party: u64, kind: Kind) -> PathBuf {
dir.join(format!("{}-{party}.bin", kind.name()))
}
/// A call's tag: 16 lowercase hex digits (the name of the call in file
/// names, never a path).
fn checked_tag(tag: &str) -> Result<&str, Error> {
if tag.len() == 16 && tag.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f')) {
Ok(tag)
} else {
Err(Error::Io(std::io::Error::other("not a call tag")))
}
}
fn staged_path(dir: &Path, party: u64, kind: Kind, tag: &str) -> Result<PathBuf, Error> {
Ok(dir.join(format!(
"{}-{party}.staged-{}",
kind.name(),
checked_tag(tag)?
)))
}
fn purging_path(dir: &Path, party: u64, kind: Kind, tag: &str) -> Result<PathBuf, Error> {
Ok(dir.join(format!(
"{}-{party}.purging-{}",
kind.name(),
checked_tag(tag)?
)))
}
/// Stage the purge of what the vault in `dir` holds for a party, for the
/// call `tag` (INVARIANT 7): each record is set aside under a name no
/// reader opens, and is deleted only when [`settle`] says the call
/// committed (and put back when it didn't). Needs no key. Returns whether
/// anything was there.
pub fn stage_purge(dir: &Path, party: u64, tag: &str) -> Result<bool, Error> {
let mut any = false;
for kind in [Kind::Tin, Kind::W9] {
let aside = purging_path(dir, party, kind, tag)?;
match std::fs::rename(record_path(dir, party, kind), aside) {
Ok(()) => any = true,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
Err(e) => return Err(Error::Io(e)),
}
}
Ok(any)
}
/// What a call's staged files came to.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Settled {
/// Staged records made final.
pub promoted: usize,
/// Staged records dropped (the call did not commit).
pub dropped: usize,
/// Purged records deleted (the call committed).
pub purged: usize,
/// Records put back (the call that set them aside did not commit).
pub restored: usize,
}
/// The tags of every call that left a staged or set-aside file in the
/// vault in `dir` (INVARIANT 7): the calls whose outcome `settle` is
/// still to apply, after a crash.
pub fn pending_tags(dir: &Path) -> Result<Vec<String>, Error> {
let mut tags = std::collections::BTreeSet::new();
let entries = match std::fs::read_dir(dir) {
Ok(e) => e,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
Err(e) => return Err(Error::Io(e)),
};
for entry in entries {
let name = entry?.file_name().to_string_lossy().into_owned();
for marker in [".staged-", ".purging-"] {
if let Some((_, tag)) = name.split_once(marker)
&& checked_tag(tag).is_ok()
{
tags.insert(tag.to_string());
}
}
}
Ok(tags.into_iter().collect())
}
/// Apply the outcome of the call `tag` to its staged files (INVARIANT 7):
/// if it `committed`, staged records become the party's records and
/// set-aside ones are deleted; if not, staged ones are deleted and
/// set-aside ones are put back. Safe to repeat; needs no key.
pub fn settle(dir: &Path, tag: &str, committed: bool) -> Result<Settled, Error> {
checked_tag(tag)?;
let mut done = Settled::default();
let entries = match std::fs::read_dir(dir) {
Ok(e) => e.collect::<Result<Vec<_>, _>>()?,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(done),
Err(e) => return Err(Error::Io(e)),
};
for entry in entries {
let name = entry.file_name().to_string_lossy().into_owned();
let path = entry.path();
// `tin-12.staged-TAG`: the record's own name is what's before the
// marker, plus `.bin`.
if let Some(stem) = name.strip_suffix(&format!(".staged-{tag}")) {
if committed {
std::fs::rename(&path, dir.join(format!("{stem}.bin")))?;
done.promoted += 1;
} else {
std::fs::remove_file(&path)?;
done.dropped += 1;
}
} else if let Some(stem) = name.strip_suffix(&format!(".purging-{tag}")) {
let own = dir.join(format!("{stem}.bin"));
if committed || own.exists() {
std::fs::remove_file(&path)?;
done.purged += 1;
} else {
std::fs::rename(&path, own)?;
done.restored += 1;
}
}
}
Ok(done)
}
/// What the vault in `dir` holds for a party, `(TIN, W-9 file)`, without
/// the key: whether each record's file exists (nothing is decrypted).
pub fn records_held(dir: &Path, party: u64) -> Result<(bool, bool), Error> {
+140
View File
@@ -237,3 +237,143 @@ fn purge_and_holdings_need_no_key() {
(false, false)
);
}
const TAG: &str = "0123456789abcdef";
const OTHER: &str = "fedcba9876543210";
fn tin_a() -> Tin {
Tin::new("123-45-6789", TinType::Ssn).unwrap()
}
fn tin_b() -> Tin {
Tin::new("765-43-2109", TinType::Ssn).unwrap()
}
/// INVARIANT 7: a staged record is not the party's record: a reader sees
/// the old one (or none) until `settle` says the call committed.
#[test]
fn a_staged_record_is_read_by_no_one_until_its_call_commits() {
let d = dir("stage-commit");
let v = vault(&d);
let old_hash = v.put_tin(7, &tin_a()).unwrap();
let new_hash = v.stage_tin(7, &tin_b(), TAG).unwrap();
assert_ne!(old_hash, new_hash);
// Nothing changed for a reader.
assert_eq!(v.tin(7).unwrap().unwrap().last4(), "6789");
assert_eq!(
v.record_hash(7).unwrap().as_deref(),
Some(old_hash.as_str())
);
assert_eq!(
ledger_vault::pending_tags(&d.join("vault")).unwrap(),
[TAG.to_string()]
);
let done = ledger_vault::settle(&d.join("vault"), TAG, true).unwrap();
assert_eq!(done.promoted, 1);
assert_eq!(v.tin(7).unwrap().unwrap().last4(), "2109");
assert_eq!(
v.record_hash(7).unwrap().as_deref(),
Some(new_hash.as_str())
);
assert!(
ledger_vault::pending_tags(&d.join("vault"))
.unwrap()
.is_empty()
);
// Settling again changes nothing.
assert_eq!(
ledger_vault::settle(&d.join("vault"), TAG, true).unwrap(),
Default::default()
);
}
/// INVARIANT 7: a call that did not commit leaves the old record whole,
/// and nothing of the new one.
#[test]
fn a_call_that_did_not_commit_leaves_the_old_record_whole() {
let d = dir("stage-drop");
let v = vault(&d);
let old_hash = v.put_tin(7, &tin_a()).unwrap();
v.stage_tin(7, &tin_b(), TAG).unwrap();
// Another call's staged file is not this call's to settle.
v.stage_tin(8, &tin_b(), OTHER).unwrap();
let done = ledger_vault::settle(&d.join("vault"), TAG, false).unwrap();
assert_eq!(done.dropped, 1);
assert_eq!(v.tin(7).unwrap().unwrap().last4(), "6789");
assert_eq!(
v.record_hash(7).unwrap().as_deref(),
Some(old_hash.as_str())
);
assert_eq!(
ledger_vault::pending_tags(&d.join("vault")).unwrap(),
[OTHER.to_string()]
);
assert!(v.tin(8).unwrap().is_none());
}
/// INVARIANT 7: a purge is destroyed only when its call commits; if it
/// doesn't, every record is put back, byte for byte.
#[test]
fn a_purge_is_final_only_when_its_call_commits() {
let d = dir("stage-purge");
let v = vault(&d);
let hash = v.put_tin(7, &tin_a()).unwrap();
v.put_w9(
7,
&W9File {
file_name: "w9.pdf".into(),
mime_type: "application/pdf".into(),
bytes: b"%PDF fake".to_vec(),
},
)
.unwrap();
assert!(ledger_vault::stage_purge(&d.join("vault"), 7, TAG).unwrap());
// Out of sight at once ...
assert_eq!(
ledger_vault::records_held(&d.join("vault"), 7).unwrap(),
(false, false)
);
// ... and back if the call didn't commit.
let undone = ledger_vault::settle(&d.join("vault"), TAG, false).unwrap();
assert_eq!(undone.restored, 2);
assert_eq!(v.record_hash(7).unwrap().as_deref(), Some(hash.as_str()));
assert!(v.w9(7).unwrap().is_some());
// Committed: gone for good.
ledger_vault::stage_purge(&d.join("vault"), 7, TAG).unwrap();
let gone = ledger_vault::settle(&d.join("vault"), TAG, true).unwrap();
assert_eq!(gone.purged, 2);
assert_eq!(
ledger_vault::records_held(&d.join("vault"), 7).unwrap(),
(false, false)
);
assert!(
ledger_vault::pending_tags(&d.join("vault"))
.unwrap()
.is_empty()
);
}
/// A tag names a call in a file name: anything else is refused, so it can't
/// name a path.
#[test]
fn a_tag_that_is_not_sixteen_hex_digits_is_refused() {
let d = dir("stage-tag");
let v = vault(&d);
for bad in [
"",
"../x",
"0123456789ABCDEF",
"0123456789abcde",
"0123456789abcdefg",
] {
assert!(v.stage_tin(7, &tin_a(), bad).is_err(), "{bad}");
assert!(
ledger_vault::stage_purge(&d.join("vault"), 7, bad).is_err(),
"{bad}"
);
assert!(
ledger_vault::settle(&d.join("vault"), bad, true).is_err(),
"{bad}"
);
}
}