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
133 changes: 123 additions & 10 deletions src/E2E/Engine/EngineSession.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,9 @@ internal sealed class EngineSession : IEngineSession, IEngineFixtureHost
private readonly string _runId;
private readonly string _attemptId;
private readonly string _engineName;
private readonly Lock _locatedLock = new();
private readonly OrderedDictionary<string, SemanticNode> _located = new(StringComparer.Ordinal);
private readonly System.Runtime.CompilerServices.ConditionalWeakTable<SemanticNode, object> _minted = new();

private EngineSession(IEngineSession engine, string runId, string attemptId, string engineName)
{
Expand Down Expand Up @@ -178,6 +181,7 @@ public Task PerformAsync(SemanticNode node, LocatorAction action, CancellationTo
Guard("actions", cancellationToken, () =>
{
RequireKeyOf(action);
RejectSuperseded(node);
return _engine.PerformAsync(node, action, cancellationToken);
});

Expand All @@ -189,6 +193,7 @@ CancellationToken cancellationToken
) => Guard("actions", cancellationToken, () =>
{
RequireKeyOf(action);
RejectSuperseded(node);
return _engine.PerformAsync(node, action, Stamp(context), cancellationToken);
});

Expand All @@ -210,10 +215,11 @@ public Task<IReadOnlyDictionary<string, string>> ReadStyleAsync(
IReadOnlyList<string> properties,
OperationContext context,
CancellationToken cancellationToken
) =>
Guard("computed styles", cancellationToken, () =>
_engine.ReadStyleAsync(node, properties, Stamp(context), cancellationToken)
);
) => Guard("computed styles", cancellationToken, () =>
{
RejectSuperseded(node);
return _engine.ReadStyleAsync(node, properties, Stamp(context), cancellationToken);
});

public bool MeasuresViewport => _engine.MeasuresViewport;

