This is an automated email from the ASF dual-hosted git repository.

petrov-mg pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/ignite.git


The following commit(s) were added to refs/heads/master by this push:
     new 0ed608676f6 IGNITE-29116 Fixed Operation Context propagation for 
Ignite Compute (#13664)
0ed608676f6 is described below

commit 0ed608676f6d5ad9c53201da9f6df115b68da068
Author: Mikhail Petrov <[email protected]>
AuthorDate: Tue Oct 13 15:09:14 2026 +0300

    IGNITE-29116 Fixed Operation Context propagation for Ignite Compute (#13664)
---
 .../internal/processors/job/GridJobWorker.java     |  93 +++--
 .../internal/processors/task/GridTaskWorker.java   |  15 +
 ...ComputeTaskOperationContextPropagationTest.java | 434 +++++++++++++++++++++
 .../ignite/testsuites/SecurityTestSuite.java       |   2 +
 4 files changed, 509 insertions(+), 35 deletions(-)

diff --git 
a/modules/core/src/main/java/org/apache/ignite/internal/processors/job/GridJobWorker.java
 
b/modules/core/src/main/java/org/apache/ignite/internal/processors/job/GridJobWorker.java
index 5c58d42811e..7dfc10746d2 100644
--- 
a/modules/core/src/main/java/org/apache/ignite/internal/processors/job/GridJobWorker.java
+++ 
b/modules/core/src/main/java/org/apache/ignite/internal/processors/job/GridJobWorker.java
@@ -56,6 +56,8 @@ import 
org.apache.ignite.internal.processors.security.SecurityUtils;
 import 
org.apache.ignite.internal.processors.service.GridServiceNotFoundException;
 import org.apache.ignite.internal.processors.task.GridInternal;
 import org.apache.ignite.internal.processors.timeout.GridTimeoutObject;
+import org.apache.ignite.internal.thread.context.OperationContext;
+import org.apache.ignite.internal.thread.context.OperationContextSnapshot;
 import org.apache.ignite.internal.thread.context.Scope;
 import org.apache.ignite.internal.util.typedef.F;
 import org.apache.ignite.internal.util.typedef.X;
@@ -170,8 +172,8 @@ public class GridJobWorker extends GridWorker implements 
GridTimeoutObject {
     /** Request topology version. */
     private final String execName;
 
-    /** Security context. */
-    private final SecurityContext secCtx;
+    /** */
+    private final OperationContextSnapshot opCtxSnp;
 
     /** Job status. */
     private volatile ComputeJobStatusEnum status = QUEUED;
@@ -247,7 +249,7 @@ public class GridJobWorker extends GridWorker implements 
GridTimeoutObject {
         jobTopic = TOPIC_JOB.topic(ses.getJobId(), locNodeId);
         taskTopic = TOPIC_TASK.topic(ses.getJobId(), locNodeId);
 
-        secCtx = ctx.security().securityContext();
+        opCtxSnp = OperationContext.createSnapshot();
     }
 
     /**
@@ -491,28 +493,32 @@ public class GridJobWorker extends GridWorker implements 
GridTimeoutObject {
 
     /** {@inheritDoc} */
     @Override protected void body() {
-        assert job != null;
+        try (Scope ignored = OperationContext.restoreSnapshot(opCtxSnp)) {
+            assert job != null;
 
-        startTime = U.currentTimeMillis();
+            startTime = U.currentTimeMillis();
 
-        isStarted = true;
+            isStarted = true;
 
-        status = RUNNING;
+            status = RUNNING;
 
-        // Event notification.
-        evtLsnr.onJobStarted(this);
+            // Event notification.
+            evtLsnr.onJobStarted(this);
 
-        if (!internal && ctx.event().isRecordable(EVT_JOB_STARTED))
-            recordEvent(EVT_JOB_STARTED, /*no message for success*/null);
+            if (!internal && ctx.event().isRecordable(EVT_JOB_STARTED))
+                recordEvent(EVT_JOB_STARTED, /*no message for success*/null);
 
-        execute0(true);
+            execute0(true);
+        }
     }
 
     /**
      * Executes the job.
      */
     public void execute() {
-        execute0(false);
+        try (Scope ignored = OperationContext.restoreSnapshot(opCtxSnp)) {
+            execute0(false);
+        }
     }
 
     /**
@@ -525,7 +531,7 @@ public class GridJobWorker extends GridWorker implements 
GridTimeoutObject {
 
         SqlFieldsQuery.setThreadedQueryInitiatorId("task:" + ses.getTaskName() 
+ ":" + getJobId());
 
-        try (Scope ignored = ctx.security().withContext(secCtx)) {
+        try {
             if (partsReservation != null) {
                 try {
                     if (!partsReservation.reserve()) {
@@ -728,32 +734,34 @@ public class GridJobWorker extends GridWorker implements 
GridTimeoutObject {
      * @param sys System flag.
      */
     public void cancel(boolean sys) {
-        if (log.isDebugEnabled())
-            log.debug("Cancelling job: " + ses);
+        try (Scope ignored = OperationContext.restoreSnapshot(opCtxSnp)) {
+            if (log.isDebugEnabled())
+                log.debug("Cancelling job: " + ses);
 
-        boolean firstCancel = isCancelled.compareAndSet(false, true);
+            boolean firstCancel = isCancelled.compareAndSet(false, true);
 
-        isCancelledBySystem = sys;
+            isCancelledBySystem = sys;
 
-        status = CANCELLED;
+            status = CANCELLED;
 
-        final ComputeJob job0 = job;
+            final ComputeJob job0 = job;
 
-        try (Scope ignored = ctx.security().withContext(secCtx)) {
-            U.wrapThreadLoader(dep.classLoader(), job0::cancel);
-        }
-        catch (Throwable e) { // Catch throwable to protect against bad user 
code.
-            U.error(log, "Failed to cancel job due to undeclared user 
exception [jobId=" + ses.getJobId() +
-                ", ses=" + ses + ']', e);
+            try {
+                U.wrapThreadLoader(dep.classLoader(), job0::cancel);
+            }
+            catch (Throwable e) { // Catch throwable to protect against bad 
user code.
+                U.error(log, "Failed to cancel job due to undeclared user 
exception [jobId=" + ses.getJobId() +
+                    ", ses=" + ses + ']', e);
 
-            if (e instanceof Error)
-                throw e;
-        }
-        finally {
-            onCancel(firstCancel);
+                if (e instanceof Error)
+                    throw e;
+            }
+            finally {
+                onCancel(firstCancel);
 
-            if (!internal && ctx.event().isRecordable(EVT_JOB_CANCELLED))
-                recordEvent(EVT_JOB_CANCELLED, "Job was cancelled: " + job0);
+                if (!internal && ctx.event().isRecordable(EVT_JOB_CANCELLED))
+                    recordEvent(EVT_JOB_CANCELLED, "Job was cancelled: " + 
job0);
+            }
         }
     }
 
@@ -782,6 +790,9 @@ public class GridJobWorker extends GridWorker implements 
GridTimeoutObject {
         evt.taskSessionId(ses.getId());
         evt.type(evtType);
         evt.taskNode(taskNode);
+
+        SecurityContext secCtx = ses.session().initiatorSecurityContext();
+
         evt.taskSubjectId(secCtx != null ? secCtx.subject().id() : null);
 
         ctx.event().record(evt);
@@ -801,7 +812,7 @@ public class GridJobWorker extends GridWorker implements 
GridTimeoutObject {
     }
 
     /**
-     * @param res Resuilt.
+     * @param res Result.
      * @param ex Exception
      * @param sndReply If {@code true}, reply will be sent.
      * @param retry If {@code true}, retry response will be sent.
@@ -811,6 +822,18 @@ public class GridJobWorker extends GridWorker implements 
GridTimeoutObject {
         @Nullable IgniteException ex,
         boolean sndReply,
         boolean retry
+    ) {
+        try (Scope ignored = OperationContext.restoreSnapshot(opCtxSnp)) {
+            finishJob0(res, ex, sndReply, retry);
+        }
+    }
+
+    /** */
+    private void finishJob0(
+        @Nullable Object res,
+        @Nullable IgniteException ex,
+        boolean sndReply,
+        boolean retry
     ) {
         // Avoid finishing a job more than once from different threads.
         if (!finishing.compareAndSet(false, true))
@@ -1029,7 +1052,7 @@ public class GridJobWorker extends GridWorker implements 
GridTimeoutObject {
     boolean onMasterNodeLeft() {
         if (job instanceof ComputeJobMasterLeaveAware) {
             if (masterLeaveGuard.compareAndSet(false, true)) {
-                try {
+                try (Scope ignored = 
OperationContext.restoreSnapshot(opCtxSnp)) {
                     
((ComputeJobMasterLeaveAware)job).onMasterNodeLeft(ses.session());
 
                     if (log.isDebugEnabled())
diff --git 
a/modules/core/src/main/java/org/apache/ignite/internal/processors/task/GridTaskWorker.java
 
b/modules/core/src/main/java/org/apache/ignite/internal/processors/task/GridTaskWorker.java
index 12f5dfd8d10..d2f14202da9 100644
--- 
a/modules/core/src/main/java/org/apache/ignite/internal/processors/task/GridTaskWorker.java
+++ 
b/modules/core/src/main/java/org/apache/ignite/internal/processors/task/GridTaskWorker.java
@@ -76,6 +76,9 @@ import 
org.apache.ignite.internal.processors.job.ComputeJobStatusEnum;
 import org.apache.ignite.internal.processors.security.PublicAccessJob;
 import 
org.apache.ignite.internal.processors.service.GridServiceNotFoundException;
 import org.apache.ignite.internal.processors.timeout.GridTimeoutObject;
+import org.apache.ignite.internal.thread.context.OperationContext;
+import org.apache.ignite.internal.thread.context.OperationContextSnapshot;
+import org.apache.ignite.internal.thread.context.Scope;
 import org.apache.ignite.internal.util.lang.GridPlainRunnable;
 import org.apache.ignite.internal.util.typedef.CO;
 import org.apache.ignite.internal.util.typedef.F;
@@ -159,6 +162,9 @@ public class GridTaskWorker<T, R> extends GridWorker 
implements GridTimeoutObjec
     /** */
     private final GridTaskSessionImpl ses;
 
+    /** */
+    private final OperationContextSnapshot opCtxSnp;
+
     /** */
     private final ComputeTaskInternalFuture<R> fut;
 
@@ -320,6 +326,8 @@ public class GridTaskWorker<T, R> extends GridWorker 
implements GridTimeoutObjec
         this.opts = opts;
         this.subjId = subjId;
 
+        opCtxSnp = OperationContext.createSnapshot();
+
         log = U.logger(ctx, logRef, this);
 
         boolean noResCacheAnnotation = dep.annotation(taskCls, 
ComputeTaskNoResultCache.class) != null;
@@ -714,6 +722,13 @@ public class GridTaskWorker<T, R> extends GridWorker 
implements GridTimeoutObjec
      * @param msg Job execution response.
      */
     void onResponse(GridJobExecuteResponse msg) {
+        try (Scope ignored = OperationContext.restoreSnapshot(opCtxSnp)) {
+            onResponse0(msg);
+        }
+    }
+
+    /** */
+    private void onResponse0(GridJobExecuteResponse msg) {
         assert msg != null;
 
         if (fut.isDone()) {
diff --git 
a/modules/core/src/test/java/org/apache/ignite/internal/thread/context/ComputeTaskOperationContextPropagationTest.java
 
b/modules/core/src/test/java/org/apache/ignite/internal/thread/context/ComputeTaskOperationContextPropagationTest.java
new file mode 100644
index 00000000000..dd6bff0c80f
--- /dev/null
+++ 
b/modules/core/src/test/java/org/apache/ignite/internal/thread/context/ComputeTaskOperationContextPropagationTest.java
@@ -0,0 +1,434 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ignite.internal.thread.context;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.function.Consumer;
+import org.apache.ignite.cluster.ClusterNode;
+import org.apache.ignite.compute.ComputeJob;
+import org.apache.ignite.compute.ComputeJobAdapter;
+import org.apache.ignite.compute.ComputeJobContext;
+import org.apache.ignite.compute.ComputeJobMasterLeaveAware;
+import org.apache.ignite.compute.ComputeJobResult;
+import org.apache.ignite.compute.ComputeJobResultPolicy;
+import org.apache.ignite.compute.ComputeTaskAdapter;
+import org.apache.ignite.compute.ComputeTaskSession;
+import org.apache.ignite.configuration.IgniteConfiguration;
+import org.apache.ignite.internal.GridJobExecuteResponse;
+import org.apache.ignite.internal.IgniteEx;
+import org.apache.ignite.internal.TestRecordingCommunicationSpi;
+import org.apache.ignite.internal.processors.authentication.User;
+import org.apache.ignite.lang.IgniteFuture;
+import org.apache.ignite.plugin.AbstractTestPluginProvider;
+import org.apache.ignite.plugin.PluginContext;
+import org.apache.ignite.resources.JobContextResource;
+import org.apache.ignite.spi.IgniteSpiAdapter;
+import org.apache.ignite.spi.IgniteSpiException;
+import org.apache.ignite.spi.IgniteSpiMultipleInstancesSupport;
+import org.apache.ignite.spi.collision.CollisionContext;
+import org.apache.ignite.spi.collision.CollisionExternalListener;
+import org.apache.ignite.spi.collision.CollisionJobContext;
+import org.apache.ignite.spi.collision.CollisionSpi;
+import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest;
+import org.jetbrains.annotations.Nullable;
+import org.junit.Test;
+
+import static java.util.concurrent.TimeUnit.MILLISECONDS;
+import static org.apache.ignite.events.EventType.EVT_JOB_REJECTED;
+import static org.apache.ignite.internal.TestRecordingCommunicationSpi.spi;
+import static 
org.apache.ignite.internal.thread.context.OperationContextDispatcher.MAX_ATTRS_CNT;
+
+/** */
+public class ComputeTaskOperationContextPropagationTest extends 
GridCommonAbstractTest {
+    /** */
+    private static final OperationContextAttribute<User> USR_ATTR = 
OperationContextAttribute.newInstance();
+
+    /** */
+    private static final User FIRST_USR_VAL = User.create("0", "0");
+
+    /** */
+    private static final User SECOND_USR_VAL = User.create("1", "1");
+
+    /** */
+    private static volatile Consumer<CollisionContext> onCollision;
+
+    /** */
+    private static volatile CountDownLatch firstJobArrivedLatch;
+
+    /** {@inheritDoc} */
+    @Override protected IgniteConfiguration getConfiguration(String 
igniteInstanceName) throws Exception {
+        IgniteConfiguration cfg = super.getConfiguration(igniteInstanceName);
+
+        cfg.setCommunicationSpi(new TestRecordingCommunicationSpi());
+        cfg.setPluginProviders(new TestIgniteComponent());
+        cfg.setIncludeEventTypes(EVT_JOB_REJECTED);
+
+        if (getTestIgniteInstanceIndex(igniteInstanceName) == 1)
+            cfg.setCollisionSpi(new TestCollisionSpi());
+
+        return cfg;
+    }
+
+    /** {@inheritDoc} */
+    @Override protected void beforeTest() throws Exception {
+        super.beforeTest();
+
+        onCollision = null;
+        firstJobArrivedLatch = new CountDownLatch(1);
+
+        startGrids(2);
+    }
+
+    /** {@inheritDoc} */
+    @Override protected void afterTest() throws Exception {
+        stopAllGrids();
+
+        super.afterTest();
+    }
+
+    /** */
+    @Test
+    public void testJobNodeLeftResponseIsProcessedUnderTheTaskContext() throws 
Exception {
+        spi(grid(1)).blockMessages((node, msg) -> msg instanceof 
GridJobExecuteResponse);
+
+        IgniteFuture<TaskExecution> fut = executeWithContext(new RegularJob(), 
FIRST_USR_VAL);
+
+        assertTrue(spi(grid(1)).waitForBlocked(1, getTestTimeout()));
+
+        stopGrid(1);
+
+        assertEquals(new TaskExecution(FIRST_USR_VAL, FIRST_USR_VAL, null), 
fut.get(getTestTimeout()));
+    }
+
+    /** */
+    @Test
+    public void testJobRejectedByAnotherTaskIsProcessedUnderItsOwnContext() 
throws Exception {
+        // The first job stays queued; the second one rejects it and runs.
+        onCollision = ctx -> {
+            List<CollisionJobContext> waiting = new 
ArrayList<>(ctx.waitingJobs());
+
+            if (waiting.size() == 1)
+                firstJobArrivedLatch.countDown();
+            else if (waiting.size() == 2) {
+                waiting.get(0).cancel();
+                waiting.get(1).activate();
+            }
+        };
+
+        AtomicReference<User> attrSeenByRejectionLsnr = new 
AtomicReference<>();
+        CountDownLatch jobRejectedLatch = new CountDownLatch(1);
+
+        grid(1).events().localListen(evt -> {
+            attrSeenByRejectionLsnr.set(OperationContext.get(USR_ATTR));
+
+            jobRejectedLatch.countDown();
+
+            return true;
+        }, EVT_JOB_REJECTED);
+
+        IgniteFuture<TaskExecution> firstTaskFut = executeWithContext(new 
RegularJob(), FIRST_USR_VAL);
+
+        assertTrue(firstJobArrivedLatch.await(getTestTimeout(), MILLISECONDS));
+
+        TaskExecution secondExecRes = executeWithContext(new RegularJob(), 
SECOND_USR_VAL).get(getTestTimeout());
+        TaskExecution firstExecRes = firstTaskFut.get(getTestTimeout());
+
+        assertEquals(new TaskExecution(FIRST_USR_VAL, FIRST_USR_VAL, null), 
firstExecRes);
+        assertExecutedWith(SECOND_USR_VAL, secondExecRes);
+
+        assertTrue(jobRejectedLatch.await(getTestTimeout(), MILLISECONDS));
+        assertEquals(FIRST_USR_VAL, attrSeenByRejectionLsnr.get());
+    }
+
+    /** */
+    @Test
+    public void testJobActivatedByAnotherTaskRunsUnderTheJobContext() throws 
Exception {
+        // The first job stays queued; the second one activates both.
+        onCollision = ctx -> {
+            if (ctx.waitingJobs().size() == 1)
+                firstJobArrivedLatch.countDown();
+            else
+                ctx.waitingJobs().forEach(CollisionJobContext::activate);
+        };
+
+        IgniteFuture<TaskExecution> firstFut = executeWithContext(new 
RegularJob(), FIRST_USR_VAL);
+
+        assertTrue(firstJobArrivedLatch.await(getTestTimeout(), MILLISECONDS));
+
+        TaskExecution secondExecRes = executeWithContext(new RegularJob(), 
SECOND_USR_VAL).get(getTestTimeout());
+        TaskExecution firstExecRes = firstFut.get(getTestTimeout());
+
+        assertExecutedWith(FIRST_USR_VAL, firstExecRes);
+        assertExecutedWith(SECOND_USR_VAL, secondExecRes);
+    }
+
+    /** */
+    @Test
+    public void testJobCancelledByAnotherTaskIsCancelledUnderTheJobContext() 
throws Exception {
+        // The first job runs; the second one cancels it and runs.
+        onCollision = ctx -> {
+            if (ctx.waitingJobs().isEmpty())
+                return;
+
+            ctx.activeJobs().forEach(CollisionJobContext::cancel);
+            ctx.waitingJobs().forEach(CollisionJobContext::activate);
+
+            firstJobArrivedLatch.countDown();
+        };
+
+        IgniteFuture<TaskExecution> firstFut = executeWithContext(new 
CancellableJob(), FIRST_USR_VAL);
+
+        assertTrue(firstJobArrivedLatch.await(getTestTimeout(), MILLISECONDS));
+
+        TaskExecution secondExecRes = executeWithContext(new RegularJob(), 
SECOND_USR_VAL).get(getTestTimeout());
+        TaskExecution firstExecRes = firstFut.get(getTestTimeout());
+
+        assertExecutedWith(FIRST_USR_VAL, firstExecRes);
+        assertExecutedWith(SECOND_USR_VAL, secondExecRes);
+    }
+
+    /** */
+    @Test
+    public void 
testSuspendedJobResumedUnderAnotherContextRunsUnderTheJobContext() throws 
Exception {
+        SuspendedJob.jobSuspendedLatch = new CountDownLatch(1);
+
+        IgniteFuture<TaskExecution> fut = executeWithContext(new 
SuspendedJob(), FIRST_USR_VAL);
+
+        assertTrue(SuspendedJob.jobSuspendedLatch.await(getTestTimeout(), 
MILLISECONDS));
+
+        try (Scope ignored = OperationContext.set(USR_ATTR, SECOND_USR_VAL)) {
+            SuspendedJob.jobCtx.callcc();
+        }
+
+        assertExecutedWith(FIRST_USR_VAL, fut.get(getTestTimeout()));
+    }
+
+    /** */
+    @Test
+    public void testMasterNodeLeftCallbackRunsUnderTheJobContext() throws 
Exception {
+        MasterLeaveAwareJob.jobStartedLatch = new CountDownLatch(1);
+        MasterLeaveAwareJob.masterNodeLeftLatch = new CountDownLatch(1);
+
+        executeWithContext(new MasterLeaveAwareJob(), FIRST_USR_VAL);
+
+        try {
+            
assertTrue(MasterLeaveAwareJob.jobStartedLatch.await(getTestTimeout(), 
MILLISECONDS));
+
+            stopGrid(0, true);
+
+            
assertTrue(MasterLeaveAwareJob.masterNodeLeftLatch.await(getTestTimeout(), 
MILLISECONDS));
+            assertEquals(FIRST_USR_VAL, 
MasterLeaveAwareJob.attrSeenByMasterLeft);
+        }
+        finally {
+            MasterLeaveAwareJob.masterNodeLeftLatch.countDown();
+        }
+    }
+
+    /** */
+    private static void assertExecutedWith(User expAttrVal, TaskExecution 
exec) {
+        assertEquals(new TaskExecution(expAttrVal, expAttrVal, expAttrVal), 
exec);
+    }
+
+    /** */
+    private IgniteFuture<TaskExecution> executeWithContext(ComputeJob job, 
User attrVal) {
+        IgniteEx initiator = grid(0);
+
+        try (Scope ignored = OperationContext.set(USR_ATTR, attrVal)) {
+            return 
initiator.compute(initiator.cluster().forNodeId(grid(1).localNode().id())).executeAsync(SingleJobTask.class,
 job);
+        }
+    }
+
+    /** */
+    private record TaskExecution(
+        @Nullable User attributeSeenByTaskResult,
+        @Nullable User attributeSeenByTaskReduce,
+        @Nullable User attributeSeenByJob
+    ) {}
+
+    /** */
+    private static class SingleJobTask extends ComputeTaskAdapter<ComputeJob, 
TaskExecution> {
+        /** */
+        private @Nullable User seenByResult;
+
+        /** {@inheritDoc} */
+        @Override public Map<? extends ComputeJob, ClusterNode> 
map(List<ClusterNode> subgrid, ComputeJob job) {
+            return Map.of(job, subgrid.get(0));
+        }
+
+        /** {@inheritDoc} */
+        @Override public ComputeJobResultPolicy result(ComputeJobResult res, 
List<ComputeJobResult> rcvd) {
+            seenByResult = OperationContext.get(USR_ATTR);
+
+            return ComputeJobResultPolicy.REDUCE;
+        }
+
+        /** {@inheritDoc} */
+        @Override public TaskExecution reduce(List<ComputeJobResult> results) {
+            User seenByReduce = OperationContext.get(USR_ATTR);
+
+            return new TaskExecution(seenByResult, seenByReduce, 
results.get(0).getData());
+        }
+    }
+
+    /** */
+    private static class RegularJob extends ComputeJobAdapter {
+        /** {@inheritDoc} */
+        @Override public Object execute() {
+            return OperationContext.get(USR_ATTR);
+        }
+    }
+
+    /** */
+    private static class CancellableJob extends ComputeJobAdapter {
+        /** */
+        private final CountDownLatch jobCancelledLatch = new CountDownLatch(1);
+
+        /** */
+        private @Nullable User attrSeenByCancel;
+
+        /** {@inheritDoc} */
+        @Override public Object execute() {
+            try {
+                jobCancelledLatch.await();
+            }
+            catch (InterruptedException ignored) {
+                Thread.currentThread().interrupt();
+            }
+
+            return attrSeenByCancel;
+        }
+
+        /** {@inheritDoc} */
+        @Override public void cancel() {
+            attrSeenByCancel = OperationContext.get(USR_ATTR);
+
+            jobCancelledLatch.countDown();
+        }
+    }
+
+    /** */
+    private static class SuspendedJob extends ComputeJobAdapter {
+        /** */
+        static volatile CountDownLatch jobSuspendedLatch;
+
+        /** */
+        static volatile ComputeJobContext jobCtx;
+
+        /** */
+        @JobContextResource
+        private transient ComputeJobContext ctx;
+
+        /** */
+        private boolean suspended;
+
+        /** {@inheritDoc} */
+        @Override public Object execute() {
+            if (suspended)
+                return OperationContext.get(USR_ATTR);
+
+            suspended = true;
+
+            jobCtx = ctx;
+
+            ctx.holdcc();
+
+            jobSuspendedLatch.countDown();
+
+            return null;
+        }
+    }
+
+    /** */
+    private static class MasterLeaveAwareJob extends ComputeJobAdapter 
implements ComputeJobMasterLeaveAware {
+        /** */
+        static volatile CountDownLatch jobStartedLatch;
+
+        /** */
+        static volatile CountDownLatch masterNodeLeftLatch;
+
+        /** */
+        static volatile User attrSeenByMasterLeft;
+
+        /** {@inheritDoc} */
+        @Override public Object execute() {
+            jobStartedLatch.countDown();
+
+            try {
+                masterNodeLeftLatch.await();
+            }
+            catch (InterruptedException ignored) {
+                Thread.currentThread().interrupt();
+            }
+
+            return null;
+        }
+
+        /** {@inheritDoc} */
+        @Override public void onMasterNodeLeft(ComputeTaskSession ses) {
+            attrSeenByMasterLeft = OperationContext.get(USR_ATTR);
+
+            masterNodeLeftLatch.countDown();
+        }
+    }
+
+    /** */
+    @IgniteSpiMultipleInstancesSupport(true)
+    public static class TestCollisionSpi extends IgniteSpiAdapter implements 
CollisionSpi {
+        /** {@inheritDoc} */
+        @Override public void onCollision(CollisionContext ctx) {
+            Consumer<CollisionContext> hnd = onCollision;
+
+            if (hnd == null)
+                ctx.waitingJobs().forEach(CollisionJobContext::activate);
+            else
+                hnd.accept(ctx);
+        }
+
+        /** {@inheritDoc} */
+        @Override public void 
setExternalCollisionListener(CollisionExternalListener lsnr) {
+            // No-op.
+        }
+
+        /** {@inheritDoc} */
+        @Override public void spiStart(String igniteInstanceName) throws 
IgniteSpiException {
+            // No-op.
+        }
+
+        /** {@inheritDoc} */
+        @Override public void spiStop() throws IgniteSpiException {
+            // No-op.
+        }
+    }
+
+    /** */
+    private static class TestIgniteComponent extends 
AbstractTestPluginProvider {
+        /** {@inheritDoc} */
+        @Override public String name() {
+            return "TestComputeTaskOperationContextAttributeRegistrator";
+        }
+
+        /** {@inheritDoc} */
+        @Override public void start(PluginContext ctx) {
+            
((IgniteEx)ctx.grid()).context().operationContextDispatcher().registerDistributedAttribute(MAX_ATTRS_CNT
 - 1, USR_ATTR);
+        }
+    }
+}
diff --git 
a/modules/core/src/test/java/org/apache/ignite/testsuites/SecurityTestSuite.java
 
b/modules/core/src/test/java/org/apache/ignite/testsuites/SecurityTestSuite.java
index 375908bcca8..da768a22290 100644
--- 
a/modules/core/src/test/java/org/apache/ignite/testsuites/SecurityTestSuite.java
+++ 
b/modules/core/src/test/java/org/apache/ignite/testsuites/SecurityTestSuite.java
@@ -74,6 +74,7 @@ import 
org.apache.ignite.internal.processors.security.scheduler.SchedulerRemoteS
 import 
org.apache.ignite.internal.processors.security.service.ServiceAuthorizationTest;
 import 
org.apache.ignite.internal.processors.security.service.ServiceStaticConfigTest;
 import 
org.apache.ignite.internal.processors.security.snapshot.SnapshotPermissionCheckTest;
+import 
org.apache.ignite.internal.thread.context.ComputeTaskOperationContextPropagationTest;
 import 
org.apache.ignite.internal.thread.context.OperationContextAttributePropagationTest;
 import 
org.apache.ignite.internal.thread.context.OperationContextAttributesTest;
 import 
org.apache.ignite.plugin.security.SecurityBasicPermissionSetSerializationTest;
@@ -152,6 +153,7 @@ import org.junit.runners.Suite;
     NodeConnectionCertificateCapturingTest.class,
     OperationContextAttributesTest.class,
     OperationContextAttributePropagationTest.class,
+    ComputeTaskOperationContextPropagationTest.class,
     SecurityBasicPermissionSetSerializationTest.class,
 })
 public class SecurityTestSuite {

Reply via email to