You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@seata.apache.org by "Code-Fight (via GitHub)" <gi...@apache.org> on 2025/09/24 15:49:10 UTC

[PR] Saga end-to-end verification [incubator-seata-go]

Code-Fight opened a new pull request, #897:
URL: https://github.com/apache/incubator-seata-go/pull/897

   <!--  Thanks for sending a pull request! 
   -->
   
   **What this PR does**:
   
   1. Saga end-to-end verification
   2. bug fix
   
   **Which issue(s) this PR fixes**:
   <!--
   *Automatically closes linked issue when PR is merged.
   Usage: `Fixes #<issue number>`, or `Fixes (paste link of issue)`.
   _If PR is about `failing-tests or flakes`, please post the related issues/tests in a comment and do not use `Fixes`_*
   -->
   Fixes #
   
   **Special notes for your reviewer**:
   e2e sample : https://github.com/apache/incubator-seata-go-samples/pull/74 
   How to use, refer to : https://github.com/apache/incubator-seata-go-samples/pull/74/files#diff-24b8938589c9efcf1440e59602b467825c27716546e285b617d61650cf77486aR18
   
   **In addition to the e2e sample I provided, I hope you can perform detailed verification according to your own ideas. If you find any issues, please share with me your test cases and state machine definition diagram. Thank you very much.**
   
   **除了我提供的e2e sample 希望能按照你的想法进行详细的验证,若发现有问题,请提供给我你的测试例子和状态机定义图,非常感谢**
   
   **Does this PR introduce a user-facing change?**:
   <!--
   If no, just write "NONE" in the release-note block below.
   If yes, a release note is required:
   Enter your extended release note in the block below. If the PR requires additional action from users switching to the new release, include the string "action required".
   -->
   ```release-note
   
   ```


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@seata.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@seata.apache.org
For additional commands, e-mail: notifications-help@seata.apache.org


Re: [PR] Saga end-to-end verification [incubator-seata-go]

Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #897:
URL: https://github.com/apache/incubator-seata-go/pull/897#discussion_r2377431880


