Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -293,6 +293,70 @@ public async Task CompileAsync_WhenSharedWorkerBuildFails_ShouldFallbackToOneSho
}
}

/// <summary>
/// Verifies a lifecycle transition during worker startup silently falls back to one-shot Roslyn.
/// </summary>
[Test]
public async Task CompileAsync_WhenWorkerLifecycleClosesDuringStartup_ShouldFallbackWithoutErrorLogs()
{
ExternalCompilerPaths externalCompilerPaths = ExternalCompilerPathResolver.Resolve();
Assert.That(externalCompilerPaths, Is.Not.Null, "Unity external compiler layout should be available.");

string sourcePath = Path.Combine(_tempDirectoryPath, "LifecycleFallbackSmoke.cs");
string dllPath = Path.Combine(_tempDirectoryPath, "LifecycleFallbackSmoke.dll");
File.WriteAllText(
sourcePath,
"public static class LifecycleFallbackSmoke { public static int Execute() { return 11; } }");
List<string> references = new DynamicReferenceSetBuilderService().BuildReferenceSet(
new List<string>(),
null,
externalCompilerPaths);
int buildCount = 0;
bool buildStarted = false;
bool buildFinished = false;

DynamicCompilationHealthMonitor.ResetForTests();
SharedRoslynCompilerWorkerHost.ShutdownForTests();
LogAssert.NoUnexpectedReceived();

Func<ExternalCompilerPaths, string, string, string, CompilerMessage[]> previousWorkerCompiler =
SharedRoslynCompilerWorkerHost.SwapWorkerAssemblyCompilerForTests(
(ExternalCompilerPaths paths, string workerSourcePath, string workerAssemblyPath, string workerCompileResponseFilePath) =>
{
SharedRoslynCompilerWorkerHost.ShutdownForTests();
return Array.Empty<CompilerMessage>();
});

try
{
using CancellationTokenSource compileCancellationTokenSource = new CancellationTokenSource();
compileCancellationTokenSource.CancelAfter(FallbackCompileTimeoutMilliseconds);
DynamicCompilationBackendResult result = await RoslynCompilerBackend.CompileAsync(
sourcePath,
dllPath,
references,
externalCompilerPaths,
new RoslynCompilerOptions(Array.Empty<string>(), false),
compileCancellationTokenSource.Token,
() => buildStarted = true,
() => buildFinished = true,
() => buildCount++);

Assert.That(result, Is.Not.Null);
Assert.That(result.BackendKind, Is.EqualTo(DynamicCompilationBackendKind.OneShotRoslyn));
Assert.That(File.Exists(dllPath), Is.True);
Assert.That(buildCount, Is.EqualTo(1));
Assert.That(buildStarted, Is.True);
Assert.That(buildFinished, Is.True);
LogAssert.NoUnexpectedReceived();
}
finally
{
SharedRoslynCompilerWorkerHost.SwapWorkerAssemblyCompilerForTests(previousWorkerCompiler);
SharedRoslynCompilerWorkerHost.ShutdownForTests();
}
}

[Test]
public void ReportInfrastructureFallback_WhenCompilerPathLayoutIsKnown_ShouldIncludeLayoutKind()
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
using System.Text;
using System.Threading.Tasks;
using NUnit.Framework;
using UnityEngine.TestTools;
using UnityEditor.Compilation;

