Skip to content

Commit

Permalink
Add task isolation leaking (cadence-workflow#6544)
Browse files Browse the repository at this point in the history
Add taskIsolationDuration, the time during which tasks will only be routed to pollers belonging to the same isolation group as them*.

Additionally replace the hardcoded constants of 1 minute and 10s for startup flexibilility and recent poller lookback respectively with a single value: TaskIsolationPollerWindow.

For the sake of measuring impact we now include the original partition group within the partition config prior to dispatching the task. This value isn't persisted within the tasks table and is only necessary so that a task that is forwarded after abandoning isolation will emit the correct metric. No behavior depends on this value, it is only used in metrics.

Add integration tests for tasklist isolation, as well as unit tests for getIsolationGroupForTask.

Update the matching simulator to include this new value.
  • Loading branch information
natemort authored Dec 13, 2024
1 parent 339f04f commit 6f41871
Show file tree
Hide file tree
Showing 26 changed files with 852 additions and 57 deletions.
26 changes: 26 additions & 0 deletions common/dynamicconfig/constants.go
Original file line number Diff line number Diff line change
Expand Up @@ -2796,6 +2796,20 @@ const (
// Allowed filters: domainName, taskListName, taskListType
LocalTaskWaitTime

// TaskIsolationDuration is the time period for which we attempt to respect tasklist isolation before allowing any poller to process the task
// KeyName: matching.taskIsolationDuration
// Value type: Duration
// Default value: 0
// Allowed filters: domainName, taskListName, taskListType
TaskIsolationDuration

// TaskIsolationPollerWindow is the time period for which pollers are remembered when deciding whether to skip tasklist isolation due to unpolled isolation groups.
// KeyName: matching.taskIsolationPollerWindow
// Value type: Duration
// Default value: 10s
// Allowed filters: domainName, taskListName, taskListType
TaskIsolationPollerWindow

// LastDurationKey must be the last one in this const group
LastDurationKey
)
Expand Down Expand Up @@ -5077,6 +5091,18 @@ var DurationKeys = map[DurationKey]DynamicDuration{
Description: "LocalTaskWaitTime is the time a task waits for a poller to arrive before considering task forwarding",
DefaultValue: time.Millisecond * 10,
},
TaskIsolationDuration: {
KeyName: "matching.taskIsolationDuration",
Filters: []Filter{DomainName, TaskListName, TaskType},
Description: "TaskIsolationDuration is the time period for which we attempt to respect tasklist isolation before allowing any poller to process the task",
DefaultValue: 0,
},
TaskIsolationPollerWindow: {
KeyName: "matching.taskIsolationPollerWindow",
Filters: []Filter{DomainName, TaskListName, TaskType},
Description: "TaskIsolationDuration is the time period for which we attempt to respect tasklist isolation before allowing any poller to process the task",
DefaultValue: time.Second * 10,
},
}