##########
pkg/saga/statemachine/statelang/state_instance.go:
##########
@@ -319,7 +319,10 @@ func (s *StateInstanceImpl) SetIgnoreStatus(ignoreStatus bool) {
 }
 
 func (s *StateInstanceImpl) IsForCompensation() bool {
-	return s.stateIdCompensatedFor == ""
+	// A state instance is considered a compensation execution if it points
+	// back to an original forward state via stateIdCompensatedFor.
+	// When this field is non-empty, this instance is a compensation.
+	return s.stateIdCompensatedFor != ""

Review Comment:
   The logic appears inverted based on the comment. A state instance should be considered 'for compensation' when it IS compensating another state (stateIdCompensatedFor != ''), but the comment suggests the opposite semantics.



##########
pkg/saga/statemachine/engine/config/default_statemachine_config.go:
##########
@@ -641,13 +696,24 @@ func NewDefaultStateMachineConfig(opts ...Option) (*DefaultStateMachineConfig, e
 
 	c.stateMachineRepository = repository.GetStateMachineRepositoryImpl()
 	c.stateLogRepository = repository.NewStateLogRepositoryImpl()
+	repository.GetStateMachineRepositoryImpl().SetDefaultTenantId(c.defaultTenantId)
 
 	c.syncProcessCtrlEventPublisher = process_ctrl.NewProcessCtrlEventPublisher(c.syncEventBus)
 	c.asyncProcessCtrlEventPublisher = process_ctrl.NewProcessCtrlEventPublisher(c.asyncEventBus)
 
 	for _, opt := range opts {
 		opt(c)
 	}
+	repository.GetStateMachineRepositoryImpl().SetDefaultTenantId(c.defaultTenantId)
+
+	if _, statErr := os.Stat("config.yaml"); statErr == nil {
+		if err := c.LoadConfig("config.yaml"); err == nil {
+			repository.GetStateMachineRepositoryImpl().SetDefaultTenantId(c.defaultTenantId)
+			log.Printf("Successfully loaded config from config.yaml")
+		} else {
+			log.Printf("Failed to load config file (using default/env values): %v", err)

Review Comment:
   [nitpick] Hard-coded config file name 'config.yaml' makes configuration inflexible. Consider making this configurable or checking multiple standard config file names.
   ```suggestion
   	// Try to load the first available config file from a list of standard names
   	configFiles := []string{"config.yaml", "config.yml", "state-machine.yaml", "state-machine.yml"}
   	var loadedConfigFile string
   	for _, fname := range configFiles {
   		if _, statErr := os.Stat(fname); statErr == nil {
   			if err := c.LoadConfig(fname); err == nil {
   				repository.GetStateMachineRepositoryImpl().SetDefaultTenantId(c.defaultTenantId)
   				log.Printf("Successfully loaded config from %s", fname)
   				loadedConfigFile = fname
   			} else {
   				log.Printf("Failed to load config file %s (using default/env values): %v", fname, err)
   			}
   			break
   ```



##########
pkg/saga/statemachine/store/db/statelog.go:
##########
@@ -949,9 +1118,9 @@ func execStateInstanceStatementForUpdate(obj statelang.StateInstance, stmt *sql.
 		serializedError,
 		obj.Status(),
 		obj.SerializedOutputParams(),
-		obj.EndTime(),
+		time.Now(),
 		obj.ID(),
-		obj.MachineInstanceID(),
+		obj.StateMachineInstance().ID(),

Review Comment:
   Hard-coded time.Now() for updated time instead of using obj.UpdatedTime() may cause inconsistent timestamps and break optimistic locking logic.



##########
pkg/saga/statemachine/store/db/statelog.go:
##########
@@ -949,9 +1118,9 @@ func execStateInstanceStatementForUpdate(obj statelang.StateInstance, stmt *sql.
 		serializedError,
 		obj.Status(),
 		obj.SerializedOutputParams(),
-		obj.EndTime(),
+		time.Now(),

Review Comment:
   Hard-coded time.Now() for updated time instead of using obj.UpdatedTime() may cause inconsistent timestamps and break optimistic locking logic.
   ```suggestion
   		obj.UpdatedTime(),
   ```



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@seata.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@seata.apache.org
For additional commands, e-mail: notifications-help@seata.apache.org


Re: [PR] Saga end-to-end verification [incubator-seata-go]

Posted by "kaori-seasons (via GitHub)" <gi...@apache.org>.
kaori-seasons commented on code in PR #897:
URL: https://github.com/apache/incubator-seata-go/pull/897#discussion_r2377467627


##########
pkg/saga/statemachine/engine/pcext/state_router_impl.go:
##########
@@ -53,15 +68,81 @@ func (t TaskStateRouter) Route(ctx context.Context, processContext process_ctrl.
 		return nil, nil
 	}
 
-	// The current CompensationTriggerState can mark the compensation process is started and perform compensation
-	// route processing.
-	compensationTriggerState, ok := processContext.GetVariable(constant.VarNameCurrentCompensateTriggerState).(statelang.State)
-	if ok {
+	// If current state is CompensationTrigger or compensation has been flagged, start compensation routing
+	if state != nil && state.Type() == constant.StateTypeCompensationTrigger {
+		// flag into context for downstream calls (best-effort)
+		if hpc, ok := processContext.(process_ctrl.HierarchicalProcessContext); ok {
+			hpc.SetVariableLocally(constant.VarNameCurrentCompensateTriggerState, state)
+			hpc.SetVariableLocally(constant.VarNameFirstCompensationStateStarted, false)
+		} else {
+			processContext.SetVariable(constant.VarNameCurrentCompensateTriggerState, state)
+			processContext.SetVariable(constant.VarNameFirstCompensationStateStarted, false)
+		}
+
+		// build compensation stack from executed forward states (latest first)
+		smInst := processContext.GetVariable(constant.VarNameStateMachineInst).(statelang.StateMachineInstance)
+		holder := GetCurrentCompensationHolder(ctx, processContext, true)
+		stack := holder.StateStackNeedCompensation()
+		sm := processContext.GetVariable(constant.VarNameStateMachine).(statelang.StateMachine)
+		states := smInst.StateList()
+		for i := len(states) - 1; i >= 0; i-- {
+			si := states[i]
+			// exclude compensation states
+			if si.StateIDCompensatedFor() != "" {
+				continue
+			}
+			// only successful forward states are subject to compensation
+			if si.Status() != statelang.SU {
+				continue
+			}
+			originName := GetOriginStateName(si)
+			def := sm.State(originName)
+			// ensure the definition has a compensate state
+			var task *sagaState.AbstractTaskState
+			switch s := def.(type) {
+			case *sagaState.ServiceTaskStateImpl:
+				task = s.AbstractTaskState
+			case *sagaState.ScriptTaskStateImpl:
+				task = s.AbstractTaskState
+			case *sagaState.SubStateMachineImpl:
+				if s.ServiceTaskStateImpl != nil {
+					task = s.ServiceTaskStateImpl.AbstractTaskState
+				}
+			}
+			if task == nil || task.CompensateState() == "" {
+				continue
+			}
+			stack.Push(si)
+		}
+		// fallback: if nothing pushed, try last successful forward state
+		if stack.Empty() {
+			for i := len(states) - 1; i >= 0; i-- {
+				si := states[i]
+				if si.StateIDCompensatedFor() != "" {
+					continue
+				}
+				if si.Status() != statelang.SU {
+					continue
+				}
+				stack.Push(si)
+				break
+			}
+		}
+
+		// mark machine compensation running
+		smInst.SetCompensationStatus(statelang.RU)
+
+		return t.compensateRoute(ctx, processContext, state)

Review Comment:
   In the core method Route in process_router.go , the routing logic checks the state type currently executed by the state machine:
   
   - If it is a normal Task state, the StateInstruction determines the next state to execute based on it.
   
   - If it is a Choice state, the routing logic first selects a "next" branch using an expression or branch condition and updates it to the StateInstruction:
   
   ```
   stateInstruction.SetStateName(next)
   ```
   This allows the state machine to execute different branches based on the Choice condition.
   
   Specifically, the branch selection result of the Choice state is assigned to the corresponding field of the StateInstruction (such as StateName), thus affecting subsequent processes.
   
   #### Existing Issues
   
   The compensation chain is constructed only backwards from the execution stack. If there is no compensable state after the Choice/Failure branch, the process simply marks it as NoCompensation, but the final state normalization is not explicit enough.
   
   Multi-branch, multi-stage compensation, and compensation failure lack fine-grained state recording. Recommendations
   
   #### Recommendations
   When building a compensation chain, traverse the state list to clearly mark the branch source and compensation result of each compensated state. We recommend adding a new structure such as CompensationTrace[]CompensationResult, which includes the branch, compensation status, and exception.
   When a Fail End is reached without compensation, the state is normalized to FA and the compensation status is cleared. We recommend also exposing the compensation chain record to the instance for easy querying.
   When compensating multiple branches, it is recommended that each branch record its compensation result separately, and the final state is normalized based on the compensation results of all branches.
   
   
   Scenario Description
   Assume the following SAGA state machine definition:
   
   ```
   Start -> Choice
   Choice:
   if (A) -> Service1
   else -> Service2
   Service1 -> Service3
   Service2 -> Service4
   Service3/Service4 -> FailEnd
   FailEnd: Compensation triggers
   ```
   
   Data Input Example (Choice condition is false, branch to Service2)
   Initial Business Parameters: 
   ```{"userId": 111, "amount": 100, "route": "B"}```
   State Machine Execution Path: 
   ```Start → Choice (route == B, choose Service2) → Service2 → Service4 → FailEnd```
   
   #### Boundary Issues
   
   - Issue 1: If the compensation chain is not constructed rigorously, FailEnd triggers compensation, but the compensation chain incorrectly includes the unexecuted Service1/Service3 branches.
   - Issue 2: If Service4 does not define a compensation state, the compensation chain is empty. In this case, the compensation chain is not properly normalized, resulting in the final state machine instance remaining in "Compensation in Progress" or "Unknown" instead of "Failure without Compensation."
   
   
   
   Data output without boundary processing (pseudo-JSON)
   ```
   {
     "stateMachineInstance": {
       "id": "saga-123",
       "status": "FA",
       "compensationStatus": "RU",
       "compensationChain": [
         {"state": "Service1", "executed": false},   // 不该出现
         {"state": "Service2", "executed": true, "compensated": false},
         {"state": "Service4", "executed": true, "compensated": false}
       ],
       "exception": "补偿链错误包含了未执行分支"
     }
   }
   ```
   
   
   Issue: The compensation chain incorrectly includes unexecuted branches, and the final state machine instance compensationStatus is not normalized (still RU), misleading the API/Ops layer into thinking compensation is still in progress.
   
   Data output after boundary processing
   ```
   {
     "stateMachineInstance": {
       "id": "saga-123",
       "status": "FA",
       "compensationStatus": "",
       "compensationChain": [
         {"state": "Service2", "executed": true, "compensated": false},
         {"state": "Service4", "executed": true, "compensated": false}
       ],
       "exception": null
     }
   }
   ```
   Unexecuted branches (Service1) removed
   The compensation chain strictly includes only states that are "actually executed and have compensation defined."
   If no compensation is actually made (Service4 has no compensation defined), the compensationStatus field is initialized to null, the status field is initialized to "failed" (FA), the exception field is empty, and the process is explicitly terminated.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@seata.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@seata.apache.org
For additional commands, e-mail: notifications-help@seata.apache.org


Re: [PR] Saga end-to-end verification [incubator-seata-go]

Posted by "kaori-seasons (via GitHub)" <gi...@apache.org>.
kaori-seasons commented on code in PR #897:
URL: https://github.com/apache/incubator-seata-go/pull/897#discussion_r2377477530


##########
pkg/saga/statemachine/engine/repo/repository/state_machine_repository.go:
##########
@@ -71,6 +71,14 @@ func GetStateMachineRepositoryImpl() *StateMachineRepositoryImpl {
 	return stateMachineRepositoryImpl
 }
 
+func (s *StateMachineRepositoryImpl) SetDefaultTenantId(tenantId string) {
+	s.defaultTenantId = tenantId
+}
+
+func (s *StateMachineRepositoryImpl) GetDefaultTenantId() string {
+	return s.defaultTenantId

Review Comment:
   pkg/saga/statemachine/engine/config/default_statemachine_config.go
   pkg/saga/statemachine/engine/repo/repository/state_machine_repository.go
   Issue
   
   The tenant field is only set in some registration/loading locations. State instances, compensation chains, logs, and other functions do not fully carry tenant information, which may lead to cross-tenancy.
   Suggestion
   
   Add the TenantId field to structures such as StateMachineInstance and StateInstance. All persistence, logs, and compensation chains carry tenant information.
   All methods, such as GetStateMachineByNameAndTenantId and RegistryStateMachine, must pass and verify tenant information.



##########
pkg/saga/statemachine/engine/pcext/state_router_impl.go:
##########
@@ -53,15 +68,81 @@ func (t TaskStateRouter) Route(ctx context.Context, processContext process_ctrl.
 		return nil, nil
 	}
 
-	// The current CompensationTriggerState can mark the compensation process is started and perform compensation
-	// route processing.
-	compensationTriggerState, ok := processContext.GetVariable(constant.VarNameCurrentCompensateTriggerState).(statelang.State)
-	if ok {
+	// If current state is CompensationTrigger or compensation has been flagged, start compensation routing
+	if state != nil && state.Type() == constant.StateTypeCompensationTrigger {
+		// flag into context for downstream calls (best-effort)
+		if hpc, ok := processContext.(process_ctrl.HierarchicalProcessContext); ok {
+			hpc.SetVariableLocally(constant.VarNameCurrentCompensateTriggerState, state)
+			hpc.SetVariableLocally(constant.VarNameFirstCompensationStateStarted, false)
+		} else {
+			processContext.SetVariable(constant.VarNameCurrentCompensateTriggerState, state)
+			processContext.SetVariable(constant.VarNameFirstCompensationStateStarted, false)
+		}
+
+		// build compensation stack from executed forward states (latest first)
+		smInst := processContext.GetVariable(constant.VarNameStateMachineInst).(statelang.StateMachineInstance)
+		holder := GetCurrentCompensationHolder(ctx, processContext, true)
+		stack := holder.StateStackNeedCompensation()
+		sm := processContext.GetVariable(constant.VarNameStateMachine).(statelang.StateMachine)
+		states := smInst.StateList()
+		for i := len(states) - 1; i >= 0; i-- {
+			si := states[i]
+			// exclude compensation states
+			if si.StateIDCompensatedFor() != "" {
+				continue
+			}
+			// only successful forward states are subject to compensation
+			if si.Status() != statelang.SU {
+				continue
+			}
+			originName := GetOriginStateName(si)
+			def := sm.State(originName)
+			// ensure the definition has a compensate state
+			var task *sagaState.AbstractTaskState
+			switch s := def.(type) {
+			case *sagaState.ServiceTaskStateImpl:
+				task = s.AbstractTaskState
+			case *sagaState.ScriptTaskStateImpl:
+				task = s.AbstractTaskState
+			case *sagaState.SubStateMachineImpl:
+				if s.ServiceTaskStateImpl != nil {
+					task = s.ServiceTaskStateImpl.AbstractTaskState
+				}
+			}
+			if task == nil || task.CompensateState() == "" {
+				continue
+			}
+			stack.Push(si)
+		}
+		// fallback: if nothing pushed, try last successful forward state
+		if stack.Empty() {
+			for i := len(states) - 1; i >= 0; i-- {
+				si := states[i]
+				if si.StateIDCompensatedFor() != "" {
+					continue
+				}
+				if si.Status() != statelang.SU {
+					continue
+				}
+				stack.Push(si)
+				break
+			}
+		}
+
+		// mark machine compensation running
+		smInst.SetCompensationStatus(statelang.RU)
+
+		return t.compensateRoute(ctx, processContext, state)

Review Comment:
   In the core method Route in process_router.go , the routing logic checks the state type currently executed by the state machine:
   
   - If it is a normal Task state, the StateInstruction determines the next state to execute based on it.
   
   - If it is a Choice state, the routing logic first selects a "next" branch using an expression or branch condition and updates it to the StateInstruction:
   
   ```
   stateInstruction.SetStateName(next)
   ```
   This allows the state machine to execute different branches based on the Choice condition.
   
   Specifically, the branch selection result of the Choice state is assigned to the corresponding field of the StateInstruction (such as StateName), thus affecting subsequent processes.
   
   #### Existing Issues
   
   The compensation chain is constructed only backwards from the execution stack. If there is no compensable state after the Choice/Failure branch, the process simply marks it as NoCompensation, but the final state normalization is not explicit enough.
   
   Multi-branch, multi-stage compensation, and compensation failure lack fine-grained state recording. Recommendations
   
   #### Recommendations
   When building a compensation chain, traverse the state list to clearly mark the branch source and compensation result of each compensated state. We recommend adding a new structure such as CompensationTrace[]CompensationResult, which includes the branch, compensation status, and exception.
   When a Fail End is reached without compensation, the state is normalized to FA and the compensation status is cleared. We recommend also exposing the compensation chain record to the instance for easy querying.
   When compensating multiple branches, it is recommended that each branch record its compensation result separately, and the final state is normalized based on the compensation results of all branches.
   
   
   Scenario Description
   Assume the following SAGA state machine definition:
   
   Code
   Start -> Choice
   Choice:
   if (A) -> Service1
   else -> Service2
   Service1 -> Service3
   Service2 -> Service4
   Service3/Service4 -> FailEnd
   FailEnd: Compensation triggers
   Data Input Example (Choice condition is false, branch to Service2)
   Initial Business Parameters: 
   ```{"userId": 111, "amount": 100, "route": "B"}```
   State Machine Execution Path: 
   ```Start → Choice (route == B, choose Service2) → Service2 → Service4 → FailEnd```
   
   #### Boundary Issues
   
   - Issue 1: If the compensation chain is not constructed rigorously, FailEnd triggers compensation, but the compensation chain incorrectly includes the unexecuted Service1/Service3 branches.
   - Issue 2: If Service4 does not define a compensation state, the compensation chain is empty. In this case, the compensation chain is not properly normalized, resulting in the final state machine instance remaining in "Compensation in Progress" or "Unknown" instead of "Failure without Compensation."
   
   
   
   Data output without boundary processing (pseudo-JSON)
   ```
   {
     "stateMachineInstance": {
       "id": "saga-123",
       "status": "FA",
       "compensationStatus": "RU",
       "compensationChain": [
         {"state": "Service1", "executed": false},   // 不该出现
         {"state": "Service2", "executed": true, "compensated": false},
         {"state": "Service4", "executed": true, "compensated": false}
       ],
       "exception": "补偿链错误包含了未执行分支"
     }
   }
   ```
   
   
   Issue: The compensation chain incorrectly includes unexecuted branches, and the final state machine instance compensationStatus is not normalized (still RU), misleading the API/Ops layer into thinking compensation is still in progress.
   
   Data output after boundary processing
   ```
   {
     "stateMachineInstance": {
       "id": "saga-123",
       "status": "FA",
       "compensationStatus": "",
       "compensationChain": [
         {"state": "Service2", "executed": true, "compensated": false},
         {"state": "Service4", "executed": true, "compensated": false}
       ],
       "exception": null
     }
   }
   ```
   Unexecuted branches (Service1) removed
   The compensation chain strictly includes only states that are "actually executed and have compensation defined."
   If no compensation is actually made (Service4 has no compensation defined), the compensationStatus field is initialized to null, the status field is initialized to "failed" (FA), the exception field is empty, and the process is explicitly terminated.



##########
pkg/saga/statemachine/engine/pcext/process_handler.go:
##########
@@ -53,18 +59,29 @@ func NewStateMachineProcessHandler() *StateMachineProcessHandler {
 }
 
 func (s *StateMachineProcessHandler) Process(ctx context.Context, processContext process_ctrl.ProcessContext) error {
-	stateInstruction, _ := processContext.GetInstruction().(StateInstruction)
+	var stateInstruction *StateInstruction
+	switch v := processContext.GetInstruction().(type) {
+	case *StateInstruction:
+		stateInstruction = v
+	case StateInstruction:
+		tmp := v
+		stateInstruction = &tmp
+	default:
+		return errors.New("invalid state instruction from processContext")

Review Comment:
   #### Issue
   
   Exceptions in operations such as branchRegister/branchReport/finish are only logged, lacking visibility. Some return values ​​are not fully propagated, making them difficult for the API and upper layers to detect.
   Optimistic lock update failures (affected=0) only result in a fallback, but this is not exposed to the state machine instance or API layer.
   
   #### Recommendation
   
   When all key DB operations/TC interactions (branchRegister, Report, and Finish) fail, the error object should be written to the StateMachineInstance.Exception field and exposed in the API layer.
   When branchRegister fails (e.g., due to an invalid branchId), the process should be terminated immediately, the state should be set to FA, the exception should be written to the instance, and an error should be returned.
   In fallback update scenarios, if the failure persists after a reload, it is recommended that the exception be written to the state machine instance and propagated to avoid silent failure.
   When compensation fails, the failure state and exception should be written to the compensation state instance and appended to the StateMachineInstance.Exception list.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@seata.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@seata.apache.org
For additional commands, e-mail: notifications-help@seata.apache.org


Re: [PR] Saga end-to-end verification [incubator-seata-go]

Posted by "Code-Fight (via GitHub)" <gi...@apache.org>.
Code-Fight commented on code in PR #897:
URL: https://github.com/apache/incubator-seata-go/pull/897#discussion_r2412491728


##########
pkg/saga/statemachine/engine/repo/repository/state_machine_repository.go:
##########
@@ -71,6 +71,14 @@ func GetStateMachineRepositoryImpl() *StateMachineRepositoryImpl {
 	return stateMachineRepositoryImpl
 }
 
+func (s *StateMachineRepositoryImpl) SetDefaultTenantId(tenantId string) {
+	s.defaultTenantId = tenantId
+}
+
+func (s *StateMachineRepositoryImpl) GetDefaultTenantId() string {
+	return s.defaultTenantId

Review Comment:
   这个不需要,目前java实现也是这么做的



##########
pkg/saga/statemachine/engine/pcext/state_router_impl.go:
##########
@@ -53,15 +68,81 @@ func (t TaskStateRouter) Route(ctx context.Context, processContext process_ctrl.
 		return nil, nil
 	}
 
-	// The current CompensationTriggerState can mark the compensation process is started and perform compensation
-	// route processing.
-	compensationTriggerState, ok := processContext.GetVariable(constant.VarNameCurrentCompensateTriggerState).(statelang.State)
-	if ok {
+	// If current state is CompensationTrigger or compensation has been flagged, start compensation routing
+	if state != nil && state.Type() == constant.StateTypeCompensationTrigger {
+		// flag into context for downstream calls (best-effort)
+		if hpc, ok := processContext.(process_ctrl.HierarchicalProcessContext); ok {
+			hpc.SetVariableLocally(constant.VarNameCurrentCompensateTriggerState, state)
+			hpc.SetVariableLocally(constant.VarNameFirstCompensationStateStarted, false)
+		} else {
+			processContext.SetVariable(constant.VarNameCurrentCompensateTriggerState, state)
+			processContext.SetVariable(constant.VarNameFirstCompensationStateStarted, false)
+		}
+
+		// build compensation stack from executed forward states (latest first)
+		smInst := processContext.GetVariable(constant.VarNameStateMachineInst).(statelang.StateMachineInstance)
+		holder := GetCurrentCompensationHolder(ctx, processContext, true)
+		stack := holder.StateStackNeedCompensation()
+		sm := processContext.GetVariable(constant.VarNameStateMachine).(statelang.StateMachine)
+		states := smInst.StateList()
+		for i := len(states) - 1; i >= 0; i-- {
+			si := states[i]
+			// exclude compensation states
+			if si.StateIDCompensatedFor() != "" {
+				continue
+			}
+			// only successful forward states are subject to compensation
+			if si.Status() != statelang.SU {
+				continue
+			}
+			originName := GetOriginStateName(si)
+			def := sm.State(originName)
+			// ensure the definition has a compensate state
+			var task *sagaState.AbstractTaskState
+			switch s := def.(type) {
+			case *sagaState.ServiceTaskStateImpl:
+				task = s.AbstractTaskState
+			case *sagaState.ScriptTaskStateImpl:
+				task = s.AbstractTaskState
+			case *sagaState.SubStateMachineImpl:
+				if s.ServiceTaskStateImpl != nil {
+					task = s.ServiceTaskStateImpl.AbstractTaskState
+				}
+			}
+			if task == nil || task.CompensateState() == "" {
+				continue
+			}
+			stack.Push(si)
+		}
+		// fallback: if nothing pushed, try last successful forward state
+		if stack.Empty() {
+			for i := len(states) - 1; i >= 0; i-- {
+				si := states[i]
+				if si.StateIDCompensatedFor() != "" {
+					continue
+				}
+				if si.Status() != statelang.SU {
+					continue
+				}
+				stack.Push(si)
+				break
+			}
+		}
+
+		// mark machine compensation running
+		smInst.SetCompensationStatus(statelang.RU)
+
+		return t.compensateRoute(ctx, processContext, state)

Review Comment:
   这个暂时不需要,已经在 statelog.go:231-258 有完善的补偿逻辑



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@seata.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@seata.apache.org
For additional commands, e-mail: notifications-help@seata.apache.org


Re: [PR] Saga end-to-end verification [incubator-seata-go]

Posted by "Code-Fight (via GitHub)" <gi...@apache.org>.
Code-Fight commented on code in PR #897:
URL: https://github.com/apache/incubator-seata-go/pull/897#discussion_r2412316802


##########
pkg/saga/statemachine/store/db/statelog.go:
##########
@@ -949,9 +1118,9 @@ func execStateInstanceStatementForUpdate(obj statelang.StateInstance, stmt *sql.
 		serializedError,
 		obj.Status(),
 		obj.SerializedOutputParams(),
-		obj.EndTime(),
+		time.Now(),

Review Comment:
   无需调整,与java侧保持一致



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@seata.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@seata.apache.org
For additional commands, e-mail: notifications-help@seata.apache.org


Re: [PR] Saga end-to-end verification [incubator-seata-go]

Posted by "xjlgod (via GitHub)" <gi...@apache.org>.
xjlgod commented on code in PR #897:
URL: https://github.com/apache/incubator-seata-go/pull/897#discussion_r2382526957


##########
pkg/saga/statemachine/engine/pcext/engine_utils.go:
##########
@@ -77,11 +116,16 @@ func EndStateMachine(ctx context.Context, processContext process_ctrl.ProcessCon
 	}
 	stateMachineInstance.SetEndParams(endParams)
 
-	stateInstruction, ok := processContext.GetInstruction().(StateInstruction)
-	if !ok {
+	switch v := processContext.GetInstruction().(type) {

Review Comment:
   Will there be two situations here?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@seata.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@seata.apache.org
For additional commands, e-mail: notifications-help@seata.apache.org


Re: [PR] Saga end-to-end verification [incubator-seata-go]

Posted by "Code-Fight (via GitHub)" <gi...@apache.org>.
Code-Fight commented on code in PR #897:
URL: https://github.com/apache/incubator-seata-go/pull/897#discussion_r2506668807


##########
pkg/saga/statemachine/engine/core/process_ctrl_statemachine_engine_async_test.go:
##########
@@ -0,0 +1,67 @@
+/*
+ * 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 core
+
+import (
+	"context"
+	"testing"
+
+	"github.com/stretchr/testify/require"
+
+	"github.com/seata/seata-go/pkg/saga/statemachine/engine/config"
+	engExc "github.com/seata/seata-go/pkg/saga/statemachine/engine/exception"
+	"github.com/seata/seata-go/pkg/util/errors"
+)
+
+func TestStartAsyncDisabled(t *testing.T) {

Review Comment:
   ref:https://github.com/apache/incubator-seata-go-samples/pull/74



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@seata.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@seata.apache.org
For additional commands, e-mail: notifications-help@seata.apache.org


Re: [PR] Saga end-to-end verification [incubator-seata-go]

Posted by "xjlgod (via GitHub)" <gi...@apache.org>.
xjlgod commented on code in PR #897:
URL: https://github.com/apache/incubator-seata-go/pull/897#discussion_r2382513465


##########
pkg/saga/statemachine/engine/config/default_statemachine_config.go:
##########
@@ -442,6 +484,19 @@ func (c *DefaultStateMachineConfig) Init() error {
 		}
 	}
 
+	if c.tcEnabled {

Review Comment:
   If this configuration is not turned on, how will saga execute?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@seata.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@seata.apache.org
For additional commands, e-mail: notifications-help@seata.apache.org


Re: [PR] Saga end-to-end verification [incubator-seata-go]

Posted by "Code-Fight (via GitHub)" <gi...@apache.org>.
Code-Fight commented on code in PR #897:
URL: https://github.com/apache/incubator-seata-go/pull/897#discussion_r2410438430


##########
pkg/saga/statemachine/engine/config/default_statemachine_config.go:
##########
@@ -641,13 +696,24 @@ func NewDefaultStateMachineConfig(opts ...Option) (*DefaultStateMachineConfig, e
 
 	c.stateMachineRepository = repository.GetStateMachineRepositoryImpl()
 	c.stateLogRepository = repository.NewStateLogRepositoryImpl()
+	repository.GetStateMachineRepositoryImpl().SetDefaultTenantId(c.defaultTenantId)
 
 	c.syncProcessCtrlEventPublisher = process_ctrl.NewProcessCtrlEventPublisher(c.syncEventBus)
 	c.asyncProcessCtrlEventPublisher = process_ctrl.NewProcessCtrlEventPublisher(c.asyncEventBus)
 
 	for _, opt := range opts {
 		opt(c)
 	}
+	repository.GetStateMachineRepositoryImpl().SetDefaultTenantId(c.defaultTenantId)
+
+	if _, statErr := os.Stat("config.yaml"); statErr == nil {
+		if err := c.LoadConfig("config.yaml"); err == nil {
+			repository.GetStateMachineRepositoryImpl().SetDefaultTenantId(c.defaultTenantId)
+			log.Printf("Successfully loaded config from config.yaml")
+		} else {
+			log.Printf("Failed to load config file (using default/env values): %v", err)

Review Comment:
   暂不需要



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@seata.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@seata.apache.org
For additional commands, e-mail: notifications-help@seata.apache.org


Re: [PR] Saga end-to-end verification [incubator-seata-go]

Posted by "Code-Fight (via GitHub)" <gi...@apache.org>.
Code-Fight merged PR #897:
URL: https://github.com/apache/incubator-seata-go/pull/897


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@seata.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@seata.apache.org
For additional commands, e-mail: notifications-help@seata.apache.org


Re: [PR] Saga end-to-end verification [incubator-seata-go]

Posted by "xjlgod (via GitHub)" <gi...@apache.org>.
xjlgod commented on code in PR #897:
URL: https://github.com/apache/incubator-seata-go/pull/897#discussion_r2382552313


##########
pkg/saga/statemachine/engine/core/process_ctrl_statemachine_engine_async_test.go:
##########
@@ -0,0 +1,67 @@
+/*
+ * 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 core
+
+import (
+	"context"
+	"testing"
+
+	"github.com/stretchr/testify/require"
+
+	"github.com/seata/seata-go/pkg/saga/statemachine/engine/config"
+	engExc "github.com/seata/seata-go/pkg/saga/statemachine/engine/exception"
+	"github.com/seata/seata-go/pkg/util/errors"
+)
+
+func TestStartAsyncDisabled(t *testing.T) {

Review Comment:
   Can we add some real simple state machine tests here



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@seata.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@seata.apache.org
For additional commands, e-mail: notifications-help@seata.apache.org


Re: [PR] Saga end-to-end verification [incubator-seata-go]

Posted by "Code-Fight (via GitHub)" <gi...@apache.org>.
Code-Fight commented on code in PR #897:
URL: https://github.com/apache/incubator-seata-go/pull/897#discussion_r2410436248


##########
pkg/saga/statemachine/statelang/state_instance.go:
##########
@@ -319,7 +319,10 @@ func (s *StateInstanceImpl) SetIgnoreStatus(ignoreStatus bool) {
 }
 
 func (s *StateInstanceImpl) IsForCompensation() bool {
-	return s.stateIdCompensatedFor == ""
+	// A state instance is considered a compensation execution if it points
+	// back to an original forward state via stateIdCompensatedFor.
+	// When this field is non-empty, this instance is a compensation.
+	return s.stateIdCompensatedFor != ""

Review Comment:
   注释只是为了说明。实际是一致的



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@seata.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@seata.apache.org
For additional commands, e-mail: notifications-help@seata.apache.org


Re: [PR] Saga end-to-end verification [incubator-seata-go]

Posted by "Code-Fight (via GitHub)" <gi...@apache.org>.
Code-Fight commented on code in PR #897:
URL: https://github.com/apache/incubator-seata-go/pull/897#discussion_r2410447667


##########
pkg/saga/statemachine/engine/config/default_statemachine_config.go:
##########
@@ -442,6 +484,19 @@ func (c *DefaultStateMachineConfig) Init() error {
 		}
 	}
 
+	if c.tcEnabled {

Review Comment:
   当 tcEnabled=false 时 Saga 仅做本地状态机编排,不会向 TC 注册分支。这个在事务模式下基本不会用到,但是用作AI agent Workflow的时候,就不需要tc了



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@seata.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@seata.apache.org
For additional commands, e-mail: notifications-help@seata.apache.org


Re: [PR] Saga end-to-end verification [incubator-seata-go]

Posted by "Code-Fight (via GitHub)" <gi...@apache.org>.
Code-Fight commented on code in PR #897:
URL: https://github.com/apache/incubator-seata-go/pull/897#discussion_r2410453627


##########
pkg/saga/statemachine/engine/pcext/engine_utils.go:
##########
@@ -77,11 +116,16 @@ func EndStateMachine(ctx context.Context, processContext process_ctrl.ProcessCon
 	}
 	stateMachineInstance.SetEndParams(endParams)
 
-	stateInstruction, ok := processContext.GetInstruction().(StateInstruction)
-	if !ok {
+	switch v := processContext.GetInstruction().(type) {

Review Comment:
   GetInstruction() 既可能返回值,也可能返回指针,switch 是为了兼容和预防



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@seata.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@seata.apache.org
For additional commands, e-mail: notifications-help@seata.apache.org