Merge branch 't3/mcp-refusals-write-nothing': a refused call writes nothing; four tools checked before writing
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
commit
bf977b1bc7
16 files changed
+415
-23
No files matched your search
@@ -302,6 +302,8 @@ fn types(books: &Books) -> Vec<String> {
|
||||
/// corrupt page would.
|
||||
#[test]
|
||||
fn a_call_that_wrote_lines_and_then_failed_leaves_the_books_and_its_key_as_they_were() {
|
||||
// The fault is put there on purpose: this call fails part way.
|
||||
common::expect_failed_calls();
|
||||
let books = Books::new("calls-failed-lines");
|
||||
let mut w = books.session("test");
|
||||
let before = types(&books);
|
||||
@@ -675,6 +677,8 @@ fn set_tin(key: &str, tin: &str) -> Value {
|
||||
/// neither, and once the call can run again it is the new one that is kept.
|
||||
#[test]
|
||||
fn a_set_tin_that_fails_leaves_the_vault_as_it_was() {
|
||||
// The fault is put there on purpose: this call fails part way.
|
||||
common::expect_failed_calls();
|
||||
let books = Books::new("calls-vault-fail");
|
||||
let mut w = books.session("test");
|
||||
let party = answer_of(&w.call(
|
||||
|
||||
@@ -712,6 +712,46 @@ pub struct Books {
|
||||
pub currency: String,
|
||||
}
|
||||
|
||||
std::thread_local! {
|
||||
/// Whether this test means to leave a failed call in its books.
|
||||
static FAILED_CALLS_EXPECTED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
|
||||
}
|
||||
|
||||
/// This test makes a call fail part way on purpose (an injected fault):
|
||||
/// its books may end holding a `call.closed` with the outcome `failed`.
|
||||
/// No other test's may: see [`Books`]'s drop.
|
||||
#[allow(dead_code)]
|
||||
pub fn expect_failed_calls() {
|
||||
FAILED_CALLS_EXPECTED.with(|e| e.set(true));
|
||||
}
|
||||
|
||||
/// A refusal is decided before anything is written (D-88): a failed call
|
||||
/// on the record is for one that failed part way, which only a fault
|
||||
/// injected on purpose does. So when a test's books are dropped, none
|
||||
/// holds a failed call unless the test said it would
|
||||
/// ([`expect_failed_calls`]); a tool that writes a line and then refuses
|
||||
/// fails every test that makes it refuse, not only a test written for it.
|
||||
impl Drop for Books {
|
||||
fn drop(&mut self) {
|
||||
if std::thread::panicking() || FAILED_CALLS_EXPECTED.with(std::cell::Cell::get) {
|
||||
return;
|
||||
}
|
||||
let journal = self.journal_raw();
|
||||
let failed: Vec<String> = String::from_utf8_lossy(&journal)
|
||||
.lines()
|
||||
.filter(|l| {
|
||||
l.contains(r#""type":"call.closed""#) && l.contains(r#""outcome":"failed""#)
|
||||
})
|
||||
.filter_map(|l| serde_json::from_str::<Value>(l).ok())
|
||||
.map(|v| format!("{} (journal line {})", v["payload"]["tool"], v["seq"]))
|
||||
.collect();
|
||||
assert!(
|
||||
failed.is_empty(),
|
||||
"a call failed after it began writing, and its failure is on the books' record; a refusal must be decided before anything is written: {failed:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
impl Books {
|
||||
/// New books in a new home, kept in USD, with no settings set.
|
||||
pub fn new(tag: &str) -> Self {
|
||||
|
||||
@@ -896,6 +896,164 @@ fn hostile_tool_arguments_never_stop_the_server() {
|
||||
reopens(m, &p, "every tool");
|
||||
}
|
||||
|
||||
/// The journal's bytes, frame lines in: what "a refusal wrote nothing"
|
||||
/// is compared on, so a stray `call.begun` or `call.closed` is seen.
|
||||
fn journal_raw(p: &Places) -> Vec<u8> {
|
||||
std::fs::read(p.books.join("journal.jsonl")).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The line types a journal gained, in order, and nothing of their
|
||||
/// payloads (the guard names what was written, never what it held).
|
||||
fn gained_types(before: &[u8], after: &[u8]) -> Vec<String> {
|
||||
let rest = after.strip_prefix(before).unwrap_or(after);
|
||||
String::from_utf8_lossy(rest)
|
||||
.lines()
|
||||
.filter_map(|l| serde_json::from_str::<Value>(l).ok())
|
||||
.map(|v| v["type"].as_str().unwrap_or("?").to_string())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// `v` with its `which`th string (counting in order) carrying a made-up
|
||||
/// full tax id (a 9xx area number: no one is issued one), so a refusal
|
||||
/// for a text that names one has something to leave out; the number of
|
||||
/// strings `v` holds is added to `seen`.
|
||||
fn with_tin_in_string(v: &Value, which: usize, seen: &mut usize) -> Value {
|
||||
match v {
|
||||
Value::String(s) => {
|
||||
*seen += 1;
|
||||
if *seen - 1 == which {
|
||||
Value::String(format!("{s} 987-65-4321"))
|
||||
} else {
|
||||
v.clone()
|
||||
}
|
||||
}
|
||||
Value::Array(a) => Value::Array(
|
||||
a.iter()
|
||||
.map(|x| with_tin_in_string(x, which, seen))
|
||||
.collect(),
|
||||
),
|
||||
Value::Object(o) => Value::Object(
|
||||
o.iter()
|
||||
.map(|(k, x)| (k.clone(), with_tin_in_string(x, which, seen)))
|
||||
.collect(),
|
||||
),
|
||||
other => other.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
/// A refusal is decided before anything is written (D-88: a failed
|
||||
/// transaction is on the record, for a call that failed part way, not for
|
||||
/// a call that could have been refused up front): whatever a tool answers
|
||||
/// with an error to hostile arguments, the journal is byte for byte what
|
||||
/// it was before the call. Over every tool, at a small number of cases
|
||||
/// (`MCP_REFUSAL_CASES`, default 100), and again with a made-up tax id in
|
||||
/// each string of the arguments in turn: no journal line holds one
|
||||
/// (BS-partner-2).
|
||||
#[test]
|
||||
fn a_refused_call_leaves_the_journal_byte_for_byte_as_it_was() {
|
||||
let p = places("refusals");
|
||||
let mut m = Mcp::start(&p);
|
||||
fixture(&mut m, &p);
|
||||
let list = m.rpc("tools/list", json!({}));
|
||||
let tools: Vec<(String, Value)> = list["result"]["tools"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|t| {
|
||||
(
|
||||
t["name"].as_str().unwrap().to_string(),
|
||||
t["inputSchema"].clone(),
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
let per_tool: Vec<BoxedStrategy<(String, Value)>> = tools
|
||||
.iter()
|
||||
.map(|(name, schema)| {
|
||||
let name = name.clone();
|
||||
args_for(schema, &p)
|
||||
.prop_map(move |a| (name.clone(), a))
|
||||
.boxed()
|
||||
})
|
||||
.collect();
|
||||
let call = proptest::strategy::Union::new(per_tool);
|
||||
let cases = std::env::var("MCP_REFUSAL_CASES")
|
||||
.ok()
|
||||
.and_then(|v| v.parse().ok())
|
||||
.unwrap_or(100);
|
||||
let mut runner = TestRunner::new(Config {
|
||||
cases,
|
||||
failure_persistence: None,
|
||||
max_shrink_iters: 0,
|
||||
..Config::default()
|
||||
});
|
||||
let m = std::cell::RefCell::new(m);
|
||||
// Every refusal that wrote: (tool, the line types it left).
|
||||
let found = std::cell::RefCell::new(Vec::<(String, Vec<String>)>::new());
|
||||
let refused = std::cell::Cell::new(0u32);
|
||||
let tried = |m: &mut Mcp, tool: &str, args: Value| {
|
||||
let before = journal_raw(&p);
|
||||
let r = m.rpc("tools/call", json!({"name": tool, "arguments": args}));
|
||||
let after = journal_raw(&p);
|
||||
let no = r.get("error").is_some() || r["result"]["isError"] == json!(true);
|
||||
if no {
|
||||
refused.set(refused.get() + 1);
|
||||
if before != after {
|
||||
found
|
||||
.borrow_mut()
|
||||
.push((tool.to_string(), gained_types(&before, &after)));
|
||||
}
|
||||
}
|
||||
// A refusal leaves no trace of a tax id it was given: not in a
|
||||
// line it wrote, not in the error a failed call's closing line
|
||||
// keeps (BS-partner-2). (What a call that succeeded keeps is the
|
||||
// tool's own text rules, not this guard's.)
|
||||
let gained = after.strip_prefix(before.as_slice()).unwrap_or(&after);
|
||||
let tin = no && String::from_utf8_lossy(gained).contains("987-65-4321");
|
||||
(no, tin)
|
||||
};
|
||||
runner
|
||||
.run(&call, |(tool, args)| {
|
||||
let mut m = m.borrow_mut();
|
||||
let (_, tin) = tried(&mut m, &tool, args);
|
||||
prop_assert!(!tin, "{} journaled a tax id", tool);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
// Every tool a couple of times, each time with a tax id put in one
|
||||
// string of its arguments in turn: the refusals that name a text.
|
||||
let mut m = m.into_inner();
|
||||
let mut det = TestRunner::deterministic();
|
||||
for (tool, schema) in &tools {
|
||||
for _ in 0..2 {
|
||||
let args = args_for(schema, &p).new_tree(&mut det).unwrap().current();
|
||||
let (_, tin) = tried(&mut m, tool, args.clone());
|
||||
assert!(!tin, "{tool} journaled a tax id");
|
||||
let mut strings = 0;
|
||||
with_tin_in_string(&args, usize::MAX, &mut strings);
|
||||
for which in 0..strings.min(6) {
|
||||
let given = with_tin_in_string(&args, which, &mut 0);
|
||||
let (_, tin) = tried(&mut m, tool, given);
|
||||
assert!(!tin, "{tool} journaled a tax id it was given");
|
||||
}
|
||||
}
|
||||
}
|
||||
let found = found.into_inner();
|
||||
assert!(
|
||||
refused.get() >= 100,
|
||||
"the guard saw too few refusals: {}",
|
||||
refused.get()
|
||||
);
|
||||
let mut by_tool = std::collections::BTreeMap::<String, Vec<String>>::new();
|
||||
for (tool, types) in found {
|
||||
by_tool.entry(tool).or_default().push(types.join(","));
|
||||
}
|
||||
assert!(
|
||||
by_tool.is_empty(),
|
||||
"refusals that wrote to the journal (tool: line types left): {by_tool:#?}"
|
||||
);
|
||||
reopens(m, &p, "every refusal");
|
||||
}
|
||||
|
||||
/// INVARIANT 4: whatever the calls journaled, the books open again. A
|
||||
/// hostile call a command accepts but replay refuses would leave books
|
||||
/// that never reopen (BS-entry-4): the server is restarted on them and
|
||||
|
||||
@@ -805,20 +805,10 @@ fn tin_bearing_files_are_refused_when_given_back_to_be_filed() {
|
||||
);
|
||||
}
|
||||
}
|
||||
// (Each upload begun is a call, with its closing line: those only.)
|
||||
let calls_only = |j: Vec<u8>| -> Vec<String> {
|
||||
String::from_utf8(j)
|
||||
.unwrap()
|
||||
.lines()
|
||||
.filter(|l| !l.contains(r#""type":"call.closed""#))
|
||||
.map(str::to_string)
|
||||
.collect()
|
||||
};
|
||||
assert_eq!(
|
||||
calls_only(books.journal()),
|
||||
calls_only(journal),
|
||||
"a refusal stored something"
|
||||
);
|
||||
// Raw bytes, frame lines included: an upload slot writes no line, and a
|
||||
// refusal is decided before anything is written, so no frame (begun or
|
||||
// closed, with its error text) stands for any of these calls.
|
||||
assert_eq!(books.journal_raw(), journal, "a refusal stored something");
|
||||
// Without TINs, the 1099 worksheet is an ordinary file: it may be
|
||||
// filed like any other.
|
||||
let plain = mcp.call("books.vendor_1099", json!({"year": 2026, "csv": true}));
|
||||
@@ -2986,6 +2976,7 @@ fn rename_account_end_to_end_defect_15() {
|
||||
post_pair(&mut mcp, "2025-11-20", "6150", "1000", "29.00");
|
||||
let verified = mcp.call("books.verify", json!({"blobs": false}));
|
||||
let events = verified["events"].as_u64().unwrap();
|
||||
let journal_before = books.journal_raw();
|
||||
for (name, says) in [
|
||||
("", "must not be empty"),
|
||||
(" Software ", "already named"),
|
||||
@@ -2998,11 +2989,17 @@ fn rename_account_end_to_end_defect_15() {
|
||||
);
|
||||
assert!(err.contains(says), "{name:?}: {err}");
|
||||
}
|
||||
// (The first verify is a call too: its own closing line is the one
|
||||
// line the second counts more; the refusals wrote none.)
|
||||
// A verify that finds nothing to heal writes no line, so it has no
|
||||
// frame (WB-format-8); and the refusals, decided before anything is
|
||||
// written, left the journal byte for byte as it was.
|
||||
assert_eq!(
|
||||
books.journal_raw(),
|
||||
journal_before,
|
||||
"refusals write nothing"
|
||||
);
|
||||
assert_eq!(
|
||||
mcp.call("books.verify", json!({"blobs": false}))["events"],
|
||||
json!(events + 1),
|
||||
json!(events),
|
||||
"refusals write nothing"
|
||||
);
|
||||
let out = mcp.call(
|
||||
@@ -3022,9 +3019,8 @@ fn rename_account_end_to_end_defect_15() {
|
||||
assert_eq!(after["status"], "ok");
|
||||
// New books declare account_renamed (with the rest of this version's
|
||||
// format) as they are created: the rename journals only itself, in
|
||||
// its frame (begun, the rename, closed), after the two verifies'
|
||||
// closing lines.
|
||||
assert_eq!(after["events"], json!(events + 1 + 1 + 3), "the rename");
|
||||
// its frame (begun, the rename, closed); the verifies wrote nothing.
|
||||
assert_eq!(after["events"], json!(events + 3), "the rename");
|
||||
let chart = mcp.call("books.chart", json!({}));
|
||||
let acct = chart["accounts"]
|
||||
.as_array()
|
||||
|
||||
@@ -1295,6 +1295,31 @@ fn a_reversed_run_is_not_posted() {
|
||||
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.
|
||||
#[test]
|
||||
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);
|
||||
}
|
||||
|
||||
/// 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]
|
||||
fn documents_file_under_the_attachment_kinds() {
|
||||
let mut m = books("categories");
|
||||
|
||||
@@ -314,6 +314,38 @@ fn templates_draft_through_the_server() {
|
||||
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
|
||||
/// it left out.
|
||||
#[test]
|
||||
|
||||
@@ -1215,6 +1215,23 @@ fn suggest_names_likely_parties_and_refuses_nothing() {
|
||||
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
|
||||
/// nothing until the entry names a party or is marked as having none;
|
||||
/// no_party_reason is refused alongside a party.
|
||||
|
||||
@@ -241,7 +241,11 @@ fn require_tax_category_refuses_defect_8() {
|
||||
json!({"code": "6160", "name": "Hosting", "account_type": "expense", "tax_category": "other_deductions"}),
|
||||
);
|
||||
assert!(out.get("warnings").is_none(), "{out}");
|
||||
assert_eq!(m.events(), before + 2, "account.added and account.tax_set");
|
||||
assert_eq!(
|
||||
m.events(),
|
||||
before + 4,
|
||||
"call.begun, account.added, account.tax_set, call.closed"
|
||||
);
|
||||
// A header is exempt.
|
||||
add(
|
||||
&mut m,
|
||||
|
||||
@@ -5583,6 +5583,14 @@ impl Ledger {
|
||||
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() {
|
||||
return Err(LedgerError::InvalidParty(
|
||||
"say why the entry has no counterparty".into(),
|
||||
|
||||
@@ -996,8 +996,15 @@ impl BooksServer {
|
||||
}
|
||||
.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())?;
|
||||
// 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()
|
||||
&& !proceeds.amount.is_zero()
|
||||
|
||||
@@ -112,6 +112,11 @@ impl BooksServer {
|
||||
let (file_name, mime_type) = named(p.file_name, p.mime_type, &file)?;
|
||||
let (bytes, claim) = (file.bytes, file.claim);
|
||||
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
|
||||
.attach_receipt(
|
||||
p.entry_id,
|
||||
@@ -170,6 +175,11 @@ impl BooksServer {
|
||||
let (file_name, mime_type) = named(p.file_name, p.mime_type, &file)?;
|
||||
let (bytes, claim) = (file.bytes, file.claim);
|
||||
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
|
||||
.file_document(
|
||||
&p.category,
|
||||
|
||||
@@ -207,6 +207,9 @@ impl BooksServer {
|
||||
.as_deref()
|
||||
.map(|ps| parse_shares(&store, ps))
|
||||
.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()) {
|
||||
return Err(
|
||||
"no_party_reason is for an entry with no counterparty: pass it without party, parties, or vendor".into(),
|
||||
|
||||
@@ -1778,6 +1778,9 @@ impl BooksServer {
|
||||
.map(|r| resolve_party(&store, r))
|
||||
.transpose()?;
|
||||
// Every check before anything is journaled.
|
||||
if let Some(r) = no_party {
|
||||
ledger_core::Ledger::check_no_party_reason(r).map_err(bad)?;
|
||||
}
|
||||
store
|
||||
.ledger()
|
||||
.template_lines(&p.template_id, amount, &p.accounts)
|
||||
|
||||
@@ -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`,
|
||||
/// `accounting`, `other`).
|
||||
pub fn file_document(
|
||||
|
||||
Reference in new issue
Block a user