pkg/service/process_pool_test.go

package service

import (
	"context"
	"fmt"
	"io"
	"net"
	"net/http"
	"net/http/httptest"
	"os"
	"os/exec"
	"path/filepath"
	"strings"
	"sync"
	"sync/atomic"
	"testing"
	"time"

	"git.cafe/ezterry/ez-agent/pkg/ezagentapi"
	"git.cafe/ezterry/ez-agent/pkg/protocol"
	"git.cafe/ezterry/ez-agent/pkg/service/config"
)

func TestProcessPoolHelper(t *testing.T) {
	mode := os.Getenv("EZ_AGENT_POOL_HELPER")
	if mode == "" {
		return
	}
	if mode == "immediate" {
		os.Exit(23)
	}
	if mode == "hold-fds" {
		time.Sleep(2 * time.Second)
		os.Exit(0)
	}
	fmt.Println(`{"type":"hello","protocol":1,"name":"helper"}`)
	var ack string
	fmt.Scanln(&ack)
	fmt.Println(`{"type":"announce","tools":[],"plugins":[],"macros":[]}`)
	if mode == "close-ipc" {
		trigger := os.Getenv("EZ_AGENT_POOL_CLOSE_IPC")
		for {
			if err := os.Remove(trigger); err == nil {
				break
			}
			time.Sleep(time.Millisecond)
		}
		_ = os.Stdout.Close()
		// Deliberately remain alive after EOF. Only the pool can retire us.
		for {
			time.Sleep(time.Hour)
		}
	}
	if mode == "descendant" {
		d := exec.Command(os.Args[0], "-test.run", "^TestProcessPoolHelper$")
		d.Env = append(os.Environ(), "EZ_AGENT_POOL_HELPER=hold-fds")
		d.Stdout, d.Stderr = os.Stdout, os.Stderr
		if err := d.Start(); err != nil {
			os.Exit(25)
		}
		os.Exit(24)
	}
	if mode == "healthy" {
		for {
			time.Sleep(time.Hour)
		}
	}
	os.Exit(24)
}

func helperScript(t *testing.T, mode string) string {
	t.Helper()
	path := filepath.Join(t.TempDir(), "helper")
	body := fmt.Sprintf("#!/bin/sh\nEZ_AGENT_POOL_HELPER=%s exec %q -test.run '^TestProcessPoolHelper$'\n", mode, os.Args[0])
	if err := os.WriteFile(path, []byte(body), 0o700); err != nil {
		t.Fatal(err)
	}
	return path
}

func helperCallbacks(registered func(*Connection)) SpawnCallbacks {
	return SpawnCallbacks{
		RegisterConn: registered,
		ServiceOptions: func(c *Connection) ezagentapi.ServiceOptions {
			return ezagentapi.ServiceOptions{
				OnHello: func(context.Context, ezagentapi.ServiceHello) (ezagentapi.HelloAck, error) {
					c.helloDone.Store(true)
					c.closeHelloCh()
					return ezagentapi.HelloAck{ServerID: "test", Ready: true, Message: "READY"}, nil
				},
				Handlers: ezagentapi.Handlers{OnAnnounce: func(context.Context, protocol.Announce) error { c.closeAnnounceCh(); return nil }},
			}
		},
	}
}