using io.github.hatayama.UnityCliLoop.FirstPartyTools;
Expand All @@ -17,6 +18,35 @@ namespace io.github.hatayama.UnityCliLoop.Tests.Editor.DynamicCodeToolTests
[TestFixture]
public class SharedRoslynCompilerWorkerHostTests
{
/// <summary>
/// Verifies lifecycle closure is returned as a non-error compile outcome.
/// </summary>
[Test]
public void SharedWorkerCompileOutcome_WhenLifecycleCloses_ShouldCarryLifecycleClosedReason()
{
SharedWorkerCompileOutcome outcome = SharedWorkerCompileOutcome.Failed(
SharedWorkerFailureReasons.LifecycleClosed,
new { reason = "lifecycle_generation_advanced" });

Assert.That(outcome.Succeeded, Is.False);
Assert.That(outcome.FailureReason, Is.EqualTo(SharedWorkerFailureReasons.LifecycleClosed));
Assert.That(outcome.IsLifecycleClosed, Is.True);
}

/// <summary>
/// Verifies non-lifecycle worker failures retain their failure reason for error reporting.
/// </summary>
[Test]
public void SharedWorkerCompileOutcome_WhenWorkerStartFails_ShouldCarryFailureReason()
{
SharedWorkerCompileOutcome outcome = SharedWorkerCompileOutcome.Failed(
"worker_start_failed",
new { reason = "process_start_failed" });

Assert.That(outcome.Succeeded, Is.False);
Assert.That(outcome.FailureReason, Is.EqualTo("worker_start_failed"));
}

[Test]
public void ConfigureWorkerDotnetRuntimeEnvironment_WhenCalled_ShouldDisableMultilevelLookup()
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,15 @@ public static void ReportSharedWorkerFailure(string reason, object context = nul
"Investigate worker startup, request handling, and Unity-version-specific runtime assumptions.");
}

public static void ReportSharedWorkerLifecycleClosed(object context = null)
{
LogInfoOnce(
SharedWorkerFailureReasons.LifecycleClosed,
"dynamic_code_shared_worker_lifecycle_closed",
"execute-dynamic-code shared Roslyn worker closed during an expected Unity lifecycle transition",
context ?? new { reason = SharedWorkerFailureReasons.LifecycleClosed });
}

