fix(mcp,store,core): four refusals are decided before the call's first line (P15 T1, D-88)

A refusal is decided before anything is written; a failed call on the
record is for a call that failed part way. Four tools wrote a line and then
refused, so under T1 each left a begun line, its lines and a failed closing
line in the journal for a plain "no":

- books.attach_receipt and books.file_document: bytes already filed are one
  file, so filing them again links the existing attachment; a link it
  already holds was refused after the earlier links were written. The store
  now asks first (Store::check_filing_links).
- books.draft_entry and books.draft_from_template: a no_party_reason that
  names a full tax id was refused by the mark, after the draft was made.
  Ledger::check_no_party_reason is asked first.
- books.dispose_asset: a receipt named twice was refused at its second
  link, after the disposal was posted. The ids are checked for repeats
  first.

Each has a test that the journal is byte for byte as it was. No journal
format or frame shape changes.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude Fable 5.2 committed 2026-11-21 12:30:25 -07:00
1 parent bc55a10101
commit 38612ab553
11 files changed
+192 -2

No files matched your search

+25
View File
@@ -1295,6 +1295,31 @@ fn a_reversed_run_is_not_posted() {
assert_eq!(dec(&a, "book_value").as_deref(), Some("1200")); assert_eq!(dec(&a, "book_value").as_deref(), Some("1200"));
} }
/// A bill of sale named twice is refused before the disposal is written:
/// the second link would be refused after the first, and a refusal is
/// decided before anything is written (D-88), so the journal is byte for
/// byte what it was and the asset is still held.
#[test]
fn disposing_with_a_receipt_named_twice_is_refused_before_anything_is_written() {
let mut m = books("disposed-twice");
m.post(
"2026-01-01",
&[("1000", "debit", "9000.00"), ("3000", "credit", "9000.00")],
);
let (id, sold) = m.register_ok(json!({}));
let doc = m.file_bill_of_sale();
let before = m.journal_raw();
let why = m.refuse(
"books.dispose_asset",
json!({"tag": sold, "date": "2026-03-31", "proceeds": "100.00",
"proceeds_account": "1000", "gain_loss_account": "7100",
"confirmed": true, "receipt_attachment_ids": [doc, doc]}),
);
assert!(why.contains("twice"), "{why}");
assert!(m.journal_raw() == before, "a refusal wrote to the journal");
assert_eq!(m.asset(id)["status"], "active");
}
/// A disposed asset is not held: every figure 0.00 once it left the books. /// A disposed asset is not held: every figure 0.00 once it left the books.
#[test] #[test]
fn a_disposed_asset_has_left_the_books() { fn a_disposed_asset_has_left_the_books() {
@@ -747,6 +747,62 @@ fn filing_links_in_the_same_call_all_or_nothing() {
assert_eq!(m.count("document.filed"), 1); assert_eq!(m.count("document.filed"), 1);
} }
/// Bytes already filed are one file (P6 step 4): filing them again links the
/// existing attachment to the new subjects. A link the file already has is
/// refused, and the refusal is decided before the first link is written:
/// the journal is byte for byte what it was (D-88: a failed transaction is
/// on the record for a call that failed part way, never for one that could
/// have been refused up front).
#[test]
fn filing_bytes_already_linked_is_refused_before_any_link_is_written() {
let mut m = books("dedup-links");
let e = m.draft("2026-01-05", json!({}), &[]);
let other = m.draft("2026-01-06", json!({}), &[]);
m.add_party("Acme Design", &["contractor"]);
// Two uploads of each file begun before either is filed (a file whose
// bytes are stored already is not given a second upload).
let r = m.upload(b"same receipt", "r.pdf", "application/pdf", "receipt");
let r2 = m.upload(b"same receipt", "r.pdf", "application/pdf", "receipt");
let c = m.upload(b"same contract", "c.pdf", "application/pdf", "document");
let c2 = m.upload(b"same contract", "c.pdf", "application/pdf", "document");
// A receipt on `e`, linked to the party; a document linked to the company.
m.ok(
"books.attach_receipt",
json!({"entry_id": e, "upload_id": r, "link_to": [{"kind": "party", "id": "Acme Design"}]}),
);
m.ok(
"books.file_document",
json!({"category": "contract", "upload_id": c, "link_to": [{"kind": "company"}]}),
);
let before = m.journal_raw();
// The same bytes, again: `other` would be linked first, then the party
// (already linked) refused.
let why = m.refuse(
"books.attach_receipt",
json!({"entry_id": e, "upload_id": r2,
"link_to": [{"kind": "entry", "id": other}, {"kind": "party", "id": "Acme Design"}]}),
);
assert!(why.contains("already linked"), "{why}");
// The same, filed on another entry first: that link and then the party.
let why = m.refuse(
"books.attach_receipt",
json!({"entry_id": other, "upload_id": r2,
"link_to": [{"kind": "party", "id": "Acme Design"}]}),
);
assert!(why.contains("already linked"), "{why}");
let why = m.refuse(
"books.file_document",
json!({"category": "contract", "upload_id": c2,
"link_to": [{"kind": "entry", "id": e}, {"kind": "company"}]}),
);
assert!(why.contains("already linked"), "{why}");
assert!(
m.journal_raw() == before,
"a refusal wrote to the journal: {:?}",
m.journal_types()
);
}
#[test] #[test]
fn documents_file_under_the_attachment_kinds() { fn documents_file_under_the_attachment_kinds() {
let mut m = books("categories"); let mut m = books("categories");
+32
View File
@@ -314,6 +314,38 @@ fn templates_draft_through_the_server() {
assert_eq!(d["lines"][1]["account"], "1000"); assert_eq!(d["lines"][1]["account"], "1000");
} }
/// A reason that names a full tax id is refused (BS-partner-2) before the
/// draft's first line is written: the journal is byte for byte what it was
/// (D-88), and the error says nothing of the number.
#[test]
fn a_template_draft_with_a_tax_id_in_its_reason_is_refused_before_it_is_written() {
let books = Books::new("kept-template-tin");
let mut m = Mcp::spawn(&books);
init(&mut m);
chart(&mut m);
m.call(
"books.set_convention",
json!({"id": "bank-expense", "kind": "posting_template",
"title": "Expense paid from the bank", "body_md": "Dr the expense / Cr 1000.",
"structured": {"lines": [
{"account": "6000", "side": "debit", "share": "1"},
{"account": "1000", "side": "credit", "share": "1"}]},
"decided_by": "A"}),
);
let before = books.journal_raw();
let e = m.call_err(
"books.draft_from_template",
json!({"template_id": "bank-expense", "date": "2026-10-02", "amount": "12.00",
"no_party_reason": "own account, tax id 987-65-4321"}),
);
assert!(!e.contains("987-65-4321"), "{e}");
assert_eq!(
books.journal_raw(),
before,
"a refusal wrote to the journal"
);
}
/// books.start stays at most 8 KB whatever the books hold, and says what /// books.start stays at most 8 KB whatever the books hold, and says what
/// it left out. /// it left out.
#[test] #[test]
+17
View File
@@ -1215,6 +1215,23 @@ fn suggest_names_likely_parties_and_refuses_nothing() {
assert_eq!(s[0]["party_id"], apple); assert_eq!(s[0]["party_id"], apple);
} }
/// A reason that names a full tax id is refused (BS-partner-2), and the
/// refusal is decided before the draft's first line is written: the journal
/// is byte for byte what it was, with no draft, no failed call and no
/// error text in it (D-88).
#[test]
fn a_no_party_reason_that_carries_a_tax_id_is_refused_before_the_draft_is_written() {
let mut m = books("no-party-tin");
let before = m.journal_raw();
let e = m.refuse(
"books.draft_entry",
json!({"date": "2026-03-01", "description": "transfer",
"no_party_reason": "own account, tax id 987-65-4321"}),
);
assert!(!e.contains("987-65-4321"), "{e}");
assert_eq!(m.journal_raw(), before, "a refusal wrote to the journal");
}
/// Oracle: "require": posting is refused (party_required) and journals /// Oracle: "require": posting is refused (party_required) and journals
/// nothing until the entry names a party or is marked as having none; /// nothing until the entry names a party or is marked as having none;
/// no_party_reason is refused alongside a party. /// no_party_reason is refused alongside a party.
+8
View File
@@ -5583,6 +5583,14 @@ impl Ledger {
format!("entry {entry}'s reversal chain entry {e} names a party; clear it first") format!("entry {entry}'s reversal chain entry {e} names a party; clear it first")
})); }));
} }
Self::check_no_party_reason(reason)
}
/// What a no-party reason must be, whatever entry it is for: said in
/// words, and carrying no full tax id (BS-partner-2). A caller that
/// makes an entry and marks it asks this first, so a refusal for the
/// reason is decided before the entry's first line is written.
pub fn check_no_party_reason(reason: &str) -> Result<(), LedgerError> {
if reason.trim().is_empty() { if reason.trim().is_empty() {
return Err(LedgerError::InvalidParty( return Err(LedgerError::InvalidParty(
"say why the entry has no counterparty".into(), "say why the entry has no counterparty".into(),
+8 -1
View File
@@ -996,8 +996,15 @@ impl BooksServer {
} }
.to_tool_error()); .to_tool_error());
} }
for aid in &attachment_ids { for (n, aid) in attachment_ids.iter().enumerate() {
store.check_linkable(*aid).map_err(|e| e.to_string())?; store.check_linkable(*aid).map_err(|e| e.to_string())?;
// Linked once each: a second link of one file to the new entry
// would be refused after the disposal was written.
if attachment_ids[..n].contains(aid) {
return Err(format!(
"receipt_attachment_ids names attachment {aid} twice: name each file once"
));
}
} }
if buyer.is_none() if buyer.is_none()
&& !proceeds.amount.is_zero() && !proceeds.amount.is_zero()
@@ -112,6 +112,11 @@ impl BooksServer {
let (file_name, mime_type) = named(p.file_name, p.mime_type, &file)?; let (file_name, mime_type) = named(p.file_name, p.mime_type, &file)?;
let (bytes, claim) = (file.bytes, file.claim); let (bytes, claim) = (file.bytes, file.claim);
self.refuse_tin_file(&store, &bytes, &mime_type, &file_name)?; self.refuse_tin_file(&store, &bytes, &mime_type, &file_name)?;
// Bytes already filed are one file: a link it has is refused now,
// before the filing writes anything.
store
.check_filing_links(&bytes, &link_to)
.map_err(|e| e.to_string())?;
let (attachment_id, sha256, deduplicated) = store let (attachment_id, sha256, deduplicated) = store
.attach_receipt( .attach_receipt(
p.entry_id, p.entry_id,
@@ -170,6 +175,11 @@ impl BooksServer {
let (file_name, mime_type) = named(p.file_name, p.mime_type, &file)?; let (file_name, mime_type) = named(p.file_name, p.mime_type, &file)?;
let (bytes, claim) = (file.bytes, file.claim); let (bytes, claim) = (file.bytes, file.claim);
self.refuse_tin_file(&store, &bytes, &mime_type, &file_name)?; self.refuse_tin_file(&store, &bytes, &mime_type, &file_name)?;
// Bytes already filed are one file: a link it has is refused now,
// before the filing writes anything.
store
.check_filing_links(&bytes, &link_to)
.map_err(|e| e.to_string())?;
let (attachment_id, sha256, deduplicated) = store let (attachment_id, sha256, deduplicated) = store
.file_document( .file_document(
&p.category, &p.category,
+3
View File
@@ -207,6 +207,9 @@ impl BooksServer {
.as_deref() .as_deref()
.map(|ps| parse_shares(&store, ps)) .map(|ps| parse_shares(&store, ps))
.transpose()?; .transpose()?;
if let Some(r) = no_party {
ledger_core::Ledger::check_no_party_reason(r).map_err(|e| e.to_string())?;
}
if no_party.is_some() && (party.is_some() || vendor.is_some() || shares.is_some()) { if no_party.is_some() && (party.is_some() || vendor.is_some() || shares.is_some()) {
return Err( return Err(
"no_party_reason is for an entry with no counterparty: pass it without party, parties, or vendor".into(), "no_party_reason is for an entry with no counterparty: pass it without party, parties, or vendor".into(),
+3
View File
@@ -1778,6 +1778,9 @@ impl BooksServer {
.map(|r| resolve_party(&store, r)) .map(|r| resolve_party(&store, r))
.transpose()?; .transpose()?;
// Every check before anything is journaled. // Every check before anything is journaled.
if let Some(r) = no_party {
ledger_core::Ledger::check_no_party_reason(r).map_err(bad)?;
}
store store
.ledger() .ledger()
.template_lines(&p.template_id, amount, &p.accounts) .template_lines(&p.template_id, amount, &p.accounts)
+19
View File
@@ -4765,6 +4765,25 @@ impl Store {
}) })
} }
/// Whether filing `bytes` and linking them to `link_to` would be
/// refused for a link the file already has: bytes already filed are one
/// file, so a link the existing attachment holds is refused
/// (`AlreadyLinked`). Asked before the filing writes its first line, so
/// a call that is refused for it has written nothing (a refusal is
/// decided before anything is written, D-88).
pub fn check_filing_links(&self, bytes: &[u8], link_to: &[Subject]) -> Result<(), StoreError> {
let Some(existing) = self.live_attachment_with_sha(&sha256_hex(bytes))? else {
return Ok(());
};
let held = self.attachment_links(existing.id)?;
for sub in link_to {
if held.contains(sub) {
return Err(StoreError::AlreadyLinked(existing.id, sub.describe()));
}
}
Ok(())
}
/// File a document under a category (`formation`, `legal`, `tax`, /// File a document under a category (`formation`, `legal`, `tax`,
/// `accounting`, `other`). /// `accounting`, `other`).
pub fn file_document( pub fn file_document(
+11 -1
View File
@@ -344,8 +344,18 @@ it does when an access record cannot be written. A call whose closing line
the store heals from the journal where it can, and where it cannot says so the store heals from the journal where it can, and where it cannot says so
(`StoreError::CallCommitted`: the call was completed and counts, do not do (`StoreError::CallCommitted`: the call was completed and counts, do not do
it again), stops taking writes, and is rebuilt at the next open. it again), stops taking writes, and is rebuilt at the next open.
A call that is refused for a reason that could have been known up front
(a bad argument, a rule that says no) writes nothing: its refusal is decided
before its first line, so the journal is byte for byte what it was and no
failed call stands for it. A failed call on the record is for a call that
failed part way (a fault, a crash), never for one that could have been
refused first. A tool that has several writes to make checks every one of
them before the first (`Store::check_filing_links`,
`Ledger::check_no_party_reason`, the duplicate receipt ids of
`books.dispose_asset`); a test's books holding a failed call fail the test
unless it injected the fault on purpose (`common::expect_failed_calls`).
*Enforced:* `Store::close_call`, `StoreError::CallCommitted`, ledger-mcp `calls::answered_ok`, `calls::close`, `calls::recover_vault`, `calls::put_tin`, `calls::purge_records`, `calls::settle_vault`, `ledger_vault::stage_tin`, `ledger_vault::stage_w9`, `ledger_vault::stage_purge`, `ledger_vault::settle`, `ledger_vault::pending_tags`. *Enforced:* `Store::close_call`, `StoreError::CallCommitted`, ledger-mcp `calls::answered_ok`, `calls::close`, `calls::recover_vault`, `calls::put_tin`, `calls::purge_records`, `calls::settle_vault`, `ledger_vault::stage_tin`, `ledger_vault::stage_w9`, `ledger_vault::stage_purge`, `ledger_vault::settle`, `ledger_vault::pending_tags`.
*Checked:* `ledger-store` `tests/calls.rs` (`a_failed_call_is_on_the_record_and_builds_nothing`, `a_call_that_wrote_nothing_leaves_no_line_and_is_remembered_for_the_session`, `a_closing_line_on_disk_but_sqlite_failing_is_a_call_that_counts`); `ledger-vault` `tests/vault.rs` (`a_staged_record_is_read_by_no_one_until_its_call_commits`, `a_call_that_did_not_commit_leaves_the_old_record_whole`, `a_purge_is_final_only_when_its_call_commits`); `ledger-cli` `tests/call_transactions.rs` (`a_failed_write_leaves_the_books_and_its_key_as_they_were`, `a_call_that_wrote_lines_and_then_failed_leaves_the_books_and_its_key_as_they_were`, `a_crash_with_the_ok_close_on_disk_but_sqlite_not_committed_leaves_the_call_done_once`, `a_set_tin_that_fails_leaves_the_vault_as_it_was`, `a_crash_between_the_commit_and_the_vault_settling_is_finished_at_the_next_start`). *Checked:* `ledger-store` `tests/calls.rs` (`a_failed_call_is_on_the_record_and_builds_nothing`, `a_call_that_wrote_nothing_leaves_no_line_and_is_remembered_for_the_session`, `a_closing_line_on_disk_but_sqlite_failing_is_a_call_that_counts`); `ledger-vault` `tests/vault.rs` (`a_staged_record_is_read_by_no_one_until_its_call_commits`, `a_call_that_did_not_commit_leaves_the_old_record_whole`, `a_purge_is_final_only_when_its_call_commits`); `ledger-cli` `tests/hostile_args.rs` (`a_refused_call_leaves_the_journal_byte_for_byte_as_it_was`), `tests/spec_attachments.rs` (`filing_bytes_already_linked_is_refused_before_any_link_is_written`), `tests/spec_parties.rs` (`a_no_party_reason_that_carries_a_tax_id_is_refused_before_the_draft_is_written`), `tests/spec_kept.rs` (`a_template_draft_with_a_tax_id_in_its_reason_is_refused_before_it_is_written`), `tests/spec_assets.rs` (`disposing_with_a_receipt_named_twice_is_refused_before_anything_is_written`), `ledger-cli` `tests/call_transactions.rs` (`a_failed_write_leaves_the_books_and_its_key_as_they_were`, `a_call_that_wrote_lines_and_then_failed_leaves_the_books_and_its_key_as_they_were`, `a_crash_with_the_ok_close_on_disk_but_sqlite_not_committed_leaves_the_call_done_once`, `a_set_tin_that_fails_leaves_the_vault_as_it_was`, `a_crash_between_the_commit_and_the_vault_settling_is_finished_at_the_next_start`).
*Proved:* Lean `Calls.replay_drop_frame`, `Calls.keyTable_failed_absent`, `Calls.keyTable_submit_failed` (bookspec law 47, `docs/verification.md` law 47): a failed call counts for nothing and leaves its key out of the table. *Proved:* Lean `Calls.replay_drop_frame`, `Calls.keyTable_failed_absent`, `Calls.keyTable_submit_failed` (bookspec law 47, `docs/verification.md` law 47): a failed call counts for nothing and leaves its key out of the table.
**WB-format-11 Books that have not declared `call_transactions` take no **WB-format-11 Books that have not declared `call_transactions` take no