func TestLayeredOrdinaryDirectServiceStartsAndClaimsCapability(t *testing.T) {
	const serviceName = "ordinary-direct-service"
	path := filepath.Join(t.TempDir(), "config.yaml")
	servicePath := helperScript(t, "healthy")
	body := fmt.Sprintf(`providers:
  test:
    type: openai_compatible
    base_url: http://127.0.0.1:1
    models: [{name: model}]
default_model: test/model
services:
  %s:
    path: %q
    direct: true
    tools: [ordinary-direct.tool]
`, serviceName, servicePath)
	if err := os.WriteFile(path, []byte(body), 0o600); err != nil {
		t.Fatal(err)
	}
	cfg, err := config.LoadLayered(path, "")
	if err != nil {
		t.Fatal(err)
	}
	if cfg.ConfigError != "" {
		t.Fatalf("ordinary direct config rejected: %s", cfg.ConfigError)
	}
	svc, ok := cfg.Services[serviceName]
	if !ok {
		t.Fatal("ordinary direct service missing from layered config")
	}
	srv := NewServer(cfg, nil)
	defer srv.pool.Shutdown()
	conn, err := srv.ensureDirectConn(serviceName, &svc)
	if err != nil {
		t.Fatalf("ordinary direct service did not start: %v", err)
	}
	provider, lazyName, err := srv.registry.FindTool("ordinary-direct.tool")
	if err != nil || provider == nil || provider.ConnID != conn.ID || lazyName != "" {
		t.Fatalf("ordinary direct capability owner=%+v lazy=%q err=%v", provider, lazyName, err)
	}
}

func TestExactRubyAPIClientServiceStartsAndClaimsCapability(t *testing.T) {
	const serviceName = "ruby-api-client"
	servicePath := helperScript(t, "healthy")
	cfg := &config.Config{Services: map[string]config.ServiceConfig{
		serviceName: {Path: servicePath, Direct: true, Tools: []string{"ruby-api-client.tool"}},
	}}
	srv := NewServer(cfg, nil)
	defer srv.pool.Shutdown()
	svc := cfg.Services[serviceName]
	conn, err := srv.ensureDirectConn(serviceName, &svc)
	if err != nil {
		t.Fatalf("exact-name service did not start: %v", err)
	}
	provider, lazyName, err := srv.registry.FindTool("ruby-api-client.tool")
	if err != nil || provider == nil || provider.ConnID != conn.ID || lazyName != "" {
		t.Fatalf("exact-name capability owner=%+v lazy=%q err=%v", provider, lazyName, err)
	}
}

func TestProcessPoolImmediateExitIsReapedAndNotPublished(t *testing.T) {
	p := NewProcessPool()
	defer p.Shutdown()
	var rec *childRecord
	cb := helperCallbacks(func(*Connection) { p.mu.Lock(); rec = p.procs["tool"]; p.mu.Unlock() })
	_, err := p.GetOrSpawn("tool", &config.ServiceConfig{Direct: true, Path: helperScript(t, "immediate")}, cb)
	if err == nil {
		t.Fatal("immediate exit was published")
	}
	poolAwait(t, rec.finished)
	if got := p.Get("tool"); got != nil {
		t.Fatalf("dead child remains published: %v", got.ID)
	}
	p.mu.Lock()
	empty := len(p.procs) == 0
	p.mu.Unlock()
	if !empty {
		t.Fatal("reaped child record remains in pool")
	}
}

func TestProcessPoolConcurrentCallersShareSpawnFailure(t *testing.T) {
	p := NewProcessPool()
	defer p.Shutdown()
	cfg := &config.ServiceConfig{Direct: true, Path: helperScript(t, "immediate")}
	entered, release := make(chan struct{}), make(chan struct{})
	var registrations atomic.Int32
	cb := helperCallbacks(func(*Connection) { registrations.Add(1); close(entered); <-release })
	const n = 12
	errs := make([]error, n)
	var wg sync.WaitGroup
	wg.Add(n)
	go func() {
		defer wg.Done()
		// Fail independently of the handshake: transport starts only after
		// publication, and a fully handshaken child may exit after admission.
		_, errs[0] = p.GetOrSpawn("tool", cfg, cb)
	}()
	<-entered
	for i := 1; i < n; i++ {
		go func(i int) {
			defer wg.Done()
			_, errs[i] = p.GetOrSpawn("tool", &config.ServiceConfig{Direct: true, Path: "must-not-spawn"}, cb)
		}(i)
	}
	waitForPoolWaiters(t, p, n)
	close(release)
	wg.Wait()
	if registrations.Load() != 1 {
		t.Fatalf("spawn count = %d, want 1", registrations.Load())
	}
	for i, err := range errs {
		if err == nil {
			t.Fatalf("caller %d got nil error", i)
		}
	}
	first := errs[0].Error()
	for i, err := range errs[1:] {
		if err.Error() != first {
			t.Fatalf("caller %d error %q differs from %q", i+1, err, first)
		}
	}
}

