Skip to content

Commit 5b84186

Browse files
committed
Bound CLI metadata probes and duplex process IO
1 parent 0cfcbb6 commit 5b84186

9 files changed

Lines changed: 382 additions & 40 deletions

File tree

‎.github/workflows/release.yml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ jobs:
3535
fi
3636
3737
while (( SECONDS < deadline )); do
38-
run=$(gh api "repos/${GITHUB_REPOSITORY}/actions/runs" \
38+
run=$(gh api --method GET "repos/${GITHUB_REPOSITORY}/actions/runs" \
3939
-f head_sha="$GITHUB_SHA" \
4040
-F per_page=100 \
4141
--jq "[.workflow_runs[] | select(.workflow_id == $ci_workflow_id and .head_sha == \"$GITHUB_SHA\" and .head_branch == \"main\" and .event == \"push\")] | sort_by(.created_at) | last // empty")

‎CodexSharpSDK.Tests/Unit/CodexClientTests.cs‎

Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
using System.Diagnostics;
12
using ManagedCode.CodexSharpSDK.Client;
23
using ManagedCode.CodexSharpSDK.Configuration;
34
using ManagedCode.CodexSharpSDK.Execution;
@@ -25,6 +26,11 @@ public class CodexClientTests
2526
private const string DotCodexDirectoryName = ".codex";
2627
private const string CodexConfigFileName = "config.toml";
2728
private const string CodexModelsCacheFileName = "models_cache.json";
29+
private const string MetadataLeaseScriptFileName = "codex-metadata-lease.sh";
30+
private const string MetadataLeaseMarkerFileName = "metadata-lease-starts.txt";
31+
private const string MetadataLeaseProbeCommandTemplate = "#!/bin/sh\nprintf 'started\\n' >> '{0}'\nsleep 2\nprintf 'codex 0.0.1\\n'\n";
32+
private const string MetadataLeaseProbePathPlaceholder = "{0}";
33+
private const string ProbeLeaseBusyMessage = "CLI metadata process probe could not acquire its bounded process lease.";
2834
private const int SmallMetadataFileLimit = 256;
2935
private const string MetadataFileLimitMessage = "CLI metadata file exceeded the configured character limit.";
3036
private const string CodexConfigFixture = "model = \"" + CodexModels.Gpt53Codex + "\"";
@@ -354,6 +360,84 @@ public async Task CodexCli_GetCliMetadata_UsesExplicitHomeFallbackWhenInheritanc
354360
}
355361
}
356362

