1use std::path::Path;
43
44use rusqlite::Connection;
45
46use super::error::StoreError;
47
48#[path = "agents_consolidate_steps.rs"]
49pub mod steps;
50
51pub const CONSOLIDATE_MARKER: &str = "migration_agents_consolidate_v1.flag";
54
55#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
57pub struct ConsolidateStats {
58 pub templates_inserted: usize,
59 pub user_defs_inserted: usize,
60 pub instances_as_clone_inserted: usize,
61 pub instances_folded_into_def: usize,
62 pub instances_skipped_continuation: usize,
63 pub instances_skipped_no_definition: usize,
64 pub instances_collision_warned: usize,
65 pub already_done: bool,
66}
67
68pub fn consolidate_looks_incomplete(conn: &Connection) -> Result<bool, StoreError> {
94 let defs = table_row_count_if_exists(conn, "db_agent_definitions")?;
95 let insts = table_row_count_if_exists(conn, "db_agent_instances")?;
96 let agents: i64 = conn.query_row("SELECT COUNT(*) FROM db_agents", [], |r| r.get(0))?;
97 Ok((defs > 0 || insts > 0) && agents == 0)
98}
99
100fn table_row_count_if_exists(conn: &Connection, table: &str) -> Result<i64, StoreError> {
104 if !crate::migrations::table_exists(conn, table)? {
105 return Ok(0);
106 }
107 Ok(conn.query_row(&format!("SELECT COUNT(*) FROM {table}"), [], |r| r.get(0))?)
108}
109
110pub fn run_consolidate_migration(
120 conn: &mut Connection,
121 data_dir: Option<&Path>,
122) -> Result<ConsolidateStats, StoreError> {
123 if steps::marker_says_done(conn, data_dir)? {
124 return Ok(ConsolidateStats {
125 already_done: true,
126 ..Default::default()
127 });
128 }
129
130 if !steps::definitions_table_exists(conn)? {
138 return Ok(ConsolidateStats::default());
139 }
140
141 let tx = conn.transaction()?;
146
147 let mut stats = ConsolidateStats::default();
148
149 steps::backfill_definitions(&tx, &mut stats)?;
150 let inst_rows = steps::load_instances(&tx)?;
151 steps::project_instances(&tx, &inst_rows, &mut stats)?;
152
153 tx.commit()?;
154
155 if let Some(dir) = data_dir {
158 steps::write_marker(dir);
159 }
160
161 steps::log_completed(&stats);
162 Ok(stats)
163}
164
165#[cfg(test)]
166mod tests {
167 use super::*;
168 use crate::backend::storage::migrations::run_object_schema;
169 use rusqlite::params;
170
171 fn fresh_conn() -> Connection {
181 let conn = Connection::open_in_memory().unwrap();
182 conn.execute_batch("PRAGMA foreign_keys=ON;").unwrap();
183 run_object_schema(&conn).unwrap();
184 conn.execute_batch(
185 "CREATE TABLE db_agent_definitions (
186 id TEXT PRIMARY KEY,
187 slug TEXT NOT NULL DEFAULT '',
188 name TEXT NOT NULL,
189 icon TEXT NOT NULL DEFAULT '✦',
190 provider TEXT NOT NULL,
191 description TEXT NOT NULL DEFAULT '',
192 working_directory TEXT NOT NULL DEFAULT '',
193 shell TEXT NOT NULL DEFAULT '',
194 provider_flags TEXT NOT NULL DEFAULT '',
195 auto_start INTEGER NOT NULL DEFAULT 0,
196 restart_on_crash INTEGER NOT NULL DEFAULT 0,
197 idle_timeout_minutes INTEGER NOT NULL DEFAULT 0,
198 agent_type TEXT NOT NULL DEFAULT 'standalone',
199 environment TEXT NOT NULL DEFAULT '',
200 agent_bus_id TEXT NOT NULL DEFAULT '',
201 is_seeded INTEGER NOT NULL DEFAULT 0,
202 accounts TEXT NOT NULL DEFAULT '',
203 parent_id TEXT NOT NULL DEFAULT '',
204 branch_label TEXT NOT NULL DEFAULT '',
205 created_at INTEGER NOT NULL DEFAULT 0,
206 updated_at INTEGER NOT NULL DEFAULT 0,
207 user_hidden INTEGER NOT NULL DEFAULT 0
208 );
209 CREATE TABLE db_agent_instances (
210 id TEXT PRIMARY KEY,
211 definition_id TEXT NOT NULL,
212 parent_instance_id TEXT NOT NULL DEFAULT '',
213 block_id TEXT NOT NULL DEFAULT '',
214 session_id TEXT NOT NULL DEFAULT '',
215 status TEXT NOT NULL DEFAULT 'running',
216 github_context TEXT NOT NULL DEFAULT '',
217 identity_id TEXT NOT NULL DEFAULT '',
218 memory_id TEXT NOT NULL DEFAULT '',
219 instance_name TEXT NOT NULL DEFAULT '',
220 working_directory TEXT NOT NULL DEFAULT '',
221 display_hidden INTEGER NOT NULL DEFAULT 0,
222 started_at INTEGER NOT NULL DEFAULT 0,
223 ended_at INTEGER NOT NULL DEFAULT 0,
224 created_at INTEGER NOT NULL DEFAULT 0,
225 FOREIGN KEY (definition_id) REFERENCES db_agent_definitions(id) ON DELETE CASCADE
226 );",
227 )
228 .unwrap();
229 conn
230 }
231
232 fn insert_def(
233 conn: &Connection,
234 id: &str,
235 name: &str,
236 is_seeded: i64,
237 parent_id: &str,
238 ) {
239 conn.execute(
240 "INSERT INTO db_agent_definitions
241 (id, slug, name, icon, provider, description, working_directory, shell,
242 provider_flags, auto_start, restart_on_crash, idle_timeout_minutes,
243 created_at, agent_type, environment, agent_bus_id, is_seeded, accounts,
244 parent_id, branch_label, updated_at)
245 VALUES (?1, ?2, ?3, '✦', 'claude', 'desc', '', 'bash',
246 '', 0, 0, 0,
247 ?4, 'standalone', '', '', ?5, '',
248 ?6, '', ?4)",
249 params![id, id, name, 1000_i64, is_seeded, parent_id],
250 )
251 .unwrap();
252 }
253
254 fn insert_instance(
255 conn: &Connection,
256 id: &str,
257 definition_id: &str,
258 instance_name: &str,
259 identity_id: &str,
260 memory_id: &str,
261 working_directory: &str,
262 created_at: i64,
263 display_hidden: bool,
264 ) {
265 conn.execute(
266 "INSERT INTO db_agent_instances
267 (id, definition_id, parent_instance_id, block_id, session_id, status,
268 github_context, started_at, ended_at, created_at, identity_id, memory_id,
269 instance_name, working_directory, display_hidden)
270 VALUES (?1, ?2, '', '', '', 'running', '', ?3, 0, ?3, ?4, ?5, ?6, ?7, ?8)",
271 params![
272 id,
273 definition_id,
274 created_at,
275 identity_id,
276 memory_id,
277 instance_name,
278 working_directory,
279 if display_hidden { 1_i64 } else { 0_i64 },
280 ],
281 )
282 .unwrap();
283 }
284
285 fn count_agents(conn: &Connection, where_clause: &str) -> i64 {
286 let sql = format!("SELECT COUNT(*) FROM db_agents WHERE {where_clause}");
287 conn.query_row(&sql, [], |row| row.get(0)).unwrap()
288 }
289
290 #[test]
291 fn round_trip_template_user_clone_and_instance_lifecycle() {
292 let mut conn = fresh_conn();
293
294 insert_def(&conn, "tpl-1", "Coder", 1, "");
300 insert_def(&conn, "tpl-2", "Reviewer", 1, "");
301 insert_def(&conn, "def-u1", "Maks-the-Coder", 0, "tpl-1");
302 insert_instance(&conn, "inst-A", "tpl-1", "Maks", "id-1", "mem-1", "/wd/a", 100, false);
303 insert_instance(&conn, "inst-B", "tpl-2", "", "", "", "/wd/b", 200, false);
304 insert_instance(&conn, "inst-C", "def-u1", "Custom", "id-2", "mem-2", "/wd/c", 300, false);
305
306 let stats = run_consolidate_migration(&mut conn, None).unwrap();
307 assert_eq!(stats.templates_inserted, 2);
308 assert_eq!(stats.user_defs_inserted, 1);
309 assert_eq!(stats.instances_as_clone_inserted, 2);
310 assert_eq!(stats.instances_folded_into_def, 1);
311 assert_eq!(stats.instances_skipped_continuation, 0);
312
313 assert_eq!(count_agents(&conn, "is_template = 1"), 2);
315 for tpl in &["tpl-1", "tpl-2"] {
316 let parent: String = conn
317 .query_row(
318 "SELECT parent_template_id FROM db_agents WHERE id = ?1",
319 params![tpl],
320 |r| r.get(0),
321 )
322 .unwrap();
323 assert_eq!(parent, "");
324 }
325
326 assert_eq!(count_agents(&conn, "is_template = 0"), 3);
328
329 let (parent, name, identity): (String, String, String) = conn
331 .query_row(
332 "SELECT parent_template_id, name, identity_id FROM db_agents WHERE id = 'inst-A'",
333 [],
334 |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
335 )
336 .unwrap();
337 assert_eq!(parent, "tpl-1");
338 assert_eq!(name, "Maks");
339 assert_eq!(identity, "id-1");
340
341 let name: String = conn
343 .query_row(
344 "SELECT name FROM db_agents WHERE id = 'inst-B'",
345 [],
346 |r| r.get(0),
347 )
348 .unwrap();
349 assert_eq!(name, "Reviewer");
350
351 let (name, identity, memory): (String, String, String) = conn
353 .query_row(
354 "SELECT name, identity_id, memory_id FROM db_agents WHERE id = 'def-u1'",
355 [],
356 |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
357 )
358 .unwrap();
359 assert_eq!(name, "Custom"); assert_eq!(identity, "id-2");
361 assert_eq!(memory, "mem-2");
362 }
363
364 #[test]
365 fn multiple_instances_on_one_user_clone_keeps_most_recent_bindings() {
366 let mut conn = fresh_conn();
367 insert_def(&conn, "tpl-1", "Coder", 1, "");
368 insert_def(&conn, "def-u1", "User Coder", 0, "tpl-1");
369 insert_instance(&conn, "inst-old", "def-u1", "Old", "id-OLD", "mem-OLD", "/wd/old", 100, false);
371 insert_instance(&conn, "inst-new", "def-u1", "New", "id-RECENT", "mem-RECENT", "/wd/new", 999, false);
372
373 let stats = run_consolidate_migration(&mut conn, None).unwrap();
374 assert_eq!(stats.instances_collision_warned, 1);
375
376 let identity: String = conn
377 .query_row(
378 "SELECT identity_id FROM db_agents WHERE id = 'def-u1'",
379 [],
380 |r| r.get(0),
381 )
382 .unwrap();
383 assert_eq!(identity, "id-RECENT", "most-recent instance's bindings must win");
384 }
385
386 #[test]
387 fn fold_into_user_clone_stamps_updated_at_from_instance_created_at() {
388 let mut conn = fresh_conn();
397 insert_def(&conn, "tpl-1", "Coder", 1, "");
400 insert_def(&conn, "def-u1", "User Coder", 0, "tpl-1");
401 insert_instance(
403 &conn, "inst-1", "def-u1", "Maks", "id-1", "mem-1", "/wd/m", 5000, false,
404 );
405
406 run_consolidate_migration(&mut conn, None).unwrap();
407
408 let updated_at: i64 = conn
409 .query_row(
410 "SELECT updated_at FROM db_agents WHERE id = 'def-u1'",
411 [],
412 |r| r.get(0),
413 )
414 .unwrap();
415 assert_eq!(
416 updated_at, 5000,
417 "folded user-clone row's updated_at must reflect the instance's launch time, \
418 not the def's edit time, so ORDER BY updated_at picks the right row"
419 );
420 }
421
422 #[test]
423 fn fold_into_user_clone_keeps_higher_updated_at() {
424 let mut conn = fresh_conn();
428 insert_def(&conn, "tpl-1", "Coder", 1, "");
429 conn.execute(
431 "UPDATE db_agent_definitions SET updated_at = 8000 WHERE id = 'tpl-1'",
432 [],
433 )
434 .unwrap();
435 insert_def(&conn, "def-u1", "User Coder", 0, "tpl-1");
436 conn.execute(
437 "UPDATE db_agent_definitions SET updated_at = 8000 WHERE id = 'def-u1'",
438 [],
439 )
440 .unwrap();
441 insert_instance(
443 &conn, "inst-1", "def-u1", "Maks", "id-1", "mem-1", "/wd/m", 3000, false,
444 );
445
446 run_consolidate_migration(&mut conn, None).unwrap();
447
448 let updated_at: i64 = conn
449 .query_row(
450 "SELECT updated_at FROM db_agents WHERE id = 'def-u1'",
451 [],
452 |r| r.get(0),
453 )
454 .unwrap();
455 assert_eq!(
456 updated_at, 8000,
457 "later def edit beats older instance launch — MAX(updated_at, inst.created_at)"
458 );
459 }
460
461 #[test]
462 fn marker_short_circuits_second_run() {
463 let mut conn = fresh_conn();
464 insert_def(&conn, "tpl-1", "Coder", 1, "");
465 let tmp = tempfile::tempdir().unwrap();
466
467 let stats1 = run_consolidate_migration(&mut conn, Some(tmp.path())).unwrap();
468 assert_eq!(stats1.templates_inserted, 1);
469 assert!(!stats1.already_done);
470 assert!(tmp.path().join(CONSOLIDATE_MARKER).exists());
471
472 insert_def(&conn, "tpl-2", "Reviewer", 1, "");
475 let stats2 = run_consolidate_migration(&mut conn, Some(tmp.path())).unwrap();
476 assert!(stats2.already_done);
477 assert_eq!(stats2.templates_inserted, 0);
478 assert_eq!(count_agents(&conn, "is_template = 1"), 1);
481 }
482
483 #[test]
484 fn skips_continuation_rows() {
485 let mut conn = fresh_conn();
486 insert_def(&conn, "tpl-1", "Coder", 1, "");
487 insert_instance(&conn, "inst-A", "tpl-1", "Original", "", "", "/wd/a", 100, false);
488 conn.execute(
490 "INSERT INTO db_agent_instances
491 (id, definition_id, parent_instance_id, block_id, session_id, status,
492 github_context, started_at, ended_at, created_at, identity_id, memory_id,
493 instance_name, working_directory, display_hidden)
494 VALUES ('inst-cont', 'tpl-1', 'inst-A', '', '', 'running', '', 200, 0, 200,
495 '', '', 'Original', '/wd/a', 0)",
496 [],
497 )
498 .unwrap();
499
500 let stats = run_consolidate_migration(&mut conn, None).unwrap();
501 assert_eq!(stats.instances_skipped_continuation, 1);
502 assert_eq!(count_agents(&conn, "1 = 1"), 2);
504 assert_eq!(count_agents(&conn, "id = 'inst-cont'"), 0);
505 }
506
507 #[test]
508 fn empty_database_is_clean_noop() {
509 let mut conn = fresh_conn();
510 let stats = run_consolidate_migration(&mut conn, None).unwrap();
511 assert_eq!(stats, ConsolidateStats::default());
512 assert_eq!(count_agents(&conn, "1 = 1"), 0);
513 }
514
515 #[test]
516 fn preserves_hidden_flag_into_user_hidden() {
517 let mut conn = fresh_conn();
518 insert_def(&conn, "tpl-1", "Coder", 1, "");
519 insert_instance(&conn, "inst-H", "tpl-1", "Hidden", "", "", "/wd/h", 100, true);
520 run_consolidate_migration(&mut conn, None).unwrap();
521 let hidden: i64 = conn
522 .query_row(
523 "SELECT user_hidden FROM db_agents WHERE id = 'inst-H'",
524 [],
525 |r| r.get(0),
526 )
527 .unwrap();
528 assert_eq!(hidden, 1);
529 }
530
531 #[test]
532 fn definition_working_directory_survives_the_pass_1_2_backfill() {
533 let mut conn = fresh_conn();
543 conn.execute(
544 "INSERT INTO db_agent_definitions
545 (id, slug, name, icon, provider, description, working_directory, shell,
546 provider_flags, auto_start, restart_on_crash, idle_timeout_minutes,
547 created_at, agent_type, environment, agent_bus_id, is_seeded, accounts,
548 parent_id, branch_label, updated_at)
549 VALUES ('tpl-wd', 'tpl-wd', 'Coder', '✦', 'claude', 'desc',
550 '/home/user/my-project', 'bash',
551 '', 0, 0, 0,
552 1000, 'standalone', '', '', 1, '',
553 '', '', 1000)",
554 [],
555 )
556 .unwrap();
557
558 run_consolidate_migration(&mut conn, None).unwrap();
559
560 let working_directory: String = conn
561 .query_row(
562 "SELECT working_directory FROM db_agents WHERE id = 'tpl-wd'",
563 [],
564 |r| r.get(0),
565 )
566 .unwrap();
567 assert_eq!(
568 working_directory, "/home/user/my-project",
569 "a definition's working_directory must survive Pass 1/2 consolidation \
570 even when it was never instantiated (no instance row to fold bindings from)"
571 );
572 }
573
574 #[test]
577 fn consolidate_looks_incomplete_is_false_on_a_fresh_db() {
578 let conn = fresh_conn();
579 assert!(!consolidate_looks_incomplete(&conn).unwrap());
581 }
582
583 #[test]
589 fn consolidate_looks_incomplete_tolerates_both_tables_being_physically_absent() {
590 let conn = Connection::open_in_memory().unwrap();
591 conn.execute_batch("PRAGMA foreign_keys=ON;").unwrap();
592 run_object_schema(&conn).unwrap();
593 assert!(!consolidate_looks_incomplete(&conn).unwrap());
594 }
595
596 #[test]
604 fn run_consolidate_migration_tolerates_both_tables_being_physically_absent() {
605 let mut conn = Connection::open_in_memory().unwrap();
606 conn.execute_batch("PRAGMA foreign_keys=ON;").unwrap();
607 run_object_schema(&conn).unwrap();
608 let stats = run_consolidate_migration(&mut conn, None).unwrap();
609 assert_eq!(stats, ConsolidateStats::default());
610 }
611
612 #[test]
613 fn consolidate_looks_incomplete_is_false_once_backfilled() {
614 let mut conn = fresh_conn();
615 insert_def(&conn, "tpl-1", "Coder", 1, "");
616 run_consolidate_migration(&mut conn, None).unwrap();
617 assert!(!consolidate_looks_incomplete(&conn).unwrap());
618 }
619
620 #[test]
621 fn consolidate_looks_incomplete_is_true_when_source_has_rows_but_db_agents_is_empty() {
622 let conn = fresh_conn();
623 insert_def(&conn, "tpl-1", "Coder", 1, "");
626 assert!(consolidate_looks_incomplete(&conn).unwrap());
627 }
628
629 #[test]
630 fn stale_marker_does_not_block_a_real_backfill() {
631 let tmp = tempfile::TempDir::new().unwrap();
637 std::fs::write(tmp.path().join(CONSOLIDATE_MARKER), b"phase3a").unwrap();
638
639 let mut conn = fresh_conn();
640 insert_def(&conn, "tpl-1", "Coder", 1, "");
641 assert_eq!(count_agents(&conn, "1=1"), 0, "db_agents must start empty for this test to be meaningful");
642
643 let stats = run_consolidate_migration(&mut conn, Some(tmp.path())).unwrap();
644 assert!(!stats.already_done, "a stale marker must not short-circuit as already_done");
645 assert_eq!(stats.templates_inserted, 1);
646 assert_eq!(count_agents(&conn, "1=1"), 1, "db_agents must actually get populated, not silently skipped");
647 }
648
649 #[test]
650 fn genuinely_completed_marker_still_short_circuits() {
651 let tmp = tempfile::TempDir::new().unwrap();
655 std::fs::write(tmp.path().join(CONSOLIDATE_MARKER), b"phase3a").unwrap();
656
657 let mut conn = fresh_conn();
658 insert_def(&conn, "tpl-1", "Coder", 1, "");
659 run_consolidate_migration(&mut conn, None).unwrap(); assert_eq!(count_agents(&conn, "1=1"), 1);
661
662 let stats = run_consolidate_migration(&mut conn, Some(tmp.path())).unwrap();
663 assert!(stats.already_done, "a marker backed by real data must still short-circuit");
664 assert_eq!(count_agents(&conn, "1=1"), 1, "must not double-insert");
665 }
666
667 const AGENT_COLUMNS: &str = "id, name, icon, description, is_template, parent_template_id, \
670 provider, provider_flags, shell, environment, agent_type, agent_bus_id, accounts, \
671 auto_start, restart_on_crash, idle_timeout_minutes, slug, branch_label, \
672 identity_id, memory_id, working_directory, github_context, instance_name, \
673 created_at, updated_at, is_seeded, user_hidden";
674
675 fn row_of(conn: &Connection, id: &str) -> String {
677 let cols: Vec<String> = AGENT_COLUMNS
678 .split(',')
679 .map(|c| format!("CAST({} AS TEXT)", c.trim()))
680 .collect();
681 let sql = format!("SELECT {} FROM db_agents WHERE id = ?1", cols.join(", "));
682 conn.query_row(&sql, params![id], |r| {
683 let mut parts = Vec::new();
684 for i in 0..27 {
685 parts.push(r.get::<_, String>(i)?);
686 }
687 Ok(parts.join("|"))
688 })
689 .unwrap()
690 }
691
692 fn rich_def(conn: &Connection, id: &str, name: &str, is_seeded: i64, parent_id: &str) {
694 conn.execute(
695 "INSERT INTO db_agent_definitions
696 (id, slug, name, icon, provider, description, working_directory, shell,
697 provider_flags, auto_start, restart_on_crash, idle_timeout_minutes,
698 created_at, agent_type, environment, agent_bus_id, is_seeded, accounts,
699 parent_id, branch_label, updated_at)
700 VALUES (?1, ?1, ?2, 'ic', 'prov', 'descr', '/def/wd', 'zsh',
701 '--fl', 1, 1, 7,
702 111, 'sub', 'K=V', 'bus-9', ?3, 'acct-1',
703 ?4, 'br-1', 222)",
704 params![id, name, is_seeded, parent_id],
705 )
706 .unwrap();
707 }
708
709 fn rich_instance(
711 conn: &Connection,
712 id: &str,
713 definition_id: &str,
714 parent_instance_id: &str,
715 instance_name: &str,
716 created_at: i64,
717 display_hidden: bool,
718 ) {
719 conn.execute(
720 "INSERT INTO db_agent_instances
721 (id, definition_id, parent_instance_id, block_id, session_id, status,
722 github_context, started_at, ended_at, created_at, identity_id, memory_id,
723 instance_name, working_directory, display_hidden)
724 VALUES (?1, ?2, ?3, 'blk', 'sess', 'running', 'ghc', 1, 0, ?4, 'idn', 'mem',
725 ?5, '/inst/wd', ?6)",
726 params![id, definition_id, parent_instance_id, created_at, instance_name, display_hidden as i64],
727 )
728 .unwrap();
729 }
730
731 #[test]
732 fn a_seeded_definition_becomes_a_template_carrying_every_column() {
733 let mut conn = fresh_conn();
734 rich_def(&conn, "tpl", "Tpl", 1, "ignored-parent");
736 run_consolidate_migration(&mut conn, None).unwrap();
737 assert_eq!(
738 row_of(&conn, "tpl"),
739 "tpl|Tpl|ic|descr|1||prov|--fl|zsh|K=V|sub|bus-9|acct-1|1|1|7|tpl|br-1|||/def/wd|||111|222|1|0"
740 );
741 }
742
743 #[test]
744 fn an_unseeded_definition_becomes_a_user_clone_of_its_parent() {
745 let mut conn = fresh_conn();
746 rich_def(&conn, "tpl", "Tpl", 1, "");
747 rich_def(&conn, "usr", "Usr", 0, "tpl");
748 run_consolidate_migration(&mut conn, None).unwrap();
749 assert_eq!(
750 row_of(&conn, "usr"),
751 "usr|Usr|ic|descr|0|tpl|prov|--fl|zsh|K=V|sub|bus-9|acct-1|1|1|7|usr|br-1|||/def/wd|||111|222|0|0"
752 );
753 }
754
755 #[test]
756 fn an_instance_of_a_template_becomes_a_user_clone_keyed_by_the_instance() {
757 let mut conn = fresh_conn();
758 rich_def(&conn, "tpl", "Tpl", 1, "");
759 rich_instance(&conn, "i1", "tpl", "", "Inst", 555, true);
760 let stats = run_consolidate_migration(&mut conn, None).unwrap();
761 assert_eq!(stats.instances_as_clone_inserted, 1);
762 assert_eq!(
765 row_of(&conn, "i1"),
766 "i1|Inst|ic|descr|0|tpl|prov|--fl|zsh|K=V|sub|bus-9|acct-1|1|1|7|tpl|br-1|idn|mem|/inst/wd|ghc|Inst|555|555|0|1"
767 );
768 }
769
770 #[test]
771 fn two_instances_of_one_template_each_get_their_own_clone() {
772 let mut conn = fresh_conn();
773 rich_def(&conn, "tpl", "Tpl", 1, "");
774 rich_instance(&conn, "i1", "tpl", "", "One", 100, false);
775 rich_instance(&conn, "i2", "tpl", "", "Two", 200, false);
776 let stats = run_consolidate_migration(&mut conn, None).unwrap();
777 assert_eq!(stats.instances_as_clone_inserted, 2);
778 assert_eq!(stats.instances_collision_warned, 0);
779 assert_eq!(count_agents(&conn, "is_template = 0"), 2);
780 }
781
782 #[test]
783 fn folding_an_instance_into_a_user_clone_rewrites_only_the_binding_columns() {
784 let mut conn = fresh_conn();
785 rich_def(&conn, "tpl", "Tpl", 1, "");
786 rich_def(&conn, "usr", "Usr", 0, "tpl");
787 rich_instance(&conn, "i2", "usr", "", "Folded", 333, false);
789 let stats = run_consolidate_migration(&mut conn, None).unwrap();
790 assert_eq!(stats.instances_folded_into_def, 1);
791 assert_eq!(
792 row_of(&conn, "usr"),
793 "usr|Folded|ic|descr|0|tpl|prov|--fl|zsh|K=V|sub|bus-9|acct-1|1|1|7|usr|br-1|idn|mem|/inst/wd|ghc|Folded|111|333|0|0"
794 );
795 assert_eq!(count_agents(&conn, "id = 'i2'"), 0);
797 }
798
799 #[test]
800 fn an_unnamed_instance_folds_in_under_its_definitions_name() {
801 let mut conn = fresh_conn();
802 rich_def(&conn, "tpl", "Tpl", 1, "");
803 rich_def(&conn, "usr", "Usr", 0, "tpl");
804 rich_instance(&conn, "i2", "usr", "", "", 333, true);
805 run_consolidate_migration(&mut conn, None).unwrap();
806 assert_eq!(
807 row_of(&conn, "usr"),
808 "usr|Usr|ic|descr|0|tpl|prov|--fl|zsh|K=V|sub|bus-9|acct-1|1|1|7|usr|br-1|idn|mem|/inst/wd|ghc||111|333|0|1"
809 );
810 }
811
812 #[test]
813 fn three_instances_on_one_user_clone_fold_the_newest_and_warn_twice() {
814 let mut conn = fresh_conn();
815 rich_def(&conn, "tpl", "Tpl", 1, "");
816 rich_def(&conn, "usr", "Usr", 0, "tpl");
817 rich_instance(&conn, "old", "usr", "", "Old", 100, false);
818 rich_instance(&conn, "mid", "usr", "", "Mid", 200, false);
819 rich_instance(&conn, "new", "usr", "", "New", 300, false);
820 let stats = run_consolidate_migration(&mut conn, None).unwrap();
821 assert_eq!(stats.instances_folded_into_def, 1);
822 assert_eq!(stats.instances_collision_warned, 2);
823 assert_eq!(row_of(&conn, "usr").split('|').nth(22), Some("New"));
824 }
825
826 #[test]
827 fn a_newer_continuation_row_does_not_use_up_the_fold_slot() {
828 let mut conn = fresh_conn();
829 rich_def(&conn, "tpl", "Tpl", 1, "");
830 rich_def(&conn, "usr", "Usr", 0, "tpl");
831 rich_instance(&conn, "real", "usr", "", "Real", 100, false);
832 rich_instance(&conn, "cont", "usr", "real", "Cont", 900, false);
833 let stats = run_consolidate_migration(&mut conn, None).unwrap();
834 assert_eq!(stats.instances_skipped_continuation, 1);
835 assert_eq!(stats.instances_collision_warned, 0);
836 assert_eq!(stats.instances_folded_into_def, 1);
837 assert_eq!(row_of(&conn, "usr").split('|').nth(22), Some("Real"));
838 }
839
840 #[test]
841 fn an_instance_with_no_definition_is_skipped_and_counted() {
842 let mut conn = fresh_conn();
843 conn.execute_batch("PRAGMA foreign_keys=OFF;").unwrap();
846 rich_def(&conn, "tpl", "Tpl", 1, "");
847 rich_instance(&conn, "orphan", "ghost", "", "Orphan", 100, false);
848 let stats = run_consolidate_migration(&mut conn, None).unwrap();
849 assert_eq!(stats.instances_skipped_no_definition, 1);
850 assert_eq!(stats.instances_skipped_continuation, 0);
851 assert_eq!(stats.instances_as_clone_inserted, 0);
852 assert_eq!(count_agents(&conn, "1 = 1"), 1);
853 }
854
855 #[test]
856 fn an_orphaned_continuation_row_counts_as_a_continuation_not_an_orphan() {
857 let mut conn = fresh_conn();
858 conn.execute_batch("PRAGMA foreign_keys=OFF;").unwrap();
859 rich_instance(&conn, "cont", "ghost", "parent", "Cont", 100, false);
860 let stats = run_consolidate_migration(&mut conn, None).unwrap();
862 assert_eq!(stats.instances_skipped_continuation, 1);
863 assert_eq!(stats.instances_skipped_no_definition, 0);
864 }
865
866 #[test]
867 fn a_missing_instances_table_still_backfills_the_definitions() {
868 let mut conn = fresh_conn();
869 conn.execute_batch("DROP TABLE db_agent_instances;").unwrap();
870 rich_def(&conn, "tpl", "Tpl", 1, "");
871 rich_def(&conn, "usr", "Usr", 0, "tpl");
872 let tmp = tempfile::tempdir().unwrap();
873 let stats = run_consolidate_migration(&mut conn, Some(tmp.path())).unwrap();
874 assert_eq!(stats.templates_inserted, 1);
875 assert_eq!(stats.user_defs_inserted, 1);
876 assert_eq!(stats.instances_as_clone_inserted, 0);
877 assert_eq!(count_agents(&conn, "1 = 1"), 2);
878 assert!(tmp.path().join(CONSOLIDATE_MARKER).exists());
879 }
880
881 #[test]
882 fn a_missing_definitions_table_returns_empty_stats_and_writes_no_marker() {
883 let mut conn = Connection::open_in_memory().unwrap();
884 run_object_schema(&conn).unwrap();
885 conn.execute_batch("CREATE TABLE db_agent_instances (id TEXT PRIMARY KEY);").unwrap();
886 let tmp = tempfile::tempdir().unwrap();
887 let stats = run_consolidate_migration(&mut conn, Some(tmp.path())).unwrap();
888 assert_eq!(stats, ConsolidateStats::default());
889 assert!(!tmp.path().join(CONSOLIDATE_MARKER).exists());
890 }
891
892 #[test]
893 fn a_completed_run_writes_the_marker_even_with_nothing_to_move() {
894 let mut conn = fresh_conn();
895 let tmp = tempfile::tempdir().unwrap();
896 let stats = run_consolidate_migration(&mut conn, Some(tmp.path())).unwrap();
897 assert_eq!(stats, ConsolidateStats::default());
898 assert_eq!(std::fs::read(tmp.path().join(CONSOLIDATE_MARKER)).unwrap(), b"phase3a");
899 }
900
901 #[test]
902 fn a_marker_that_cannot_be_written_does_not_fail_the_run() {
903 let mut conn = fresh_conn();
904 rich_def(&conn, "tpl", "Tpl", 1, "");
905 let tmp = tempfile::tempdir().unwrap();
906 let missing = tmp.path().join("no-such-dir");
907 let stats = run_consolidate_migration(&mut conn, Some(&missing)).unwrap();
908 assert_eq!(stats.templates_inserted, 1);
909 assert_eq!(count_agents(&conn, "1 = 1"), 1);
910 assert!(!missing.exists());
911 }
912
913 #[test]
914 fn a_failure_part_way_rolls_everything_back_and_leaves_no_marker() {
915 let mut conn = fresh_conn();
916 rich_def(&conn, "tpl", "Tpl", 1, "");
917 rich_instance(&conn, "i1", "tpl", "", "Inst", 100, false);
918 conn.execute_batch(
920 "CREATE TRIGGER refuse_clone BEFORE INSERT ON db_agents
921 WHEN NEW.id = 'i1'
922 BEGIN SELECT RAISE(ABORT, 'refused'); END;",
923 )
924 .unwrap();
925 let tmp = tempfile::tempdir().unwrap();
926 assert!(run_consolidate_migration(&mut conn, Some(tmp.path())).is_err());
927 assert_eq!(count_agents(&conn, "1 = 1"), 0, "the template insert must roll back too");
928 assert!(!tmp.path().join(CONSOLIDATE_MARKER).exists());
929
930 conn.execute_batch("DROP TRIGGER refuse_clone;").unwrap();
932 let stats = run_consolidate_migration(&mut conn, Some(tmp.path())).unwrap();
933 assert_eq!(stats.templates_inserted, 1);
934 assert_eq!(stats.instances_as_clone_inserted, 1);
935 assert_eq!(count_agents(&conn, "1 = 1"), 2);
936 assert!(tmp.path().join(CONSOLIDATE_MARKER).exists());
937 }
938
939 #[test]
940 fn running_twice_without_a_marker_replaces_rows_instead_of_failing() {
941 let mut conn = fresh_conn();
942 rich_def(&conn, "tpl", "Tpl", 1, "");
943 rich_def(&conn, "usr", "Usr", 0, "tpl");
944 rich_instance(&conn, "i1", "tpl", "", "Inst", 100, false);
945 rich_instance(&conn, "i2", "usr", "", "Folded", 333, false);
946 let first = run_consolidate_migration(&mut conn, None).unwrap();
947 let rows_after_first: Vec<String> =
948 ["tpl", "usr", "i1"].iter().map(|id| row_of(&conn, id)).collect();
949 let second = run_consolidate_migration(&mut conn, None).unwrap();
950 assert_eq!(first, second);
951 let rows_after_second: Vec<String> =
952 ["tpl", "usr", "i1"].iter().map(|id| row_of(&conn, id)).collect();
953 assert_eq!(rows_after_first, rows_after_second);
954 assert_eq!(count_agents(&conn, "1 = 1"), 3);
955 }
956}