func TestProcessPoolConcurrentCallersShareHealthyConnection(t *testing.T) {
	p := NewProcessPool()
	defer p.Shutdown()
	cfg := &config.ServiceConfig{Direct: true, Path: helperScript(t, "healthy")}
	entered, release := make(chan struct{}), make(chan struct{})
	var registrations atomic.Int32
	cb := helperCallbacks(func(*Connection) { registrations.Add(1); close(entered); <-release })
	const n = 12
	connections := make([]*Connection, n)
	errs := make([]error, n)
	var wg sync.WaitGroup
	wg.Add(n)
	go func() {
		defer wg.Done()
		connections[0], errs[0] = p.GetOrSpawn("tool", cfg, cb)
	}()
	<-entered
	for i := 1; i < n; i++ {
		go func(i int) {
			defer wg.Done()
			connections[i], errs[i] = p.GetOrSpawn("tool", &config.ServiceConfig{Direct: true, Path: "must-not-spawn"}, cb)
		}(i)
	}
	waitForPoolWaiters(t, p, n)
	close(release)
	wg.Wait()
	if registrations.Load() != 1 {
		t.Fatalf("spawn count = %d, want 1", registrations.Load())
	}
	for i := range connections {
		if errs[i] != nil {
			t.Fatalf("caller %d: %v", i, errs[i])
		}
		if connections[i] != connections[0] {
			t.Fatalf("caller %d got %p, want %p", i, connections[i], connections[0])
		}
	}
	p.Shutdown()
}

func TestProcessPoolReapsChildWithDescendantHoldingOutputPipes(t *testing.T) {
	p := NewProcessPool()
	if p.outputDrainTimeout != processOutputDrainTimeout {
		t.Fatalf("output drain timeout = %v, want %v", p.outputDrainTimeout, processOutputDrainTimeout)
	}
	p.outputDrainTimeout = 10 * time.Millisecond
	var rec *childRecord
	cleaned := make(chan struct{})
	cb := helperCallbacks(func(*Connection) { p.mu.Lock(); rec = p.procs["tool"]; p.mu.Unlock() })
	cb.CleanupConn = func(*Connection) { close(cleaned) }
	start := time.Now()
	_, _ = p.GetOrSpawn("tool", &config.ServiceConfig{Direct: true, Path: helperScript(t, "descendant")}, cb)
	if rec == nil {
		t.Fatal("lifecycle record was not observed")
	}
	select {
	case <-rec.done:
	case <-time.After(time.Second):
		t.Fatal("direct child was not reaped")
	}
	select {
	case <-cleaned:
	case <-time.After(time.Second):
		t.Fatal("cleanup blocked on inherited descriptors")
	}
	if p.Get("tool") != nil {
		t.Fatal("reaped direct child remains published")
	}
	if d := time.Since(start); d > time.Second {
		t.Fatalf("reap and cleanup took %v", d)
	}
}