363+
[Test]
364+
[NotInParallel]
365+
public async Task CodexCli_MetadataLeaseTimeoutIsIndependentAndPreventsSecondProbeStart()
366+
{
367+
if (OperatingSystem.IsWindows())
368+
{
369+
Skip.Test("The metadata lease fixture uses a POSIX executable script.");
370+
return;
371+
}
372+
373+
var sandbox = CreateMetadataSandbox();
374+
var markerPath = Path.Combine(sandbox, MetadataLeaseMarkerFileName);
375+
var executablePath = Path.Combine(sandbox, MetadataLeaseScriptFileName);
376+
File.WriteAllText(executablePath, MetadataLeaseProbeCommandTemplate.Replace(
377+
MetadataLeaseProbePathPlaceholder,
378+
markerPath,
379+
StringComparison.Ordinal));
380+
File.SetUnixFileMode(executablePath, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute);
381+
var environment = new Dictionary<string, string>(StringComparer.Ordinal)
382+
{
383+
[PathEnvironmentVariable] = Environment.GetEnvironmentVariable(PathEnvironmentVariable) ?? string.Empty,
384+
};
385+
using var firstClient = new CodexClient(new CodexOptions
386+
{
387+
CodexExecutablePath = executablePath,
388+
EnvironmentVariables = environment,
389+
InheritEnvironmentVariables = false,
390+
CliMetadataProbeTimeout = TimeSpan.FromSeconds(5),
391+
CliMetadataProbeLeaseTimeout = TimeSpan.FromSeconds(5),
392+
});
393+
using var secondClient = new CodexClient(new CodexOptions
394+
{
395+
CodexExecutablePath = executablePath,
396+
EnvironmentVariables = environment,
397+
InheritEnvironmentVariables = false,
398+
CliMetadataProbeTimeout = TimeSpan.FromSeconds(5),
399+
CliMetadataProbeLeaseTimeout = TimeSpan.FromMilliseconds(100),
400+
});
401+
402+
try
403+
{
404+
var firstProbe = Task.Run(firstClient.GetCliMetadata);
405+
var started = Stopwatch.StartNew();
406+
while (!File.Exists(markerPath) && started.Elapsed < TimeSpan.FromSeconds(3))
407+
{
408+
await Task.Delay(TimeSpan.FromMilliseconds(10));
409+
}
410+
411+
await Assert.That(File.Exists(markerPath)).IsTrue();
412+
var secondProbe = () => secondClient.GetCliMetadata();
413+
var exception = await Assert.That(secondProbe).ThrowsException();
414+
415+
await Assert.That(exception).IsTypeOf<InvalidOperationException>();
416+
await Assert.That(exception!.Message).IsEqualTo(ProbeLeaseBusyMessage);
417+
await Assert.That(started.Elapsed).IsLessThan(TimeSpan.FromSeconds(2));
418+
var result = await firstProbe.WaitAsync(TimeSpan.FromSeconds(5));
419+
await Assert.That(result.InstalledVersion).IsEqualTo("codex 0.0.1");
420+
await Assert.That(File.ReadAllLines(markerPath)).Count().IsEqualTo(1);
421+
}
422+
finally
423+
{
424+
Directory.Delete(sandbox, recursive: true);
425+
}
426+
}
427+
428+
[Test]
429+
public async Task CodexCli_GetCliMetadataRejectsNonPositiveProbeLeaseTimeout()
430+
{
431+
foreach (var timeout in new[] { TimeSpan.Zero, TimeSpan.FromMilliseconds(-1) })
432+
{
433+
using var client = new CodexClient(new CodexOptions { CliMetadataProbeLeaseTimeout = timeout });
434+
var action = () => client.GetCliMetadata();
435+
var exception = await Assert.That(action).ThrowsException();
436+
437+
await Assert.That(exception).IsTypeOf<ArgumentOutOfRangeException>();
438+
}
439+
}
440+
357441
[Test]
358442
public async Task CodexCli_GetCliMetadata_RejectsOversizedConfigLine()
359443
{

‎CodexSharpSDK.Tests/Unit/CodexExecTests.cs‎

Lines changed: 118 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,11 @@ public class CodexExecTests
1414
{
1515
private const string LongRunningCliScript = "#!/bin/sh\necho $$\nexec /bin/sleep 30\n";
1616
private const string DescendantHoldingStderrScript = "/usr/bin/setsid /bin/sleep 30 >&2 & echo $!; exit 0";
17+
private const string DescendantHoldingStderrWhileParentRunsScript =
18+
"/usr/bin/setsid /bin/sleep 30 >&2 & echo $!; exec /bin/sleep 30";
19+
private const string WindowsDuplexStdinCommandTemplate = "$pressure = 'o' * {0}; [Console]::Out.WriteLine($pressure); [Console]::Out.Flush(); [Console]::Error.WriteLine(('e' * {0})); [Console]::Error.Flush(); $prompt = [Console]::In.ReadToEnd(); [Console]::Out.Write($prompt); [Console]::Out.WriteLine(\"stdin-length:$($prompt.Length)\"); [Console]::Out.WriteLine('stdin-eof')";
20+
private const string PosixDuplexStdinScriptTemplate = "head -c {0} /dev/zero | tr '\\000' 'o'; printf '\\n'; head -c {0} /dev/zero | tr '\\000' 'e' >&2; printf '\\n' >&2; prompt=$(cat); printf '%s\\n' \"$prompt\"; printf 'stdin-length:%s\\n' \"${#prompt}\"; printf 'stdin-eof\\n'";
21+
private const string DuplexPressureTemplatePlaceholder = "{0}";
1722
private const string PosixFixtureSkipReason = "The public CLI yield-boundary fixture currently uses a POSIX executable script.";
1823
private const string LinuxFixtureSkipReason = "The detached stderr-retention fixture requires Linux setsid.";
1924
private const string StderrClosureFailure = "stderr stream closed";
@@ -34,12 +39,119 @@ public class CodexExecTests
3439
private const string ExpectedSecondLine = "second";
3540
private const int SmallOutputLimitCharacters = 64;
3641
private const int AggregateOutputLimitCharacters = 24;
42+
private const int DuplexPipePressureCharacters = 131072;
43+
private const int DuplexPromptCharacters = 262144;
44+
private const int DuplexMaximumProcessOutputCharacters = 1048576;
45+
private static readonly TimeSpan ProcessOutputCleanupAssertionBound = TimeSpan.FromSeconds(8);
3746
private const string TestInput = "test";
3847
private const string CancellationScriptFileName = "codex-cancel.sh";
3948
private const string MissingExecutableNamePrefix = "missing-codex-cli-";
4049
private const string PosixShellPath = "/bin/sh";
4150
private const string PosixShellCommandFlag = "-c";
4251

52+
[Test]
53+
public async Task DefaultProcessRunner_DrainsBothOutputPipesWhileWritingLargePrompt()
54+
{
55+
var sandboxDirectory = CreateSandboxDirectory();
56+
var prompt = new string('p', DuplexPromptCharacters);
57+
58+
try
59+
{
60+
var invocation = OperatingSystem.IsWindows()
61+
? new CodexProcessInvocation(
62+
WindowsPowerShellPath,
63+
[
64+
WindowsNoProfileFlag,
65+
WindowsNonInteractiveFlag,
66+
WindowsCommandFlag,
67+
WindowsDuplexStdinCommandTemplate.Replace(
68+
DuplexPressureTemplatePlaceholder,
69+
DuplexPipePressureCharacters.ToString(CultureInfo.InvariantCulture),
70+
StringComparison.Ordinal),
71+
],
72+
CreateProcessEnvironment(),
73+
prompt)
74+
: CreateShellScript(
75+
sandboxDirectory,
76+
"duplex-stdin",
77+
PosixDuplexStdinScriptTemplate.Replace(
78+
DuplexPressureTemplatePlaceholder,
79+
DuplexPipePressureCharacters.ToString(CultureInfo.InvariantCulture),
80+
StringComparison.Ordinal))
81+
.Invocation with
82+
{ Input = prompt };
83+
invocation = invocation with { MaximumProcessOutputCharacters = DuplexMaximumProcessOutputCharacters };
84+
var runner = new DefaultCodexProcessRunner();
85+
86+
var lines = await DrainToListAsync(runner.RunAsync(invocation, NullLogger.Instance, CancellationToken.None));
87+
88+
await Assert.That(lines).Contains(prompt);
89+
await Assert.That(lines).Contains(new string('o', DuplexPipePressureCharacters));
90+
await Assert.That(lines).Contains($"stdin-length:{prompt.Length}");
91+
await Assert.That(lines).Contains("stdin-eof");
92+
}
93+
finally
94+
{
95+
Directory.Delete(sandboxDirectory, recursive: true);
96+
}
97+
}
98+
99+
[Test]
100+
public async Task CancellationWithDescendantHoldingStderrSurfacesUnconfirmedCleanup()
101+
{
102+
if (!OperatingSystem.IsLinux())
103+
{
104+
Skip.Test(LinuxFixtureSkipReason);
105+
return;
106+
}
107+
108+
using var cancellation = new CancellationTokenSource();
109+
var standardErrorReaderCompleted = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
110+
var standardOutputReadCompleted = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
111+
var invocation = new CodexProcessInvocation(
112+
PosixShellPath,
113+
[PosixShellCommandFlag, DescendantHoldingStderrWhileParentRunsScript],
114+
CreateProcessEnvironment(),
115+
string.Empty)
116+
{
117+
ProcessTerminationTimeout = TimeSpan.FromMilliseconds(250),
118+
StandardErrorReaderCompleted = () => standardErrorReaderCompleted.TrySetResult(),
119+
StandardOutputReadCompleted = () => standardOutputReadCompleted.TrySetResult(),
120+
};
121+
var runner = new DefaultCodexProcessRunner();
122+
await using var enumerator = runner.RunAsync(invocation, NullLogger.Instance, cancellation.Token)
123+
.GetAsyncEnumerator(cancellation.Token);
124+
var childProcessId = 0;
125+
126+
try
127+
{
128+
await Assert.That(await enumerator.MoveNextAsync()).IsTrue();
129+
childProcessId = int.Parse(enumerator.Current, CultureInfo.InvariantCulture);
130+
cancellation.Cancel();
131+
132+
var action = async () => await enumerator.MoveNextAsync().AsTask().WaitAsync(TimeSpan.FromSeconds(3));
133+
var exception = await Assert.That(action).ThrowsException();
134+
135+
await Assert.That(exception).IsTypeOf<InvalidOperationException>();
136+
await Assert.That(exception!.Message).Contains(StderrClosureFailure);
137+
await standardOutputReadCompleted.Task.WaitAsync(TimeSpan.FromSeconds(1));
138+
await standardErrorReaderCompleted.Task.WaitAsync(TimeSpan.FromSeconds(1));
139+
}
140+
finally
141+
{
142+
try
143+
{
144+
using var child = Process.GetProcessById(childProcessId);
145+
child.Kill(entireProcessTree: true);
146+
await child.WaitForExitAsync().WaitAsync(TimeSpan.FromSeconds(5));
147+
}
148+
catch (ArgumentException)
149+
{
150+
// The detached fixture child already exited.
151+
}
152+
}
153+
}
154+
43155
[Test]
44156
public async Task DefaultProcessRunner_PreservesMultilineOutputWithinConfiguredBudget()
45157
{
@@ -87,19 +199,19 @@ public async Task DefaultProcessRunner_RejectsAggregateMultilineOutputAboveConfi
87199
[Test]
88200
public async Task DefaultProcessRunner_StandardErrorPressureStopsQuietRootWithinBound()
89201
{
202+
var stopwatch = new Stopwatch();
90203
var invocation = CreateOutputInvocation(
91204
OperatingSystem.IsWindows() ? WindowsStandardErrorPressureCommand : PosixStandardErrorPressureCommand,
92-
TimeSpan.FromSeconds(2), SmallOutputLimitCharacters);
205+
TimeSpan.FromSeconds(2), SmallOutputLimitCharacters, stopwatch.Start);
93206
var runner = new DefaultCodexProcessRunner();
94-
var stopwatch = Stopwatch.StartNew();
95207
var action = async () => await DrainToListAsync(runner.RunAsync(invocation, NullLogger.Instance, CancellationToken.None));
96208

97209
var exception = await Assert.That(action).ThrowsException();
98210
stopwatch.Stop();
99211

100212
await Assert.That(exception).IsTypeOf<InvalidOperationException>();
101213
await Assert.That(exception!.Message).Contains(ProcessOutputLimitMessage);
102-
await Assert.That(stopwatch.Elapsed < TimeSpan.FromSeconds(5)).IsTrue();
214+
await Assert.That(stopwatch.Elapsed < ProcessOutputCleanupAssertionBound).IsTrue();
103215
}
104216

105217
[Test]
@@ -679,7 +791,8 @@ private static string CreateSandboxDirectory()
679791
private static CodexProcessInvocation CreateOutputInvocation(
680792
string command,
681793
TimeSpan processTerminationTimeout,
682-
int maximumProcessOutputCharacters)
794+
int maximumProcessOutputCharacters,
795+
Action? standardErrorOutputLimitExceeded = null)
683796
{
684797
return new CodexProcessInvocation(
685798
OperatingSystem.IsWindows() ? WindowsPowerShellPath : PosixShellPath,
@@ -691,6 +804,7 @@ private static CodexProcessInvocation CreateOutputInvocation(
691804
{
692805
ProcessTerminationTimeout = processTerminationTimeout,
693806
MaximumProcessOutputCharacters = maximumProcessOutputCharacters,
807+
StandardErrorOutputLimitExceeded = standardErrorOutputLimitExceeded,
694808
};
695809
}
696810

‎CodexSharpSDK/Client/CodexClient.cs‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -62,22 +62,25 @@ public CodexThread ResumeThread(string id, ThreadOptions? options = null)
6262
public CodexCliMetadata GetCliMetadata()
6363
{
6464
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(_options.CliMetadataMaximumFileCharacters);
65+
ArgumentOutOfRangeException.ThrowIfLessThanOrEqual(_options.CliMetadataProbeLeaseTimeout, TimeSpan.Zero);
6566
var executablePath = CodexCliLocator.FindCodexPath(_options.CodexExecutablePath);
6667
using var exec = CreateExec();
6768
return CodexCliMetadataReader.Read(executablePath, exec.BuildEnvironment(_options.BaseUrl, _options.ApiKey),
6869
_options.InheritEnvironmentVariables ?? _options.EnvironmentVariables is null,
6970
_options.CliMetadataProbeTimeout, _options.CliMetadataMaximumOutputCharacters,
70-
_options.CliMetadataMaximumFileCharacters);
71+
_options.CliMetadataMaximumFileCharacters, _options.CliMetadataProbeLeaseTimeout);
7172
}
7273

7374
public CodexCliUpdateStatus GetCliUpdateStatus()
7475
{
76+
ArgumentOutOfRangeException.ThrowIfLessThanOrEqual(_options.CliMetadataProbeLeaseTimeout, TimeSpan.Zero);
7577
var executablePath = CodexCliLocator.FindCodexPath(_options.CodexExecutablePath);
7678
using var exec = CreateExec();
7779
return CodexCliMetadataReader.ReadUpdateStatus(executablePath,
7880
exec.BuildEnvironment(_options.BaseUrl, _options.ApiKey),
7981
_options.InheritEnvironmentVariables ?? _options.EnvironmentVariables is null,
80-
_options.CliMetadataProbeTimeout, _options.CliMetadataMaximumOutputCharacters);
82+
_options.CliMetadataProbeTimeout, _options.CliMetadataMaximumOutputCharacters,
83+
_options.CliMetadataProbeLeaseTimeout);
8184
}
8285

8386
public void Dispose() => _connectionState.Dispose();

‎CodexSharpSDK/Configuration/CodexOptions.cs‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,8 @@ public sealed record CodexOptions
99

1010
public static TimeSpan DefaultCliMetadataProbeTimeout { get; } = TimeSpan.FromSeconds(10);
1111

12+
public static TimeSpan DefaultCliMetadataProbeLeaseTimeout { get; } = TimeSpan.FromMinutes(2);
13+
1214
public const int DefaultCliMetadataMaximumOutputCharacters = 65536;
1315

1416
public const int DefaultCliMetadataMaximumFileCharacters = 1048576;
@@ -29,6 +31,8 @@ public sealed record CodexOptions
2931

3032
public TimeSpan CliMetadataProbeTimeout { get; init; } = DefaultCliMetadataProbeTimeout;
3133

34+
public TimeSpan CliMetadataProbeLeaseTimeout { get; init; } = DefaultCliMetadataProbeLeaseTimeout;
35+
3236
public int CliMetadataMaximumOutputCharacters { get; init; } = DefaultCliMetadataMaximumOutputCharacters;
3337

3438
public int CliMetadataMaximumFileCharacters { get; init; } = DefaultCliMetadataMaximumFileCharacters;

0 commit comments

Comments
 (0)