From be35515ef770ddefd95425a7b2a7f20a25a2a062 Mon Sep 17 00:00:00 2001
From: Eelco Dolstra <edolstra@gmail.com>
Date: Tue, 18 Feb 2025 11:56:19 +0100
Subject: [PATCH] startDaemon(): Detect if the daemon crashes before creating
 the socket

This avoids timeouts like those seen in
https://github.com/NixOS/nix/actions/runs/13376958708/job/37358120348?pr=6962.

(cherry picked from commit 11c42cb2e1b5bb44719e40d9c17750fb8a99d750)
---
 tests/functional/common/vars-and-functions.sh | 14 +++++++++-----
 1 file changed, 9 insertions(+), 5 deletions(-)

diff --git a/tests/functional/common/vars-and-functions.sh b/tests/functional/common/vars-and-functions.sh
index a665f236f..9eec0ecfa 100644
--- a/tests/functional/common/vars-and-functions.sh
+++ b/tests/functional/common/vars-and-functions.sh
@@ -122,7 +122,7 @@ startDaemon() {
       die "startDaemon: not supported when testing on NixOS. Is it really needed? If so add conditionals; e.g. if ! isTestOnNixOS; then ..."
     fi
 
-    # Don’t start the daemon twice, as this would just make it loop indefinitely
+    # Don't start the daemon twice, as this would just make it loop indefinitely.
     if [[ "${_NIX_TEST_DAEMON_PID-}" != '' ]]; then
         return
     fi
@@ -131,15 +131,19 @@ startDaemon() {
     PATH=$DAEMON_PATH nix --extra-experimental-features 'nix-command' daemon &
     _NIX_TEST_DAEMON_PID=$!
     export _NIX_TEST_DAEMON_PID
-    for ((i = 0; i < 300; i++)); do
+    for ((i = 0; i < 60; i++)); do
         if [[ -S $NIX_DAEMON_SOCKET_PATH ]]; then
           DAEMON_STARTED=1
           break;
         fi
+        if ! kill -0 "$_NIX_TEST_DAEMON_PID"; then
+          echo "daemon died unexpectedly" >&2
+          exit 1
+        fi
         sleep 0.1
     done
     if [[ -z ${DAEMON_STARTED+x} ]]; then
-      fail "Didn’t manage to start the daemon"
+      fail "Didn't manage to start the daemon"
     fi
     trap "killDaemon" EXIT
     # Save for if daemon is killed
@@ -152,7 +156,7 @@ killDaemon() {
       die "killDaemon: not supported when testing on NixOS. Is it really needed? If so add conditionals; e.g. if ! isTestOnNixOS; then ..."
     fi
 
-    # Don’t fail trying to stop a non-existant daemon twice
+    # Don't fail trying to stop a non-existant daemon twice.
     if [[ "${_NIX_TEST_DAEMON_PID-}" == '' ]]; then
         return
     fi
@@ -277,7 +281,7 @@ assertStderr() {
 
 needLocalStore() {
   if [[ "$NIX_REMOTE" == "daemon" ]]; then
-    skipTest "Can’t run through the daemon ($1)"
+    skipTest "Can't run through the daemon ($1)"
   fi
 }