func TestProcessPoolShutdownRacingSpawnLeavesNoChild(t *testing.T) {
	p := NewProcessPool()
	entered, release := make(chan struct{}), make(chan struct{})
	cb := helperCallbacks(func(*Connection) { close(entered); <-release })
	result := make(chan error, 1)
	go func() {
		_, err := p.GetOrSpawn("tool", &config.ServiceConfig{Direct: true, Path: helperScript(t, "healthy")}, cb)
		result <- err
	}()
	<-entered
	shutdown := make(chan struct{})
	go func() { p.Shutdown(); close(shutdown) }()
	waitForPoolShutdown(t, p)
	close(release)
	select {
	case err := <-result:
		if err == nil {
			t.Fatal("spawn racing shutdown succeeded")
		}
	case <-time.After(3 * time.Second):
		t.Fatal("spawn hung")
	}
	select {
	case <-shutdown:
	case <-time.After(3 * time.Second):
		t.Fatal("shutdown did not observe reap")
	}
	if p.Get("tool") != nil {
		t.Fatal("child published after shutdown")
	}
}

func TestProcessPoolGenerationCleanupDoesNotRemoveReplacement(t *testing.T) {
	p := NewProcessPool()
	old := &childRecord{name: "tool", conn: &Connection{ID: "same"}}
	newer := &childRecord{name: "tool", conn: &Connection{ID: "same"}, published: true}
	p.procs["tool"] = newer
	p.cleanupRecord(old, SpawnCallbacks{})
	if p.Get("tool") != newer.conn {
		t.Fatal("old cleanup removed newer generation")
	}
}

func TestAgentCLIForServiceExecutableRequiresExecutableSibling(t *testing.T) {
	dir := t.TempDir()
	serviceExe := filepath.Join(dir, "ez-agent-service")
	candidate := filepath.Join(dir, "ez-agent")

	if got := agentCLIForServiceExecutable(serviceExe); got != "" {
		t.Fatalf("missing sibling returned %q", got)
	}
	if err := os.WriteFile(candidate, []byte("client"), 0o600); err != nil {
		t.Fatal(err)
	}
	if got := agentCLIForServiceExecutable(serviceExe); got != "" {
		t.Fatalf("non-executable sibling returned %q", got)
	}
	if err := os.Chmod(candidate, 0o700); err != nil {
		t.Fatal(err)
	}
	want, err := filepath.Abs(candidate)
	if err != nil {
		t.Fatal(err)
	}
	if got := agentCLIForServiceExecutable(serviceExe); got != want {
		t.Fatalf("agentCLIForServiceExecutable() = %q, want %q", got, want)
	}
}

func TestFilterChildEnvironmentRemovesCredentialsAndPreservesOperationSettings(t *testing.T) {
	input := []string{
		"XDG_CONFIG_HOME=/config", "XDG_STATE_HOME=/state", "LANG=en_US.UTF-8", "LC_TIME=C", "PATH=/bin",
		"OPENAI_API_KEY=openai-secret", "CUSTOM_ACCESS_TOKEN=token-secret", "DATABASE_PASSWORD=password-secret",
		"HTTPS_PROXY=http://proxy-user:proxy-pass@example.test:8443", "http_proxy=proxy-user:proxy-pass@example.test:8080",
		"NO_PROXY=localhost,.internal", "no_proxy=127.0.0.1", "AGENTCLI=/stale", "SERVICE_SETTING=retained",
	}
	input = append(input, "RELAY_KEY=relay-secret", "HF_TOKEN=hf-secret", "AZURE_CLIENT_SECRET=azure-secret")
	got := filterChildEnvironment(input, "RELAY_KEY")
	joined := strings.Join(got, "\n")
	for _, retained := range []string{"XDG_CONFIG_HOME=/config", "XDG_STATE_HOME=/state", "LANG=en_US.UTF-8", "LC_TIME=C", "PATH=/bin", "SERVICE_SETTING=retained", "HTTPS_PROXY=http://example.test:8443", "http_proxy=example.test:8080", "NO_PROXY=localhost,.internal", "no_proxy=127.0.0.1"} {
		if !strings.Contains(joined, retained) {
			t.Errorf("required environment entry removed: %s; got %v", retained, got)
		}
	}
	for _, secret := range []string{"openai-secret", "token-secret", "password-secret", "proxy-user", "/stale", "relay-secret", "hf-secret", "azure-secret"} {
		if strings.Contains(joined, secret) {
			t.Errorf("credential leaked into child environment: %q in %v", secret, got)
		}
	}
}