Expand All @@ -228,8 +234,10 @@ CancellationToken cancellationToken
) =>
CheckIntersection(
await Guard("viewport geometry (toBeInViewport)", cancellationToken, () =>
_engine.ViewportIntersectionAsync(node, Stamp(context), cancellationToken)
)
{
RejectSuperseded(node);
return _engine.ViewportIntersectionAsync(node, Stamp(context), cancellationToken);
})
.ConfigureAwait(false),
_engineName
);
Expand Down Expand Up @@ -292,8 +300,13 @@ public Task<IReadOnlyList<SemanticNode>> LocateAsync(
TimeSpan timeout,
CancellationToken cancellationToken
) =>
Guard("locators (screen)", cancellationToken, () =>
_engine.LocateAsync(expression, timeout, cancellationToken)
Guard("locators (screen)", cancellationToken, async () =>
Mint(
Visible(
expression,
await _engine.LocateAsync(expression, timeout, cancellationToken).ConfigureAwait(false)
)
)
);

public Task<IReadOnlyList<SemanticNode>> LocateAsync(
Expand All @@ -302,10 +315,110 @@ public Task<IReadOnlyList<SemanticNode>> LocateAsync(
OperationContext context,
CancellationToken cancellationToken
) =>
Guard("locators (screen)", cancellationToken, () =>
_engine.LocateAsync(expression, timeout, Stamp(context), cancellationToken)
Guard("locators (screen)", cancellationToken, async () =>
Mint(
Visible(
expression,
await _engine
.LocateAsync(expression, timeout, Stamp(context), cancellationToken)
.ConfigureAwait(false)
)
)
);

/// <summary>
/// Upstream's top-level <c>visible</c> filter of <c>locate</c>: an engine answers <c>visible</c> inside scopes, filters, and indices, where
/// only it can; a top-level query is held to the same predicate so a direct query never resolves to a node its own state calls hidden.
/// </summary>
private static IReadOnlyList<SemanticNode> Visible(
LocatorExpression expression,
IReadOnlyList<SemanticNode> nodes
) => expression.Visible ? nodes.Where(node => node.States?.Hidden != true).ToArray() : nodes;

/// <summary>
/// Records the nodes one locate answered, newest last, as the resolution <see cref="ReadAsync"/> answers from (upstream's <c>located</c>
/// map). A node's revision upstream is the instance here: a node of an older locate is no longer the one held under its id.
/// </summary>
private IReadOnlyList<SemanticNode> Mint(IReadOnlyList<SemanticNode> nodes)
{
lock (_locatedLock)
{
var thisLocate = new HashSet<string>(StringComparer.Ordinal);
foreach (var node in nodes)
{
// A ref a locate names twice stays the first node, so the node the caller got first is not superseded by its own locate.
if (!thisLocate.Add(node.Ref))
{
continue;
}

_located.Remove(node.Ref);
_located[node.Ref] = node;
_minted.AddOrUpdate(node, node);
}

var keep = Math.Max(EngineSessions.MaxLocatedRefs, nodes.Count);
while (_located.Count > keep)
{
_located.RemoveAt(0);
}
}

return nodes;
}

/// <summary>Upstream's <c>rejectSupersededLocate</c>: a located node that a later locate replaced never reaches the engine.</summary>
private void RejectSuperseded(SemanticNode node)
{
lock (_locatedLock)
{
if (
_minted.TryGetValue(node, out _)
&& _located.TryGetValue(node.Ref, out var known)
&& !ReferenceEquals(known, node)
)
{
throw Stale(node);
}
}
}

private static EngineException Stale(SemanticNode node) =>
new(EngineErrorCodes.NodeStale, $"node {node.Ref} is stale; re-resolve", retryable: true);

/// <summary>
/// Reads one located node from the resolution that minted it (upstream's <c>session.read</c>), failing with <c>NODE_STALE</c> when a
/// later locate superseded it, which the locator engine treats as retryable.
/// </summary>
internal Task<SemanticNode> ReadAsync(
SemanticNode node,
OperationContext context,
CancellationToken cancellationToken
)
{
if (cancellationToken.IsCancellationRequested)
{
return Task.FromCanceled<SemanticNode>(cancellationToken);
}

if (!_engine.CanLocate)
{
return Task.FromException<SemanticNode>(
new EngineException(
EngineErrorCodes.UnsupportedCapability,
"locators (screen) is not supported by this engine."
)
);
}

lock (_locatedLock)
{
return _located.TryGetValue(node.Ref, out var known) && ReferenceEquals(known, node)
? Task.FromResult(known)
: Task.FromException<SemanticNode>(Stale(node));
}
}

public Task SwipeAsync(ScrollDirection direction, CancellationToken cancellationToken) =>
Guard("actions", cancellationToken, () => _engine.SwipeAsync(direction, cancellationToken));

Expand Down
1 change: 1 addition & 0 deletions src/E2E/Run/E2ESession.cs
Original file line number Diff line number Diff line change
Expand Up @@ -734,6 +734,7 @@ options.ResultsDirectory is null
? (expression, timeout, token) =>
engine.LocateAsync(expression, timeout, OperationContext.Test, token)
: null,
Read = engine is EngineSession located && engine.CanLocate ? located.ReadAsync : null,
ViewportIntersection = engine.MeasuresViewport ? engine.ViewportIntersectionAsync : null,
Perform = engine.PerformAsync,
PerformAt = engine.PerformAtAsync,
Expand Down
84 changes: 84 additions & 0 deletions tests/E2E.Tests/Engine/EngineSessionLocatedTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
// Copyright 2026 TesterArmy.
// Modified by Dario Kondratiuk.
// SPDX-License-Identifier: Apache-2.0

using E2E.Engine;
using E2E.Tests.AgentFallbackHandoff;

namespace E2E.Tests.Engine;

/// <summary>
/// .NET-only: the port's engine-to-session adapter (<c>EngineSession</c>) keeps the nodes of a locate and answers <c>read</c> from the
/// resolution that minted them, as upstream's <c>createEngineSession</c> does. Upstream's own cases are in
/// <see cref="CreateEngineSessionTests"/>. The revision upstream stamps onto a ref is the node instance here.
/// </summary>
public sealed class EngineSessionLocatedTests
{
private static readonly LocatorExpression Query = new() { Role = "button" };

private static SemanticNode Node(string id, string name) =>
new()
{
Ref = id,
Role = "button",
Name = name,
};

private static async Task<IEngineSession> SessionAsync(
Func<IReadOnlyList<SemanticNode>> locate,
List<string>? performed = null
) =>
EngineSession.Create(
await new FallbackEngine
{
Locate = _ => locate(),
Perform = (node, _) => performed?.Add(node.Name ?? ""),
}.StartAsync(new EngineStartOptions(), CancellationToken.None),
"run",
"attempt"
);

[Fact]
public async Task Rejects_a_superseded_located_node_but_lets_observed_nodes_through_to_the_engine()
{
var performed = new List<string>();
var session = await SessionAsync(() => [Node("n1", "Save")], performed);
var first = (await session.LocateAsync(Query, TimeSpan.FromSeconds(1), OperationContext.Test, default))[0];
await session.LocateAsync(Query, TimeSpan.FromSeconds(1), OperationContext.Test, default);

var error = await Assert.ThrowsAsync<EngineException>(() =>
session.PerformAsync(first, new LocatorAction.Tap(), OperationContext.Test, default)
);
Assert.Equal(EngineErrorCodes.NodeStale, error.Code);

var observed = Node("n1", "Observed");
await session.PerformAsync(observed, new LocatorAction.Tap(), OperationContext.Test, default);
Assert.Equal(["Observed"], performed);
}

[Fact]
public async Task Reads_back_every_node_of_a_locate_with_more_matches_than_the_located_bound()
{
IReadOnlyList<SemanticNode> nodes = Enumerable.Range(0, 2100).Select(i => Node($"a{i}", $"Row {i}")).ToArray();
var session = (EngineSession)await SessionAsync(() => nodes);
var located = await session.LocateAsync(Query, TimeSpan.FromSeconds(1), OperationContext.Test, default);
Assert.Equal(2100, located.Count);
foreach (var node in located)
{
Assert.Same(node, await session.ReadAsync(node, OperationContext.Test, default));
}

nodes = Enumerable.Range(0, 10).Select(i => Node($"b{i}", $"Row {i}")).ToArray();
var later = await session.LocateAsync(Query, TimeSpan.FromSeconds(1), OperationContext.Test, default);
foreach (var node in later)
{
await session.ReadAsync(node, OperationContext.Test, default);
}

var stale = await Assert.ThrowsAsync<EngineException>(() =>
session.ReadAsync(located[0], OperationContext.Test, default)
);
Assert.Equal(EngineErrorCodes.NodeStale, stale.Code);
Assert.Equal("Row 2099", (await session.ReadAsync(located[^1], OperationContext.Test, default)).Name);
}
}
Loading