tests.rs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482
  1. use super::command::{DockerCommandCtx, build_docker_command};
  2. use super::*;
  3. use crate::config::{DeployTarget, DistributedBackend};
  4. use crate::pre_serve::{RecipeArgs, VenvSetup};
  5. use std::collections::HashMap;
  6. fn tcls() -> Cluster {
  7. Cluster {
  8. name: "t".into(),
  9. master_ib_ip: Some("1".into()),
  10. nodes: vec![
  11. Node {
  12. name: "n0".into(),
  13. ssh_ip: "10.0.0.1".into(),
  14. ib_ip: Some("1".into()),
  15. rank: 0,
  16. host_key: None,
  17. entity: None,
  18. },
  19. Node {
  20. name: "n1".into(),
  21. ssh_ip: "10.0.0.2".into(),
  22. ib_ip: Some("2".into()),
  23. rank: 1,
  24. host_key: None,
  25. entity: None,
  26. },
  27. ],
  28. extra_entities: vec![],
  29. }
  30. }
  31. fn tnccl() -> NcclConfig {
  32. NcclConfig {
  33. ib_hca: "r".into(),
  34. socket_ifname: "e".into(),
  35. ib_gid_index: Some(3),
  36. ib_disable: 0,
  37. gloo_socket_ifname: None,
  38. ucx_net_devices: None,
  39. nccl_cross_nic: None,
  40. nccl_proto: None,
  41. nccl_p2p_level: None,
  42. }
  43. }
  44. fn trec() -> Recipe {
  45. Recipe {
  46. build_profile: None,
  47. parent_model: None,
  48. archived: false,
  49. engine: "vllm".into(),
  50. name: "T".into(),
  51. docker_image: "img".into(),
  52. model: "mdl".into(),
  53. port: 8000,
  54. required_nodes: Some(2),
  55. pipeline_parallel_size: Some(2),
  56. tensor_parallel_size: 1,
  57. args: RecipeArgs::List(vec!["--x".into(), "4096".into()]),
  58. env: HashMap::from([("K".into(), "V".into())]),
  59. cluster: None,
  60. entrypoint: vec![],
  61. distributed_backend: Some(DistributedBackend::Mp),
  62. before_serve: vec![],
  63. after_stop: vec![],
  64. solo: None,
  65. deploy: DeployTarget::Docker,
  66. venv: None,
  67. venv_setup: VenvSetup::default(),
  68. venv_setup_script: None,
  69. mods: Default::default(),
  70. shm_size: String::new(),
  71. devices: vec![],
  72. memory_limit: None,
  73. cpus: None,
  74. sync_image: true,
  75. docker_image_dir: None,
  76. extra_mounts: vec![],
  77. extra_mounts_manifest: None,
  78. build: Default::default(),
  79. composed_model: None,
  80. staging: vec![],
  81. dgpp: None,
  82. }
  83. }
  84. fn make_dm_ctx(recipe: &Recipe, nnodes: u32, pp: u32, tp: u32, keep: bool) -> DockerCommandCtx {
  85. DockerCommandCtx {
  86. cluster: tcls(),
  87. nccl: Some(tnccl()),
  88. recipe: recipe.clone(),
  89. recipe_name: "r".to_string(),
  90. pp_size: pp,
  91. tp_size: tp,
  92. nnodes,
  93. cache_dir: "/home/user/.cache/huggingface".to_string(),
  94. keep,
  95. init_port: 25000,
  96. mods_remote_path: String::new(),
  97. extra_mounts: vec![],
  98. }
  99. }
  100. /// Remove the single-quote wrapping `shq` adds, so existing assertions that
  101. /// check the un-quoted command shape keep working. Quoting itself is asserted
  102. /// separately (see `malicious_env_value_cannot_inject` etc.).
  103. fn squash(s: &str) -> String {
  104. s.replace('\'', "")
  105. }
  106. fn run(recipe: &Recipe, node: &Node, head: bool) -> String {
  107. let tp = if recipe.required_nodes == Some(recipe.tensor_parallel_size) {
  108. 2
  109. } else {
  110. recipe.tensor_parallel_size
  111. };
  112. squash(
  113. &build_docker_command(&make_dm_ctx(recipe, 2, 2, tp, false), node, head)
  114. .unwrap()
  115. .join(" "),
  116. )
  117. }
  118. #[test]
  119. fn nccl_gid_unresolved_renders_auto() {
  120. // A cluster [nccl] block without `ib_gid_index` (auto-detect) renders
  121. // `NCCL_IB_GID_INDEX=auto` — the launcher resolves the real index per
  122. // node before the docker run; `auto` only appears on the dry-run/unresolved
  123. // path. Confirms the env is emitted and clearly marked, not dropped.
  124. let mut nccl = tnccl();
  125. nccl.ib_gid_index = None;
  126. let mut ctx = make_dm_ctx(&trec(), 2, 2, 2, false);
  127. ctx.nccl = Some(nccl);
  128. let cmd = squash(
  129. &build_docker_command(&ctx, &tcls().nodes[0], true)
  130. .unwrap()
  131. .join(" "),
  132. );
  133. assert!(
  134. cmd.contains("-e NCCL_IB_GID_INDEX=auto"),
  135. "unresolved GID should render 'auto' placeholder: {cmd}"
  136. );
  137. }
  138. fn run_keep(recipe: &Recipe, node: &Node, head: bool) -> String {
  139. let tp = if recipe.required_nodes == Some(recipe.tensor_parallel_size) {
  140. 2
  141. } else {
  142. recipe.tensor_parallel_size
  143. };
  144. squash(
  145. &build_docker_command(&make_dm_ctx(recipe, 2, 2, tp, true), node, head)
  146. .unwrap()
  147. .join(" "),
  148. )
  149. }
  150. #[test]
  151. fn mp() {
  152. let cmd = run(&trec(), &tcls().nodes[0], true);
  153. assert!(cmd.contains("docker run -d --gpus all"));
  154. assert!(cmd.contains("-e NCCL_IB_HCA=r"));
  155. assert!(cmd.contains("-e K=V"));
  156. assert!(cmd.contains("--name sm121_r_0"));
  157. assert!(
  158. !cmd.contains("-p "),
  159. "host networking: no port mapping expected"
  160. );
  161. assert!(cmd.contains("--label sm121.recipe=r"));
  162. assert!(cmd.contains("--label sm121.rank=0"));
  163. assert!(cmd.contains("img"));
  164. assert!(cmd.contains("mdl"));
  165. assert!(cmd.contains("--tensor-parallel-size 1"));
  166. assert!(cmd.contains("--pipeline-parallel-size 2"));
  167. assert!(cmd.contains("--nnodes 2"));
  168. assert!(cmd.contains("--node-rank 0"));
  169. assert!(cmd.contains("--master-addr 1"));
  170. assert!(cmd.contains("--master-port 25000"));
  171. // vLLM auto-detects mp; only explicitly pass for ray
  172. assert!(
  173. !cmd.contains("--distributed-executor-backend"),
  174. "mp backend should be auto-detected"
  175. );
  176. assert!(!cmd.contains("RAY_ADDRESS"));
  177. assert!(cmd.contains("--rm"), "default --rm should be present");
  178. // New: defaults & cluster env
  179. assert!(
  180. !cmd.contains("--shm-size"),
  181. "shm-size should not be set by default"
  182. );
  183. assert!(cmd.contains("--ulimit memlock=-1"));
  184. assert!(cmd.contains("--ulimit stack=67108864"));
  185. assert!(
  186. cmd.contains("-e GLOO_SOCKET_IFNAME=e"),
  187. "default GLOO_SOCKET_IFNAME missing"
  188. );
  189. assert!(
  190. cmd.contains("-e TP_SOCKET_IFNAME=e"),
  191. "default TP_SOCKET_IFNAME missing"
  192. );
  193. assert!(
  194. cmd.contains("-e OMP_NUM_THREADS=4"),
  195. "default OMP_NUM_THREADS missing"
  196. );
  197. assert!(
  198. cmd.contains("-e NCCL_IGNORE_CPU_AFFINITY=1"),
  199. "default NCCL_IGNORE_CPU_AFFINITY missing"
  200. );
  201. assert!(cmd.contains("-e NCCL_NET=IB"), "default NCCL_NET missing");
  202. assert!(
  203. cmd.contains("-e NCCL_DEBUG=WARN"),
  204. "default NCCL_DEBUG missing"
  205. );
  206. assert!(
  207. cmd.contains("-e MN_IF_NAME=e"),
  208. "cluster MN_IF_NAME missing"
  209. );
  210. assert!(
  211. cmd.contains("-e UCX_NET_DEVICES=e"),
  212. "cluster UCX_NET_DEVICES missing"
  213. );
  214. assert!(
  215. cmd.contains("-e OMPI_MCA_btl_tcp_if_include=e"),
  216. "cluster OMPI_MCA_btl_tcp_if_include missing"
  217. );
  218. // Head node: no --headless
  219. assert!(!cmd.contains("--headless"));
  220. }
  221. #[test]
  222. fn worker_no_port() {
  223. let cmd = run(&trec(), &tcls().nodes[1], false);
  224. assert!(!cmd.contains("-p 8000:8000"));
  225. assert!(cmd.contains("--node-rank 1"));
  226. assert!(cmd.contains("--label sm121.rank=1"));
  227. assert!(cmd.contains("--name sm121_r_1"));
  228. // New: vLLM workers run --headless
  229. assert!(cmd.contains("--headless"), "vLLM worker should be headless");
  230. }
  231. #[test]
  232. fn ray_backend() {
  233. let mut r = trec();
  234. r.distributed_backend = Some(DistributedBackend::Ray);
  235. let cmd = run(&r, &tcls().nodes[0], true);
  236. assert!(cmd.contains("-e RAY_ADDRESS=1:6379"));
  237. assert!(cmd.contains("-e RAY_PORT=6379"));
  238. assert!(cmd.contains("--node-rank 0"));
  239. assert!(cmd.contains("--distributed-executor-backend ray"));
  240. }
  241. #[test]
  242. fn custom_tensor_parallel_size() {
  243. // Per-node TP=1 is the default. Custom TP (e.g. multi-node TP)
  244. // can be set via recipe.tensor_parallel_size.
  245. let mut r = trec();
  246. r.tensor_parallel_size = 2;
  247. let cmd = run(&r, &tcls().nodes[0], true);
  248. assert!(cmd.contains("--tensor-parallel-size 2"), "custom TP");
  249. }
  250. #[test]
  251. fn auto_pp_size() {
  252. let cmd = run(&trec(), &tcls().nodes[0], true);
  253. assert!(cmd.contains("--pipeline-parallel-size 2"));
  254. }
  255. #[test]
  256. fn entrypoint() {
  257. let mut r = trec();
  258. r.entrypoint = vec!["py".into(), "-m".into(), "mod".into()];
  259. let cmd = run(&r, &tcls().nodes[0], true);
  260. let ep = cmd.find("--entrypoint py").unwrap();
  261. let ip = cmd.find("img").unwrap();
  262. let mp = cmd.find("mdl").unwrap();
  263. assert!(
  264. ep < ip && ip < mp,
  265. "entrypoint flag before image, model after image"
  266. );
  267. }
  268. #[test]
  269. fn keep_disables_rm() {
  270. let cmd = run_keep(&trec(), &tcls().nodes[0], true);
  271. assert!(!cmd.contains("--rm"), "--keep should suppress --rm");
  272. assert!(cmd.contains("docker run -d"));
  273. assert!(cmd.contains("--gpus all"));
  274. assert!(cmd.contains("-e HF_HOME=/root/.cache/huggingface"));
  275. assert!(cmd.contains("-v /home/user/.cache/huggingface:/root/.cache/huggingface"));
  276. }
  277. #[test]
  278. fn recipe_env_overrides_cluster_defaults() {
  279. // Recipe-level env should win over the defaults we inject.
  280. let mut r = trec();
  281. r.env.insert("NCCL_CUMEM_ENABLE".into(), "1".into());
  282. r.env.insert("OMP_NUM_THREADS".into(), "16".into());
  283. r.env.insert("NCCL_IGNORE_CPU_AFFINITY".into(), "0".into());
  284. r.env.insert("NCCL_NET".into(), "SOCKET".into());
  285. r.env.insert("NCCL_CROSS_NIC".into(), "0".into());
  286. r.env.insert("NCCL_DEBUG".into(), "INFO".into());
  287. let cmd = run(&r, &tcls().nodes[0], true);
  288. // Docker uses the last -e for duplicate keys, so recipe values come after.
  289. // rfind returns the last occurrence, which should be the recipe override.
  290. let cumem_pos = cmd.rfind("NCCL_CUMEM_ENABLE=").unwrap();
  291. assert!(
  292. cmd[cumem_pos..].starts_with("NCCL_CUMEM_ENABLE=1"),
  293. "recipe override should be last: slice starts at {}",
  294. cumem_pos
  295. );
  296. let omp_pos = cmd.rfind("OMP_NUM_THREADS=").unwrap();
  297. assert!(
  298. cmd[omp_pos..].starts_with("OMP_NUM_THREADS=16"),
  299. "recipe override should be last"
  300. );
  301. // New NCCL defaults can also be overridden.
  302. let ignore_pos = cmd.rfind("NCCL_IGNORE_CPU_AFFINITY=").unwrap();
  303. assert!(
  304. cmd[ignore_pos..].starts_with("NCCL_IGNORE_CPU_AFFINITY=0"),
  305. "NCCL_IGNORE_CPU_AFFINITY should be overridable"
  306. );
  307. let net_pos = cmd.rfind("NCCL_NET=").unwrap();
  308. assert!(
  309. cmd[net_pos..].starts_with("NCCL_NET=SOCKET"),
  310. "NCCL_NET should be overridable"
  311. );
  312. let cross_pos = cmd.rfind("NCCL_CROSS_NIC=").unwrap();
  313. assert!(
  314. cmd[cross_pos..].starts_with("NCCL_CROSS_NIC=0"),
  315. "NCCL_CROSS_NIC should be overridable"
  316. );
  317. let debug_pos = cmd.rfind("NCCL_DEBUG=").unwrap();
  318. assert!(
  319. cmd[debug_pos..].starts_with("NCCL_DEBUG=INFO"),
  320. "NCCL_DEBUG should be overridable"
  321. );
  322. }
  323. #[test]
  324. fn custom_init_port() {
  325. // Non-default init_port should propagate to vLLM master-port and
  326. // SGLang dist-init-addr.
  327. let r = trec();
  328. let tp = if r.required_nodes == Some(r.tensor_parallel_size) {
  329. 2
  330. } else {
  331. r.tensor_parallel_size
  332. };
  333. let mut ctx = make_dm_ctx(&r, 2, 2, tp, false);
  334. ctx.init_port = 29500;
  335. let cmd = squash(
  336. &build_docker_command(&ctx, &tcls().nodes[0], true)
  337. .unwrap()
  338. .join(" "),
  339. );
  340. assert!(cmd.contains("--master-port 29500"));
  341. assert!(cmd.contains("--master-addr 1"));
  342. }
  343. // ── Logs command format ───────────────────────────────────────
  344. #[test]
  345. fn logs_tail_cmd_format() {
  346. let cmd = super::logs::logs_tail_cmd("test-sleep", 0, 100);
  347. assert!(cmd.contains("docker ps -q"));
  348. assert!(cmd.contains("--filter 'label=sm121.recipe=test-sleep'"));
  349. assert!(cmd.contains("--filter label=sm121.rank=0"));
  350. assert!(cmd.contains("xargs -r docker logs"));
  351. assert!(cmd.contains("--timestamps"));
  352. assert!(cmd.contains("--tail=100"));
  353. assert!(cmd.ends_with(" 2>&1"));
  354. }
  355. #[test]
  356. fn logs_tail_cmd_per_rank() {
  357. let cmd0 = super::logs::logs_tail_cmd("glm51", 0, 100);
  358. let cmd2 = super::logs::logs_tail_cmd("glm51", 2, 100);
  359. assert!(cmd0.contains("label=sm121.rank=0"));
  360. assert!(cmd2.contains("label=sm121.rank=2"));
  361. assert!(!cmd0.contains("label=sm121.rank=2"));
  362. }
  363. #[test]
  364. fn logs_follow_cmd_format() {
  365. let cmd = super::logs::logs_follow_cmd("test-sleep");
  366. assert!(cmd.contains("xargs -r docker logs -f"));
  367. assert!(cmd.contains("--timestamps"));
  368. // Follow targets the head node only (rank=0).
  369. assert!(cmd.contains("--filter label=sm121.rank=0"));
  370. // Follow should not include --tail (we want a live stream from now).
  371. assert!(!cmd.contains("--tail"));
  372. // Follow must redirect stderr so docker's own errors are captured
  373. // (mirrors the behaviour of logs_tail_cmd).
  374. assert!(
  375. cmd.contains("2>&1"),
  376. "follow cmd must capture stderr, got: {cmd}"
  377. );
  378. }
  379. // ── Shell quoting ─────────────────────────────────────────────
  380. #[test]
  381. fn shq_wraps_simple_strings() {
  382. assert_eq!(shq("foo"), "'foo'");
  383. assert_eq!(shq(""), "''");
  384. assert_eq!(shq("foo bar"), "'foo bar'");
  385. }
  386. #[test]
  387. fn shq_escapes_inner_single_quotes() {
  388. // "don't" → 'don'\''t'
  389. assert_eq!(shq("don't"), "'don'\\''t'");
  390. }
  391. #[test]
  392. fn entrypoint_script_is_shell_quoted() {
  393. // Every tail word — incl. the `sh -c` script — is shell-quoted.
  394. let mut r = trec();
  395. r.entrypoint = vec!["sh".into(), "-c".into(), "echo $i; sleep 1".into()];
  396. let cmd = build_docker_command(&make_dm_ctx(&r, 2, 2, 2, false), &tcls().nodes[0], true)
  397. .unwrap()
  398. .join(" ");
  399. assert!(
  400. cmd.contains("'echo $i; sleep 1'"),
  401. "must be shell-quoted: {cmd}"
  402. );
  403. }
  404. #[test]
  405. fn entrypoint_script_non_sh_passes_through() {
  406. // For non `sh -c` entrypoints (e.g. ["sh", "-c", "...", "extra"]) or
  407. // direct binaries, we leave the args alone — no false positive shq.
  408. let mut r = trec();
  409. r.entrypoint = vec!["sh".into(), "-c".into()];
  410. let cmd = run(&r, &tcls().nodes[0], true);
  411. assert!(cmd.contains("docker run"));
  412. }
  413. #[path = "solo_tests.rs"]
  414. mod solo_tests;
  415. #[path = "sglang_tests.rs"]
  416. mod sglang_tests;
  417. /// Symlinks in a build context (upstream repos may link a directory, e.g.
  418. /// `vllm -> .submodules/spark-agent/vllm`) must not be dereferenced: reading
  419. /// one as a file returns EISDIR and killed `sm121 build` before the first
  420. /// byte. They hash as their dotted target text instead — the upload tar
  421. /// dereferences separately (`tar --dereference`), so the digest tracks the
  422. /// tree shape, not the copied bytes.
  423. #[test]
  424. fn dir_checksum_hashes_symlinks_by_target_text() {
  425. use super::build_dir::compute_dir_checksum;
  426. let root = std::env::temp_dir().join(format!("sm121-chksum-link-{}", std::process::id()));
  427. let dir = root.join("ctx");
  428. let _ = std::fs::remove_dir_all(&root);
  429. // Linked target lives OUTSIDE the hashed tree (like an upstream submodule
  430. // checkout outside the build context's flattened Docker view).
  431. std::fs::create_dir_all(root.join("linked")).unwrap();
  432. std::fs::write(root.join("linked/status-server.py"), b"# py").unwrap();
  433. std::fs::create_dir_all(&dir).unwrap();
  434. std::fs::write(dir.join("top.txt"), b"top").unwrap();
  435. std::os::unix::fs::symlink("../linked", dir.join("vllm")).unwrap();
  436. // Regression: previously File::open on the directory link -> EISDIR.
  437. let first = compute_dir_checksum(&dir).unwrap();
  438. assert_eq!(first, compute_dir_checksum(&dir).unwrap(), "deterministic");
  439. // The target lives outside and is never followed: edits there do not
  440. // move the digest.
  441. std::fs::write(root.join("linked/status-server.py"), b"# changed").unwrap();
  442. assert_eq!(first, compute_dir_checksum(&dir).unwrap());
  443. // The link's own text is part of the digest: retarget -> different hash.
  444. std::fs::remove_file(dir.join("vllm")).unwrap();
  445. std::os::unix::fs::symlink("../top.txt", dir.join("vllm")).unwrap();
  446. assert_ne!(first, compute_dir_checksum(&dir).unwrap());
  447. let _ = std::fs::remove_dir_all(&root);
  448. }