Skip to content

Introduce ScriptTrigger & CommandsTrigger for the .NET plugin - #435

Merged
fdelbrayelle merged 5 commits into
kestra-io:mainfrom
InnoxCodes:feature/dotnet-script-commands-triggers
Sep 23, 2026
Merged

fdelbrayelle merged 5 commits into
kestra-io:mainfrom
InnoxCodes:feature/dotnet-script-commands-triggers

Conversation

@InnoxCodes

@InnoxCodes InnoxCodes commented Sep 16, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Fixes #424, part of #313. plugin-scripts wants every submodule to expose a ScriptTrigger and a CommandsTrigger, so a flow can be triggered whenever the underlying script/commands execution completes, with an exit condition deciding whether the trigger fires. plugin-script-dotnet was missing both.

Implementation

Ports the pattern already established in plugin-script-go and plugin-script-node (checked both as reference implementations, per the issue), with the edge state kept in the namespace KV store instead of an in-memory field. A polling trigger that:

  • Runs the sub-plugin's Script/Commands task once per poll
  • Matches the rendered exitCondition against either the exit code (exit N) or a regex/substring against the emitted vars. A failed run has no vars, so only exit N can match a failure
  • Supports edge mode (default on) to emit only on a not-matching-to-matching transition, so the trigger doesn't fire repeatedly on every poll while the condition stays true. The previous result is stored in the namespace KV store under a length prefixed key built from the flow and trigger ids, and it survives the trigger being rebuilt between polls. The write is skipped when a poll repeats the previous result, so a condition that stays true for hours does not rewrite the same value every interval

ScriptTrigger wraps io.kestra.plugin.scripts.dotnet.Script; CommandsTrigger wraps io.kestra.plugin.scripts.dotnet.Commands. Both default containerImage to mcr.microsoft.com/dotnet/sdk:10.0, matching the existing Script/Commands tasks' own default. The module doc has a Triggers section and AGENTS.md lists both classes.

Testing