func TestServiceSpawnCallbacksUseCurrentConfiguredCredentialNames(t *testing.T) {
	s := NewServer(&config.Config{Auth: map[string]config.AuthProvider{"relay": {APIKeyEnv: "RELAY_KEY"}}}, nil)
	callback := s.serviceSpawnCallbacks().CredentialEnvironmentNames
	if callback == nil {
		t.Fatal("spawn credential-name callback is nil")
	}
	if got := strings.Join(callback(), ","); got != "RELAY_KEY" {
		t.Fatalf("spawn credential names = %q", got)
	}
	s.mu.Lock()
	s.config = &config.Config{Auth: map[string]config.AuthProvider{"next": {APIKeyEnv: "NEXT_KEY"}}}
	s.mu.Unlock()
	if got := strings.Join(callback(), ","); got != "NEXT_KEY" {
		t.Fatalf("reloaded spawn credential names = %q", got)
	}
}

func TestConfiguredCredentialEnvironmentNamesDoNotReachChildProcess(t *testing.T) {
	if os.Getenv("EZ_AGENT_CREDENTIAL_ENV_HELPER") != "" {
		for _, name := range []string{"RELAY_KEY", "HF_TOKEN", "AZURE_CLIENT_SECRET"} {
			if os.Getenv(name) != "" {
				fmt.Print("leaked " + name)
			}
		}
		return
	}
	t.Setenv("RELAY_KEY", "arbitrary-configured-secret")
	t.Setenv("HF_TOKEN", "conventional-token")
	t.Setenv("AZURE_CLIENT_SECRET", "conventional-secret")
	cmd := exec.Command(os.Args[0], "-test.run=^TestConfiguredCredentialEnvironmentNamesDoNotReachChildProcess$")
	cmd.Env = append(directChildEnvironment("RELAY_KEY"), "EZ_AGENT_CREDENTIAL_ENV_HELPER=1")
	output, err := cmd.CombinedOutput()
	if err != nil || strings.Contains(string(output), "leaked ") {
		t.Fatalf("credential-filter child = %q, %v", output, err)
	}
}

func TestFilteredChildProxyEnvironmentPreservesRoutingAndBypass(t *testing.T) {
	if os.Getenv("EZ_AGENT_CHILD_PROXY_HELPER") != "" {
		response, err := http.Get(os.Getenv("EZ_AGENT_CHILD_PROXY_TARGET"))
		if err != nil {
			t.Fatal(err)
		}
		defer response.Body.Close()
		body, err := io.ReadAll(response.Body)
		if err != nil {
			t.Fatal(err)
		}
		fmt.Print(string(body))
		return
	}

	proxy := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if r.Header.Get("Proxy-Authorization") != "" {
			t.Error("proxy credentials reached child request")
		}
		_, _ = io.WriteString(w, "proxy")
	}))
	defer proxy.Close()
	direct := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		_, _ = io.WriteString(w, "direct")
	}))
	defer direct.Close()

	proxyURL := strings.Replace(proxy.URL, "http://", "http://proxy-user:proxy-pass@", 1)
	for _, test := range []struct {
		name, proxyName, noProxyName, target, want string
	}{
		{"uppercase proxy", "HTTP_PROXY", "NO_PROXY", "http://provider.invalid/resource", "proxy"},
		{"lowercase bypass", "http_proxy", "no_proxy", direct.URL, "direct"},
	} {
		t.Run(test.name, func(t *testing.T) {
			env := filterChildEnvironment([]string{
				"EZ_AGENT_CHILD_PROXY_HELPER=1", "EZ_AGENT_CHILD_PROXY_TARGET=" + test.target,
				test.proxyName + "=" + proxyURL, test.noProxyName + "=127.0.0.1",
			})
			cmd := exec.Command(os.Args[0], "-test.run=^TestFilteredChildProxyEnvironmentPreservesRoutingAndBypass$")
			cmd.Env = env
			output, err := cmd.CombinedOutput()
			if err != nil || !strings.HasPrefix(string(output), test.want) {
				t.Fatalf("child proxy operation = %q, %v; want prefix %q", output, err, test.want)
			}
			if strings.Contains(string(output), "proxy-user") || strings.Contains(string(output), "proxy-pass") {
				t.Fatalf("proxy credentials leaked: %q", output)
			}
		})
	}
}