public static void ReportOneShotCompilerStartFailure(object context)
{
LogErrorOnce(
Expand Down Expand Up @@ -101,6 +110,25 @@ private static void LogErrorOnce(
Debug.LogError(FormatConsoleErrorMessage(operation, message, context));
}

private static void LogInfoOnce(
string issueKey,
string operation,
string message,
object context)
{
string effectiveIssueKey = CreateEffectiveIssueKey(issueKey);

lock (ReportedIssueLock)
{
if (!ReportedIssues.Add(effectiveIssueKey))
{
return;
}
}

VibeLogger.LogInfo(operation, message, context);
}

private static string CreateEffectiveIssueKey(string issueKey)
{
Debug.Assert(!string.IsNullOrEmpty(issueKey), "issueKey must not be empty");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,29 +71,33 @@ public static async Task<DynamicCompilationBackendResult> CompileAsync(
defineSymbols,
allowUnsafeCode);

CompilerMessage[] workerMessages = await SharedRoslynCompilerWorkerHost.TryCompileAsync(
SharedWorkerCompileOutcome workerOutcome = await SharedRoslynCompilerWorkerHost.TryCompileAsync(
workerRequestFilePath,
externalCompilerPaths,
ct,
markBuildStarted,
markBuildFinished,
incrementBuildCount).ConfigureAwait(false);
if (workerMessages != null)
UnityEngine.Debug.Assert(workerOutcome != null, "Shared worker compile outcome must not be null");
if (workerOutcome.Succeeded)
{
return new DynamicCompilationBackendResult(
workerMessages,
workerOutcome.Messages,
DynamicCompilationBackendKind.SharedRoslynWorker);
}

DynamicCompilationHealthMonitor.ReportSharedWorkerFallback(
"worker_unavailable",
new
{
platform = UnityEngine.Application.platform.ToString(),
dotnet_host_path = externalCompilerPaths.DotnetHostPath,
compiler_dll_path = externalCompilerPaths.CompilerDllPath,
layout_kind = externalCompilerPaths.LayoutKind.ToString()
});
if (!workerOutcome.IsLifecycleClosed)
{
DynamicCompilationHealthMonitor.ReportSharedWorkerFallback(
"worker_unavailable",
new
{
platform = UnityEngine.Application.platform.ToString(),
dotnet_host_path = externalCompilerPaths.DotnetHostPath,
compiler_dll_path = externalCompilerPaths.CompilerDllPath,
layout_kind = externalCompilerPaths.LayoutKind.ToString()
});
}

ct.ThrowIfCancellationRequested();
OneShotCompileResult oneShotResult = await CompileWithOneShotAsync(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ internal static void RegisterLifecycleForEditorStartup()
EditorApplication.quitting += ShutdownForQuit;
}

public static Task<CompilerMessage[]> TryCompileAsync(
public static Task<SharedWorkerCompileOutcome> TryCompileAsync(
string requestFilePath,
ExternalCompilerPaths externalCompilerPaths,
CancellationToken ct,
Expand All @@ -47,7 +47,7 @@ public static Task<CompilerMessage[]> TryCompileAsync(
ct);
}

private static async Task<CompilerMessage[]> TryCompileWithRetriesAsync(
private static async Task<SharedWorkerCompileOutcome> TryCompileWithRetriesAsync(
string requestFilePath,
ExternalCompilerPaths externalCompilerPaths,
CancellationToken ct,
Expand All @@ -71,7 +71,7 @@ private static async Task<CompilerMessage[]> TryCompileWithRetriesAsync(

if (attemptResult.Succeeded)
{
return attemptResult.Messages;
return SharedWorkerCompileOutcome.SucceededWith(attemptResult.Messages);
}

ServiceValue.ExecuteWithStateLock(ServiceValue.ShutdownProcessLocked);
Expand All @@ -81,13 +81,24 @@ private static async Task<CompilerMessage[]> TryCompileWithRetriesAsync(
continue;
}

DynamicCompilationHealthMonitor.ReportSharedWorkerFailure(
attemptResult.FailureReason,
AppendAttempt(attemptResult.FailureContext, attempt));
return null;
object failureContext = AppendAttempt(attemptResult.FailureContext, attempt);
if (attemptResult.FailureReason == SharedWorkerFailureReasons.LifecycleClosed)
{
DynamicCompilationHealthMonitor.ReportSharedWorkerLifecycleClosed(failureContext);
}
else
{
DynamicCompilationHealthMonitor.ReportSharedWorkerFailure(
attemptResult.FailureReason,
failureContext);
}

return SharedWorkerCompileOutcome.Failed(attemptResult.FailureReason, failureContext);
}

return null;
return SharedWorkerCompileOutcome.Failed(
"worker_unknown_failure",
new { reason = "retry_loop_exhausted" });
}

private static async Task<WorkerAttemptResult> TryCompileOnceAsync(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,47 @@

namespace io.github.hatayama.UnityCliLoop.FirstPartyTools
{
internal static class SharedWorkerFailureReasons
{
internal const string LifecycleClosed = "shared_worker_lifecycle_closed";
}

/// <summary>
/// Carries shared worker compilation messages and the reason for a failed compilation.
/// </summary>
internal sealed class SharedWorkerCompileOutcome
{
public CompilerMessage[] Messages { get; }

public string FailureReason { get; }

public object FailureContext { get; }

private SharedWorkerCompileOutcome(
CompilerMessage[] messages,
string failureReason,
object failureContext)
{
Messages = messages;
FailureReason = failureReason;
FailureContext = failureContext;
}

public bool Succeeded => Messages != null;

public bool IsLifecycleClosed => FailureReason == SharedWorkerFailureReasons.LifecycleClosed;

public static SharedWorkerCompileOutcome SucceededWith(CompilerMessage[] messages)
{
return new SharedWorkerCompileOutcome(messages, null, null);
}

public static SharedWorkerCompileOutcome Failed(string failureReason, object failureContext)
{
return new SharedWorkerCompileOutcome(null, failureReason, failureContext);
}
}

/// <summary>
/// Carries the result data produced by Worker Attempt behavior.
/// </summary>
Expand Down Expand Up @@ -85,7 +126,7 @@ public static WorkerStartupResult ClosedLifecycleFailure()
return new WorkerStartupResult(
false,
false,
"shared_worker_lifecycle_closed",
SharedWorkerFailureReasons.LifecycleClosed,
new { reason = "lifecycle_generation_advanced" });
}
}
Expand Down
Loading