agentmux_srv_core/backend/wcore/object_meta.rs
1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Merge a meta update into a stored object, in one transaction.
5//!
6//! Moved here from `server/service/object_helpers.rs` (task #1350, architecture
7//! cleanup stage 2): the blockcontroller and session code in `backend/` calls
8//! it, and it uses nothing above the store. `server::service` re-exports it.
9
10use crate::backend::obj::*;
11use crate::backend::storage::store::Store;
12
13/// Update object meta by oref string. Merges meta into existing object.
14///
15/// The whole read-merge-write round trip runs inside ONE `Store::with_tx`
16/// critical section (a single acquisition of the store's connection Mutex,
17/// wrapping a real SQLite transaction) instead of two separate
18/// `must_get`/`update` calls. This closes a lost-update race: two
19/// call sites can legitimately fire on the SAME block within milliseconds
20/// of each other — e.g. `persist_session_id` (clearing a stale `--resume`
21/// id) and `clear_active_pid` both run from independent async tasks on a
22/// persistent controller's process exit. Each used to read a pre-write
23/// snapshot of the block's *entire* meta map, merge in its own single key,
24/// and write the *entire* merged map back — so whichever of the two won
25/// the race to write LAST silently reverted the other's change (every key
26/// it didn't itself touch reverts to whatever it read, which may already
27/// be stale). `with_tx` holds the one connection lock across the full
28/// read+merge+write, so no other `Store::*` call for ANY object can
29/// interleave inside it — the two writers now strictly serialize instead
30/// of racing, and each one's merge is always built from the other's
31/// already-committed result. See
32/// REPORT_LOGIN_PERSIST_FAILURE_AND_STUCK_WORKING_2026_07_27.md.
33pub fn update_object_meta(
34 store: &Store,
35 oref_str: &str,
36 meta_update: &MetaMapType,
37) -> Result<(), String> {
38 let oref = crate::backend::ORef::parse(oref_str).map_err(|e| e.to_string())?;
39
40 // Validate the otype up front — StoreTx's methods return StoreError, so
41 // the "unsupported otype" case (a plain String) has to be rejected
42 // before entering with_tx rather than from inside its closure.
43 match oref.otype.as_str() {
44 OTYPE_CLIENT | OTYPE_WINDOW | OTYPE_WORKSPACE | OTYPE_TAB | OTYPE_BLOCK => {}
45 _ => return Err(format!("cannot update meta for otype: {}", oref.otype)),
46 }
47
48 store
49 .with_tx(|tx| {
50 match oref.otype.as_str() {
51 OTYPE_CLIENT => {
52 let mut obj = tx.must_get::<Client>(&oref.oid)?;
53 obj.meta = merge_meta(&obj.meta, meta_update, true);
54 tx.update(&mut obj)?;
55 }
56 OTYPE_WINDOW => {
57 let mut obj = tx.must_get::<Window>(&oref.oid)?;
58 obj.meta = merge_meta(&obj.meta, meta_update, true);
59 tx.update(&mut obj)?;
60 }
61 OTYPE_WORKSPACE => {
62 let mut obj = tx.must_get::<Workspace>(&oref.oid)?;
63 obj.meta = merge_meta(&obj.meta, meta_update, true);
64 tx.update(&mut obj)?;
65 }
66 OTYPE_TAB => {
67 let mut obj = tx.must_get::<Tab>(&oref.oid)?;
68 obj.meta = merge_meta(&obj.meta, meta_update, true);
69 tx.update(&mut obj)?;
70 }
71 OTYPE_BLOCK => {
72 let mut obj = tx.must_get::<Block>(&oref.oid)?;
73 obj.meta = merge_meta(&obj.meta, meta_update, true);
74 tx.update(&mut obj)?;
75 }
76 // Unreachable — validated above, before with_tx was entered.
77 _ => unreachable!("otype validated before with_tx"),
78 }
79 Ok(())
80 })
81 .map_err(|e| e.to_string())
82}
83
84#[cfg(test)]
85mod tests {
86 use super::*;
87 use crate::backend::storage::store::Store;
88 use std::sync::{Arc, Barrier};
89 use std::thread;
90
91 fn insert_block(store: &Store, block_id: &str) {
92 let mut block = Block {
93 oid: block_id.to_string(),
94 parentoref: String::new(),
95 version: 0,
96 runtimeopts: None,
97 stickers: None,
98 meta: MetaMapType::new(),
99 subblockids: None,
100 };
101 store.insert(&mut block).unwrap();
102 }
103
104 /// Pins the fix for a real, reproduced lost-update race: two concurrent
105 /// `update_object_meta` calls on the SAME block, each merging in a
106 /// DIFFERENT single key, must both survive — neither may silently
107 /// revert the other's key by writing back a merged snapshot it read
108 /// before the other's write landed. This is exactly the shape of the
109 /// `persist_session_id` / `clear_active_pid` race
110 /// (REPORT_LOGIN_PERSIST_FAILURE_AND_STUCK_WORKING_2026_07_27.md): both
111 /// fire from independent async tasks on a persistent controller's
112 /// process exit, each touching one key of the same block's meta.
113 ///
114 /// A `Barrier` forces both threads to call `update_object_meta` as
115 /// close to simultaneously as real concurrent tasks would, maximizing
116 /// the odds this test actually exercises the race window rather than
117 /// happening to run the two calls back-to-back. Before the `with_tx`
118 /// fix (two separate `must_get`+`update` lock acquisitions instead of
119 /// one spanning both), this test was flaky — failing whenever the two
120 /// threads' read-then-write windows overlapped.
121 #[test]
122 fn update_object_meta_concurrent_writers_both_keys_survive() {
123 let store = Arc::new(Store::open_in_memory().unwrap());
124 // ORef::parse requires a UUID-shaped oid (see oref.rs) — a plain
125 // slug like "block-race" fails to parse, not the race itself.
126 let block_id = uuid::Uuid::new_v4().to_string();
127 insert_block(&store, &block_id);
128 let oref_str = format!("block:{block_id}");
129
130 let barrier = Arc::new(Barrier::new(2));
131
132 let store_a = Arc::clone(&store);
133 let oref_a = oref_str.clone();
134 let barrier_a = Arc::clone(&barrier);
135 let handle_a = thread::spawn(move || {
136 let mut meta = MetaMapType::new();
137 meta.insert("agent:sessionid".to_string(), serde_json::Value::String(String::new()));
138 barrier_a.wait();
139 update_object_meta(&store_a, &oref_a, &meta).unwrap();
140 });
141
142 let store_b = Arc::clone(&store);
143 let oref_b = oref_str.clone();
144 let barrier_b = Arc::clone(&barrier);
145 let handle_b = thread::spawn(move || {
146 let mut meta = MetaMapType::new();
147 meta.insert("session:active_pid".to_string(), serde_json::Value::from(4242));
148 barrier_b.wait();
149 update_object_meta(&store_b, &oref_b, &meta).unwrap();
150 });
151
152 handle_a.join().unwrap();
153 handle_b.join().unwrap();
154
155 let final_block = store.must_get::<Block>(&block_id).unwrap();
156 // Both threads' writes must have stuck — a lost-update race would
157 // have whichever writer finished LAST silently revert the other's
158 // key back to absent, since it wrote back a meta snapshot it read
159 // before the other's write landed.
160 assert_eq!(
161 final_block.meta.get("agent:sessionid").and_then(|v| v.as_str()),
162 Some(""),
163 "agent:sessionid should be the empty string thread A wrote, not missing/reverted",
164 );
165 assert_eq!(
166 final_block.meta.get("session:active_pid").and_then(|v| v.as_i64()),
167 Some(4242),
168 "session:active_pid should be the value thread B wrote, not missing/reverted",
169 );
170 // Version must reflect exactly two applied updates (1 insert + 2
171 // updates = version 3) — a lost update would also show as a
172 // version that skipped one of the two writers' increments in a
173 // way that leaves one key's write invisible (already covered by
174 // the assert above); this is a secondary, cheap corroboration.
175 assert_eq!(final_block.version, 3, "both concurrent updates must have applied, not one clobbering the other");
176 }
177}