func TestShutdownWaitsForAdmittedPreStartRecord(t *testing.T) {
	p := NewProcessPool()
	rec := &childRecord{
		name:     "starting",
		done:     make(chan struct{}),
		finished: make(chan struct{}),
	}
	p.procs[rec.name] = rec
	returned := make(chan struct{})
	go func() {
		p.Shutdown()
		close(returned)
	}()
	select {
	case <-returned:
		t.Fatal("shutdown returned before admitted startup completed")
	case <-time.After(50 * time.Millisecond):
	}
	rec.markFinished()
	select {
	case <-returned:
	case <-time.After(time.Second):
		t.Fatal("shutdown did not observe startup lifecycle completion")
	}
}

func TestResolveServicePathRules(t *testing.T) {
	home := t.TempDir()
	t.Setenv("HOME", home)
	got, err := resolveServicePath("~/services/test.rb")
	if err != nil {
		t.Fatal(err)
	}
	if want := filepath.Join(home, "services", "test.rb"); got != want {
		t.Fatalf("tilde path = %q, want %q", got, want)
	}
	absolute := filepath.Join(t.TempDir(), "service")
	if got, err := resolveServicePath(absolute); err != nil || got != absolute {
		t.Fatalf("absolute path = %q, %v", got, err)
	}
	if _, err := resolveServicePath("~other/service"); err == nil {
		t.Fatal("~user path accepted")
	}

	exe, err := os.Executable()
	if err != nil {
		t.Fatal(err)
	}
	physical, err := filepath.EvalSymlinks(exe)
	if err != nil {
		physical, _ = filepath.Abs(exe)
	}
	if got, err := resolveServicePath("sibling-service"); err != nil || got != filepath.Join(filepath.Dir(physical), "sibling-service") {
		t.Fatalf("sibling path = %q, %v", got, err)
	}
	if _, err := resolveServicePath("../escape"); err == nil {
		t.Fatal("escaping relative path accepted")
	}
}

func TestServiceCommandPreservesArgsAndBuildsRubyInvocation(t *testing.T) {
	nativePath := filepath.Join(t.TempDir(), "native")
	native, err := serviceCommand(&config.ServiceConfig{Path: nativePath, Args: []string{"", "~/literal", "same", "same"}})
	if err != nil {
		t.Fatal(err)
	}
	wantNative := []string{nativePath, "", "~/literal", "same", "same"}
	if fmt.Sprint(native.Args) != fmt.Sprint(wantNative) {
		t.Fatalf("native argv = %#v, want %#v", native.Args, wantNative)
	}

	script := filepath.Join(t.TempDir(), "service.rb")
	ruby, err := serviceCommand(&config.ServiceConfig{Path: script, Ruby: true, Args: []string{"--flag", "value"}})
	if err != nil {
		t.Fatal(err)
	}
	launcher, err := resolveServicePath("ez-agent-ruby")
	if err != nil {
		t.Fatal(err)
	}
	wantRuby := []string{launcher, script, "--flag", "value"}
	if fmt.Sprint(ruby.Args) != fmt.Sprint(wantRuby) {
		t.Fatalf("ruby argv = %#v, want %#v", ruby.Args, wantRuby)
	}
}