Ran locally with Docker, 28 tests across these four classes, all passing:

  • ScriptTriggerTest (13): pure condition-matching unit tests that call the real package-private matchesCondition, no Docker needed
  • EdgeStateTest (10): edge state in the KV store, no Docker needed. Each poll runs on a JSON round-tripped copy of the trigger, and there are cases for edge: false, for state being scoped per flow and per trigger, for the key format, and for the write being skipped on a repeated result (checked against the KV entry's version, which stays put across repeats and increments on a real transition). Removing either kvStore.put makes the matching tests fail
  • ScriptTriggerEvaluateTest (3): runs the real ScriptTrigger#evaluate in a container (fires on exit 1, stays quiet on exit 0, suppresses the second poll in edge mode)
  • CommandsTriggerTest (4): same for CommandsTrigger. Its edge test also fails without the KV write
  • ./gradlew :plugin-script-dotnet:spotlessCheck fails, but only on Script.java, which has a pre-existing import-order violation on main unrelated to this PR

🤖 AI-assisted: I used Claude Code to help draft and verify this fix, and cross-checked it against the existing Go/Node reference implementations before opening this PR.

@github-project-automation github-project-automation Bot moved this to To review in Pull Requests Sep 16, 2026
@fdelbrayelle
fdelbrayelle requested review from a team and fdelbrayelle September 16, 2026 10:38
@fdelbrayelle fdelbrayelle added area/plugin Plugin-related issue or feature request kind/external Pull requests raised by community contributors labels Sep 16, 2026
@InnoxCodes
InnoxCodes force-pushed the feature/dotnet-script-commands-triggers branch from 58614bf to 4c23436 Compare September 18, 2026 15:05
@InnoxCodes

InnoxCodes commented Sep 18, 2026 •

Copy link
Copy Markdown
Contributor Author

Heads up for whoever reviews this: it is the same code as the PowerShell (#436), Deno (#434) and Bun (#433) ports, and those reviews found issues that apply here unchanged, so I ported the fixes before review (4c23436, rebased onto current main).

  • ScriptTriggerTest now calls the real package-private matchesCondition instead of asserting against a copy of it. 13/13 pass locally, and breaking the exit-code branch makes 4 of them fail.
  • The edge mode limitation is documented (code comment, schema descriptions, note on the edge test): lastMatched does not survive the worker's serialize/deserialize round trip, so a distributed deployment fires on every matching poll. The real fix needs a cross-poll state mechanism shared by the whole plugin family, tracked separately by the maintainers.
  • The "failure logs" claim is removed from the docs (only exit N can match a failed run), @EqualsAndHashCode.Exclude is on lastMatched, and example intervals are PT60S.
  • I corrected the spotlessCheck line in the description: it fails only on Script.java, which is already unformatted on main.

Left as in the sibling PRs, and open to changing once decided for the family: extractFailure returning a null exit code when there is no TaskException, and the per-poll regex compile. No Docker on my side, so the container-backed tests are unrun here.

🤖 AI-assisted, as noted in the description.

Update: the edge limitation described above is fixed in 3cd505f. The state now lives in the namespace KV store, and I have since run the container-backed tests locally (28 across the four trigger test classes, all passing).

@fdelbrayelle fdelbrayelle left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Kestra Plugin Code Review

Business Requirements — partial

The PR delivers a ScriptTrigger and CommandsTrigger for plugin-script-dotnet, addressing the core ask of #424/#313 (poll the underlying Script/Commands task, emit an execution when a condition matches). However, neither issue's stated commandPattern / argumentsPattern properties nor the exitCode != 0 expression-style exitCondition syntax shown in both issues' example YAML are implemented — only a literal exit N or regex/substring match against emitted vars is supported. This mirrors the precedent already merged in plugin-script-go and plugin-script-node (neither implements commandPattern/argumentsPattern either), so it's a pre-existing, repo-wide scope reduction rather than something unique to this PR — flagging for visibility, not blocking on it alone.

Kestra Guidelines — 5 findings

  • 🔴 Edge-mode dedup does not work as documented/defaulted (see inline, both trigger files)
  • 🟠 Missing @ToString.Exclude on mutable lastMatched field (both trigger files)
  • 🟠 Class-level @Schema(description = ...) uses a single-line string instead of a text block (both trigger files)
  • 🟠 Package how-to doc not updated with a ## Triggers section (cross-cutting, see below)
  • 🟠 AGENTS.md not updated to list the new trigger classes (cross-cutting, see below)

Cross-cutting (not anchorable to the new-file diff):

  1. 🟠 [Guidelines] Package how-to doc missing Triggers section
    Problem: plugin-script-dotnet/src/main/resources/doc/io.kestra.plugin.scripts.dotnet.md documents only Script/Commands under ## Tasks; it has no ## Triggers section for the two new trigger classes this PR adds.
    Fix: add a ## Triggers section listing ScriptTrigger/CommandsTrigger, their key properties (exitCondition, edge, interval, containerImage) and outputs, per the "Plugin How-To Doc" guideline ("when a task, trigger... is added... update the matching section"). Note: plugin-script-go's and plugin-script-node's docs have the same gap — worth a follow-up across the repo, but this PR is the one adding new trigger surface right now.

  2. 🟠 [Guidelines] AGENTS.md not updated for new trigger classes
    Problem: AGENTS.md §"Key Plugin Classes" → plugin-script-dotnet still lists only Commands/Script; the two new ScriptTrigger/CommandsTrigger classes aren't listed, so an agent reading AGENTS.md won't know they exist.
    Fix: add io.kestra.plugin.scripts.dotnet.ScriptTrigger and io.kestra.plugin.scripts.dotnet.CommandsTrigger to the plugin-script-dotnet entry (same gap exists for go/node, but keep this PR's own module in sync per the "Must Do" AGENTS.md rule).

Security (OWASP Top 10:2025 + KPS) — ✅ No issues found

No secret fields, no HTTP calls, no manual shell string concatenation (commands/script are handed to the existing Commands/Script tasks unchanged), no deserialization or XML parsing. Broad catch (Exception e) in evaluate() logs via runContext.logger().warn(..., e) without leaking any secret-shaped data.

Performance — ✅ No issues found

Per-poll synchronous container execution matches the existing go/node pattern; the only dynamically-compiled Pattern is the user-supplied exitCondition regex, which is unavoidable per-evaluation compilation for a feature that accepts arbitrary user regex — the static exit-code pattern is correctly hoisted to a static final. No unbounded collections or leaked resources introduced.

Verdict: REQUEST CHANGES

Part of kestra-io#313. plugin-scripts wants every submodule to expose a
ScriptTrigger and a CommandsTrigger so a flow can be triggered whenever
the underlying script/commands execution completes, with an exit
condition deciding whether the trigger fires. plugin-script-dotnet was
missing both.

Ports the pattern already established in plugin-script-go and
plugin-script-node (the two existing reference implementations checked
against): a polling trigger that runs the sub-plugin's Script/Commands
task once per poll, matches the rendered exitCondition against either
the exit code ('exit N') or a regex/substring against the emitted vars
and failure logs, and supports edge mode (default on) to emit only on
a not-matching-to-matching transition.

- ScriptTrigger wraps io.kestra.plugin.scripts.dotnet.Script
- CommandsTrigger wraps io.kestra.plugin.scripts.dotnet.Commands
- Both default containerImage to 'mcr.microsoft.com/dotnet/sdk:10.0',
  matching the existing Script/Commands tasks' default

Fixes kestra-io#424
…/CommandsTrigger (dotnet)

The same code was reviewed on the PowerShell, Deno and Bun PRs and the
findings apply here unchanged, so this ports them before review.

- ScriptTriggerTest no longer asserts against a private copy of the
  matching logic. matchesCondition is package-private and the tests
  call it on a real ScriptTrigger (CsvSource table for exit codes).
- Documented the edge mode limitation instead of leaving it silently
  broken: lastMatched is a plain field that does not survive the
  worker's serialize/deserialize round trip, so in a distributed
  deployment edge mode fires on every matching poll. Code comment,
  corrected schema descriptions, and a note on the edge test that only
  proves same-instance dedup. The real fix needs a cross-poll state
  mechanism shared by the whole plugin family and is tracked
  separately.
- Removed the "failure logs" claim from the docs: a failed run passes
  null vars, so only 'exit N' can match a failure.
- @EqualsAndHashCode.Exclude on lastMatched, with a comment that says
  only what the exclusion does (equals already falls back to object
  identity via AbstractTrigger and callSuper=call).
- Example intervals PT10S -> PT60S, matching the coded default.
The edge flag lived in an AtomicBoolean on the trigger, but a polling
trigger is rebuilt on every poll, so with the default edge=true a
condition that stays true fired on every interval. The previous result
is now stored under a length prefixed key built from the flow and
trigger ids in the namespace KV store and updated on every poll.

Also from the review:
- class level @Schema descriptions are text blocks
- an empty exitCondition now fails with a clear message instead of
  silently never matching
- add a Docker backed ScriptTrigger#evaluate test
- add KV state tests that run without Docker
- document the triggers in the module doc and list them in AGENTS.md
@InnoxCodes
InnoxCodes force-pushed the feature/dotnet-script-commands-triggers branch from 4c23436 to 3cd505f Compare September 21, 2026 12:58
@fdelbrayelle

Copy link
Copy Markdown
Member

@InnoxCodes Thanks for the fixes — most of #pullrequestreview-5266633325 is addressed (KV-store edge dedup, @Schema text blocks, exitCondition now orElseThrow, ## Triggers doc section, AGENTS.md entries). Two remain open:

  • 🟠 lastMatched still has only @EqualsAndHashCode.Exclude, missing @ToString.Exclude — in both ScriptTrigger.java and CommandsTrigger.java.
  • 🟠 ScriptTriggerTest still only exercises matchesCondition(); no test calls trigger.evaluate() end-to-end the way CommandsTriggerTest does. Could you add a Docker-backed happy-path test for ScriptTrigger#evaluate()?

Can you take a pass at these two?

@InnoxCodes

Copy link
Copy Markdown
Contributor Author

Thanks for checking back. Both of these were actually already done in 3cd505f, the same commit you called the KV-store dedup fixed in:

lastMatched is not there anymore, the whole field is gone. There is nothing left to put @ToString.Exclude on. The dedup state lives in the namespace KV store now (shouldEmit/edgeStateKey in both trigger classes), which is presumably why you saw it as fixed.

ScriptTriggerEvaluateTest.java was added in that same commit and does exactly what you are asking for: three Docker-backed cases that call trigger.evaluate(...) end to end (fires on exit 1, stays quiet on exit 0, and suppresses a second poll in edge mode on a serialized copy of the trigger). I ran it locally along with the rest, 28 tests pass.

Both are still there on the current head (55d02e7, after your merge from main just now). Let me know if something did not come through on your side, happy to double check.

…dotnet)

Malaydewangan09 flagged this on the PowerShell PR: with the default
60s interval, a condition that stays matched or stays unmatched wrote
the same value to the namespace KV store on every single poll for no
reason. Now the write only happens when the poll actually changes the
result. Verified with a test that checks the KV entry's version stays
put across repeated polls and still increments on a real transition,
and that removing the guard makes it fail.
@fdelbrayelle

Copy link
Copy Markdown
Member

Verified against dc1fc1b8 (current head). All 8 items from #pullrequestreview-5266633325 are closed:

  • lastMatched removed, KV-store watermark confirmed correct across all four transition cases (false→false, false→true, true→true, true→false).
  • @ToString.Exclude items: moot, confirmed — field no longer exists.
  • Both class-level @Schema descriptions: confirmed text blocks.
  • exitCondition: confirmed orElseThrow, with the WARN logged by evaluate()'s catch.
  • ScriptTriggerEvaluateTest: confirmed genuinely end-to-end (not vacuous — traced that the two polls in the edge-suppression case hit the same KV key across the JSON round-trip).

One correction on your last comment: dc1fc1b8 (one commit past what you described) changed the KV write from unconditional-every-poll to skip-if-repeated-result. Functionally still correct — no state loss, no TTL involved — but "written on every poll including non-matches" is now stale wording, worth fixing in the description if you touch this again.

One new (non-blocking) finding from the fix itself: shouldEmit, edgeStateKey, matchesCondition, buildHaystack, safeExitCode, safeVars, extractFailure/ExtractedFailure are byte-for-byte duplicated between ScriptTrigger.java and CommandsTrigger.java. That's new surface area from this round of fixes, not pre-existing. Both extend AbstractTrigger — could this move to a shared base class before merge? Not blocking, but the guidelines flag this exact pattern.

Otherwise LGTM from my side.

@InnoxCodes

Copy link
Copy Markdown
Contributor Author

Thanks for the thorough re-verification, and for catching the stale wording, fixed that inline comment.

Good catch on the duplication too, and you are right that it is new: those seven items were identical before too (same pattern already existed for the exit-code matching and the failure extraction), but the KV fix added shouldEmit/edgeStateKey as two more copies on top of that.

I held off on a shared base class in this PR for one reason: the exact same duplicated shape now exists identically in the sibling PowerShell PR (#436), since it got the same fix for the same review comment, and Bun (#433) had it before merging too. Pulling it into a shared base only in this PR would leave dotnet structurally different from its siblings for no functional reason, and a real fix should cover the whole family in one place, either an AbstractScriptTrigger in plugin-script or a small stateless helper class, not something I want to design unilaterally mid-review in a single-plugin PR. Ruby already has a TODO pointing at the same idea for a different reason (the family carries the exact same six methods copy-pasted six times over, not just two).

Happy to open a tracking issue for it if one does not already exist. Let me know if you would rather I take a pass at the extraction here instead.

@fdelbrayelle
fdelbrayelle merged commit 688518b into kestra-io:main Sep 23, 2026
2 checks passed
@github-project-automation github-project-automation Bot moved this from To review to Done in Pull Requests Sep 23, 2026
@fdelbrayelle

Copy link
Copy Markdown
Member

Edition: OSS | Docker tag: develop (next: 2.1.0-SNAPSHOT)
Instance: http://ei6l2.kestra.docker.localhost:1355/ui/ (left running for manual review, docker rm -f kestra-ei6l2 to stop)
Screenshots: https://claude.ai/artifact/KyozbXvnhM6MiPar93KmDQ (private artifact, share it from the page's Share menu)

QA results: all 6 scenarios pass

Flow Type Result
dotnet_script_trigger new ✅ fired once (edge)
dotnet_commands_trigger new ✅ fired once (edge)
dotnet_script_trigger_noedge new ✅ fired on every poll (4 in ~75s)
dotnet_script_trigger_nomatch new ✅ never fired
dotnet_script_task non-regression ✅ SUCCESS
dotnet_commands_task non-regression ✅ SUCCESS

Flows were created through the API, results checked via API and UI (Gantt screenshots in the gallery).

Flow 1: dotnet_script_trigger (✅ SUCCESS)

Flow YAML
id: dotnet_script_trigger
namespace: qa.dotnet
triggers:
  - id: script_failure
    type: io.kestra.plugin.scripts.dotnet.ScriptTrigger
    interval: PT10S
    exitCondition: "exit 1"
    edge: true
    containerImage: mcr.microsoft.com/dotnet/sdk:10.0
    script: |
      System.Environment.Exit(1);
tasks:
  - id: log
    type: io.kestra.plugin.core.log.Log
    message: "Triggered with exitCode={{ trigger.exitCode }} (condition={{ trigger.condition }})"

Gantt (screenshot)

Task Status Duration
log SUCCESS 0.04s
Total SUCCESS 0.09s

Logs: Triggered with exitCode=1 (condition=exit 1).
Outputs: none. Trigger variables: exitCode: 1, condition: exit 1, timestamp.
Edge mode: only one execution after several polls.

Flow 2: dotnet_commands_trigger (✅ SUCCESS)

Flow YAML
id: dotnet_commands_trigger
namespace: qa.dotnet
triggers:
  - id: commands_failure
    type: io.kestra.plugin.scripts.dotnet.CommandsTrigger
    interval: PT10S
    exitCondition: "exit 1"
    edge: true
    containerImage: mcr.microsoft.com/dotnet/sdk:10.0
    commands:
      - dotnet run --project missing
tasks:
  - id: log
    type: io.kestra.plugin.core.log.Log
    message: "Triggered with exitCode={{ trigger.exitCode }} (condition={{ trigger.condition }})"

Gantt (screenshot)

Task Status Duration
log SUCCESS 0.05s
Total SUCCESS 0.10s

Logs: Triggered with exitCode=1 (condition=exit 1).
Outputs: none. Trigger variables: exitCode: 1, condition: exit 1.

Flow 3: dotnet_script_trigger_noedge (✅ SUCCESS)

Flow YAML
id: dotnet_script_trigger_noedge
namespace: qa.dotnet
triggers:
  - id: script_failure
    type: io.kestra.plugin.scripts.dotnet.ScriptTrigger
    interval: PT10S
    exitCondition: "exit 1"
    edge: false
    containerImage: mcr.microsoft.com/dotnet/sdk:10.0
    script: |
      System.Environment.Exit(1);
tasks:
  - id: log
    type: io.kestra.plugin.core.log.Log
    message: "Triggered with exitCode={{ trigger.exitCode }} (condition={{ trigger.condition }})"

Same as flow 1 with edge: false. Fired on every poll while the condition stayed true (4 executions vs 1 with edge on).

Flow 4: dotnet_script_trigger_nomatch (✅ no execution)

Flow YAML
id: dotnet_script_trigger_nomatch
namespace: qa.dotnet
triggers:
  - id: script_failure
    type: io.kestra.plugin.scripts.dotnet.ScriptTrigger
    interval: PT10S
    exitCondition: "exit 1"
    edge: true
    containerImage: mcr.microsoft.com/dotnet/sdk:10.0
    script: |
      System.Environment.Exit(0);
tasks:
  - id: log
    type: io.kestra.plugin.core.log.Log
    message: "Triggered with exitCode={{ trigger.exitCode }} (condition={{ trigger.condition }})"

Script exits 0, condition is exit 1. No execution created.

Flow 5: dotnet_script_task (✅ SUCCESS, non-regression)

Flow YAML
id: dotnet_script_task
namespace: qa.dotnet
tasks:
  - id: s
    type: io.kestra.plugin.scripts.dotnet.Script
    script: |
      System.Console.WriteLine("hello from dotnet script");

Gantt (screenshot)

Task Status Duration
s SUCCESS 9.4s
Total SUCCESS 9.4s

Logs: hello from dotnet script, Command succeed with exit code 0. Outputs: none.

Flow 6: dotnet_commands_task (✅ SUCCESS, non-regression)

Flow YAML
id: dotnet_commands_task
namespace: qa.dotnet
tasks:
  - id: c
    type: io.kestra.plugin.scripts.dotnet.Commands
    commands:
      - dotnet --version
Task Status Duration
c SUCCESS 1.6s
Total SUCCESS 1.7s

Logs: Command succeed with exit code 0. Outputs: none.

Notes

  • No timeouts. Topology view skipped (PR does not touch artifacts or UI).
  • On a fresh OSS develop image, the admin user must be created in the UI setup page before API calls work (Basic auth returned 401 until then).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area/plugin Plugin-related issue or feature request kind/external Pull requests raised by community contributors

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

Introduce ScriptTrigger & CommandsTrigger for the .NET plugin

2 participants