before_serve_tests.rs 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  1. //! Tests for `before_serve` (split at the 500-line cap).
  2. use super::*;
  3. use crate::config::{Node, PreServeCommand};
  4. use crate::pre_serve::VenvSetup;
  5. use std::collections::HashMap;
  6. fn test_cluster() -> Cluster {
  7. Cluster {
  8. name: "c1".to_string(),
  9. master_ib_ip: Some("1.2.3.4".to_string()),
  10. nodes: vec![
  11. Node {
  12. name: "n0".to_string(),
  13. ssh_ip: "10.0.0.1".to_string(),
  14. ib_ip: Some("1.2.3.4".to_string()),
  15. rank: 0,
  16. host_key: None,
  17. entity: None,
  18. },
  19. Node {
  20. name: "n1".to_string(),
  21. ssh_ip: "10.0.0.2".to_string(),
  22. ib_ip: Some("1.2.3.5".to_string()),
  23. rank: 1,
  24. host_key: None,
  25. entity: None,
  26. },
  27. ],
  28. extra_entities: vec![],
  29. }
  30. }
  31. fn test_config(before_serve: HashMap<String, crate::config::BeforeServeTable>) -> Config {
  32. Config {
  33. ssh_user: "u".to_string(),
  34. ssh_key_path: "/k".into(),
  35. clusters: vec![test_cluster()],
  36. nccl: HashMap::new(),
  37. hf_cache_dir: None,
  38. init_port: 25000,
  39. before_serve,
  40. exec_aliases: HashMap::new(),
  41. home_assistant: None,
  42. mikrotik: None,
  43. global_mods_dir: None,
  44. drop_caches: true,
  45. mount_aliases: HashMap::new(),
  46. recipe_sources: Vec::new(),
  47. recipe_repos: Vec::new(),
  48. docker_image_sources: Vec::new(),
  49. cluster_sources: Vec::new(),
  50. registry: None,
  51. }
  52. }
  53. #[test]
  54. fn truncate_keeps_short_string_unchanged() {
  55. assert_eq!(truncate("short", 120), "short");
  56. assert_eq!(truncate("", 120), "");
  57. }
  58. #[test]
  59. fn truncate_shortens_to_char_boundary() {
  60. // 10 chars, cap at 4 → first 4 chars + ellipsis
  61. let out = truncate("abcdefghij", 4);
  62. assert_eq!(out, "abcd…");
  63. }
  64. #[test]
  65. fn truncate_does_not_panic_on_multibyte() {
  66. // Each 'é' is 2 bytes; a byte slice `&s[..3]` would land mid-char and
  67. // panic. The char-based impl must not. (Regression for C-2.)
  68. let s = "éééééé"; // 6 chars, 12 bytes
  69. assert_eq!(truncate(s, 3), "ééé…");
  70. // cap exactly at a multibyte boundary must also be safe
  71. assert_eq!(truncate(s, 4), "éééé…");
  72. }
  73. #[test]
  74. fn truncate_cjk_chars() {
  75. // 3-byte CJK: byte-slice at any non-multiple-of-3 would panic.
  76. let s = "你好世界你好";
  77. assert_eq!(truncate(s, 2), "你好…");
  78. }
  79. #[test]
  80. fn combined_runs_global_then_cluster_then_recipe() {
  81. let mut bs = HashMap::new();
  82. bs.insert(
  83. "c1".to_string(),
  84. crate::config::BeforeServeTable {
  85. commands: vec![PreServeCommand::Bare("cluster_cmd".into())],
  86. },
  87. );
  88. bs.insert(
  89. "*".to_string(),
  90. crate::config::BeforeServeTable {
  91. commands: vec![PreServeCommand::Bare("global_cmd".into())],
  92. },
  93. );
  94. let cfg = test_config(bs);
  95. let recipe = Recipe {
  96. before_serve: vec![PreServeCommand::Bare("recipe_cmd".into())],
  97. ..test_recipe()
  98. };
  99. let cmds = combined_commands(&cfg, &test_cluster(), &recipe);
  100. let names: Vec<&str> = cmds.iter().map(|(_, c)| c.command()).collect();
  101. let origins: Vec<&str> = cmds.iter().map(|(o, _)| *o).collect();
  102. assert_eq!(names, vec!["global_cmd", "cluster_cmd", "recipe_cmd"]);
  103. assert_eq!(origins, vec!["global", "cluster", "recipe"]);
  104. }
  105. #[test]
  106. fn combined_global_applies_to_unlisted_cluster() {
  107. let mut bs = HashMap::new();
  108. bs.insert(
  109. "*".to_string(),
  110. crate::config::BeforeServeTable {
  111. commands: vec![PreServeCommand::Bare("global_cmd".into())],
  112. },
  113. );
  114. // Cluster "c1" has no specific entry — only the global hook runs.
  115. let cfg = test_config(bs);
  116. let recipe = Recipe {
  117. before_serve: vec![],
  118. after_stop: vec![],
  119. solo: None,
  120. ..test_recipe()
  121. };
  122. let cmds = combined_commands(&cfg, &test_cluster(), &recipe);
  123. let names: Vec<&str> = cmds.iter().map(|(_, c)| c.command()).collect();
  124. assert_eq!(names, vec!["global_cmd"]);
  125. }
  126. #[test]
  127. fn combined_orders_cluster_then_recipe() {
  128. let mut bs = HashMap::new();
  129. bs.insert(
  130. "c1".to_string(),
  131. crate::config::BeforeServeTable {
  132. commands: vec![PreServeCommand::Bare("cluster_cmd_1".into())],
  133. },
  134. );
  135. let cfg = test_config(bs);
  136. let recipe = Recipe {
  137. before_serve: vec![
  138. PreServeCommand::Bare("recipe_cmd_1".into()),
  139. PreServeCommand::Bare("recipe_cmd_2".into()),
  140. ],
  141. ..test_recipe()
  142. };
  143. let cmds = combined_commands(&cfg, &test_cluster(), &recipe);
  144. let names: Vec<&str> = cmds.iter().map(|(_, c)| c.command()).collect();
  145. let origins: Vec<&str> = cmds.iter().map(|(o, _)| *o).collect();
  146. assert_eq!(names, vec!["cluster_cmd_1", "recipe_cmd_1", "recipe_cmd_2"]);
  147. assert_eq!(origins, vec!["cluster", "recipe", "recipe"]);
  148. }
  149. #[test]
  150. fn combined_empty_when_unconfigured() {
  151. let cfg = test_config(HashMap::new());
  152. let recipe = Recipe {
  153. before_serve: vec![],
  154. after_stop: vec![],
  155. solo: None,
  156. ..test_recipe()
  157. };
  158. assert!(combined_commands(&cfg, &test_cluster(), &recipe).is_empty());
  159. }
  160. fn test_recipe() -> Recipe {
  161. Recipe {
  162. build_profile: None,
  163. parent_model: None,
  164. archived: false,
  165. engine: "vllm".to_string(),
  166. name: "Test".to_string(),
  167. docker_image: String::new(),
  168. model: "x".to_string(),
  169. port: 30000,
  170. required_nodes: None,
  171. pipeline_parallel_size: None,
  172. tensor_parallel_size: 1,
  173. args: crate::pre_serve::RecipeArgs::default(),
  174. cold_args: crate::pre_serve::RecipeArgs::default(),
  175. env: HashMap::new(),
  176. cluster: None,
  177. entrypoint: vec![],
  178. distributed_backend: Some(crate::config::DistributedBackend::Mp),
  179. before_serve: vec![],
  180. after_stop: vec![],
  181. solo: None,
  182. deploy: crate::config::DeployTarget::Docker,
  183. venv: None,
  184. venv_setup: VenvSetup::default(),
  185. venv_setup_script: None,
  186. mods: Default::default(),
  187. sync_image: true,
  188. docker_image_dir: None,
  189. shm_size: String::new(),
  190. devices: vec![],
  191. memory_limit: None,
  192. cpus: None,
  193. extra_mounts: vec![],
  194. extra_mounts_manifest: None,
  195. build: Default::default(),
  196. composed_model: None,
  197. staging: vec![],
  198. dgpp: None,
  199. }
  200. }
  201. // ── Deserialization tests (the ones that live in this module) ──
  202. #[test]
  203. fn parses_cluster_level_before_serve() {
  204. let toml_str = r#"
  205. ssh_user = "u"
  206. ssh_key_path = "/k"
  207. [[clusters]]
  208. name = "c1"
  209. master_ib_ip = "1.1.1.1"
  210. nodes = [
  211. { name = "n0", ssh_ip = "2.2.2.2", ib_ip = "1.1.1.1", rank = 0 },
  212. ]
  213. [before_serve."c1"]
  214. commands = [
  215. "sudo nvidia-smi -lgc 300,2300",
  216. { command = "sudo nvidia-smi -pm 1", on_failure = "warn" },
  217. ]
  218. "#;
  219. let cfg: Config = toml::from_str(toml_str).unwrap();
  220. assert!(cfg.before_serve.contains_key("c1"));
  221. let list = &cfg.before_serve["c1"].commands;
  222. assert_eq!(list.len(), 2);
  223. assert_eq!(list[0].command(), "sudo nvidia-smi -lgc 300,2300");
  224. assert_eq!(list[0].on_failure(), OnFailure::Abort); // default
  225. assert_eq!(list[1].command(), "sudo nvidia-smi -pm 1");
  226. assert_eq!(list[1].on_failure(), OnFailure::Warn);
  227. }
  228. #[test]
  229. fn parses_recipe_level_before_serve() {
  230. let toml_str = r#"
  231. name = "Demo"
  232. model = "x"
  233. before_serve = [
  234. "echo a",
  235. { command = "echo b", on_failure = "continue" },
  236. ]
  237. "#;
  238. let r: Recipe = toml::from_str(toml_str).unwrap();
  239. assert_eq!(r.before_serve.len(), 2);
  240. assert_eq!(r.before_serve[0].command(), "echo a");
  241. assert_eq!(r.before_serve[0].on_failure(), OnFailure::Abort);
  242. assert_eq!(r.before_serve[1].command(), "echo b");
  243. assert_eq!(r.before_serve[1].on_failure(), OnFailure::Continue);
  244. }
  245. /// A recipe-relative hook script is read from the recipe dir; absolute
  246. /// paths and `..` traversal are refused (a synced recipe repo must not be
  247. /// able to run an arbitrary file on a node).
  248. #[tokio::test]
  249. async fn recipe_scripts_resolve_inside_the_recipe_dir() {
  250. let dir = std::env::temp_dir().join(format!("sm121-hook-{}", std::process::id()));
  251. tokio::fs::create_dir_all(dir.join("scripts"))
  252. .await
  253. .unwrap();
  254. tokio::fs::write(dir.join("scripts/prepare.sh"), "echo hi\n")
  255. .await
  256. .unwrap();
  257. let body = read_recipe_script("scripts/prepare.sh", Some(&dir), "n0")
  258. .await
  259. .expect("recipe script reads");
  260. assert_eq!(body, "echo hi\n");
  261. let abs = read_recipe_script("/etc/passwd", Some(&dir), "n0").await;
  262. assert!(abs.is_err(), "absolute paths are refused");
  263. let trav = read_recipe_script("scripts/../../etc/passwd", Some(&dir), "n0").await;
  264. assert!(trav.is_err(), "`..` traversal is refused");
  265. let missing = read_recipe_script("scripts/nope.sh", Some(&dir), "n0").await;
  266. assert!(missing.is_err(), "missing file names the built-in aliases");
  267. let no_dir = read_recipe_script("scripts/prepare.sh", None, "n0").await;
  268. assert!(no_dir.is_err(), "unresolvable recipe dir is an error");
  269. let _ = tokio::fs::remove_dir_all(&dir).await;
  270. }
  271. /// A built-in alias wins over a same-named file in recipe sources.
  272. #[test]
  273. fn builtin_aliases_resolve_before_recipe_files() {
  274. assert!(crate::builtin_scripts::resolve("stop_dgx_services").is_some());
  275. assert!(crate::builtin_scripts::resolve("scripts/prepare.sh").is_none());
  276. }