fix: close batch execution and recovery lifecycle

This commit is contained in:
阿白叔 committed 2026-11-17 16:56:29 +08:00
1 parent b19afc6a53
commit d9cf6a07e9
91 files changed
+5779 -454

No files matched your search

@@ -249,6 +249,7 @@ Function QPNativeCollectMode(ByRef SelectedUids, ByVal Token, ByVal Project, ByV
QPNativeRequireContext Project, Sheet, Guid
QPInvalidatePinIndex
Set Components = QP_App.ActiveView.Query(VDM_COMP, VD_ALL)
QPBindSheetReferences Components
Set Seen = CreateObject("Scripting.Dictionary")
Set Found = CreateObject("Scripting.Dictionary")
Text = "NR1" & vbTab & Token & vbTab & QPEncode(Project) & vbTab & QPEncode(Sheet) & vbCrLf
@@ -306,6 +307,13 @@ Function QPBuildNativeReadScript(ByVal Source, ByRef SelectedUids, ByVal Token,
For Each Uid In SelectedUids.Keys
Body = Body & "QP_NR_Selected.Add " & QPNativeExpression(Uid) & ",True" & vbCrLf
Next
If IsObject(QP_ReferenceAliases) Then
Body=Body & "Set QP_ReferenceAliases=CreateObject(""Scripting.Dictionary"")" & vbCrLf
For Each Uid In QP_ReferenceAliases.Keys
Body=Body & "QP_ReferenceAliases.Add " & QPNativeExpression(Uid) & "," & _
QPNativeExpression(QP_ReferenceAliases(Uid)) & vbCrLf
Next
End If
Body = Body & "On Error Resume Next" & vbCrLf & _
"Set QP_App=GetObject(,""Viewdraw.Application"")" & vbCrLf & _
"If Err.Number=0 Then QP_NR_Text=QPNativeCollectMode(QP_NR_Selected," & _
@@ -315,7 +323,7 @@ Function QPBuildNativeReadScript(ByVal Source, ByRef SelectedUids, ByVal Token,
"If QP_NR_Code<>0 Then QP_NR_Text=""ERROR"" & vbTab & " & QPNativeExpression(Token) & _
" & vbTab & CStr(QP_NR_Code) & vbTab & QPEncode(QP_NR_Source) & vbTab & QPEncode(QP_NR_Description) & vbCrLf" & vbCrLf & _
"QPWriteUtf8 " & QPNativeExpression(ResultPath) & ",QP_NR_Text" & vbCrLf & "On Error GoTo 0" & vbCrLf
Names = Split("QPNativeCollectMode QPNativeRequireContext QPNativeReadInvalid QPSnapshotComponent QPUntouchedComponent QPUntouchedFullState QPUntouchedIdentity QPComponentPins QPComponentIdentityKey QPInvalidatePinIndex QPConnectionSignatureFromPins QPAddSortedSignature QPSnapshotAttribute QPReadOptionalAttributeValue QPOptionalAttributeField QPSortSnapshotLines QPLog QPAppendAscii QPEncode QPDecode QPProjectPath QPSheetIdentity QPCanonicalPath QPEnsureProjectAccess QPReadUtf8 QPWriteUtf8", " ")
Names = Split("QPNativeCollectMode QPNativeRequireContext QPNativeReadInvalid QPSnapshotComponent QPUntouchedComponent QPUntouchedFullState QPUntouchedIdentity QPComponentPins QPComponentIdentityKey QPComponentUnitKey QPBindSheetReferences QPInvalidatePinIndex QPConnectionSignatureFromPins QPAddSortedSignature QPSnapshotAttribute QPReadOptionalAttributeValue QPOptionalAttributeField QPSortSnapshotLines QPLog QPAppendAscii QPEncode QPDecode QPProjectPath QPSheetIdentity QPCanonicalPath QPEnsureProjectAccess QPReadUtf8 QPWriteUtf8", " ")
Pattern.Global = False
For Each Name In Names
Pattern.Pattern = "^(Function|Sub) " & Name & "\([^\n]*\n[\s\S]*?^End \1[ \t]*"
+365 -33
View File
@@ -28,17 +28,20 @@ Dim QP_PinContext
Dim QP_ComponentUidIndex, QP_ComponentRefdesIndex, QP_ComponentLocationIndex
Dim QP_FallbackIdentityUsed
Dim QP_FallbackIdentityWarnings
Dim QP_ReferenceAliases
Dim QP_ComponentIndexContext
Dim QP_NativeCallActive
Dim QP_BatchMode, QP_OwnedProject, QP_BatchState, QP_BatchCode, QP_BatchMessage
Dim QP_BatchSaveCommitted, QP_BatchSaveRequested
Dim QP_DiscoveryMode, QP_TargetSchematic, QP_TargetSheet
Dim QP_FailureNumber, QP_FailureSource, QP_FailureDescription
Dim QP_FailureCleanupActive
Dim QP_NcSyncSummary
Dim QP_SessionMode, QP_SessionToken, QP_SessionProject, QP_MonitorJobId
Dim QP_OwnedProjectPath, QP_SessionWaiting, QP_SessionExternalChange
Dim QP_CheckpointSchematic, QP_CheckpointSheet
Dim QP_ProjectAccess, QP_AccessProject
Dim QP_SessionItems, QP_SessionSheets, QP_SessionDocuments, QP_SessionCommitActive
Dim FailureState, CloseError
Set QP_Fso = CreateObject("Scripting.FileSystemObject")
QP_RootTemplate = "%LOCALAPPDATA%\DxProductivity\trial-task-center\quick-run"
@@ -65,6 +68,7 @@ QP_OwnedProject = False
QP_BatchState = ""
QP_BatchSaveCommitted = False
QP_BatchSaveRequested = False
QP_FailureCleanupActive = False
QP_DiscoveryMode = False
QP_TargetSchematic = ""
QP_TargetSheet = ""
@@ -82,6 +86,10 @@ QP_SessionMode = False
QP_OwnedProjectPath = ""
QP_SessionWaiting = False
QP_SessionExternalChange = False
Set QP_SessionItems = CreateObject("Scripting.Dictionary")
Set QP_SessionSheets = CreateObject("Scripting.Dictionary")
Set QP_SessionDocuments = CreateObject("Scripting.Dictionary")
QP_SessionCommitActive = False
QP_MonitorJobId = QP_ExpectedJobId
Set QP_App = Nothing
@@ -91,6 +99,7 @@ If Err.Number <> 0 Or QP_App Is Nothing Then
QP_FailureNumber = Err.Number
QP_FailureSource = Err.Source
QP_FailureDescription = Err.Description
If QP_FailureSource = "QuickPartReplace.SafeStop" And QP_SessionMode Then QPAcknowledgePrewritePause
QP_ErrorMessage = "stage=" & QP_Stage & " " & CStr(QP_FailureSource) & ": " & CStr(QP_FailureDescription)
If QP_DiscoveryMode Then QPCleanupDiscoveryFailure
QPFail QP_Root, "hard_failure", QP_FailureNumber, QP_FailureSource, QP_FailureDescription
@@ -115,6 +124,7 @@ Else
QP_FailureNumber = Err.Number
QP_FailureSource = Err.Source
QP_FailureDescription = Err.Description
If QP_FailureSource = "QuickPartReplace.SafeStop" And QP_SessionMode Then QPAcknowledgePrewritePause
If QP_DiscoveryMode Then QPCleanupDiscoveryFailure
FailureState = "hard_failure"
If QP_BatchSaveRequested Then
@@ -161,7 +171,7 @@ Sub QPMain()
Set Command = QPReadCommand(QP_Fso.BuildPath(QP_Root, "command.tsv"))
QP_CurrentJobId = CStr(Command("job_id"))
QPRequireProject Command
If QP_BatchMode And Not QP_Fso.FileExists(QP_Fso.BuildPath(QP_Root, "recovery.request")) Then _
If QP_BatchMode And QP_SessionItems.Count = 0 And Not QP_Fso.FileExists(QP_Fso.BuildPath(QP_Root, "recovery.request")) Then _
QPVerifyExpectedBaselines CStr(Command("project_path"))
SnapshotPath = QPJobSnapshotPath(CStr(Command("job_id")))
State = QPReadState(QP_Fso.BuildPath(QP_Root, "status.tsv"), _
@@ -187,7 +197,7 @@ Sub QPMain()
QPCaptureAndSelect Command, SnapshotPath
If QPReadState(QP_Fso.BuildPath(QP_Root, "status.tsv"), QP_CurrentJobId) = "no_match" Then Exit Sub
QPAutomaticReplaceAndRestore Command, SnapshotPath
ElseIf State = "awaiting_native_replace" Then
ElseIf State = "awaiting_native_replace" Or State = "pending" Then
QPAutomaticReplaceAndRestore Command, SnapshotPath
Else
Err.Raise vbObjectError + 796, "QuickPartReplace", _
@@ -266,6 +276,9 @@ Sub QPProgress(ByVal Stage, ByVal Done, ByVal Total)
Safe = 0
If Not CBool(QP_NativeMutationPossible) And Not CBool(QP_RestoreTransactionOpen) And _
Not CBool(QP_NativeCallActive) Then Safe = 1
If QP_SessionMode And IsObject(QP_SessionItems) Then
If QP_SessionItems.Exists(QP_CurrentJobId) Then Safe = 0
End If
QP_ProgressSequence = CLng(QP_ProgressSequence) + 1
Job = QP_ExpectedJobId
Suffix = ""
@@ -276,7 +289,7 @@ Sub QPProgress(ByVal Stage, ByVal Done, ByVal Total)
WScript.StdOut.WriteLine "DX_PROGRESS" & vbTab & QP_AttemptToken & vbTab & _
Job & vbTab & CStr(QP_ProgressSequence) & vbTab & Stage & _
vbTab & CStr(Done) & vbTab & CStr(Total) & vbTab & CStr(Safe) & Suffix
If Safe = 1 And Stage <> "finished" Then
If Safe = 1 And Stage <> "finished" And Stage <> "session_wait" And Not QP_FailureCleanupActive Then
StopPath = QP_Fso.BuildPath(QP_Root, "monitor-" & QP_AttemptToken & ".stop")
If QP_Fso.FileExists(StopPath) Then
If Trim(QPReadUtf8(StopPath)) = CStr(QP_AttemptToken) Then
@@ -295,6 +308,41 @@ Sub QPProgress(ByVal Stage, ByVal Done, ByVal Total)
End If
End Sub
Sub QPAcknowledgePrewritePause()
Dim Command, PauseText, ErrorNumber, ErrorDescription
If QP_NativeMutationPossible Or QP_RestoreTransactionOpen Or QP_NativeCallActive Or _
QP_BatchSaveRequested Or QP_SessionCommitActive Or QP_SessionItems.Exists(QP_CurrentJobId) Then Exit Sub
QP_FailureCleanupActive = True
On Error Resume Next
Err.Clear
If QP_OwnedProject Then
QP_SessionWaiting = False
QPVerifyFailedOriginalSnapshot
If Err.Number = 0 Then
Set Command = QPReadCommand(QP_Fso.BuildPath(QP_Root, "command.tsv"))
If Err.Number = 0 Then QPWriteVerifiedState Command
End If
If Err.Number = 0 Then QPCommitSessionProject
End If
ErrorNumber = Err.Number
ErrorDescription = Err.Description
Err.Clear
If ErrorNumber = 0 And Not QP_OwnedProject Then
PauseText = QP_SessionToken & vbTab & QPEncode(QP_SessionProject) & vbTab & QP_ExpectedJobId & vbTab & "prewrite_closed"
QPWriteUtf8 QP_Fso.BuildPath(QP_Root, "project-pause-" & QP_SessionToken & ".tsv"), PauseText
If Err.Number = 0 Then
WScript.StdOut.WriteLine "DX_PREWRITE_PAUSED" & vbTab & QP_AttemptToken & vbTab & _
QP_MonitorJobId & vbTab & QP_SessionToken & vbTab & QP_ExpectedJobId & vbTab & CStr(QP_ProgressSequence)
WScript.Quit 75
End If
ErrorDescription = Err.Description
End If
Err.Clear
On Error GoTo 0
QP_FailureCleanupActive = False
QP_FailureDescription = QP_FailureDescription & "; prewrite pause closure was not proven: " & ErrorDescription
End Sub
Sub QPReadSessionRequest()
Dim Path, Fields, Index, Character
Path = QP_Fso.BuildPath(QP_Root, "project-session.request")
@@ -331,7 +379,7 @@ Sub QPSessionNext()
QPRequireSessionCheckpoint
QP_SessionWaiting = False
If Fields(1) = "close" Then
QPCloseBatchProject QP_SessionProject, False
QPCommitSessionProject
QP_SessionMode = False
Exit Sub
End If
@@ -347,15 +395,6 @@ Sub QPSessionNext()
TargetPath = QPConfirmedProjectPath()
If QPCanonicalPath(TargetPath) <> QPCanonicalPath(QP_SessionProject) Then _
Err.Raise vbObjectError + 873, "QuickPartReplace.ProjectSession", "cannot switch project inside a session"
Set View = QP_App.ActiveView
If Not View Is Nothing Then
If CStr(View.GetName(0)) <> QP_TargetSchematic Or CStr(View.Block.SheetNum) <> QP_TargetSheet Then
Set Documents = QP_App.SchematicSheetDocuments()
If Documents.Count <> 1 Then Err.Raise vbObjectError + 873, "QuickPartReplace.ProjectSession", "owned sheet set changed"
Set Document = Documents.Item(1)
Document.Close False, ""
End If
End If
QPEnsureProject QP_App, TargetPath
Exit Sub
End If
@@ -395,10 +434,12 @@ Sub QPRequireSessionCheckpoint()
Err.Raise vbObjectError + 873, "QuickPartReplace.ProjectSession", "project modified outside worker at checkpoint; no automatic save or close"
Set Documents = QP_App.SchematicSheetDocuments()
Set View = QP_App.ActiveView
If Documents.Count <> 1 Or View Is Nothing Then _
If Documents.Count <> QP_SessionDocuments.Count Or View Is Nothing Then _
Err.Raise vbObjectError + 873, "QuickPartReplace.ProjectSession", "owned sheet set changed at checkpoint"
If CStr(View.GetName(0)) <> QP_CheckpointSchematic Or CStr(View.Block.SheetNum) <> QP_CheckpointSheet Then _
Err.Raise vbObjectError + 873, "QuickPartReplace.ProjectSession", "active sheet changed at checkpoint"
If QP_SessionSheets.Exists(QPSheetKey(QP_CheckpointSchematic, QP_CheckpointSheet)) Then _
QPRequireExpectedState QP_SessionSheets.Item(QPSheetKey(QP_CheckpointSchematic, QP_CheckpointSheet)), QPCurrentSemanticState()
End Sub
Sub QPInvalidatePinIndex()
@@ -691,6 +732,10 @@ Sub QPEnsureProject(ByRef App, ByVal TargetPath)
Set Document = Documents.Open(OnlySchematic, OnlySheet)
If Document Is Nothing Then Err.Raise vbObjectError + 857, "QuickPartReplace.Session", "target sheet could not be opened"
Document.Activate
If QP_SessionMode Then
If Not QP_SessionDocuments.Exists(QPSheetKey(OnlySchematic, OnlySheet)) Then _
QP_SessionDocuments.Add QPSheetKey(OnlySchematic, OnlySheet), Document
End If
Set View = App.ActiveView
If View Is Nothing Then Err.Raise vbObjectError + 857, "QuickPartReplace.Session", "target sheet did not become active"
If CStr(View.GetName(0)) <> OnlySchematic Or CStr(View.Block.SheetNum) <> OnlySheet Then _
@@ -806,7 +851,7 @@ Sub QPDiscoverInventory(ByRef Documents)
End Sub
Function QPComponentIdentityKey(ByRef Comp)
Dim Uid, Refdes, Number, Description
Dim Uid, Refdes, Number, Description, AliasKey, UnitKey
On Error Resume Next
Err.Clear
Uid = CStr(Comp.UID)
@@ -814,8 +859,7 @@ Function QPComponentIdentityKey(ByRef Comp)
Description = Err.Description
Err.Clear
On Error GoTo 0
If Number <> 0 Then Err.Raise vbObjectError + 872, "QuickPartReplace.Discovery", _
"component UID could not be read: " & Description
If Number <> 0 Then Uid = ""
On Error Resume Next
Err.Clear
Refdes = CStr(Comp.Refdes)
@@ -825,6 +869,20 @@ Function QPComponentIdentityKey(ByRef Comp)
On Error GoTo 0
If Number <> 0 Then Err.Raise vbObjectError + 872, _
"QuickPartReplace.Discovery", "component Refdes is unreadable; operation stopped before any replacement"
If Len(Trim(Refdes))>0 And IsObject(QP_ReferenceAliases) Then
AliasKey = LCase(QPSheetIdentity() & "|" & Trim(Refdes))
If QP_ReferenceAliases.Exists(AliasKey & "|#units") Then
UnitKey = AliasKey & "|unit=" & QPComponentUnitKey(Comp)
If Not QP_ReferenceAliases.Exists(UnitKey) Then Err.Raise vbObjectError + 872, _
"QuickPartReplace.Identity", "physical unit changed or is ambiguous"
QPComponentIdentityKey = QP_ReferenceAliases(UnitKey)
Exit Function
End If
If QP_ReferenceAliases.Exists(AliasKey) Then
QPComponentIdentityKey = QP_ReferenceAliases(AliasKey)
Exit Function
End If
End If
If Len(Trim(CStr(Uid))) > 0 Then
QPComponentIdentityKey = Trim(CStr(Uid))
Exit Function
@@ -844,6 +902,89 @@ Function QPComponentIdentityKey(ByRef Comp)
End If
End Function
Sub QPBindSheetReferences(ByRef Components)
Dim Counts, References, Units, Comp, Uid, Refdes, Key, Context, UnitKey, Identity
Set Counts=CreateObject("Scripting.Dictionary")
Set References=CreateObject("Scripting.Dictionary")
Set Units=CreateObject("Scripting.Dictionary")
Context=LCase(QPSheetIdentity())
If Not IsObject(QP_ReferenceAliases) Then Set QP_ReferenceAliases=CreateObject("Scripting.Dictionary")
For Each Comp In Components
Uid=""
On Error Resume Next
Err.Clear
Uid=Trim(CStr(Comp.UID))
Err.Clear
On Error GoTo 0
If Counts.Exists(Uid) Then Counts(Uid)=Counts(Uid)+1 Else Counts.Add Uid,1
Refdes=LCase(Trim(CStr(Comp.Refdes)))
If References.Exists(Refdes) Then References(Refdes)=References(Refdes)+1 Else References.Add Refdes,1
Next
For Each Comp In Components
Uid=""
On Error Resume Next
Err.Clear
Uid=Trim(CStr(Comp.UID))
Err.Clear
On Error GoTo 0
Refdes=Trim(CStr(Comp.Refdes))
Key=Context & "|" & LCase(Refdes)
If Len(Refdes)>0 Then
Identity=Uid
If Len(Uid)=0 Or Counts(Uid)>1 Then Identity="@REFDES|" & Refdes
If References(LCase(Refdes))>1 Then
UnitKey=Key & "|unit=" & QPComponentUnitKey(Comp)
If Units.Exists(UnitKey) Then Err.Raise vbObjectError+872, _
"QuickPartReplace.Identity","physical unit association is ambiguous"
Units.Add UnitKey,True
If Len(Uid)=0 Or Counts(Uid)>1 Then Identity=Identity & "|UNIT|" & QPComponentUnitKey(Comp)
If Not QP_ReferenceAliases.Exists(Key & "|#units") Then QP_ReferenceAliases.Add Key & "|#units","1"
If Not QP_ReferenceAliases.Exists(UnitKey) Then
QP_ReferenceAliases.Add UnitKey,Identity
End If
ElseIf Not QP_ReferenceAliases.Exists(Key) Then
QP_ReferenceAliases.Add Key,Identity
End If
End If
Next
End Sub
Function QPComponentUnitKey(ByRef Comp)
Dim Point
Set Point=Comp.GetLocation()
QPComponentUnitKey=CStr(Point.X) & "|" & CStr(Point.Y) & "|" & CStr(Comp.Orientation) & "|" & CStr(Comp.Scale)
End Function
Sub QPBindSnapshotReference(ByVal Context, ByRef Record)
Dim Key, UnitKey
If Len(Trim(CStr(Record("refdes"))))=0 Then Exit Sub
If Not IsObject(QP_ReferenceAliases) Then Set QP_ReferenceAliases=CreateObject("Scripting.Dictionary")
Key=LCase(Context & "|" & Trim(Record("refdes")))
UnitKey=Key & "|unit=" & Record("x") & "|" & Record("y") & "|" & Record("orientation") & "|" & Record("scale")
If QP_ReferenceAliases.Exists(Key) Then
If QP_ReferenceAliases(Key)<>Record("uid") Then QP_ReferenceAliases(Key & "|#units")="1"
Else
QP_ReferenceAliases.Add Key,Record("uid")
End If
QP_ReferenceAliases(UnitKey)=Record("uid")
End Sub
Sub QPBindSnapshotFullState(ByVal Context, ByVal State)
Dim Line, Fields, Record
For Each Line In Split(State,vbCrLf)
Fields=Split(Line,vbTab)
If UBound(Fields)=7 Then
If Fields(0)="C" Then
Set Record=CreateObject("Scripting.Dictionary")
Record.Add "uid",QPDecode(Fields(1)):Record.Add "refdes",QPDecode(Fields(2))
Record.Add "x",QPDecode(Fields(3)):Record.Add "y",QPDecode(Fields(4))
Record.Add "orientation",QPDecode(Fields(5)):Record.Add "scale",QPDecode(Fields(6))
QPBindSnapshotReference Context,Record
End If
End If
Next
End Sub
Function QPReadInventoryRequest()
Dim Path, Lines, Header, Result, Index, Fields, OldPart, Key
Path = QP_Fso.BuildPath(QP_Root, "inventory-request.tsv")
@@ -943,14 +1084,20 @@ Sub QPCloseBatchProject(ByVal ExpectedPath, ByVal SaveChanges)
If QPCanonicalPath(QPProjectPath()) <> QPCanonicalPath(ExpectedPath) Then _
Err.Raise vbObjectError + 871, "QuickPartReplace.Batch", "active project changed before save and close"
Set Documents = QP_App.SchematicSheetDocuments()
If Documents.Count <> 1 Then Err.Raise vbObjectError + 871, "QuickPartReplace.Batch", "open sheet set changed; no automatic close"
Set Document = Documents.Item(1)
If QP_SessionMode Then
If Documents.Count <> QP_SessionDocuments.Count Then Err.Raise vbObjectError + 871, "QuickPartReplace.Batch", "owned sheet set changed; no automatic close"
Else
If Documents.Count <> 1 Then Err.Raise vbObjectError + 871, "QuickPartReplace.Batch", "open sheet set changed; no automatic close"
End If
QPProgress "save_and_close", 0, 1
If SaveChanges Then
QP_BatchSaveRequested = True
QPLog QP_Root, "INFO", "save_requested job=" & QP_CurrentJobId
End If
Document.Close CBool(SaveChanges), ""
Do While Documents.Count > 0
Set Document = Documents.Item(1)
Document.Close CBool(SaveChanges), ""
Loop
If SaveChanges Then
QP_BatchSaveCommitted = True
QPLog QP_Root, "INFO", "save_returned job=" & QP_CurrentJobId
@@ -968,14 +1115,19 @@ Sub QPCloseBatchProject(ByVal ExpectedPath, ByVal SaveChanges)
End Sub
Sub QPDiscardFailedBatchProject(ByRef ErrorDescription)
Dim ErrorNumber, ErrorSource, Description
Dim ErrorNumber, ErrorSource, Description, HasStagedItems
ErrorDescription = ""
If (Not QP_BatchMode And Not QP_SessionMode) Or Not QP_OwnedProject Or QP_App Is Nothing Then Exit Sub
If QP_NativeMutationPossible Or QP_BatchSaveRequested Or QP_BatchSaveCommitted Then
HasStagedItems = False
If IsObject(QP_SessionItems) Then HasStagedItems = (QP_SessionItems.Count > 0)
If QP_NativeMutationPossible Or QP_BatchSaveRequested Or QP_BatchSaveCommitted Or HasStagedItems Then
ErrorDescription = "write or save outcome requires reconciliation; owned project retained without automatic save or discard"
Exit Sub
End If
' A pending pause must not interrupt the verification and close it requested.
QP_FailureCleanupActive = True
On Error Resume Next
Err.Clear
QPVerifyFailedOriginalSnapshot
If Err.Number = 0 Then QPCloseBatchProject QP_OwnedProjectPath, False
ErrorNumber = Err.Number
@@ -983,6 +1135,7 @@ Sub QPDiscardFailedBatchProject(ByRef ErrorDescription)
Description = Err.Description
Err.Clear
On Error GoTo 0
QP_FailureCleanupActive = False
If ErrorNumber <> 0 Then
ErrorDescription = CStr(ErrorSource) & ": " & CStr(Description)
Else
@@ -1018,6 +1171,10 @@ End Sub
Sub QPFinishBatchItem()
Dim Command, SnapshotPath, Records, Plans, ValueStates, Index, Record, Candidate, TargetPath, FinalState, ValueReportState, SavedSemanticState
If QP_SessionMode Then
QPStageSessionItem
Exit Sub
End If
If QP_BatchState <> "restored_ok" And QP_BatchState <> "no_match" Then _
Err.Raise vbObjectError + 871, "QuickPartReplace.Batch", "worker has no verified terminal result"
FinalState = QP_BatchState
@@ -1100,14 +1257,144 @@ Sub QPFinishBatchItem()
QPProgress "finished", 1, 1
End Sub
Sub QPStageSessionItem()
Dim Command, Records, ValueStates, Item, Index, Record, Candidate, FinalState, Code
If QP_BatchState <> "restored_ok" And QP_BatchState <> "no_match" Then _
Err.Raise vbObjectError + 871, "QuickPartReplace.Batch", "worker has no verified result to stage"
FinalState = QP_BatchState
QP_BatchState = ""
Set Command = QPReadCommand(QP_Fso.BuildPath(QP_Root, "command.tsv"))
QP_BatchState = FinalState
Set Item = CreateObject("Scripting.Dictionary")
Item.Add "command", Command
Item.Add "schematic", CStr(QP_App.ActiveView.GetName(0))
Item.Add "sheet", CStr(QP_App.ActiveView.Block.SheetNum)
Item.Add "final_state", FinalState
If FinalState = "restored_ok" Then
Set Records = QPReadSnapshot(QPJobSnapshotPath(QP_CurrentJobId))
QPRequireCommandSnapshot Command, QPJobSnapshotPath(QP_CurrentJobId)
QPVerifyUntouched Records
Set ValueStates = CreateObject("Scripting.Dictionary")
For Index = 0 To Records.Item("components").Count - 1
Set Record = Records.Item("components").Item(CStr(Index))
Set Candidate = QPFindUniqueByOldLocation(Record)
ValueStates.Add CStr(Index), QPCaptureValueState(Candidate)
QPSetRequiredNc ValueStates.Item(CStr(Index)), Record, Records.Item("attributes"), QPSyncNc(Command)
ValueStates.Item(CStr(Index)).Add "custom_value", QPCustomValue(Command)
Next
Item.Add "snapshot_path", QPJobSnapshotPath(QP_CurrentJobId)
Item.Add "value_states", ValueStates
End If
QP_SessionItems.Add QP_CurrentJobId, Item
QP_SessionSheets.Item(QPSheetKey(Item("schematic"), Item("sheet"))) = QPCurrentSemanticState()
QP_BatchMode = False
QP_NativeMutationPossible = False
QP_SessionExternalChange = False
QP_CheckpointSchematic = Item("schematic")
QP_CheckpointSheet = Item("sheet")
QP_SessionWaiting = True
Code = "session_staged"
If FinalState = "no_match" Then Code = "session_staged_no_match"
QPWriteStatus QP_Root, QP_CurrentJobId, "pending_save", Code, "Verified in memory; awaiting engineering project save and readback."
QPWriteUtf8 QP_Fso.BuildPath(QP_Root, "project-session-result.tsv"), _
QP_SessionToken & vbTab & QP_CurrentJobId & vbTab & "pending_save" & vbTab & Code
End Sub
Sub QPCommitSessionProject()
Dim Job, Item, Command, Records, Plans, ValueStates, Index, Record, Candidate, Key
Dim Documents, Document, Manifest, FinalState, OriginalJob, OriginalSchematic, OriginalSheet, VerifiedSheets, HasChanges
If QP_SessionItems.Count = 0 Then
QPCloseBatchProject QP_SessionProject, False
Exit Sub
End If
OriginalJob = QP_CurrentJobId
OriginalSchematic = QP_TargetSchematic
OriginalSheet = QP_TargetSheet
QP_SessionWaiting = False
QP_SessionCommitActive = True
QP_FailureCleanupActive = True
QP_BatchMode = True
HasChanges = False
Set VerifiedSheets = CreateObject("Scripting.Dictionary")
' Capture the final memory state once per sheet, including later replacements.
For Each Job In QP_SessionItems.Keys
Set Item = QP_SessionItems.Item(Job)
QP_TargetSchematic = Item("schematic")
QP_TargetSheet = Item("sheet")
Key = QPSheetKey(QP_TargetSchematic, QP_TargetSheet)
If Not VerifiedSheets.Exists(Key) Then
QPEnsureProject QP_App, QP_SessionProject
QPRequireExpectedState QP_SessionSheets.Item(Key), QPCurrentSemanticState()
VerifiedSheets.Add Key, True
End If
If Item("final_state") = "restored_ok" Then HasChanges = True
Next
QPCloseBatchProject QP_SessionProject, HasChanges
QP_SessionDocuments.RemoveAll
VerifiedSheets.RemoveAll
QPProgress "verify_saved_project", 0, QP_SessionItems.Count
Manifest = QP_SessionToken & vbTab & QPEncode(QP_SessionProject) & vbTab & "project_verified" & vbCrLf
For Each Job In QP_SessionItems.Keys
Set Item = QP_SessionItems.Item(Job)
Set Command = Item("command")
QP_CurrentJobId = CStr(Job)
QP_TargetSchematic = Item("schematic")
QP_TargetSheet = Item("sheet")
QPEnsureProject QP_App, QP_SessionProject
Key = QPSheetKey(QP_TargetSchematic, QP_TargetSheet)
If Not VerifiedSheets.Exists(Key) Then
QPRequireExpectedState QP_SessionSheets.Item(Key), QPCurrentSemanticState()
VerifiedSheets.Add Key, True
End If
QPWriteSemanticState Command, QP_SessionSheets.Item(Key)
FinalState = "no_match"
If Item("final_state") = "restored_ok" Then
Set Records = QPReadSnapshot(CStr(Item("snapshot_path")))
Set ValueStates = Item("value_states")
Set Plans = CreateObject("Scripting.Dictionary")
QPInvalidatePinIndex
QPInvalidateComponentIndex
For Index = 0 To Records.Item("components").Count - 1
Set Record = Records.Item("components").Item(CStr(Index))
Set Candidate = QPFindUniqueByOldLocation(Record)
If StrComp(CStr(Candidate.RefDes), CStr(Record("refdes")), vbTextCompare) <> 0 Then _
Err.Raise vbObjectError + 871, "QuickPartReplace.Batch", "saved component refdes differs"
Plans.Add CStr(Index), Candidate
Next
QPVerifyRestoredPlans Command, Records, Plans, ValueStates
QPWriteValueReadback Command, Records, Plans, "saved_ok"
FinalState = "saved_ok"
End If
Manifest = Manifest & CStr(Job) & vbTab & FinalState & vbCrLf
Next
QPCloseBatchProject QP_SessionProject, False
' This durable marker appears only after every readback and final close passes.
QPWriteUtf8 QP_Fso.BuildPath(QP_Root, "project-commit-" & QP_SessionToken & ".tsv"), Manifest
For Each Job In QP_SessionItems.Keys
Set Item = QP_SessionItems.Item(Job)
FinalState = "no_match"
If Item("final_state") = "restored_ok" Then FinalState = "saved_ok"
QPWriteStatus QP_Root, CStr(Job), FinalState, "project_committed", "Engineering project saved, reopened, readback verified, and closed."
Next
QP_CurrentJobId = OriginalJob
QP_TargetSchematic = OriginalSchematic
QP_TargetSheet = OriginalSheet
QP_SessionCommitActive = False
QP_FailureCleanupActive = False
QP_BatchMode = False
End Sub
Function QPCurrentSemanticState()
Dim Components, Comp, State
Dim Components, Comp, State, Count
QPInvalidatePinIndex
QPInvalidateComponentIndex
Set Components = QP_App.ActiveView.Query(VDM_COMP, VD_ALL)
State = ""
Count = 0
For Each Comp In Components
State = State & QPUntouchedFullState(Comp)
Count = Count + 1
QPProgress "capture_semantic_state", Count, Components.Count
Next
QPCurrentSemanticState = "S" & vbTab & "full_sheet_v1" & vbCrLf & QPSortSnapshotLines(State)
End Function
@@ -1194,14 +1481,18 @@ Sub QPWriteSemanticState(ByRef Command, ByVal SemanticState)
End Sub
Sub QPVerifyExpectedBaselines(ByVal TargetPath)
Dim ErrorNumber, Description
Dim ErrorNumber, Description, ErrorSource
On Error Resume Next
QPCheckExpectedBaselines TargetPath
ErrorNumber = Err.Number
Description = Err.Description
ErrorSource = Err.Source
Err.Clear
On Error GoTo 0
If ErrorNumber <> 0 Then Err.Raise vbObjectError + 879, "QuickPartReplace.Baseline", Description
If ErrorNumber <> 0 Then
If ErrorSource = "QuickPartReplace.SafeStop" Then Err.Raise ErrorNumber, ErrorSource, Description
Err.Raise vbObjectError + 879, "QuickPartReplace.Baseline", Description
End If
End Sub
Sub QPCheckExpectedBaselines(ByVal TargetPath)
@@ -1408,7 +1699,7 @@ Sub QPCaptureAndSelect(ByRef Command, ByVal SnapshotPath)
Dim PartNumber
Dim Snapshot
Dim Index
Dim Selectors, Selector, Uid, ValueAttr, ValueText, MatchedUids, UntouchedCount, NativeRead, AlreadyTargets
Dim Selectors, Selector, SelectorUid, FoundSelectors, Uid, ValueAttr, ValueText, MatchedUids, UntouchedCount, NativeRead, AlreadyTargets
QP_FallbackIdentityUsed = False
Set QP_FallbackIdentityWarnings = CreateObject("Scripting.Dictionary")
@@ -1419,22 +1710,27 @@ Sub QPCaptureAndSelect(ByRef Command, ByVal SnapshotPath)
QPProgress "query_components", 0, 0
Set Matches = CreateObject("Scripting.Dictionary")
Set AlreadyTargets = CreateObject("Scripting.Dictionary")
Set FoundSelectors = CreateObject("Scripting.Dictionary")
QP_Stage = "query_components"
QPLog QP_Root, "INFO", "stage=query_components"
Set Components = QP_App.ActiveView.Query(VDM_COMP, VD_ALL)
' Capture walks the queried collection directly. Build lookup indexes only
' when restoration needs them, from fresh proxies after native mutation.
Set Selectors = QPCommandTargets(Command)
QPBindSheetReferences Components
For Each Comp In Components
Uid = QPComponentIdentityKey(Comp)
SelectorUid=""
If Not Selectors Is Nothing Then SelectorUid=QPCommandTargetKey(Comp,Selectors)
If Selectors Is Nothing Then
PartNumber = QPReadableAttributeValue(Comp, "Part Number")
If StrComp(PartNumber, CStr(Command("old_part_number")), _
vbTextCompare) = 0 Then Matches.Add CStr(Matches.Count), Comp
ElseIf Selectors.Exists(Uid) Then
ElseIf Len(SelectorUid)>0 Then
FoundSelectors(SelectorUid)=True
QPRequireUniqueAttributeNames Comp
PartNumber = QPRequiredAttributeValue(Comp, "Part Number")
Selector = Selectors.Item(Uid)
Selector = Selectors.Item(SelectorUid)
ValueText = ""
Set ValueAttr = QPFindCurrentAttribute(Comp, "Value")
If Not ValueAttr Is Nothing Then ValueText = QPEffectiveAttributeValue(ValueAttr)
@@ -1452,7 +1748,7 @@ Sub QPCaptureAndSelect(ByRef Command, ByVal SnapshotPath)
QPProgress "find_components", Matches.Count, 0
Next
If Not Selectors Is Nothing Then
If Matches.Count + AlreadyTargets.Count <> Selectors.Count Then _
If FoundSelectors.Count <> Selectors.Count Then _
Err.Raise vbObjectError + 873, "QuickPartReplace.Target", "selected component is missing"
If AlreadyTargets.Count > 0 Then
If Matches.Count > 0 Then Err.Raise vbObjectError + 880, "QuickPartReplace.Target", _
@@ -1545,13 +1841,24 @@ Sub QPCaptureAndSelect(ByRef Command, ByVal SnapshotPath)
End Sub
Sub QPRequireNativeCapturedTarget(ByVal State, ByRef Command, ByVal Uid, ByRef Selectors)
Dim Fields, Selector
Dim Fields, Selector, Key, Found
Fields = Split(QPUntouchedIdentity(State, True), vbTab)
If QPDecode(Fields(1)) <> Uid Or StrComp(QPDecode(Fields(3)), _
CStr(Command("old_part_number")), vbTextCompare) <> 0 Then _
Err.Raise vbObjectError + 873, "QuickPartReplace.Target", "selected component changed during native capture"
If Not Selectors Is Nothing Then
Selector = Selectors(Uid)
Found=False
For Each Key In Selectors.Keys
Selector=Selectors(Key)
If StrComp(QPDecode(Fields(2)),CStr(Selector(0)),vbTextCompare)=0 Then
If Found Then Err.Raise vbObjectError+873,"QuickPartReplace.Target","ambiguous physical selector"
Found=True
If QPDecode(Fields(4))<>CStr(Selector(1)) Then Err.Raise vbObjectError+873, _
"QuickPartReplace.Target","selected unit Value changed during capture"
End If
Next
If Not Found Then Err.Raise vbObjectError+873,"QuickPartReplace.Target","foreign selected unit reference"
Exit Sub
If QPDecode(Fields(2)) <> CStr(Selector(0)) Or QPDecode(Fields(4)) <> CStr(Selector(1)) Then _
Err.Raise vbObjectError + 873, "QuickPartReplace.Target", "selected component changed during native capture"
End If
@@ -1573,6 +1880,19 @@ Function QPUseNativeSnapshot()
QPUseNativeSnapshot = True
End Function
Function QPCommandTargetKey(ByRef Comp, ByRef Selectors)
Dim Key, Value, Found
Found=""
For Each Key In Selectors.Keys
Value=Selectors(Key)
If StrComp(Trim(CStr(Comp.Refdes)),Trim(CStr(Value(0))),vbTextCompare)=0 Then
If Len(Found)>0 Then Err.Raise vbObjectError+873,"QuickPartReplace.Target","duplicate physical target reference"
Found=CStr(Key)
End If
Next
QPCommandTargetKey=Found
End Function
Function QPReadableAttributeValue(ByRef Comp, ByVal Name)
Dim Attr, ErrorNumber, ErrorSource, ErrorDescription
On Error Resume Next
@@ -1743,7 +2063,7 @@ Sub QPVerifyUntouched(ByRef Records)
End Sub
Function QPCommandTargets(ByRef Command)
Dim Scope, Text, Entries, Entry, Fields, Result, Index
Dim Scope, Text, Entries, Entry, Fields, Result, Index, AliasKey
Set QPCommandTargets = Nothing
If Not Command.Exists("target_scope") Then Exit Function
Scope = CStr(Command("target_scope"))
@@ -1767,6 +2087,11 @@ Function QPCommandTargets(ByRef Command)
If Result.Exists(CStr(Fields(0))) Then Err.Raise vbObjectError + 873, _
"QuickPartReplace.Target", "duplicate target UID"
Result.Add CStr(Fields(0)), Array(CStr(Fields(1)), CStr(Fields(2)))
If Command.Exists("schematic_name") And Command.Exists("sheet_number") Then
If Not IsObject(QP_ReferenceAliases) Then Set QP_ReferenceAliases=CreateObject("Scripting.Dictionary")
AliasKey=LCase(Command("schematic_name") & ":" & Command("sheet_number") & "|" & Trim(Fields(1)))
QP_ReferenceAliases(AliasKey)=CStr(Fields(0))
End If
Next
Set QPCommandTargets = Result
End Function
@@ -3363,7 +3688,7 @@ Function QPReadProjectRuleStates(ByRef Lines, ByRef Keys, ByVal StatusPath)
End Function
Function QPIsNextRuleState(ByVal State)
QPIsNextRuleState = (Len(CStr(State)) = 0)
QPIsNextRuleState = (Len(CStr(State)) = 0 Or CStr(State) = "pending")
End Function
Function QPJobSnapshotPath(ByVal JobId)
@@ -3467,6 +3792,7 @@ Function QPReadSnapshot(ByVal Path)
Record.Add "orientation", QPDecode(Fields(5))
Record.Add "scale", QPDecode(Fields(6))
Record.Add "connections", QPDecode(Fields(7))
If Result.Exists("meta") Then QPBindSnapshotReference Meta("sheet_name"),Record
Components.Add CStr(Components.Count), Record
Case "A"
If UBound(Fields) <> 11 Then Err.Raise vbObjectError + 814, _
@@ -3490,6 +3816,11 @@ Function QPReadSnapshot(ByVal Path)
If Untouched.Exists(QPDecode(Fields(1))) Then Err.Raise vbObjectError + 874, _
"QuickPartReplace.Target", "duplicate unselected component UID"
Untouched.Add QPDecode(Fields(1)), Replace(Lines(Index), vbCr, "")
If Result.Exists("meta") And Len(Trim(QPDecode(Fields(2))))>0 Then
If Not IsObject(QP_ReferenceAliases) Then Set QP_ReferenceAliases=CreateObject("Scripting.Dictionary")
If Not QP_ReferenceAliases.Exists(LCase(Meta("sheet_name") & "|" & Trim(QPDecode(Fields(2))))) Then _
QP_ReferenceAliases.Add LCase(Meta("sheet_name") & "|" & Trim(QPDecode(Fields(2)))),QPDecode(Fields(1))
End If
Case "X"
If UBound(Fields) <> 1 Or Fields(1) <> "untouched_full_v1" Then _
Err.Raise vbObjectError + 874, "QuickPartReplace.Target", "invalid unselected-state protocol"
@@ -3498,6 +3829,7 @@ Function QPReadSnapshot(ByVal Path)
If UBound(Fields) <> 2 Or Len(QPDecode(Fields(1))) = 0 Or Len(QPDecode(Fields(2))) = 0 Then _
Err.Raise vbObjectError + 874, "QuickPartReplace.Target", "invalid unselected full-state snapshot"
UntouchedFull.Add QPDecode(Fields(1)), QPDecode(Fields(2))
If Result.Exists("meta") Then QPBindSnapshotFullState Meta("sheet_name"),QPDecode(Fields(2))
End Select
End If
Next