var MapKeys = map[MapKey]DynamicMap{
Expand Down
8 changes: 8 additions & 0 deletions common/log/tag/tags.go
Original file line number Diff line number Diff line change
Expand Up @@ -982,6 +982,14 @@ func IsolationGroup(group string) Tag {
return newStringTag("isolation-group", group)
}

func TaskLatency(duration time.Duration) Tag {
return newDurationTag("task-latency", duration)
}

func IsolationDuration(duration time.Duration) Tag {
return newDurationTag("isolation-duration", duration)
}

func PartitionConfig(p map[string]string) Tag {
return newObjectTag("partition-config", p)
}
Expand Down
5 changes: 4 additions & 1 deletion common/metrics/defs.go
Original file line number Diff line number Diff line change
Expand Up @@ -2638,7 +2638,8 @@ const (
StandbyClusterTasksCompletedCounterPerTaskList
StandbyClusterTasksNotStartedCounterPerTaskList
StandbyClusterTasksCompletionFailurePerTaskList

TaskIsolationExpiredPerTaskList
TaskIsolationErrorPerTaskList
NumMatchingMetrics
)

Expand Down Expand Up @@ -3334,6 +3335,8 @@ var MetricDefs = map[ServiceIdx]map[int]metricDefinition{
StandbyClusterTasksCompletedCounterPerTaskList: {metricName: "standby_cluster_tasks_completed_per_tl", metricType: Counter},
StandbyClusterTasksNotStartedCounterPerTaskList: {metricName: "standby_cluster_tasks_not_started_per_tl", metricType: Counter},
StandbyClusterTasksCompletionFailurePerTaskList: {metricName: "standby_cluster_tasks_completion_failure_per_tl", metricType: Counter},
TaskIsolationExpiredPerTaskList: {metricName: "task_isolation_expired_per_tl", metricRollupName: "task_isolation_expired"},
TaskIsolationErrorPerTaskList: {metricName: "task_isolation_error_per_tl", metricRollupName: "task_isolation_error"},
},
Worker: {
ReplicatorMessages: {metricName: "replicator_messages"},
Expand Down
23 changes: 9 additions & 14 deletions common/metrics/tags.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@
package metrics

import (
"fmt"
"regexp"
"strconv"
)
Expand Down Expand Up @@ -65,6 +64,8 @@ const (
workflowTerminationReason = "workflow_termination_reason"
workflowCloseStatus = "workflow_close_status"
isolationEnabled = "isolation_enabled"
isolationGroup = "isolation_group"
originalIsolationGroup = "original_isolation_group"
topic = "topic"
mode = "mode"

Expand Down Expand Up @@ -312,19 +313,13 @@ func WorkflowCloseStatusTag(value string) Tag {
return simpleMetric{key: workflowCloseStatus, value: value}
}

// PartitionConfigTags returns a list of partition config tags
func PartitionConfigTags(partitionConfig map[string]string) []Tag {
tags := make([]Tag, 0, len(partitionConfig))
for k, v := range partitionConfig {
if len(k) == 0 {
continue
}
if len(v) == 0 {
v = unknownValue
}
tags = append(tags, simpleMetric{key: sanitizer.Value(fmt.Sprintf("pk_%s", k)), value: sanitizer.Value(v)})
}
return tags
func OriginalIsolationGroupTag(group string) Tag {
return simpleMetric{key: originalIsolationGroup, value: sanitizer.Value(group)}
}

func IsolationGroupTag(group string) Tag {
return simpleMetric{key: isolationGroup, value: sanitizer.Value(group)}

}

// IsolationEnabledTag returns whether isolation is enabled
Expand Down
5 changes: 3 additions & 2 deletions common/partition/default-partitioner.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,9 @@ import (
)

const (
IsolationGroupKey = "isolation-group"
WorkflowIDKey = "wf-id"
IsolationGroupKey = "isolation-group"
OriginalIsolationGroupKey = "original-isolation-group"
WorkflowIDKey = "wf-id"
)

// ErrNoIsolationGroupsAvailable is returned when there are no available isolation-groups
Expand Down
1 change: 1 addition & 0 deletions host/matching_simulation_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,7 @@ func TestMatchingSimulationSuite(t *testing.T) {
dynamicconfig.MatchingPartitionUpscaleSustainedDuration: clusterConfig.MatchingConfig.SimulationConfig.PartitionUpscaleSustainedDuration,
dynamicconfig.MatchingPartitionDownscaleSustainedDuration: clusterConfig.MatchingConfig.SimulationConfig.PartitionDownscaleSustainedDuration,
dynamicconfig.MatchingAdaptiveScalerUpdateInterval: clusterConfig.MatchingConfig.SimulationConfig.AdaptiveScalerUpdateInterval,
dynamicconfig.TaskIsolationDuration: clusterConfig.MatchingConfig.SimulationConfig.TaskIsolationDuration,
}

ctrl := gomock.NewController(t)
Expand Down
6 changes: 5 additions & 1 deletion host/onebox.go
Original file line number Diff line number Diff line change
Expand Up @@ -204,6 +204,7 @@ type (
PartitionUpscaleSustainedDuration time.Duration
PartitionDownscaleSustainedDuration time.Duration
AdaptiveScalerUpdateInterval time.Duration
TaskIsolationDuration time.Duration
}

SimulationPollerConfiguration struct {
Expand Down Expand Up @@ -1109,7 +1110,10 @@ func (c *cadenceImpl) newRPCFactory(serviceName string, host membership.HostInfo
TChannelAddress: tchannelAddress,
GRPCAddress: grpcAddress,
InboundMiddleware: yarpc.InboundMiddleware{
Unary: &versionMiddleware{},
Unary: yarpc.UnaryInboundMiddleware(&versionMiddleware{}, &rpc.ClientPartitionConfigMiddleware{}, &rpc.ForwardPartitionConfigMiddleware{}),
},
OutboundMiddleware: yarpc.OutboundMiddleware{
Unary: &rpc.ForwardPartitionConfigMiddleware{},
},

// For integration tests to generate client out of the same outbound.
Expand Down
213 changes: 213 additions & 0 deletions host/task_list_isolation_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,213 @@
// The MIT License (MIT)

// Copyright (c) 2017-2020 Uber Technologies Inc.

// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

package host

import (
"errors"
"flag"
"strconv"
"testing"
"time"

"github.com/pborman/uuid"
"github.com/stretchr/testify/require"
"github.com/stretchr/testify/suite"
"go.uber.org/yarpc"

"github.com/uber/cadence/common"
"github.com/uber/cadence/common/dynamicconfig"
"github.com/uber/cadence/common/types"
)

const (
tl = "integration-task-list-isolation-tl"
)

func TestTaskListIsolationSuite(t *testing.T) {
flag.Parse()

var isolationGroups = []any{
"a", "b", "c",
}
clusterConfig, err := GetTestClusterConfig("testdata/task_list_isolation_test_cluster.yaml")
if err != nil {
panic(err)
}
testCluster := NewPersistenceTestCluster(t, clusterConfig)
clusterConfig.FrontendDynamicConfigOverrides = map[dynamicconfig.Key]interface{}{
dynamicconfig.EnableTasklistIsolation: true,
dynamicconfig.AllIsolationGroups: isolationGroups,
dynamicconfig.MatchingNumTasklistWritePartitions: 1,
dynamicconfig.MatchingNumTasklistReadPartitions: 1,
}
clusterConfig.HistoryDynamicConfigOverrides = map[dynamicconfig.Key]interface{}{
dynamicconfig.EnableTasklistIsolation: true,
dynamicconfig.AllIsolationGroups: isolationGroups,
dynamicconfig.MatchingNumTasklistWritePartitions: 1,
dynamicconfig.MatchingNumTasklistReadPartitions: 1,
}
clusterConfig.MatchingDynamicConfigOverrides = map[dynamicconfig.Key]interface{}{
dynamicconfig.EnableTasklistIsolation: true,
dynamicconfig.AllIsolationGroups: isolationGroups,
dynamicconfig.TaskIsolationDuration: time.Second * 5,
dynamicconfig.MatchingNumTasklistWritePartitions: 1,
dynamicconfig.MatchingNumTasklistReadPartitions: 1,
}

s := new(TaskListIsolationIntegrationSuite)
params := IntegrationBaseParams{
DefaultTestCluster: testCluster,
VisibilityTestCluster: testCluster,
TestClusterConfig: clusterConfig,
}
s.IntegrationBase = NewIntegrationBase(params)
suite.Run(t, s)
}

func (s *TaskListIsolationIntegrationSuite) SetupSuite() {
s.setupSuite()
}

func (s *TaskListIsolationIntegrationSuite) TearDownSuite() {
s.tearDownSuite()
}

func (s *TaskListIsolationIntegrationSuite) SetupTest() {
// Have to define our overridden assertions in the test setup. If we did it earlier, s.T() will return nil
s.Assertions = require.New(s.T())
}

func (s *TaskListIsolationIntegrationSuite) TestTaskListIsolation() {
aPoller := s.createPoller("a")
bPoller := s.createPoller("b")

cancelB := bPoller.PollAndProcessDecisions()
defer cancelB()
cancelA := aPoller.PollAndProcessDecisions()
defer cancelA()

// Give pollers time to start
time.Sleep(time.Second)

// Running a single workflow is a bit of a coinflip: if isolation didn't work, it would pass 50% of the time.
// Run 10 workflows to demonstrate that we consistently isolate tasks to the correct poller
for i := 0; i < 10; i++ {
runID := s.startWorkflow("a").RunID
result, err := s.getWorkflowResult(runID)
s.NoError(err)
s.Equal("a", result)
}
}

func (s *TaskListIsolationIntegrationSuite) TestTaskListIsolationLeak() {
runID := s.startWorkflow("a").RunID

bPoller := s.createPoller("b")
// B will get the task as there are no pollers from A
cancelB := bPoller.PollAndProcessDecisions()
defer cancelB()

result, err := s.getWorkflowResult(runID)
s.NoError(err)
s.Equal("b", result)
}

func (s *TaskListIsolationIntegrationSuite) createPoller(group string) *TaskPoller {
return &TaskPoller{
Engine: s.engine,
Domain: s.domainName,
TaskList: &types.TaskList{Name: tl, Kind: types.TaskListKindNormal.Ptr()},
Identity: group,
DecisionHandler: func(execution *types.WorkflowExecution, wt *types.WorkflowType, previousStartedEventID, startedEventID int64, history *types.History) ([]byte, []*types.Decision, error) {
// Complete the workflow with the group name
return []byte(strconv.Itoa(0)), []*types.Decision{{
DecisionType: types.DecisionTypeCompleteWorkflowExecution.Ptr(),
CompleteWorkflowExecutionDecisionAttributes: &types.CompleteWorkflowExecutionDecisionAttributes{
Result: []byte(group),
},
}}, nil
},
Logger: s.Logger,
T: s.T(),
CallOptions: []yarpc.CallOption{withIsolationGroup(group)},
}
}

func (s *TaskListIsolationIntegrationSuite) startWorkflow(group string) *types.StartWorkflowExecutionResponse {
identity := "test"

request := &types.StartWorkflowExecutionRequest{
RequestID: uuid.New(),
Domain: s.domainName,
WorkflowID: s.T().Name(),
WorkflowType: &types.WorkflowType{
Name: "integration-task-list-isolation-type",
},
TaskList: &types.TaskList{
Name: tl,
Kind: types.TaskListKindNormal.Ptr(),
},
Input: nil,
ExecutionStartToCloseTimeoutSeconds: common.Int32Ptr(10),
TaskStartToCloseTimeoutSeconds: common.Int32Ptr(1),
Identity: identity,
WorkflowIDReusePolicy: types.WorkflowIDReusePolicyAllowDuplicate.Ptr(),
}

ctx, cancel := createContext()
defer cancel()
result, err := s.engine.StartWorkflowExecution(ctx, request, withIsolationGroup(group))
s.Nil(err)

return result
}

func (s *TaskListIsolationIntegrationSuite) getWorkflowResult(runID string) (string, error) {
ctx, cancel := createContext()
historyResponse, err := s.engine.GetWorkflowExecutionHistory(ctx, &types.GetWorkflowExecutionHistoryRequest{
Domain: s.domainName,
Execution: &types.WorkflowExecution{
WorkflowID: s.T().Name(),
RunID: runID,
},
HistoryEventFilterType: types.HistoryEventFilterTypeCloseEvent.Ptr(),
WaitForNewEvent: true,
})
cancel()
if err != nil {
return "", err
}
history := historyResponse.History

lastEvent := history.Events[len(history.Events)-1]
if *lastEvent.EventType != types.EventTypeWorkflowExecutionCompleted {
return "", errors.New("workflow didn't complete")
}

return string(lastEvent.WorkflowExecutionCompletedEventAttributes.Result), nil

}

func withIsolationGroup(group string) yarpc.CallOption {
return yarpc.WithHeader(common.ClientIsolationGroupHeaderName, group)
}
Loading

0 comments on commit 6f41871

Please sign in to comment.