func TestProcessPoolStartsAndStopsBackgroundService(t *testing.T) {
	p := NewProcessPool()
	helper := filepath.Join(t.TempDir(), "background")
	if err := os.WriteFile(helper, []byte("#!/bin/sh\necho ready\necho diagnostic >&2\nsleep 30\n"), 0o700); err != nil {
		t.Fatal(err)
	}
	if err := p.StartService("background", &config.ServiceConfig{Path: helper, OnStart: true}, SpawnCallbacks{}); err != nil {
		t.Fatal(err)
	}
	p.mu.Lock()
	rec := p.procs["background"]
	p.mu.Unlock()
	if rec == nil || !rec.published || rec.conn != nil {
		t.Fatalf("background record = %+v", rec)
	}
	p.Shutdown()
	select {
	case <-rec.done:
	case <-time.After(3 * time.Second):
		t.Fatal("background service was not reaped")
	}
}

func TestProcessPoolRejectsLazyStartForNonDirectService(t *testing.T) {
	p := NewProcessPool()
	if _, err := p.GetOrSpawn("background", &config.ServiceConfig{Path: "/unused"}, SpawnCallbacks{}); err == nil {
		t.Fatal("non-direct service accepted by lazy JSONL path")
	}
}

func TestSpawnedRestartUsesFreshConnectionIdentity(t *testing.T) {
	cfg := &config.Config{Services: map[string]config.ServiceConfig{"worker": {Direct: true, Path: helperScript(t, "healthy"), Tools: []string{"worker.tool"}}}}
	s := NewServer(cfg, nil)
	defer s.pool.Shutdown()
	allocated := make([]string, 0, 3)
	s.connectionID = func() string { id := freshConnectionID(); allocated = append(allocated, id); return id }
	service := cfg.Services["worker"]
	first, err := s.ensureDirectConn("worker", &service)
	if err != nil {
		t.Fatal(err)
	}
	s.pool.mu.Lock()
	record := s.pool.procs["worker"]
	s.pool.mu.Unlock()
	if err := first.apiConn.Close(); err != nil {
		t.Fatal(err)
	}
	receive(t, record.finished)
	second, err := s.ensureDirectConn("worker", &service)
	if err != nil {
		t.Fatal(err)
	}
	if first.ID == second.ID || first.Name != second.Name {
		t.Fatalf("restart identities: %s/%s -> %s/%s", first.Name, first.ID, second.Name, second.ID)
	}
	serverNet, peerNet := net.Pipe()
	defer peerNet.Close()
	incoming := s.registerIncomingConnection(serverNet)
	defer incoming.apiConn.Close()
	if len(allocated) != 3 || allocated[0] != first.ID || allocated[1] != second.ID || allocated[2] != incoming.ID {
		t.Fatalf("allocation policy bypassed: %v", allocated)
	}
	// The old process record and connection cannot remove the new lifetime.
	s.pool.Remove(first)
	s.cleanupConnection(first)
	if !s.isCurrentConnection(second) {
		t.Fatal("old cleanup removed restarted provider")
	}
	provider, _, err := s.registry.FindTool("worker.tool")
	if err != nil || provider.ConnID != second.ID {
		t.Fatalf("restarted claim = %+v, %v", provider, err)
	}
}

func TestProcessConnectionIdentityDoesNotDependOnServiceOrPID(t *testing.T) {
	// The spawn constructor also handles OS PID reuse. These diagnostic Process
	// values are never started, signalled, or registered with the process pool.
	first := newProcessConnection("worker", &os.Process{Pid: 123}, config.ServiceConfig{}, freshConnectionID)
	second := newProcessConnection("worker", &os.Process{Pid: 123}, config.ServiceConfig{}, freshConnectionID)
	if first.ID == second.ID || !strings.HasPrefix(first.ID, "c_") || !strings.HasPrefix(second.ID, "c_") {
		t.Fatalf("same service/PID reused connection identity: %q, %q", first.ID, second.ID)
	}
}