-
Notifications
You must be signed in to change notification settings - Fork 243
Add Workflow random streams and read-only detection #3049
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
patbeqo
wants to merge
1
commit into
main
Choose a base branch
from
patbeqo/otel-v2-workflow-prerequisites
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
105 changes: 105 additions & 0 deletions
105
temporal-sdk/src/main/java/io/temporal/internal/statemachines/WorkflowRandomStreams.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,105 @@ | ||
| package io.temporal.internal.statemachines; | ||
|
|
||
| import io.temporal.workflow.WorkflowRandomStream; | ||
| import java.nio.charset.StandardCharsets; | ||
| import java.security.MessageDigest; | ||
| import java.security.NoSuchAlgorithmException; | ||
| import java.util.Arrays; | ||
| import java.util.HashMap; | ||
| import java.util.Map; | ||
| import java.util.Objects; | ||
|
|
||
| final class WorkflowRandomStreams { | ||
| private static final byte[] SEED_VERSION = | ||
| "temporal.sdk.random.v1".getBytes(StandardCharsets.UTF_8); | ||
|
|
||
| private final Map<String, Stream> streams = new HashMap<>(); | ||
| private String runId; | ||
|
|
||
| WorkflowRandomStream get(String name) { | ||
| Objects.requireNonNull(name, "name"); | ||
| if (runId == null) { | ||
| throw new IllegalStateException("Workflow Run ID is not initialized"); | ||
| } | ||
| return streams.computeIfAbsent(name, key -> new Stream(deriveSeed(runId, key))); | ||
| } | ||
|
|
||
| void updateRunId(String runId) { | ||
| this.runId = Objects.requireNonNull(runId, "runId"); | ||
| streams.forEach((name, stream) -> stream.reseed(deriveSeed(runId, name))); | ||
| } | ||
|
|
||
| static byte[] deriveSeed(String runId, String name) { | ||
| MessageDigest digest = newSha256(); | ||
| digest.update(SEED_VERSION); | ||
| digest.update((byte) 0); | ||
| digest.update(runId.getBytes(StandardCharsets.UTF_8)); | ||
| digest.update((byte) 0); | ||
| digest.update(name.getBytes(StandardCharsets.UTF_8)); | ||
| return digest.digest(); | ||
| } | ||
|
|
||
| private static MessageDigest newSha256() { | ||
| try { | ||
| return MessageDigest.getInstance("SHA-256"); | ||
| } catch (NoSuchAlgorithmException e) { | ||
| throw new IllegalStateException("SHA-256 is unavailable", e); | ||
| } | ||
| } | ||
|
|
||
| private static final class Stream implements WorkflowRandomStream { | ||
| private final MessageDigest digest = newSha256(); | ||
| private byte[] seed; | ||
| private byte[] block = new byte[0]; | ||
| private int blockOffset; | ||
| private long counter; | ||
|
|
||
| private Stream(byte[] seed) { | ||
| reseed(seed); | ||
| } | ||
|
|
||
| @Override | ||
| public void nextBytes(byte[] bytes) { | ||
| Objects.requireNonNull(bytes, "bytes"); | ||
| int outputOffset = 0; | ||
| while (outputOffset < bytes.length) { | ||
| if (blockOffset == block.length) { | ||
| refill(); | ||
| } | ||
| int length = Math.min(bytes.length - outputOffset, block.length - blockOffset); | ||
| System.arraycopy(block, blockOffset, bytes, outputOffset, length); | ||
| blockOffset += length; | ||
| outputOffset += length; | ||
| } | ||
| } | ||
|
|
||
| @Override | ||
| public long nextLong() { | ||
| byte[] bytes = new byte[Long.BYTES]; | ||
| nextBytes(bytes); | ||
| long value = 0; | ||
| for (byte current : bytes) { | ||
| value = (value << Byte.SIZE) | (current & 0xffL); | ||
| } | ||
| return value; | ||
| } | ||
|
|
||
| private void refill() { | ||
| digest.reset(); | ||
| digest.update(seed); | ||
| for (int shift = Long.SIZE - Byte.SIZE; shift >= 0; shift -= Byte.SIZE) { | ||
| digest.update((byte) (counter >>> shift)); | ||
| } | ||
| counter++; | ||
| block = digest.digest(); | ||
| blockOffset = 0; | ||
| } | ||
|
|
||
| private void reseed(byte[] seed) { | ||
| this.seed = Arrays.copyOf(seed, seed.length); | ||
| block = new byte[0]; | ||
| blockOffset = 0; | ||
| counter = 0; | ||
| } | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
26 changes: 26 additions & 0 deletions
26
temporal-sdk/src/main/java/io/temporal/workflow/WorkflowRandomStream.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,26 @@ | ||
| package io.temporal.workflow; | ||
|
|
||
| import io.temporal.common.Experimental; | ||
| import io.temporal.workflow.unsafe.WorkflowUnsafe; | ||
|
|
||
| /** | ||
| * A named deterministic pseudorandom stream for Workflow code. | ||
| * | ||
| * <p>Repeated calls to {@link Workflow#getRandomStream(String)} with the same name return the same | ||
| * logical stream at its current position. Different names do not affect each other's sequences. | ||
| * | ||
| * <p>Each draw advances Workflow state without recording an Event in Workflow History. Replay must | ||
| * make the same draws in the same order. Do not draw in read-only code; shared code can check | ||
| * {@link WorkflowUnsafe#isReadOnly()}. | ||
| * | ||
| * <p>Use a stable package-style name. Stream names are retained for the life of the Workflow Run. | ||
| */ | ||
| @Experimental | ||
| public interface WorkflowRandomStream { | ||
|
|
||
| /** Fills {@code bytes} with the next bytes from this stream. */ | ||
| void nextBytes(byte[] bytes); | ||
|
|
||
| /** Returns the next signed 64-bit value from this stream in big-endian byte order. */ | ||
| long nextLong(); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
89 changes: 89 additions & 0 deletions
89
temporal-sdk/src/test/java/io/temporal/internal/statemachines/WorkflowRandomStreamsTest.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,89 @@ | ||
| package io.temporal.internal.statemachines; | ||
|
|
||
| import static org.junit.Assert.assertArrayEquals; | ||
| import static org.junit.Assert.assertEquals; | ||
| import static org.junit.Assert.assertNotEquals; | ||
| import static org.junit.Assert.assertSame; | ||
|
|
||
| import io.temporal.workflow.WorkflowRandomStream; | ||
| import java.util.Base64; | ||
| import org.junit.Test; | ||
|
|
||
| public class WorkflowRandomStreamsTest { | ||
| private static final String RUN_ID = "runID"; | ||
| private static final String NAME = "io.temporal.test"; | ||
|
|
||
| @Test | ||
| public void goldenSeedAndBytes() { | ||
| assertEquals( | ||
| "cYwA+k67hflWG1GVOzY897A19H2s16mOOzlic16UFtI=", | ||
| Base64.getEncoder().encodeToString(WorkflowRandomStreams.deriveSeed(RUN_ID, NAME))); | ||
|
|
||
| WorkflowRandomStreams randoms = new WorkflowRandomStreams(); | ||
| randoms.updateRunId(RUN_ID); | ||
| byte[] bytes = new byte[32]; | ||
| randoms.get(NAME).nextBytes(bytes); | ||
|
|
||
| assertEquals( | ||
| "wY4Mb9uhREeU08hmLgZRqar87inHCMHTkHCss0U8Wi0=", Base64.getEncoder().encodeToString(bytes)); | ||
| assertEquals(-4499645303130864569L, randoms(RUN_ID).get(NAME).nextLong()); | ||
| } | ||
|
|
||
| @Test | ||
| public void seedFramingSeparatesRunIdAndName() { | ||
| assertNotEquals( | ||
| Base64.getEncoder().encodeToString(WorkflowRandomStreams.deriveSeed("ab", "c")), | ||
| Base64.getEncoder().encodeToString(WorkflowRandomStreams.deriveSeed("a", "bc"))); | ||
| } | ||
|
|
||
| @Test | ||
| public void sameNameContinuesAndNamesAreIndependent() { | ||
| WorkflowRandomStreams interleaved = randoms(RUN_ID); | ||
| WorkflowRandomStream first = interleaved.get(NAME); | ||
| long firstValue = first.nextLong(); | ||
| long otherValue = interleaved.get("other").nextLong(); | ||
| WorkflowRandomStream second = interleaved.get(NAME); | ||
| long secondValue = second.nextLong(); | ||
|
|
||
| WorkflowRandomStreams isolated = randoms(RUN_ID); | ||
| assertSame(first, second); | ||
| assertEquals(firstValue, isolated.get(NAME).nextLong()); | ||
| assertEquals(secondValue, isolated.get(NAME).nextLong()); | ||
| assertEquals(otherValue, isolated.get("other").nextLong()); | ||
| assertNotEquals(firstValue, otherValue); | ||
| } | ||
|
|
||
| @Test | ||
| public void runIdUpdateReseedsExistingStreamInPlace() { | ||
| WorkflowRandomStreams randoms = randoms(RUN_ID); | ||
| WorkflowRandomStream before = randoms.get(NAME); | ||
| before.nextLong(); | ||
|
|
||
| randoms.updateRunId("new-run"); | ||
| WorkflowRandomStream after = randoms.get(NAME); | ||
|
|
||
| WorkflowRandomStreams fresh = randoms("new-run"); | ||
| assertSame(before, after); | ||
| assertEquals(fresh.get(NAME).nextLong(), after.nextLong()); | ||
| } | ||
|
|
||
| @Test | ||
| public void streamCreatedAfterRunIdUpdateUsesNewRun() { | ||
| WorkflowRandomStreams randoms = randoms(RUN_ID); | ||
| randoms.get("before-reset").nextLong(); | ||
| randoms.updateRunId("new-run"); | ||
|
|
||
| byte[] actual = new byte[32]; | ||
| randoms.get(NAME).nextBytes(actual); | ||
|
|
||
| byte[] expected = new byte[32]; | ||
| randoms("new-run").get(NAME).nextBytes(expected); | ||
| assertArrayEquals(expected, actual); | ||
| } | ||
|
|
||
| private static WorkflowRandomStreams randoms(String runId) { | ||
| WorkflowRandomStreams randoms = new WorkflowRandomStreams(); | ||
| randoms.updateRunId(runId); | ||
| return randoms; | ||
| } | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
When workflow code retains a stream and later calls
nextBytesornextLongfrom a query, update validator, or another read-only callback, this implementation advances the stream without any read-only check; the only guard is whenWorkflow.getRandomStreaminitially acquires it. Such a query therefore mutates workflow state, so subsequent workflow draws depend on whether and how often the query ran and can produce nondeterministic results during replay. Enforce the read-only restriction on every draw, not only during stream lookup.Useful? React with 👍 / 👎.