-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Expand file tree
/
Copy pathmutable_state_impl.go
More file actions
9307 lines (8304 loc) · 334 KB
/
mutable_state_impl.go
File metadata and controls
9307 lines (8304 loc) · 334 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package workflow
import (
"cmp"
"context"
"errors"
"fmt"
"math/rand"
"reflect"
"slices"
"strings"
"time"
"github.com/google/uuid"
"github.com/nexus-rpc/sdk-go/nexus"
commandpb "go.temporal.io/api/command/v1"
commonpb "go.temporal.io/api/common/v1"
deploymentpb "go.temporal.io/api/deployment/v1"
enumspb "go.temporal.io/api/enums/v1"
failurepb "go.temporal.io/api/failure/v1"
historypb "go.temporal.io/api/history/v1"
rulespb "go.temporal.io/api/rules/v1"
"go.temporal.io/api/serviceerror"
taskqueuepb "go.temporal.io/api/taskqueue/v1"
updatepb "go.temporal.io/api/update/v1"
workflowpb "go.temporal.io/api/workflow/v1"
"go.temporal.io/api/workflowservice/v1"
clockspb "go.temporal.io/server/api/clock/v1"
enumsspb "go.temporal.io/server/api/enums/v1"
historyspb "go.temporal.io/server/api/history/v1"
"go.temporal.io/server/api/historyservice/v1"
persistencespb "go.temporal.io/server/api/persistence/v1"
taskqueuespb "go.temporal.io/server/api/taskqueue/v1"
tokenspb "go.temporal.io/server/api/token/v1"
workflowspb "go.temporal.io/server/api/workflow/v1"
"go.temporal.io/server/chasm"
chasmworkflow "go.temporal.io/server/chasm/lib/workflow"
"go.temporal.io/server/common"
"go.temporal.io/server/common/backoff"
"go.temporal.io/server/common/clock"
"go.temporal.io/server/common/cluster"
"go.temporal.io/server/common/contextutil"
"go.temporal.io/server/common/convert"
"go.temporal.io/server/common/definition"
"go.temporal.io/server/common/enums"
"go.temporal.io/server/common/failure"
"go.temporal.io/server/common/headers"
"go.temporal.io/server/common/log"
"go.temporal.io/server/common/log/tag"
"go.temporal.io/server/common/metrics"
"go.temporal.io/server/common/namespace"
commonnexus "go.temporal.io/server/common/nexus"
"go.temporal.io/server/common/nexus/nexusrpc"
"go.temporal.io/server/common/payload"
"go.temporal.io/server/common/persistence"
"go.temporal.io/server/common/persistence/transitionhistory"
"go.temporal.io/server/common/persistence/versionhistory"
"go.temporal.io/server/common/primitives/timestamp"
"go.temporal.io/server/common/searchattribute/sadefs"
serviceerrors "go.temporal.io/server/common/serviceerror"
"go.temporal.io/server/common/softassert"
"go.temporal.io/server/common/util"
"go.temporal.io/server/common/worker_versioning"
"go.temporal.io/server/components/callbacks"
"go.temporal.io/server/service/history/configs"
"go.temporal.io/server/service/history/consts"
"go.temporal.io/server/service/history/events"
"go.temporal.io/server/service/history/historybuilder"
"go.temporal.io/server/service/history/hsm"
historyi "go.temporal.io/server/service/history/interfaces"
"go.temporal.io/server/service/history/tasks"
"go.temporal.io/server/service/history/workflow/update"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/types/known/durationpb"
"google.golang.org/protobuf/types/known/timestamppb"
)
const (
emptyUUID = "emptyUuid"
mutableStateInvalidHistoryActionMsg = "invalid history builder state for action"
mutableStateInvalidHistoryActionMsgTemplate = mutableStateInvalidHistoryActionMsg + ": %v, %v"
int64SizeBytes = 8
)
// Scheduled tasks with timestamp after this will not be created.
// Those tasks are too far in the future and practically never fire and just consume storage space.
// NOTE: this value is less than timer.MaxAllowedTimer so that no capped timers will be created.
var maxScheduledTaskDuration = time.Hour * 24 * 365 * 99
var (
// ErrWorkflowFinished indicates trying to mutate mutable state after workflow finished
ErrWorkflowFinished = serviceerror.NewInternal("invalid mutable state action: mutation after finish")
// ErrMissingTimerInfo indicates missing timer info
ErrMissingTimerInfo = serviceerror.NewInternal("unable to get timer info")
// ErrMissingActivityInfo indicates missing activity info
ErrMissingActivityInfo = serviceerror.NewInternal("unable to get activity info")
// ErrMissingChildWorkflowInfo indicates missing child workflow info
ErrMissingChildWorkflowInfo = serviceerror.NewInternal("unable to get child workflow info")
// ErrMissingRequestCancelInfo indicates missing request cancel info
ErrMissingRequestCancelInfo = serviceerror.NewInternal("unable to get request cancel info")
// ErrMissingSignalInfo indicates missing signal external
ErrMissingSignalInfo = serviceerror.NewInternal("unable to get signal info")
// ErrMissingWorkflowStartEvent indicates missing workflow start event
ErrMissingWorkflowStartEvent = serviceerror.NewInternal("unable to get workflow start event")
// ErrMissingWorkflowCompletionEvent indicates missing workflow completion event
ErrMissingWorkflowCompletionEvent = serviceerror.NewInternal("unable to get workflow completion event")
// ErrMissingActivityScheduledEvent indicates missing workflow activity scheduled event
ErrMissingActivityScheduledEvent = serviceerror.NewInternal("unable to get activity scheduled event")
// ErrMissingChildWorkflowInitiatedEvent indicates missing child workflow initiated event
ErrMissingChildWorkflowInitiatedEvent = serviceerror.NewInternal("unable to get child workflow initiated event")
// ErrMissingSignalInitiatedEvent indicates missing workflow signal initiated event
ErrMissingSignalInitiatedEvent = serviceerror.NewInternal("unable to get signal initiated event")
// ErrPinnedWorkflowCannotTransition indicates attempt to start a transition on a pinned workflow
ErrPinnedWorkflowCannotTransition = serviceerror.NewInternal("unable to start transition on pinned workflows")
timeZeroUTC = time.Unix(0, 0).UTC()
)
var emptyTasks = []tasks.Task{}
type (
MutableStateImpl struct {
pendingActivityTimerHeartbeats map[int64]time.Time // Scheduled Event ID -> LastHeartbeatTimeoutVisibilityInSeconds.
pendingActivityInfoIDs map[int64]*persistencespb.ActivityInfo // Scheduled Event ID -> Activity Info.
pendingActivityIDToEventID map[string]int64 // Activity ID -> Scheduled Event ID of the activity.
updateActivityInfos map[int64]*persistencespb.ActivityInfo // Modified activities from last update.
deleteActivityInfos map[int64]struct{} // Deleted activities from last update.
syncActivityTasks map[int64]struct{} // Activity to be sync to remote
pendingTimerInfoIDs map[string]*persistencespb.TimerInfo // User Timer ID -> Timer Info.
pendingTimerEventIDToID map[int64]string // User Timer Start Event ID -> User Timer ID.
updateTimerInfos map[string]*persistencespb.TimerInfo // Modified timers from last update.
deleteTimerInfos map[string]struct{} // Deleted timers from last update.
pendingChildExecutionInfoIDs map[int64]*persistencespb.ChildExecutionInfo // Initiated Event ID -> Child Execution Info
updateChildExecutionInfos map[int64]*persistencespb.ChildExecutionInfo // Modified ChildExecution Infos since last update
deleteChildExecutionInfos map[int64]struct{} // Deleted ChildExecution Info since last update
pendingRequestCancelInfoIDs map[int64]*persistencespb.RequestCancelInfo // Initiated Event ID -> RequestCancelInfo
updateRequestCancelInfos map[int64]*persistencespb.RequestCancelInfo // Modified RequestCancel Infos since last update, for persistence update
deleteRequestCancelInfos map[int64]struct{} // Deleted RequestCancel Info since last update, for persistence update
pendingSignalInfoIDs map[int64]*persistencespb.SignalInfo // Initiated Event ID -> SignalInfo
updateSignalInfos map[int64]*persistencespb.SignalInfo // Modified SignalInfo since last update
deleteSignalInfos map[int64]struct{} // Deleted SignalInfo since last update
pendingSignalRequestedIDs map[string]struct{} // Set of signaled requestIds
updateSignalRequestedIDs map[string]struct{} // Set of signaled requestIds since last update
deleteSignalRequestedIDs map[string]struct{} // Deleted signaled requestId since last update
chasmTree historyi.ChasmTree
executionInfo *persistencespb.WorkflowExecutionInfo // Workflow mutable state info.
executionState *persistencespb.WorkflowExecutionState
hBuilder *historybuilder.HistoryBuilder
// In-memory only attributes
currentVersion int64
// Running approximate total size of mutable state fields (except buffered events) when written to DB in bytes.
// Buffered events are added to this value when calling GetApproximatePersistedSize.
approximateSize int
chasmNodeSizes map[string]int // chasm node path -> key + node size in bytes
// Total number of tomestones tracked in mutable state
totalTombstones int
// Buffer events from DB
bufferEventsInDB []*historypb.HistoryEvent
// Indicates the workflow state in DB, can be used to calculate
// whether this workflow is pointed by current workflow record.
stateInDB enumsspb.WorkflowExecutionState
// TODO deprecate nextEventIDInDB in favor of dbRecordVersion.
// Indicates the next event ID in DB, for conditional update.
nextEventIDInDB int64
// Indicates the versionedTransition in DB, can be used to
// calculate if the state-based replication is disabling.
versionedTransitionInDB *persistencespb.VersionedTransition
// Indicates the DB record version, for conditional update.
dbRecordVersion int64
// Namespace entry contains a snapshot of namespace.
// NOTE: do not use the failover version inside, use currentVersion above.
namespaceEntry *namespace.Namespace
// Record if an event has been applied to mutable state.
// TODO: persist this to db
appliedEvents map[string]struct{}
// A flag indicating if workflow has attempted to close (complete/cancel/continue as new)
// but failed due to undelivered buffered events.
// The flag will be unset whenever workflow task successfully completed, timedout or failed
// due to cause other than UnhandledCommand.
workflowCloseAttempted bool
// A flag indicating if transition history feature is enabled for the current transaction.
// We need a consistent view of if transition history is enabled within one transaction in case
// dynamic configuration value changes in the middle of a transaction
// TODO: remove this flag once transition history feature is stable.
transitionHistoryEnabled bool
// following fields are for tracking if sub state machines are updated
// in a transaction. They are similar to field like updateActivityInfos
visibilityUpdated bool
executionStateUpdated bool
workflowTaskUpdated bool
updateInfoUpdated map[string]struct{}
// following xxxUserDataUpdated fields are for tracking if activity/timer user data updated.
// This help to determine if we need to update transition history: For
// user data change, we need to update transition history. No update for
// non-user data change
activityInfosUserDataUpdated map[int64]struct{}
timerInfosUserDataUpdated map[string]struct{}
// isResetStateUpdated is used to track if resetRunID is updated.
isResetStateUpdated bool
// in memory fields to track potential reapply events that needs to be reapplied during workflow update
// should only be used in the state based replication as state based replication does not have
// event inside history builder. This is only for x-run reapply (from zombie wf to current wf)
reapplyEventsCandidate []*historypb.HistoryEvent
InsertTasks map[tasks.Category][]tasks.Task
// BestEffortDeleteTasks holds keys of history tasks to be deleted after a successful
// persistence update. This deletion is done on best effort basis. Persistence layer can ignore it without
// any errors.
BestEffortDeleteTasks map[tasks.Category][]tasks.Key
speculativeWorkflowTaskTimeoutTask *tasks.WorkflowTaskTimeoutTask
// In-memory storage for workflow task timeout tasks. These are set when timeout tasks are
// generated and used to delete them when the workflow task completes. Not persisted to storage.
wftScheduleToStartTimeoutTask *tasks.WorkflowTaskTimeoutTask
wftStartToCloseTimeoutTask *tasks.WorkflowTaskTimeoutTask
// In-memory storage for CHASM pure tasks. These are set when CHASM pure tasks are generated and used to
// delete them when then are no longer needed. (i.e. when the task's scheduled time is after that of the
// earliest valid CHASM pure task's).
//
// Those pure tasks are mostly reverse ordered by their scheduled time (the VisibilityTimestamp field).
// Since a physical pure task is only generated when there's no other pure task with an earlier scheduled time,
// simply appending new pure tasks to the end of the slice maintains the order.
//
// NOTE: shard context may move those tasks' scheduled time to the future if they are earlier than the timer queue's
// max read level (otherwise those tasks won't be loaded), which may potentially break the reverse order.
// That is fine, however, as in the worst case we just delete fewer tasks than we could have, but we will never delete
// tasks that are still needed (all tasks deleted are those having an earlier scheduled time than what's needed).
// Task deletion is just a best-effort optimization after all, so not complicating the logic to account for that here.
chasmPureTasks []*tasks.ChasmTaskPure
// Do not rely on this, this is only updated on
// Load() and closeTransactionXXX methods. So when
// a transaction is in progress, this value will be
// wrong. This exists primarily for visibility via CLI.
checksum *persistencespb.Checksum
taskGenerator TaskGenerator
workflowTaskManager *workflowTaskStateMachine
QueryRegistry historyi.QueryRegistry
shard historyi.ShardContext
clusterMetadata cluster.Metadata
eventsCache events.Cache
config *configs.Config
timeSource clock.TimeSource
logger log.Logger
metricsHandler metrics.Handler
endpointRegistry chasm.EndpointRegistry
stateMachineNode *hsm.Node
subStateMachineDeleted bool
// Tracks all events added via the AddHistoryEvent method that is used by the state machine framework.
currentTransactionAddedStateMachineEventTypes []enumspb.EventType
}
lastUpdatedStateTransitionGetter interface {
proto.Message
GetLastUpdateVersionedTransition() *persistencespb.VersionedTransition
Size() int
}
)
var _ historyi.MutableState = (*MutableStateImpl)(nil)
func NewMutableState(
shard historyi.ShardContext,
eventsCache events.Cache,
logger log.Logger,
namespaceEntry *namespace.Namespace,
workflowID string,
runID string,
startTime time.Time,
) *MutableStateImpl {
namespaceName := namespaceEntry.Name().String()
logger = log.NewLazyLogger(logger, func() []tag.Tag {
return []tag.Tag{
tag.WorkflowNamespace(namespaceName),
tag.WorkflowID(workflowID),
tag.WorkflowRunID(runID),
}
})
s := &MutableStateImpl{
updateActivityInfos: make(map[int64]*persistencespb.ActivityInfo),
pendingActivityTimerHeartbeats: make(map[int64]time.Time),
pendingActivityInfoIDs: make(map[int64]*persistencespb.ActivityInfo),
pendingActivityIDToEventID: make(map[string]int64),
deleteActivityInfos: make(map[int64]struct{}),
syncActivityTasks: make(map[int64]struct{}),
pendingTimerInfoIDs: make(map[string]*persistencespb.TimerInfo),
pendingTimerEventIDToID: make(map[int64]string),
updateTimerInfos: make(map[string]*persistencespb.TimerInfo),
deleteTimerInfos: make(map[string]struct{}),
updateChildExecutionInfos: make(map[int64]*persistencespb.ChildExecutionInfo),
pendingChildExecutionInfoIDs: make(map[int64]*persistencespb.ChildExecutionInfo),
deleteChildExecutionInfos: make(map[int64]struct{}),
updateRequestCancelInfos: make(map[int64]*persistencespb.RequestCancelInfo),
pendingRequestCancelInfoIDs: make(map[int64]*persistencespb.RequestCancelInfo),
deleteRequestCancelInfos: make(map[int64]struct{}),
updateSignalInfos: make(map[int64]*persistencespb.SignalInfo),
pendingSignalInfoIDs: make(map[int64]*persistencespb.SignalInfo),
deleteSignalInfos: make(map[int64]struct{}),
updateSignalRequestedIDs: make(map[string]struct{}),
pendingSignalRequestedIDs: make(map[string]struct{}),
deleteSignalRequestedIDs: make(map[string]struct{}),
// This field will be initialized with a real chasm tree at the end of this function
// when feature flag is enabled.
chasmTree: &noopChasmTree{},
approximateSize: 0,
chasmNodeSizes: make(map[string]int),
totalTombstones: 0,
currentVersion: namespaceEntry.FailoverVersion(workflowID),
bufferEventsInDB: nil,
stateInDB: enumsspb.WORKFLOW_EXECUTION_STATE_VOID,
nextEventIDInDB: common.FirstEventID,
dbRecordVersion: 1,
namespaceEntry: namespaceEntry,
appliedEvents: make(map[string]struct{}),
InsertTasks: make(map[tasks.Category][]tasks.Task),
BestEffortDeleteTasks: make(map[tasks.Category][]tasks.Key),
transitionHistoryEnabled: shard.GetConfig().EnableTransitionHistory(namespaceName),
visibilityUpdated: false,
executionStateUpdated: false,
workflowTaskUpdated: false,
updateInfoUpdated: make(map[string]struct{}),
timerInfosUserDataUpdated: make(map[string]struct{}),
activityInfosUserDataUpdated: make(map[int64]struct{}),
reapplyEventsCandidate: []*historypb.HistoryEvent{},
QueryRegistry: NewQueryRegistry(),
shard: shard,
clusterMetadata: shard.GetClusterMetadata(),
eventsCache: eventsCache,
config: shard.GetConfig(),
timeSource: shard.GetTimeSource(),
logger: logger,
metricsHandler: shard.GetMetricsHandler().WithTags(metrics.OperationTag(metrics.WorkflowContextScope)),
endpointRegistry: shard.EndpointRegistry(),
}
s.executionInfo = &persistencespb.WorkflowExecutionInfo{
NamespaceId: namespaceEntry.ID().String(),
WorkflowId: workflowID,
WorkflowTaskVersion: common.EmptyVersion,
WorkflowTaskScheduledEventId: common.EmptyEventID,
WorkflowTaskStartedEventId: common.EmptyEventID,
WorkflowTaskRequestId: emptyUUID,
WorkflowTaskTimeout: timestamp.DurationFromSeconds(0),
WorkflowTaskAttempt: 1,
LastCompletedWorkflowTaskStartedEventId: common.EmptyEventID,
StartTime: timestamppb.New(startTime),
ExecutionTime: timestamppb.New(startTime),
VersionHistories: versionhistory.NewVersionHistories(&historyspb.VersionHistory{}),
ExecutionStats: &persistencespb.ExecutionStats{HistorySize: 0},
SubStateMachinesByType: make(map[string]*persistencespb.StateMachineMap),
}
s.executionInfo.TaskGenerationShardClockTimestamp = shard.CurrentVectorClock().GetClock()
s.approximateSize += s.executionInfo.Size()
s.executionState = &persistencespb.WorkflowExecutionState{
RunId: runID,
State: enumsspb.WORKFLOW_EXECUTION_STATE_CREATED,
Status: enumspb.WORKFLOW_EXECUTION_STATUS_RUNNING,
StartTime: timestamppb.New(startTime),
RequestIds: make(map[string]*persistencespb.RequestIDInfo),
}
s.approximateSize += s.executionState.Size()
s.hBuilder = historybuilder.New(
s.timeSource,
s.shard.GenerateTaskIDs,
s.currentVersion,
common.FirstEventID,
s.bufferEventsInDB,
s.metricsHandler,
)
s.taskGenerator = taskGeneratorProvider.NewTaskGenerator(shard, s)
s.workflowTaskManager = newWorkflowTaskStateMachine(s, s.metricsHandler)
s.mustInitHSM()
if s.config.EnableChasm(namespaceName) {
s.chasmTree = chasm.NewEmptyTree(
shard.ChasmRegistry(),
shard.GetTimeSource(),
s,
chasm.DefaultPathEncoder,
logger,
shard.GetMetricsHandler().WithTags(metrics.NamespaceTag(namespaceName)),
)
}
return s
}
func NewMutableStateFromDB(
shard historyi.ShardContext,
eventsCache events.Cache,
logger log.Logger,
namespaceEntry *namespace.Namespace,
dbRecord *persistencespb.WorkflowMutableState,
dbRecordVersion int64,
) (*MutableStateImpl, error) {
// startTime will be overridden by DB record
startTime := time.Time{}
mutableState := NewMutableState(
shard,
eventsCache,
logger,
namespaceEntry,
dbRecord.ExecutionInfo.WorkflowId,
dbRecord.ExecutionState.RunId,
startTime,
)
if dbRecord.ActivityInfos != nil {
mutableState.pendingActivityInfoIDs = dbRecord.ActivityInfos
mutableState.approximateSize += int64SizeBytes * len(mutableState.pendingActivityInfoIDs)
}
for _, activityInfo := range dbRecord.ActivityInfos {
mutableState.pendingActivityIDToEventID[activityInfo.ActivityId] = activityInfo.ScheduledEventId
mutableState.approximateSize += activityInfo.Size()
if (activityInfo.TimerTaskStatus & TimerTaskStatusCreatedHeartbeat) > 0 {
// Sets last pending timer heartbeat to year 2000.
// This ensures at least one heartbeat task will be processed for the pending activity.
mutableState.pendingActivityTimerHeartbeats[activityInfo.ScheduledEventId] = time.Unix(946684800, 0)
}
}
if dbRecord.TimerInfos != nil {
mutableState.pendingTimerInfoIDs = dbRecord.TimerInfos
}
for timerID, timerInfo := range dbRecord.TimerInfos {
mutableState.pendingTimerEventIDToID[timerInfo.GetStartedEventId()] = timerInfo.GetTimerId()
mutableState.approximateSize += timerInfo.Size()
mutableState.approximateSize += len(timerID)
}
if dbRecord.ChildExecutionInfos != nil {
mutableState.pendingChildExecutionInfoIDs = dbRecord.ChildExecutionInfos
mutableState.approximateSize += int64SizeBytes * len(mutableState.pendingChildExecutionInfoIDs)
}
for _, childInfo := range dbRecord.ChildExecutionInfos {
mutableState.approximateSize += childInfo.Size()
}
if dbRecord.RequestCancelInfos != nil {
mutableState.pendingRequestCancelInfoIDs = dbRecord.RequestCancelInfos
mutableState.approximateSize += int64SizeBytes * len(mutableState.pendingRequestCancelInfoIDs)
}
for _, cancelInfo := range dbRecord.RequestCancelInfos {
mutableState.approximateSize += cancelInfo.Size()
}
if dbRecord.SignalInfos != nil {
mutableState.pendingSignalInfoIDs = dbRecord.SignalInfos
mutableState.approximateSize += int64SizeBytes * len(mutableState.pendingSignalInfoIDs)
}
for _, signalInfo := range dbRecord.SignalInfos {
mutableState.approximateSize += signalInfo.Size()
}
mutableState.pendingSignalRequestedIDs = convert.StringSliceToSet(dbRecord.SignalRequestedIds)
for requestID := range mutableState.pendingSignalRequestedIDs {
mutableState.approximateSize += len(requestID)
}
for _, tombstoneBatch := range dbRecord.ExecutionInfo.SubStateMachineTombstoneBatches {
mutableState.totalTombstones += len(tombstoneBatch.StateMachineTombstones)
}
mutableState.approximateSize += dbRecord.ExecutionState.Size() - mutableState.executionState.Size()
mutableState.executionState = dbRecord.ExecutionState
mutableState.approximateSize += dbRecord.ExecutionInfo.Size() - mutableState.executionInfo.Size()
mutableState.executionInfo = dbRecord.ExecutionInfo
// StartTime was moved from ExecutionInfo to executionState
if mutableState.executionState.StartTime == nil && dbRecord.ExecutionInfo.StartTime != nil {
mutableState.executionState.StartTime = dbRecord.ExecutionInfo.StartTime
}
mutableState.hBuilder = historybuilder.New(
mutableState.timeSource,
mutableState.shard.GenerateTaskIDs,
common.EmptyVersion,
dbRecord.NextEventId,
dbRecord.BufferedEvents,
mutableState.metricsHandler,
)
mutableState.currentVersion = common.EmptyVersion
mutableState.bufferEventsInDB = dbRecord.BufferedEvents
mutableState.stateInDB = dbRecord.ExecutionState.State
mutableState.nextEventIDInDB = dbRecord.NextEventId
mutableState.dbRecordVersion = dbRecordVersion
mutableState.checksum = dbRecord.Checksum
mutableState.initVersionedTransitionInDB()
if len(dbRecord.Checksum.GetValue()) > 0 {
switch {
case mutableState.shouldInvalidateCheckum():
mutableState.checksum = nil
metrics.MutableStateChecksumInvalidated.With(mutableState.metricsHandler).Record(1)
case mutableState.shouldVerifyChecksum():
if err := verifyMutableStateChecksum(mutableState, dbRecord.Checksum); err != nil {
// we ignore checksum verification errors for now until this
// feature is tested and/or we have mechanisms in place to deal
// with these types of errors
metrics.MutableStateChecksumMismatch.With(mutableState.metricsHandler).Record(1)
mutableState.logError("mutable state checksum mismatch", tag.Error(err))
}
}
}
mutableState.mustInitHSM()
// Track chasm node size even if chasm is not enabled,
// because those nodes are still stored in the mutable state,
// and should be taken into account when deciding if execution
// should be terminated based on mutable state size.
for key, node := range dbRecord.ChasmNodes {
nodeSize := len(key) + node.Size()
mutableState.approximateSize += nodeSize
mutableState.chasmNodeSizes[key] = nodeSize
}
if shard.GetConfig().EnableChasm(namespaceEntry.Name().String()) {
var err error
mutableState.chasmTree, err = chasm.NewTreeFromDB(
dbRecord.ChasmNodes,
shard.ChasmRegistry(),
shard.GetTimeSource(),
mutableState,
chasm.DefaultPathEncoder,
mutableState.logger, // this logger is tagged with execution key.
shard.GetMetricsHandler().WithTags(metrics.NamespaceTag(namespaceEntry.Name().String())),
)
if err != nil {
return nil, err
}
}
return mutableState, nil
}
func NewSanitizedMutableState(
shard historyi.ShardContext,
eventsCache events.Cache,
logger log.Logger,
namespaceEntry *namespace.Namespace,
mutableStateRecord *persistencespb.WorkflowMutableState,
lastWriteVersion int64,
) (*MutableStateImpl, error) {
// Although new versions of temporal server will perform state sanitization,
// we have to keep the sanitization logic here as well for backward compatibility in case
// source cluster is running an old version and doesn't do the sanitization.
SanitizeMutableState(mutableStateRecord)
if err := common.DiscardUnknownProto(mutableStateRecord); err != nil {
return nil, err
}
mutableState, err := NewMutableStateFromDB(shard, eventsCache, logger, namespaceEntry, mutableStateRecord, 1)
if err != nil {
return nil, err
}
mutableState.currentVersion = lastWriteVersion
return mutableState, nil
}
func NewMutableStateInChain(
shardContext historyi.ShardContext,
eventsCache events.Cache,
logger log.Logger,
namespaceEntry *namespace.Namespace,
workflowID string,
runID string,
startTime time.Time,
currentMutableState historyi.MutableState,
) (*MutableStateImpl, error) {
newMutableState := NewMutableState(
shardContext,
eventsCache,
logger,
namespaceEntry,
workflowID,
runID,
startTime,
)
// carry over necessary fields from current mutable state
newMutableState.executionInfo.WorkflowExecutionTimerTaskStatus = currentMutableState.GetExecutionInfo().WorkflowExecutionTimerTaskStatus
newMutableState.executionInfo.ChildrenInitializedPostResetPoint = currentMutableState.GetExecutionInfo().ChildrenInitializedPostResetPoint
// TODO: Today other information like autoResetPoints, previousRunID, firstRunID, etc.
// are carried over in AddWorkflowExecutionStartedEventWithOptions. Ideally all information
// should be carried over here since some information is not part of the startedEvent.
return newMutableState, nil
}
func (ms *MutableStateImpl) mustInitHSM() {
if ms.executionInfo.SubStateMachinesByType == nil {
ms.executionInfo.SubStateMachinesByType = make(map[string]*persistencespb.StateMachineMap)
}
// Error only occurs if some initialization path forgets to register the workflow state machine.
stateMachineNode, err := hsm.NewRoot(ms.shard.StateMachineRegistry(), StateMachineType, ms, ms.executionInfo.SubStateMachinesByType, ms)
if err != nil {
panic(err)
}
ms.stateMachineNode = stateMachineNode
}
func (ms *MutableStateImpl) IsWorkflow() bool {
return ms.chasmTree.ArchetypeID() == chasm.WorkflowArchetypeID
}
func (ms *MutableStateImpl) HSM() *hsm.Node {
return ms.stateMachineNode
}
func (ms *MutableStateImpl) ChasmTree() historyi.ChasmTree {
return ms.chasmTree
}
// ChasmEnabled returns true if the mutable state has a real chasm tree.
// The chasmTree is initialized with a noopChasmTree which is then overwritten with an actual chasm tree if chasm is
// enabled when the mutable state is created. Once the EnableChasm dynamic config is removed and the tree is always
// initialized, this helper can be removed.
func (ms *MutableStateImpl) ChasmEnabled() bool {
_, isNoop := ms.chasmTree.(*noopChasmTree)
return !isNoop
}
// chasmCallbacksEnabled returns true if CHASM callbacks are enabled for this workflow.
func (ms *MutableStateImpl) chasmCallbacksEnabled() bool {
if !ms.ChasmEnabled() {
return false
}
// Check the callback library's EnableCallbacks config via history config
return ms.shard.GetConfig().EnableCHASMCallbacks(ms.GetNamespaceEntry().Name().String())
}
// ChasmWorkflowComponent gets the root workflow component from the CHASM tree.
// Returns the workflow component (which is *chasmworkflow.Workflow) and the CHASM mutable context.
// This method is for write operations. Callers can type assert to *chasmworkflow.Workflow if needed.
func (ms *MutableStateImpl) ChasmWorkflowComponent(ctx context.Context) (*chasmworkflow.Workflow, chasm.MutableContext, error) {
chasmCtx := chasm.NewMutableContext(ctx, ms.chasmTree.(*chasm.Node))
rootComponent, err := ms.chasmTree.ComponentByPath(chasmCtx, nil)
if err != nil {
return nil, nil, err
}
wf, ok := rootComponent.(*chasmworkflow.Workflow)
if !ok {
return nil, nil, serviceerror.NewInternalf("expected workflow component, but got %T", rootComponent)
}
return wf, chasmCtx, nil
}
func (ms *MutableStateImpl) EnsureChasmWorkflowComponent(ctx context.Context) {
// Initialize chasm tree once for new workflows.
// Using context.Background() because this is done outside an actual request context and the
// chasmworkflow.NewWorkflow does not actually use it currently.
root, ok := ms.chasmTree.(*chasm.Node)
softassert.That(ms.logger, ok, "chasmTree cast failed")
if root.ArchetypeID() == chasm.UnspecifiedArchetypeID {
mutableContext := chasm.NewMutableContext(ctx, root)
if err := root.SetRootComponent(chasmworkflow.NewWorkflow(mutableContext, chasm.NewMSPointer(ms))); err != nil {
softassert.Fail(ms.logger, "SetRootComponent failed", tag.Error(err))
}
}
}
// ChasmWorkflowComponentReadOnly gets the root workflow component from the CHASM tree.
// Returns both the workflow component and a read-only CHASM context.
// This method is for read-only operations.
func (ms *MutableStateImpl) ChasmWorkflowComponentReadOnly(ctx context.Context) (*chasmworkflow.Workflow, chasm.Context, error) {
chasmCtx := chasm.NewContext(ctx, ms.chasmTree.(*chasm.Node))
rootComponent, err := ms.chasmTree.ComponentByPath(chasmCtx, nil)
if err != nil {
return nil, nil, err
}
wf, ok := rootComponent.(*chasmworkflow.Workflow)
if !ok {
return nil, nil, serviceerror.NewInternalf("expected workflow component, but got %T", rootComponent)
}
return wf, chasmCtx, nil
}
func (ms *MutableStateImpl) EndpointRegistry() chasm.EndpointRegistry {
return ms.endpointRegistry
}
// GetNexusCompletion converts a workflow completion event into a [nexus.OperationCompletion].
// Completions may be sent to arbitrary third parties, we intentionally do not include any termination reasons, and
// expose only failure messages.
func (ms *MutableStateImpl) GetNexusCompletion(
ctx context.Context,
requestID string,
) (nexusrpc.CompleteOperationOptions, error) {
ce, err := ms.GetCompletionEvent(ctx)
if err != nil {
return nexusrpc.CompleteOperationOptions{}, err
}
// Create the link information about the workflow to be attached to fabricated started event if completion is
// received before start response.
link := &commonpb.Link_WorkflowEvent{
Namespace: ms.namespaceEntry.Name().String(),
WorkflowId: ms.executionInfo.WorkflowId,
RunId: ms.executionState.RunId,
}
requestIDInfo := ms.executionState.RequestIds[requestID]
// For a callback that is attached to a running workflow, we create a RequestIdReference link since the event may be
// buffered and not have a final event ID yet.
if requestIDInfo.GetEventType() == enumspb.EVENT_TYPE_WORKFLOW_EXECUTION_OPTIONS_UPDATED {
// If the callback was attached, then replace with RequestIdReference.
link.Reference = &commonpb.Link_WorkflowEvent_RequestIdRef{
RequestIdRef: &commonpb.Link_WorkflowEvent_RequestIdReference{
RequestId: requestID,
EventType: requestIDInfo.GetEventType(),
},
}
} else {
// For a callback that is attached on workflow start, we create an EventReference link.
link.Reference = &commonpb.Link_WorkflowEvent_EventRef{
EventRef: &commonpb.Link_WorkflowEvent_EventReference{
EventId: common.FirstEventID,
EventType: enumspb.EVENT_TYPE_WORKFLOW_EXECUTION_STARTED,
},
}
}
startLink := commonnexus.ConvertLinkWorkflowEventToNexusLink(link)
switch ce.GetEventType() {
case enumspb.EVENT_TYPE_WORKFLOW_EXECUTION_COMPLETED:
payloads := ce.GetWorkflowExecutionCompletedEventAttributes().GetResult().GetPayloads()
var p *commonpb.Payload // default to nil, the payload serializer converts nil to Nexus nil Content.
if len(payloads) > 0 {
// All of our SDKs support returning a single value from workflows, we can safely ignore the
// rest of the payloads. Additionally, even if a workflow could return more than a single value,
// Nexus does not support it.
p = payloads[0]
}
return nexusrpc.CompleteOperationOptions{
Result: p,
StartTime: ms.executionState.GetStartTime().AsTime(),
CloseTime: ce.GetEventTime().AsTime(),
Links: []nexus.Link{startLink},
}, nil
case enumspb.EVENT_TYPE_WORKFLOW_EXECUTION_FAILED:
f, err := commonnexus.TemporalFailureToNexusFailure(ce.GetWorkflowExecutionFailedEventAttributes().GetFailure())
if err != nil {
return nexusrpc.CompleteOperationOptions{}, err
}
opErr := &nexus.OperationError{
Message: "operation failed",
State: nexus.OperationStateFailed,
Cause: &nexus.FailureError{Failure: f},
}
if err := nexusrpc.MarkAsWrapperError(nexusrpc.DefaultFailureConverter(), opErr); err != nil {
return nexusrpc.CompleteOperationOptions{}, err
}
return nexusrpc.CompleteOperationOptions{
Error: opErr,
StartTime: ms.executionState.GetStartTime().AsTime(),
CloseTime: ce.GetEventTime().AsTime(),
Links: []nexus.Link{startLink},
}, nil
case enumspb.EVENT_TYPE_WORKFLOW_EXECUTION_CANCELED:
f, err := commonnexus.TemporalFailureToNexusFailure(&failurepb.Failure{
Message: "operation canceled",
FailureInfo: &failurepb.Failure_CanceledFailureInfo{
CanceledFailureInfo: &failurepb.CanceledFailureInfo{
Details: ce.GetWorkflowExecutionCanceledEventAttributes().GetDetails(),
},
},
})
if err != nil {
return nexusrpc.CompleteOperationOptions{}, err
}
opErr := &nexus.OperationError{
State: nexus.OperationStateCanceled,
Message: "operation canceled",
Cause: &nexus.FailureError{Failure: f},
}
if err := nexusrpc.MarkAsWrapperError(nexusrpc.DefaultFailureConverter(), opErr); err != nil {
return nexusrpc.CompleteOperationOptions{}, err
}
return nexusrpc.CompleteOperationOptions{
Error: opErr,
StartTime: ms.executionState.GetStartTime().AsTime(),
CloseTime: ce.GetEventTime().AsTime(),
Links: []nexus.Link{startLink},
}, nil
case enumspb.EVENT_TYPE_WORKFLOW_EXECUTION_TERMINATED:
f, err := commonnexus.TemporalFailureToNexusFailure(&failurepb.Failure{
Message: "operation terminated",
FailureInfo: &failurepb.Failure_TerminatedFailureInfo{
TerminatedFailureInfo: &failurepb.TerminatedFailureInfo{},
},
})
if err != nil {
return nexusrpc.CompleteOperationOptions{}, err
}
opErr := &nexus.OperationError{
State: nexus.OperationStateFailed,
Message: "operation failed",
Cause: &nexus.FailureError{Failure: f},
}
if err := nexusrpc.MarkAsWrapperError(nexusrpc.DefaultFailureConverter(), opErr); err != nil {
return nexusrpc.CompleteOperationOptions{}, err
}
return nexusrpc.CompleteOperationOptions{
Error: opErr,
StartTime: ms.executionState.GetStartTime().AsTime(),
CloseTime: ce.GetEventTime().AsTime(),
Links: []nexus.Link{startLink},
}, nil
case enumspb.EVENT_TYPE_WORKFLOW_EXECUTION_TIMED_OUT:
f, err := commonnexus.TemporalFailureToNexusFailure(&failurepb.Failure{
Message: "operation exceeded internal timeout",
FailureInfo: &failurepb.Failure_TimeoutFailureInfo{
TimeoutFailureInfo: &failurepb.TimeoutFailureInfo{
// Not filling in timeout type and other information, it's not particularly interesting to a Nexus
// caller.
},
},
})
if err != nil {
return nexusrpc.CompleteOperationOptions{}, err
}
opErr := &nexus.OperationError{
State: nexus.OperationStateFailed,
Message: "operation failed",
Cause: &nexus.FailureError{Failure: f},
}
if err := nexusrpc.MarkAsWrapperError(nexusrpc.DefaultFailureConverter(), opErr); err != nil {
return nexusrpc.CompleteOperationOptions{}, err
}
return nexusrpc.CompleteOperationOptions{
Error: opErr,
StartTime: ms.executionState.GetStartTime().AsTime(),
CloseTime: ce.GetEventTime().AsTime(),
Links: []nexus.Link{startLink},
}, nil
}
return nexusrpc.CompleteOperationOptions{}, serviceerror.NewInternalf("invalid workflow execution status: %v", ce.GetEventType())
}
// GetHSMCallbackArg converts a workflow completion event into a [persistencespb.HSMCallbackArg].
func (ms *MutableStateImpl) GetHSMCompletionCallbackArg(ctx context.Context) (*persistencespb.HSMCompletionCallbackArg, error) {
workflowKey := ms.GetWorkflowKey()
ce, err := ms.GetCompletionEvent(ctx)
if err != nil {
return nil, err
}
return &persistencespb.HSMCompletionCallbackArg{
NamespaceId: workflowKey.NamespaceID,
WorkflowId: workflowKey.WorkflowID,
RunId: workflowKey.RunID,
LastEvent: ce,
}, nil
}
func (ms *MutableStateImpl) CloneToProto() *persistencespb.WorkflowMutableState {
msProto := &persistencespb.WorkflowMutableState{
ActivityInfos: ms.pendingActivityInfoIDs,
TimerInfos: ms.pendingTimerInfoIDs,
ChildExecutionInfos: ms.pendingChildExecutionInfoIDs,
RequestCancelInfos: ms.pendingRequestCancelInfoIDs,
SignalInfos: ms.pendingSignalInfoIDs,
ChasmNodes: ms.chasmTree.Snapshot(nil).Nodes,
SignalRequestedIds: convert.StringSetToSlice(ms.pendingSignalRequestedIDs),
ExecutionInfo: ms.executionInfo,
ExecutionState: ms.executionState,
NextEventId: ms.hBuilder.NextEventID(),
BufferedEvents: ms.bufferEventsInDB,
Checksum: ms.checksum,
}
return common.CloneProto(msProto)
}
func (ms *MutableStateImpl) GetWorkflowKey() definition.WorkflowKey {
return definition.NewWorkflowKey(
ms.executionInfo.NamespaceId,
ms.executionInfo.WorkflowId,
ms.executionState.RunId,
)
}
func (ms *MutableStateImpl) GetCurrentBranchToken() ([]byte, error) {
currentVersionHistory, err := versionhistory.GetCurrentVersionHistory(ms.executionInfo.VersionHistories)
if err != nil {
return nil, err
}
return currentVersionHistory.GetBranchToken(), nil
}
func (ms *MutableStateImpl) getCurrentBranchTokenAndEventVersion(eventID int64) ([]byte, int64, error) {
currentVersionHistory, err := versionhistory.GetCurrentVersionHistory(ms.executionInfo.VersionHistories)
if err != nil {
return nil, 0, err
}
version, err := versionhistory.GetVersionHistoryEventVersion(currentVersionHistory, eventID)
if err != nil {
return nil, 0, err
}
return currentVersionHistory.GetBranchToken(), version, nil
}
// SetHistoryTree set treeID/historyBranches
func (ms *MutableStateImpl) SetHistoryTree(
executionTimeout *durationpb.Duration,
runTimeout *durationpb.Duration,
treeID string,
) error {
// NOTE: Unfortunately execution timeout and run timeout are not yet initialized into ms.executionInfo at this point.
// TODO: Consider explicitly initializing mutable state with these timeout parameters instead of passing them in.
workflowKey := ms.GetWorkflowKey()
archetypeID := ms.ChasmTree().ArchetypeID()
if archetypeID != chasm.WorkflowArchetypeID {
return softassert.UnexpectedInternalErr(
ms.logger,
"Backfilling history not supported for non-workflow archetype",
nil,
tag.ArchetypeID(archetypeID),
tag.WorkflowNamespaceID(workflowKey.NamespaceID),
tag.WorkflowID(workflowKey.WorkflowID),
tag.WorkflowRunID(workflowKey.RunID),
)
}
var retentionDuration *durationpb.Duration
if duration := ms.namespaceEntry.Retention(); duration > 0 {
retentionDuration = durationpb.New(duration)
}
initialBranchToken, err := ms.shard.GetExecutionManager().GetHistoryBranchUtil().NewHistoryBranch(
workflowKey.NamespaceID,
workflowKey.WorkflowID,
workflowKey.RunID,
treeID,
nil,
[]*persistencespb.HistoryBranchRange{},
runTimeout.AsDuration(),
executionTimeout.AsDuration(),
retentionDuration.AsDuration(),
)
if err != nil {
return err
}
return ms.SetCurrentBranchToken(initialBranchToken)
}
func (ms *MutableStateImpl) SetCurrentBranchToken(
branchToken []byte,
) error {
currentVersionHistory, err := versionhistory.GetCurrentVersionHistory(ms.executionInfo.VersionHistories)
if err != nil {
return err
}
versionhistory.SetVersionHistoryBranchToken(currentVersionHistory, branchToken)
return nil
}
func (ms *MutableStateImpl) SetHistoryBuilder(hBuilder *historybuilder.HistoryBuilder) {