Files
tasks/service/history/shard/context.go
Stephan BehnkeandGitHub a15204553b Clear workflow contexts on History Shard closure (#6090)
## What changed?
<!-- Describe what has changed in this PR -->

Clear all workflow contexts, found in the cache, that belong to a
History Shard that is being closed.

## Why?
<!-- Tell your future self why have you made these changes -->

Right now, when a History Shard is closed, any non-durable Update that
is still in-flight will be "lost", meaning that there is no way to
access it, cancel it or complete it anymore. The client that issued the
Update is not informed about this either (neither is the Frontend).

A better experience is to forcibly cancel any in-flight Updates
belonging to the History Shard that is closing. That way, the Frontend
can re-issue the Update request (which will land on a new History
Shard). The client won't even know that the History Shard was closed.
However, if the retry happens towards the end of the Update timeout, the
client's request might still time out after all.

## How did you test it?
<!-- How have you verified this change? Tested locally? Added a unit
test? Checked in staging env? -->

Added unit tests and functional test.

Before going live, this will have to be validated by thorough end-to-end
testing.

## Potential risks
<!-- Assuming the worst case, what can be broken when deploying this
change to production? -->

### Code Complexity

Since the workflow cache already has all the workflow contexts, I had
considered adding a by-shardID index a method to iterate over them
there. However, its cache implementation is based on `cache.Cache` (ie a
generic cache) it would have been awkward to add it there. Therefore, I
decided to track the workflow contexts in a separate place, the
Finalizer, which adds to the complexity.

### Memory Leak

There is no way to list the workflow contexts that belong to a History
Shard. Therefore, a new "Finalizer" was introduced that maintains a list
of cleanup callbacks: one callback per workflow context, grouped by
History Shard.

But since the workflow cache will eventually evict workflow contexts
that are no longer needed, if the Finalizer holds on to these cleanup
callbacks past the lifetime of the workflow context, the GC won't be
able to free them from memory. Therefore, a lifecycle hook was
introduced that removes any expired workflow contexts from the
Finalizer.

### Delayed History Shard Closure

The step to close the History Shard should not lock up if some/any of
the workflow contexts cannot be cleared. To clear them, the lock for the
workflow needs to be obtained. To prevent this from blocking
indefinitely, a timeout was introduced. It's better to make sure the
History Shard closes eventually than to clear all workflow contexts.

PS: Logging has been added to be able to monitor the timeouts and
completion rate of the Finalizer.

PPS: If any production issues should occur, the Finalizer's cleanup step
can be disabled entirely by setting the dynamic config for the timeout
to zero. However, the registering/de-registering of callbacks cannot be
disabled.

## Documentation
<!-- Have you made sure this change doesn't falsify anything currently
stated in `docs/`? If significant
new behavior is added, have you described that in `docs/`? -->

## Is hotfix candidate?
<!-- Is this PR a hotfix candidate or does it require a notification to
be sent to the broader community? (Yes/No) -->
2024-07-16 18:07:31 -07:00

138 lines
6.2 KiB
Go

// The MIT License
//
// Copyright (c) 2020 Temporal Technologies Inc. All rights reserved.
//
// Copyright (c) 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 shard
import (
"context"
"time"
commonpb "go.temporal.io/api/common/v1"
"go.temporal.io/server/api/adminservice/v1"
clockspb "go.temporal.io/server/api/clock/v1"
"go.temporal.io/server/api/historyservice/v1"
persistencespb "go.temporal.io/server/api/persistence/v1"
"go.temporal.io/server/common/archiver"
"go.temporal.io/server/common/clock"
"go.temporal.io/server/common/cluster"
"go.temporal.io/server/common/definition"
"go.temporal.io/server/common/finalizer"
"go.temporal.io/server/common/log"
"go.temporal.io/server/common/metrics"
"go.temporal.io/server/common/namespace"
"go.temporal.io/server/common/persistence"
"go.temporal.io/server/common/persistence/serialization"
"go.temporal.io/server/common/pingable"
"go.temporal.io/server/common/searchattribute"
"go.temporal.io/server/service/history/configs"
"go.temporal.io/server/service/history/events"
"go.temporal.io/server/service/history/hsm"
"go.temporal.io/server/service/history/tasks"
)
//go:generate mockgen -copyright_file ../../../LICENSE -package $GOPACKAGE -source $GOFILE -destination context_mock.go
type (
// Context represents a history engine shard
Context interface {
GetShardID() int32
GetRangeID() int64
GetOwner() string
GetExecutionManager() persistence.ExecutionManager
GetNamespaceRegistry() namespace.Registry
GetClusterMetadata() cluster.Metadata
GetConfig() *configs.Config
GetEventsCache() events.Cache
GetLogger() log.Logger
GetThrottledLogger() log.Logger
GetMetricsHandler() metrics.Handler
GetTimeSource() clock.TimeSource
GetRemoteAdminClient(string) (adminservice.AdminServiceClient, error)
GetHistoryClient() historyservice.HistoryServiceClient
GetPayloadSerializer() serialization.Serializer
GetSearchAttributesProvider() searchattribute.Provider
GetSearchAttributesMapperProvider() searchattribute.MapperProvider
GetArchivalMetadata() archiver.ArchivalMetadata
GetEngine(ctx context.Context) (Engine, error)
AssertOwnership(ctx context.Context) error
NewVectorClock() (*clockspb.VectorClock, error)
CurrentVectorClock() *clockspb.VectorClock
GenerateTaskID() (int64, error)
GenerateTaskIDs(number int) ([]int64, error)
GetQueueExclusiveHighReadWatermark(category tasks.Category) tasks.Key
GetQueueState(category tasks.Category) (*persistencespb.QueueState, bool)
SetQueueState(category tasks.Category, tasksCompleted int, state *persistencespb.QueueState) error
UpdateReplicationQueueReaderState(readerID int64, readerState *persistencespb.QueueReaderState) error
GetReplicatorDLQAckLevel(sourceCluster string) int64
UpdateReplicatorDLQAckLevel(sourCluster string, ackLevel int64) error
UpdateRemoteClusterInfo(cluster string, ackTaskID int64, ackTimestamp time.Time)
UpdateRemoteReaderInfo(readerID int64, ackTaskID int64, ackTimestamp time.Time) error
SetCurrentTime(cluster string, currentTime time.Time)
GetCurrentTime(cluster string) time.Time
GetReplicationStatus(cluster []string) (map[string]*historyservice.ShardReplicationStatusPerCluster, map[string]*historyservice.HandoverNamespaceInfo, error)
UpdateHandoverNamespace(ns *namespace.Namespace, deletedFromDb bool)
AppendHistoryEvents(ctx context.Context, request *persistence.AppendHistoryNodesRequest, namespaceID namespace.ID, execution *commonpb.WorkflowExecution) (int, error)
AddTasks(ctx context.Context, request *persistence.AddHistoryTasksRequest) error
AddSpeculativeWorkflowTaskTimeoutTask(task *tasks.WorkflowTaskTimeoutTask) error
CreateWorkflowExecution(ctx context.Context, request *persistence.CreateWorkflowExecutionRequest) (*persistence.CreateWorkflowExecutionResponse, error)
UpdateWorkflowExecution(ctx context.Context, request *persistence.UpdateWorkflowExecutionRequest) (*persistence.UpdateWorkflowExecutionResponse, error)
ConflictResolveWorkflowExecution(ctx context.Context, request *persistence.ConflictResolveWorkflowExecutionRequest) (*persistence.ConflictResolveWorkflowExecutionResponse, error)
SetWorkflowExecution(ctx context.Context, request *persistence.SetWorkflowExecutionRequest) (*persistence.SetWorkflowExecutionResponse, error)
GetCurrentExecution(ctx context.Context, request *persistence.GetCurrentExecutionRequest) (*persistence.GetCurrentExecutionResponse, error)
GetWorkflowExecution(ctx context.Context, request *persistence.GetWorkflowExecutionRequest) (*persistence.GetWorkflowExecutionResponse, error)
// DeleteWorkflowExecution add task to delete visibility, current workflow execution, and deletes workflow execution.
// If branchToken != nil, then delete history also, otherwise leave history.
DeleteWorkflowExecution(ctx context.Context, workflowKey definition.WorkflowKey, branchToken []byte, closeExecutionVisibilityTaskID int64, workflowCloseTime time.Time, stage *tasks.DeleteWorkflowExecutionStage) error
UnloadForOwnershipLost()
StateMachineRegistry() *hsm.Registry
GetFinalizer() *finalizer.Finalizer
}
// A ControllableContext is a Context plus other methods needed by
// the Controller.
ControllableContext interface {
Context
pingable.Pingable
IsValid() bool
FinishStop()
}
)