Reuse accepted chapter checkpoints with batched session position verification
This commit is contained in:
parent
3004540d94
commit
a3353c069d
@ -0,0 +1,31 @@
|
||||
# Reopening handshake: investigation checkpoint before implementation
|
||||
|
||||
Baseline: clean fast-forward to `3004540`, including the actual .30 Windows qualification. No application code had been changed when these findings were written. Development inspection was read-only. The effective `dbo.BookChapterSync` definition matches migration 248 exactly (allowing SQL Server's CREATE declaration spelling).
|
||||
|
||||
## Explicit findings A–F
|
||||
|
||||
**A — Manifest.** `NativeChapterSyncController.Manifest` → `ChapterSyncService.Manifest` loads the accepted paragraph snapshot and exact-session live validation rows. `ChapterCheckpointEngine.Build` computes current source hashes; `ChapterManifestItem` returns canonical chapter ID, native heading ID, content/identity hashes, paragraph count, physical/canonical start/end, title and a state. Array order is canonical order, but there is no explicit order, algorithm, per-checkpoint accepted revision, mapping hash, geometry hash or durable-valid flag. Manifest.Revision is the current whole-snapshot revision. State=Synchronised specifically means a matching *current-session* validation, not simply a valid durable checkpoint. Structural geometry exists in durable PositionHash, but is absent from the HTTP manifest. Consequently the manifest is close to sufficient but cannot safely authorise the proposed reuse decision as written.
|
||||
|
||||
**B — Fingerprints.** `ChapterFingerprint.Content` hashes exact ordered paragraph UTF-16 code units with version, paragraph count and per-paragraph length prefixes. There is no normalisation; CR, LF, heading text, composition, isolated surrogates and splitting/merging are preserved. `Identity` separately hashes ordered native IDs, text lengths and outline levels. Absolute positions, formatting and XML bytes are not content hashes. `ChapterWordPositions.Hash` binds measured relative native spans/picture-anchor geometry separately. MappingHash binds canonical paragraph/chapter/scene/verification/story assignments. Stored and current v1 hashes are directly comparable: the .30 reader and server use the same implementation. All 48 Windows observations were accepted with no reported repaired chapter; acceptance requires matching content/identity or explicit authorised reconciliation. The handover does not provide raw per-chapter match counters; adding them will make that distinction explicit rather than inferring it from accepted counts.
|
||||
|
||||
**C — Match branch.** `TrayCoordinator.ProcessChapter` computes the content hash but uses the manifest only to identify a chapter by native heading ID (or authorised legacy adoption). It unconditionally calls ValidateChapter. There is no local content/identity/geometry match → reuse branch. The native-position walk has already happened before this call. Only manifest entries carrying current-session Synchronised state bypass it via work.Checked.
|
||||
|
||||
**D — 48 requests.** Each first POST /chapter-sync/validate carries session/instance/manuscript identity, Word/base revisions, request/operation IDs, chapter start/end, next native heading ID, content/identity/optional geometry hashes and ordered native paragraph metadata (ID, length, outline, optional native span/anchors). It contains no paragraph prose or canonical mappings. Only a Changed + AllowText response causes a second request with this chapter's text and Reconcile=true. Thus submitted, verified and reconciled are different operations.
|
||||
|
||||
**E — Server work and measured cost.** Accept checks access/status/protected work and the authenticated saved live lease, loads/deserialises the full snapshot, builds all chapter hashes, runs the unchanged validator (which builds them again), and calls BookChapterSync accept. The procedure locks the full snapshot, parses/materialises all accepted paragraphs, checks identities/positions/conflicts, replaces checkpoint JSON, updates the full payload and writes live positions. It then returns the entire payload for deserialisation; the service rereads live rows for progress. This is not paragraph reconciliation on an unchanged match, but it repeats expensive full-snapshot work 48 times, serially: AdvanceChapter follows the awaited response. There is no background server acceptance queue in this path. Correlated actual Windows-session journal events: 48 validations total **19,543 ms** through application validation; 48 persisted events total **195,388 ms** through persistence. Their difference, **175,845 ms**, is elapsed persistence stage time, including SQL/lock/I/O/network/deserialisation rather than pure SQL CPU. Client-reported validation intervals total 198,778.3 ms, so most of that interval is corroborated by server-side elapsed events. Word reported 241,181.3 ms end-to-end. Do not attribute all elapsed time to CPU.
|
||||
|
||||
**F — Correctness.** New-session live position evidence is necessary: old offsets, filenames, saved timestamps and document associations cannot prove current contents, copy identity or positions. It must remain scoped to the current authenticated grant, session, saved Word revision and accepted source revision, with unique native IDs, exact text partition and measured geometry. Forty-eight independent requests, repeated checkpoint replacement and repeated snapshot parsing are implementation artefacts, not security requirements. A bounded proof batch can register fresh positions while preserving the durable checkpoint and the existing position consumers.
|
||||
|
||||
## Context and actual execution sequence
|
||||
|
||||
WordAdapter.Open restores saved GUID/book/server properties and creates a fresh LocalDocument session. Selection frames report the live cursor and saved state through SessionManager and TrayCoordinator. Heartbeat posts authenticated presence; NativePresenceController queries existing paragraph/chapter position stores and sends canonical chapter/scene titles. ObserveChapterPresence loads the manifest, prioritises the current chapter, and queues chapter-check through the local pipe. WordChapterRead uses the qualified .30 live-text or structural XML/native-position reader. Frames are decoded off the STA, hashes calculated, and ProcessChapter currently submits every proof. Successful acceptance populates work.Checked, clears LastPresenceKey and advances; Finish independently confirms whole-book readiness. Durable checkpoint JSON is in BookParagraphManuscripts.Payload.ChapterCheckpoints; current-session position evidence is in BookChapterValidations. Context, Intent and navigation consume those scoped positions, not the legacy local boundary list.
|
||||
|
||||
The Windows server journal records the cursor at **0**, with no chapter or scene; no later cursor transition is recorded in that interval. A verified manuscript does not invent a scene for front matter outside mapped scene ranges. SessionManager.Resolve reports awaiting-structure from the separate legacy in-memory boundary list, which the chapter path does not populate. Context=-1 is therefore an unobserved resolved scene, not evidence that 48 accepted chapters were unavailable everywhere. Qualification must observe a cursor actually within a mapped scene. No safe fix is to assign the first scene to cursor zero.
|
||||
|
||||
## Smallest safe correction to implement
|
||||
|
||||
Add optional manifest reuse metadata and a bounded metadata-only /reuse endpoint. Locally compare content, identity, algorithm, next-heading and native geometry against valid durable checkpoints. Aggregate matching proofs and register fresh session positions in one set-based stored-procedure transaction without rewriting the source payload. Flush the first current chapter separately for prompt Context, then remaining matches together; normal unchanged 48-chapter expectation is two reuse requests, zero individual acceptance/reconciliation requests. Missing/invalid/incompatible checkpoints and changed content/identity/geometry retain the existing validation/reconciliation path. Old agents/servers retain existing behaviour through an optional manifest capability.
|
||||
|
||||
Reuse the existing validator with one per-request source index so canonical mapping, native identity and geometry checks remain identical. SQL must independently enforce owner access, protected-work guards, source revision/digest/CAS, current checkpoint hashes, canonical membership, contiguous/nonoverlapping ranges, same-revision conflict rejection and idempotent resume. No durable checkpoint mutation, hash-format migration or new canonical mapping model is needed. Stale source or Word state must reject a batch safely. The existing picture reader and position digest remain authoritative for structural changes without text changes.
|
||||
|
||||
Instrumentation will distinguish calculated/matching/mismatching/missing/incompatible, pending versus committed reuse, individual submissions, actual reconciliations, request bytes, agent processing versus round-trip wait, server validation/persistence stages and first verified mapped cursor. Synthetic request/timing tests cannot certify Word COM performance.
|
||||
@ -0,0 +1,86 @@
|
||||
# Candidate 1.0.0.31 — checkpoint reuse handshake
|
||||
|
||||
Use the existing `codex/word-companion-native-phase1-20261104` branch, fetch and fast-forward only; preserve .30 and the author's saved document. Do not install or operate Word unattended. This handover describes a specific candidate, not a request to repeat whole-manuscript repair or import qualification.
|
||||
|
||||
## Finding and decision
|
||||
|
||||
Read [the investigation checkpoint](../2026-11-11-reopening-handshake-findings.md) for the complete A–F answers, request contracts, execution trace and source/persistence distinction. The [actual .30 Windows evidence](2026-11-11-v1.0.0.30-windows-qualification.md) remains authoritative for real Word performance: 241.181 s, 47 live-text/1 XML, 48 individual metadata proofs, Context unobserved at cursor zero.
|
||||
|
||||
The .30 local reader worked. The remaining bottleneck was the unconditional individual `/validate` branch after hashing: it re-established positions but also reloaded/rehash-validated the full manuscript and rewrote source checkpoint JSON 48 times. These were not 48 prose uploads. Only a changed, authorised chapter enters paragraph reconciliation. Correlated actual-session server logs sum to 19,543 ms through application validation and 195,388 ms through persistence; their difference is 175,845 ms of elapsed persistence-stage work, not proven SQL CPU. Client round-trip intervals totalled 198,778.3 ms. There is no chapter acceptance background queue in this path.
|
||||
|
||||
Durable checkpoint reuse still needs current-session identity, saved state, exact current text/paragraph partition and native position evidence. Filename, association, timestamp, source revision or text hash alone cannot establish current offsets. Forty-eight separate HTTP acknowledgements and source checkpoint rewrites are not required to establish that evidence.
|
||||
|
||||
## Corrected sequence
|
||||
|
||||
1. Restore the same authenticated book association and get one manifest. Optional `checkpointReuseSupported` and per-entry durable metadata distinguish source acceptance from current-session acceptance.
|
||||
2. Keep the qualified .30 reader and bounded scheduler. Each chapter still measures current native IDs, contiguous positions, outline and exact text; structural chapters retain the .28 XML/native-anchor path. No whole-file cache or new fingerprint format is introduced.
|
||||
3. Compare exact v1 content and identity hashes, algorithm, native boundary identity and geometry digest against a valid durable checkpoint. Missing/invalid/incompatible entries and differences enter the existing `/validate` path; changed prose is still sent only under existing OnSave/explicit repair authority.
|
||||
4. For a matching checkpoint, accumulate only the existing metadata proofs. `/reuse` validates them against one current source index and commits current-session positions set-wise, without updating the source manuscript or any checkpoint JSON. It does not adopt IDs, reconcile prose, mint canonical GUIDs or change revision semantics.
|
||||
5. Flush the chapter containing the current cursor first, for early Context. Batch the remaining matches at completion (or at conservative size/count limits). An unchanged mapped-cursor 48-chapter manuscript normally uses **two reuse POSTs, zero individual `/validate` calls and zero reconciliations**. Including GET manifest and POST finish, that is **four chapter-protocol HTTP requests**, versus fifty on the old path. If the cursor is outside every recognised chapter, there is no early mapped chapter to flush; one final reuse batch is sufficient. No scene is invented for front matter.
|
||||
6. Only server-acknowledged positions populate the accepted count; locally verified but uncommitted proofs remain pending. Finish independently checks the current persisted manifest before Up to date. Reconnection reloads current-session live rows; committed work survives and interrupted pending work is safely reverified.
|
||||
|
||||
With one changed chapter, the fixture uses two reuse POSTs for the 47 unchanged chapters and two existing `/validate` POSTs for the changed chapter (metadata detection, then authorised prose). Exactly one reconciliation occurs. Several edited chapters behave the same way per affected chapter. Missing checkpoints and geometry mismatches each require detailed acceptance, not automatic prose reconciliation.
|
||||
|
||||
## Contracts, files and safeguards
|
||||
|
||||
- `Protocol/Manuscript/ChapterFingerprint.cs`: optional manifest fields `checkpointReuseSupported`, `durableAccepted`, `algorithm`, `order`, `acceptedRevision`, `mappingHash`, `positionHash`, `nextHeadingId`. Existing ID/hash/count/order-array/state/revision fields retain their meanings. Current-session `state=Synchronised` is not confused with `durableAccepted=true`. Reuse request is `{chapters: [ChapterObservation...]}` with no paragraph Text; reply contains accepted chapter IDs, current revision and measured read/processing/validation/persistence intervals.
|
||||
- `Agent/TrayCoordinator.Chapters.cs`, `TrayCoordinator.Reuse.cs`, `CloudGateway.cs`: actual match decision, bounded pending proofs, current-chapter-first flush, exact acknowledgement checks, stale/conflict refresh and separate diagnostic counters. Older server manifests do not enable reuse; old clients ignore the new fields and retain `/validate`. No pipe protocol or ribbon layout change is needed.
|
||||
- `NativeChapterSyncController`, `ChapterSyncService`, `ChapterCheckpointEngine`, `ChapterSyncRepository`: optional 4 MiB `/reuse` route, up to 256 unique chapters/100,000 paragraphs server-side; client flushes at 64 chapters/20,000 paragraphs. Reuse requires an authenticated, available, saved current grant/session/Word revision, owner authority, coherent source revision, valid durable content/identity/mapping/boundary/geometry evidence and no native-ID adoption. One source index is reused within the request; validated checkpoint proposals are cloned so the source/index is not mutated.
|
||||
- Forward migrations **251–252** add/harden only `dbo.BookChapterReuse`; existing migration files and `dbo.BookChapterSync` remain unchanged. The procedure locks/checks source revision/manuscript/snapshot digest, guards import/analysis and owner access, parses source indices once, rejects incomplete/cross-chapter/unknown/duplicate/noncontiguous/overlapping/conflicting same-revision position evidence, supports idempotent replay, and updates only BookChapterValidations. Migration 252 explicitly rejects extra cross-chapter rows before retaining the original JSON. Both were backed up, verified, dry-run under rollback and applied only to Development. Application rollback remains compatible.
|
||||
- The .28 measured picture-anchor digest remains the structural mechanism. Moving an anchor or changing its measured native span/relative offset/native shape identity cannot pass a matching position hash. Image/layout changes that do not change exact prose, paragraph identity/outline or native evidence positions do not require canonical prose reconciliation. Unsupported structure still fails the qualified reader. No image-pixel hash, generic formatting hash or manuscript-specific rule is introduced.
|
||||
- Version metadata is .31 in DeveloperVersion.props, VSTO AssemblyInfo and MSI release metadata, with a new ProductCode and unchanged upgrade family/qualified baseline pins. This includes the static VSTO version correction discovered during .30 Windows packaging.
|
||||
|
||||
Stale manifests or server-side edits reject reuse rather than silently trust it. The retry clears uncommitted proofs and reloads authoritative current-session rows. Word revision/account/book changes or cancellation discard pending work and late replies. Committed rows remain scoped to the exact live session/revision and accepted source hashes. Existing Context/Intent/scene-start position queries consume the same table and canonical mappings.
|
||||
|
||||
## Diagnostics
|
||||
|
||||
Troubleshooting distinguishes manifest/valid checkpoint counts; calculated/matching/mismatching/missing/incompatible proofs; live/XML reads; individual submissions; acknowledged reuse; pending proofs; acknowledged reconciliations; total chapter-protocol requests; serialized UTF-8 JSON request-body bytes; local verification, round-trip and server stage times. Request bytes exclude HTTP headers/TLS and manifest response bytes. Negative Context timing remains an unobserved scene. After an interrupted acknowledgement, the reloaded accepted count can exceed the number of reuse acknowledgements observed by this process; do not treat counters as an immutable historical audit.
|
||||
|
||||
Server logs separately identify actual persisted reconciliations, even if the reply is interrupted. Server reuse replies separate awaited access/snapshot read elapsed time, synchronous validation/index work and persistence elapsed time. These are wall-clock stages; lock/network/scheduling wait is included where applicable and is not a measurement of SQL CPU. Existing .30 COM read/batch timings remain available. The first Context time denotes the first resolved canonical scene, not browser paint. Cursor zero in the actual .30 report had no mapped scene; `awaiting-structure` referred to the legacy local boundary list and cannot justify assigning the first scene to front matter.
|
||||
|
||||
## Automated evidence
|
||||
|
||||
Tests are isolated. The native HTTP-contract fixture uses 48 chapters/about 153k words with an in-memory HTTP handler: unchanged 2 reuse/0 acceptance/0 reconciliation; one edit 2 reuse/2 acceptance/1 reconciliation; three edits 2 reuse/6 acceptance/3 reconciliations. Separate missing-checkpoint and geometry-mismatch cases each perform one detailed metadata acceptance and no prose reconciliation. Each observes first-chapter Context before the remaining 47 acknowledgements. These are protocol assertions, not real Word execution or real network latency.
|
||||
|
||||
The Development SQL fixture uses 48 chapters/8,457 paragraphs/151,506 words. It executes the real services, repositories and stored procedures against a newly provisioned synthetic book, never Discovery. The final guarded run measured:
|
||||
|
||||
| Measurement | Existing individual path | Reuse path |
|
||||
| --- | ---: | ---: |
|
||||
| Manifest | 387.7 ms | 330.4 ms |
|
||||
| Proof calculation/comparison | 202.1 ms | 0.3 ms comparison of already calculated proofs |
|
||||
| Individual validation calls | 48 | 0 |
|
||||
| Reuse requests | 0 | 2 |
|
||||
| Actual reconciliation | 0 | 0 |
|
||||
| Proof JSON bytes | 791,098 | 791,174 |
|
||||
| Validation round trips | 188,139.3 ms | Included below |
|
||||
| Server source/access read elapsed | Not separately instrumented | 556.1 ms |
|
||||
| Server synchronous processing | Not separately instrumented | 154.7 ms |
|
||||
| Server persistence elapsed | Not separately instrumented | 944.2 ms |
|
||||
| First mapped chapter Context | Not separately timed | 1,154.3 ms |
|
||||
| Synthetic wall time | 188,753.0 ms through all acceptances, finish excluded | 2,813.7 ms including finish |
|
||||
|
||||
The corrected timing starts after the prepared proof array, while baseline includes constructing it; therefore these totals are not perfectly stage-symmetric. The 202 ms proof preparation difference cannot explain the approximately 186-second persistence/request improvement. Proof bytes barely change: the optimisation is fewer serial acceptances and no source rewrites, not omission of identity/position evidence. No COM/UI/network latency is simulated. The actual .30 Word 241.181-second result remains separate; .31 Word timings are pending.
|
||||
|
||||
The SQL fixture also verifies exact typed source/checkpoint serialization remains unchanged; all 48 current-session rows exist; current-scene lookup after the first reuse; completion; idempotent resume; stale source, unsaved state, foreign grant, wrong session, content and geometry mismatch refusal; conflicting same-revision ranges; and independent Save As/new-session positions. A direct repository forgery verifies SQL rejects an extra cross-chapter row without partial writes. Existing chapter regressions retain rename/insertion/deletion/reordering/split/merge, picture/native geometry and canonical GUID/scene preservation tests. Real Word versions of these cases are not certified by portable fixtures.
|
||||
|
||||
Final test/deployment identities and results are appended below.
|
||||
|
||||
## Focused Windows acceptance
|
||||
|
||||
A candidate is ready only after the Development deployment and final source identity below are recorded. Use the existing signed .31 build/package/upgrade gates, retain .30, and coordinate normal installation separately. No new trust store, installer redesign or automatic Word operation is authorised.
|
||||
|
||||
1. Open a previously synchronised saved Development test manuscript. Observe a cursor within a known mapped scene (front matter at zero need not resolve). Confirm Context promptly resolves that same scene, then Up to date. Record native .30-style timings plus match/reuse/request/reconciliation/byte/server-stage counters. For 48 valid unchanged checkpoints, expect 48 matches, zero individual acceptance/reconciliation calls and normally two reuse requests; structural XML reads may still be one. Do not request full repair.
|
||||
2. In an authorised disposable copy only, edit one chapter, save and reopen. Confirm 47 unchanged checkpoints are reused and exactly the edited chapter reconciles under the existing mode/authorisation. Check Context in that chapter and a later chapter with shifted native positions.
|
||||
3. Check the existing final-chapter floating anchor and Context after it using the retained qualified position reader; no source/scene/GUID reset or full-manuscript cycle is needed. If a refusal occurs, retain the specific diagnostics and stop mutation of author data.
|
||||
4. Record exact signed source/package identities and real measurements. Do not claim the service/SQL fixture's ~seconds timing proves Word performance. No Production work is authorised.
|
||||
|
||||
## Final Atlas gates before deployment
|
||||
|
||||
- Solution build: passed, zero warnings/errors, final bounded build 39.92 s. Native .31 agent targets and protocol/client libraries compile; Office/VSTO binding remains Windows work.
|
||||
- Application executable harness: **457 PASS**; full native foundation: **273 PASS**; focused chapter/structural engine: **66 PASS**; focused native/reopening/handshake: **239 PASS**. The focused suites were repeated after the final local concurrency guard and delayed-acknowledgement test.
|
||||
- Guarded real Development SQL scale/reuse suite: **121 PASS** with the final migration 252. Its synthetic project **8199** is archived for evidence. Earlier interrupted/fixture-correction projects 8197–8198 are also synthetic and archived. None is an author manuscript.
|
||||
- The delayed final reuse acknowledgement is explicitly tested after document close: it cannot restore a closed document or submit whole-manuscript completion.
|
||||
- Backups: `/var/opt/mssql/backup/chapter-reuse-251-20261111T204859Z.bak` and `/var/opt/mssql/backup/chapter-reuse-252-20261111T210157Z.bak`. Both passed SQL checksum verification before their respective migrations; both migrations passed a rolled-back dry run. No restore/reset occurred. The application principal could create the first backup but lacked RESTORE VERIFYONLY permission; an administrator verified it separately before applying SQL.
|
||||
- Before-change read-only Discovery audit: revision **2**, **48 Synchronised durable checkpoints**, payload length **6,524,805** UTF-16 units, SQL SHA-256 **34C8BB6B70100719103A6F469EA5B6A7FDFB14AC25C3271CDB06329E021EC7CB**. A post-deployment comparison is recorded below. The configured database was independently verified as PlotDirector_Development.
|
||||
|
||||
Development deployment, authenticated HTTP smoke results and exact pushed implementation identity follow after verification. No Windows installation or Production operation is part of Atlas's work.
|
||||
@ -128,6 +128,7 @@ public sealed partial class CloudGateway : IDisposable
|
||||
public Task<PlotDirector.Companion.Protocol.Manuscript.ChapterRepairRequested> RequestChapterRepair(int book,PlotDirector.Companion.Protocol.Manuscript.ChapterFinish selected,Guid context)=>Send<PlotDirector.Companion.Protocol.Manuscript.ChapterRepairRequested>(HttpMethod.Post,$"api/native-companion/books/{book}/chapter-sync/repair",selected,context);
|
||||
public Task<PlotDirector.Companion.Protocol.Manuscript.ChapterSyncProgress> FinishChapters(int book,PlotDirector.Companion.Protocol.Manuscript.ChapterFinish completion,Guid context)=>Send<PlotDirector.Companion.Protocol.Manuscript.ChapterSyncProgress>(HttpMethod.Post,$"api/native-companion/books/{book}/chapter-sync/finish",completion,context);
|
||||
public Task<PlotDirector.Companion.Protocol.Manuscript.ChapterManifest> ChapterManifest(int book,Guid session,long revision,Guid context)=>Send<PlotDirector.Companion.Protocol.Manuscript.ChapterManifest>(HttpMethod.Get,$"api/native-companion/books/{book}/chapter-sync?session={session}&wordRevision={revision}",null,context);
|
||||
public Task<PlotDirector.Companion.Protocol.Manuscript.ChapterReuseReply> ReuseChapters(int book,PlotDirector.Companion.Protocol.Manuscript.ChapterReuseRequest proof,Guid context)=>Send<PlotDirector.Companion.Protocol.Manuscript.ChapterReuseReply>(HttpMethod.Post,$"api/native-companion/books/{book}/chapter-sync/reuse",proof,context);
|
||||
public Task<PlotDirector.Companion.Protocol.Manuscript.ChapterSyncReply> ValidateChapter(int book,PlotDirector.Companion.Protocol.Manuscript.ChapterObservation proof,Guid context)=>Send<PlotDirector.Companion.Protocol.Manuscript.ChapterSyncReply>(HttpMethod.Post,$"api/native-companion/books/{book}/chapter-sync/validate",proof,context);
|
||||
public async Task FailCapture(Guid id,Guid context){try{await Send<NativePresence>(HttpMethod.Delete,"api/native-companion/manuscript-capture/"+id,null,context);}catch(Exception e)when(e is HttpRequestException or IOException or InvalidDataException or InvalidOperationException or OperationCanceledException or JsonException or ObjectDisposedException){}}
|
||||
public async Task<NativePresence> Capture(ManuscriptCapture capture,Guid context){var result=await Send<NativePresence>(HttpMethod.Post,"api/native-companion/manuscript-capture",capture,context);if(result.CaptureRequestId!=capture.RequestId||result.Revision!=capture.Revision)throw new InvalidDataException("Server did not acknowledge this manuscript capture. Update or reconnect before retrying.");return result;}
|
||||
@ -153,6 +154,7 @@ public sealed partial class CloudGateway : IDisposable
|
||||
try
|
||||
{
|
||||
using var response=await http.SendAsync(request,HttpCompletionOption.ResponseHeadersRead,stop.Token);
|
||||
if(response.StatusCode==HttpStatusCode.Conflict&&path.EndsWith("/chapter-sync/reuse",StringComparison.Ordinal))throw new ChapterReuseConflictException();
|
||||
if(response.StatusCode==HttpStatusCode.Unauthorized){InvalidateAccess(context);throw new InvalidOperationException("Connection needs renewal. Retry after Companion reconnects automatically.");}
|
||||
if(!response.IsSuccessStatusCode&&path=="api/native-companion/manuscript-capture"){
|
||||
var failure=await ReadCaptureFailure(response,stop.Token);
|
||||
@ -203,3 +205,5 @@ public sealed class CaptureUploadException(string code,string message,bool retry
|
||||
public string Code {get;}=code;
|
||||
public bool Retryable {get;}=retryable;
|
||||
}
|
||||
|
||||
public sealed class ChapterReuseConflictException():InvalidOperationException("Checkpoint changed; refresh the accepted manifest before reusing positions.");
|
||||
|
||||
@ -7,7 +7,9 @@ public sealed partial class TrayCoordinator
|
||||
private sealed class ChapterWork
|
||||
{
|
||||
public readonly System.Diagnostics.Stopwatch Elapsed=System.Diagnostics.Stopwatch.StartNew();
|
||||
public double RecognitionMs,ManifestMs,VerificationMs,ServerMs,ContextMs=-1,CompleteMs=-1;public int LiveReads,XmlReads,Submissions;
|
||||
public double RecognitionMs,ManifestMs,VerificationMs,ServerMs,ContextMs=-1,CompleteMs=-1;public int LiveReads,XmlReads,Submissions,Calculated,Matching,Mismatching,Missing,Incompatible,Reused,Reconciled,ReuseRequests,Requests;public long RequestBytes;
|
||||
public double ReuseReadMs,ReuseProcessingMs,ReuseValidationMs,ReusePersistenceMs;public bool ReuseFinishing;
|
||||
public readonly Dictionary<int,ChapterObservation> PendingReuse=[];
|
||||
public int Book, Attempts, Retries; public string ReviewReason = "";public Guid Manuscript;public long Revision;public Guid Context,Operation,Command;public bool Busy,Supported,Processing,Begun;public long FailedRevision=-1;public DateTime Started,RetryAfter;
|
||||
public ChapterManifest? Manifest; public ChapterSyncProgress? Completion;public readonly Dictionary<int,(int Start,int End)> Checked=[];
|
||||
public StringBuilder Text=new(),Xml=new(),Identities=new();public int Start,End,DocumentEnd,CursorWhenQueued,FirstStart=-1;public bool Finished;public bool Wrapped;public bool NativeTextVerified;public string IdentityAction="";public readonly HashSet<int> Reviewed=[];public readonly HashSet<int> Visited=[];public string Next="";
|
||||
@ -44,7 +46,7 @@ public sealed partial class TrayCoordinator
|
||||
lock(gate)
|
||||
{
|
||||
if(!chapterWork.TryGetValue(session,out var w))return "Chapter timings: awaiting recognised saved document.";
|
||||
return $"Chapter timings since document registration (ms): recognition={w.RecognitionMs:F1}, manifest={w.ManifestMs:F1}, fingerprints={w.VerificationMs:F1}, server={w.ServerMs:F1}, Context={w.ContextMs:F1}, complete={w.CompleteMs:F1}. Reads live/XML={w.LiveReads}/{w.XmlReads}, submissions={w.Submissions}. Negative timing means not observed.";
|
||||
return $"Chapter timings since document registration (ms): recognition={w.RecognitionMs:F1}, manifest={w.ManifestMs:F1}, fingerprints={w.VerificationMs:F1}, server={w.ServerMs:F1}, Context={w.ContextMs:F1}, complete={w.CompleteMs:F1}. Reads live/XML={w.LiveReads}/{w.XmlReads}, submissions={w.Submissions}. manifest/valid={w.Manifest?.Chapters.Length??0}/{w.Manifest?.Chapters.Count(c=>c.DurableAccepted)??0}; calculated/match/mismatch/missing/incompatible={w.Calculated}/{w.Matching}/{w.Mismatching}/{w.Missing}/{w.Incompatible}; reused={w.Reused}, pending={w.PendingReuse.Count}, reconciled={w.Reconciled}, reuseRequests={w.ReuseRequests}, requests={w.Requests}, bytes={w.RequestBytes}, reuse server read/process/validation/persistence ms={w.ReuseReadMs:F1}/{w.ReuseProcessingMs:F1}/{w.ReuseValidationMs:F1}/{w.ReusePersistenceMs:F1}. Negative timing means not observed.";
|
||||
}
|
||||
}
|
||||
|
||||
@ -69,6 +71,7 @@ public sealed partial class TrayCoordinator
|
||||
work.Busy = false;
|
||||
work.Processing = false;
|
||||
work.Command = Guid.Empty;
|
||||
work.PendingReuse.Clear();work.Checked.Clear();work.Reviewed.Clear();work.Visited.Clear();work.ReuseFinishing=false;work.Wrapped=false;work.FirstStart=-1;work.Attempts=0;
|
||||
work.Finished = false;
|
||||
work.Manifest = null;
|
||||
work.RetryAfter = DateTime.UtcNow.AddSeconds(15);
|
||||
@ -86,11 +89,11 @@ public sealed partial class TrayCoordinator
|
||||
finally{lock(gate)ribbonRequests.Remove(session);}
|
||||
}
|
||||
private bool IsChapterCommand(TrayDocument doc,Guid id)=>chapterWork.TryGetValue(doc.Session,out var work)&&id!=Guid.Empty&&work.Command==id;
|
||||
private void CancelChapterWork(TrayDocument doc){if(chapterWork.TryGetValue(doc.Session,out var work)){work.Command=Guid.Empty;work.Operation=Guid.Empty;work.Text=new();work.Xml=new();work.Identities=new();doc.ChapterProgress=null;work.Busy=false;work.FailedRevision=doc.Revision;}}
|
||||
private void CancelChapterWork(TrayDocument doc){if(chapterWork.TryGetValue(doc.Session,out var work)){work.Command=Guid.Empty;work.Operation=Guid.Empty;work.PendingReuse.Clear();work.ReuseFinishing=false;work.Text=new();work.Xml=new();work.Identities=new();doc.ChapterProgress=null;work.Busy=false;work.FailedRevision=doc.Revision;}}
|
||||
private void BeginChapterRepair(TrayDocument doc,Guid operation)
|
||||
{
|
||||
if(!ChapterCapable(doc.Instance))return;
|
||||
var work=GetChapterWork(doc);work.Completion=null;work.Operation=operation;work.FailedRevision=-1;work.Attempts=0;work.Retries=0;work.ReviewReason="";work.Manifest=null;work.Checked.Clear();work.Reviewed.Clear();work.Visited.Clear();work.Wrapped=false;work.FirstStart=-1;work.Finished=false;work.Command=Guid.Empty;work.Busy=false;
|
||||
var work=GetChapterWork(doc);work.Completion=null;work.Operation=operation;work.FailedRevision=-1;work.Attempts=0;work.Retries=0;work.ReviewReason="";work.Manifest=null;work.PendingReuse.Clear();work.ReuseFinishing=false;work.Checked.Clear();work.Reviewed.Clear();work.Visited.Clear();work.Wrapped=false;work.FirstStart=-1;work.Finished=false;work.Command=Guid.Empty;work.Busy=false;
|
||||
doc.Status="Repairing existing chapter mappings; accepted scenes and author decisions are retained.";work.Busy=true;work.Started=DateTime.UtcNow;_ = LoadChapterManifest(doc,work);
|
||||
}
|
||||
private ChapterWork GetChapterWork(TrayDocument doc)
|
||||
@ -101,19 +104,19 @@ public sealed partial class TrayCoordinator
|
||||
{
|
||||
if(!ChapterCapable(doc.Instance))return;
|
||||
lock(gate){if(documents.GetValueOrDefault(doc.Session)!=doc)return;var work=GetChapterWork(doc);work.Supported=reply.ChapterSyncSupported;if(work.ContextMs<0&&!string.IsNullOrEmpty(reply.SceneTitle))work.ContextMs=work.RecognitionMs+work.Elapsed.Elapsed.TotalMilliseconds;
|
||||
if(work.Manifest!=null&&reply.ParagraphRevision>0&&work.Manifest.Revision!=reply.ParagraphRevision){work.Completion=null;work.Manifest=null;work.Checked.Clear();work.Visited.Clear();work.Reviewed.Clear();work.Command=Guid.Empty;work.Finished=false;work.Busy=false;work.Wrapped=false;work.FirstStart=-1;work.FailedRevision=-1;}
|
||||
if(work.Manifest!=null&&reply.ParagraphRevision>0&&work.Manifest.Revision!=reply.ParagraphRevision){work.Completion=null;work.Manifest=null;work.PendingReuse.Clear();work.ReuseFinishing=false;work.Checked.Clear();work.Visited.Clear();work.Reviewed.Clear();work.Command=Guid.Empty;work.Finished=false;work.Busy=false;work.Wrapped=false;work.FirstStart=-1;work.FailedRevision=-1;}
|
||||
if(DateTime.UtcNow<work.RetryAfter||work.Finished||!work.Supported||doc.WordSaved!=true||doc.Book<=0||work.FailedRevision==doc.Revision||doc.Capture!=null)return;
|
||||
if(work.Busy){if(!work.Processing&&work.Command!=Guid.Empty&&work.End>work.Start&&doc.Active&&doc.Cursor!=work.CursorWhenQueued&&!work.Checked.Any(p=>doc.Cursor>=p.Value.Start&&doc.Cursor<p.Value.End)&&(doc.Cursor<work.Start||doc.Cursor>=work.End)){QueueChapter(doc,work,doc.Cursor);return;}if(DateTime.UtcNow-work.Started>TimeSpan.FromMinutes(2)){StopChapterWork(doc,work,"Chapter validation timed out. Accepted checkpoints are retained. Check the connection before retrying.");}return;}
|
||||
if(work.Manifest==null){work.Busy=true;work.Started=DateTime.UtcNow;_ = LoadChapterManifest(doc,work);return;}
|
||||
var here=work.Checked.Any(p=>doc.Cursor>=p.Value.Start&&doc.Cursor<p.Value.End);
|
||||
if(!here){QueueChapter(doc,work,doc.Cursor);return;}
|
||||
var next=work.Manifest.Chapters.FirstOrDefault(c=>!work.Checked.ContainsKey(c.ChapterId)&&!work.Reviewed.Contains(c.ChapterId)&&(c.State!="Needs review"||work.Operation!=Guid.Empty));
|
||||
var next=work.Manifest.Chapters.FirstOrDefault(c=>!work.Checked.ContainsKey(c.ChapterId)&&!work.PendingReuse.ContainsKey(c.ChapterId)&&!work.Reviewed.Contains(c.ChapterId)&&(c.State!="Needs review"||work.Operation!=Guid.Empty));
|
||||
if(next!=null)QueueChapter(doc,work,next.Start);
|
||||
}
|
||||
}
|
||||
private async Task LoadChapterManifest(TrayDocument doc,ChapterWork work)
|
||||
{
|
||||
var timing=System.Diagnostics.Stopwatch.StartNew();
|
||||
var timing=System.Diagnostics.Stopwatch.StartNew();work.Requests++;
|
||||
try{var manifest=await cloud.ChapterManifest(doc.Book,doc.Session,doc.Revision,doc.Authentication);
|
||||
lock(gate){if(!CurrentChapterWork(doc,work))return;if(manifest.ManuscriptId!=doc.Manuscript)throw new InvalidOperationException("Saved manuscript identity does not match this Word document.");work.ManifestMs+=timing.Elapsed.TotalMilliseconds;work.Manifest=manifest;work.Busy=false;if(manifest.Chapters.Length==0){StopChapterWork(doc,work,"No accepted chapter boundaries are available. Review the existing manuscript structure.");return;}if(work.Operation==Guid.Empty&&manifest.Chapters.All(c=>string.IsNullOrEmpty(c.HeadingNativeId))){StopChapterWork(doc,work,"This existing import has no native chapter identities. Use Repair Synchronisation to verify and adopt identities without reimporting.");return;}if(manifest.Mode=="Off"&&work.Operation==Guid.Empty){work.Finished=true;doc.Status="Automatic synchronisation is off. Use Synchronise or Repair for an explicit chapter check.";return;}foreach(var chapter in manifest.Chapters.Where(c=>c.State=="Synchronised"))work.Checked[chapter.ChapterId]=(chapter.Start,chapter.End);doc.Status=$"Chapter index ready: {work.Checked.Count}/{manifest.Chapters.Length} accepted for this Word session.";if(manifest.Chapters.Length>0&&work.Checked.Count==manifest.Chapters.Length){CompleteChapters(doc,work);}else if(manifest.Chapters.Length>0&&!work.Checked.Any(p=>doc.Cursor>=p.Value.Start&&doc.Cursor<p.Value.End))QueueChapter(doc,work,doc.Cursor);else{var next=manifest.Chapters.FirstOrDefault(c=>!work.Checked.ContainsKey(c.ChapterId));if(next!=null)QueueChapter(doc,work,next.Start);}}
|
||||
}catch(Exception e)when(NetworkFailure(e)){lock(gate)if(CurrentChapterWork(doc,work)){RetryChapterWork(doc,work,"Chapter index unavailable: "+e.Message);}}
|
||||
@ -168,11 +171,12 @@ public sealed partial class TrayCoordinator
|
||||
private void AdvanceChapter(TrayDocument doc,ChapterWork work)
|
||||
{
|
||||
if(work.Manifest==null)return;
|
||||
if(work.Manifest.Chapters.All(c=>work.Checked.ContainsKey(c.ChapterId)||work.Reviewed.Contains(c.ChapterId))){CompleteChapters(doc,work);return;}
|
||||
if(work.Manifest.Chapters.All(c=>work.Checked.ContainsKey(c.ChapterId)||work.PendingReuse.ContainsKey(c.ChapterId)||work.Reviewed.Contains(c.ChapterId))){CompleteChapters(doc,work);return;}
|
||||
var next=work.End;
|
||||
for(int count=0;count<work.Manifest.Chapters.Length+1;count++){
|
||||
if(work.Wrapped&&next==work.FirstStart){CompleteChapters(doc,work);return;}
|
||||
var cached=work.Checked.FirstOrDefault(p=>p.Value.Start==next&&p.Value.End>next);
|
||||
if(cached.Value.End<=next){var pending=work.PendingReuse.Values.FirstOrDefault(p=>p.Start==next&&p.End>next);if(pending!=null){next=pending.End;continue;}}
|
||||
if(cached.Value.End>next){next=cached.Value.End;continue;}
|
||||
break;
|
||||
}
|
||||
@ -183,12 +187,14 @@ public sealed partial class TrayCoordinator
|
||||
}
|
||||
private void CompleteChapters(TrayDocument doc,ChapterWork work)
|
||||
{
|
||||
if(work.PendingReuse.Count>0){if(!work.ReuseFinishing){work.ReuseFinishing=true;work.Busy=true;work.Processing=true;work.Command=Guid.Empty;_ = CompleteReuseAndChapters(doc,work);}return;}
|
||||
var expected=work.Manifest!.Chapters.Select(c=>c.ChapterId).Where(work.Checked.ContainsKey).ToArray();var actual=work.Checked.OrderBy(p=>p.Value.Start).Select(p=>p.Key).ToArray();for(int i=0;i<Math.Min(expected.Length,actual.Length);i++)if(expected[i]!=actual[i]){work.Reviewed.Add(expected[i]);work.Reviewed.Add(actual[i]);}
|
||||
work.Busy=true;work.Finished=true;work.Started=DateTime.UtcNow;_ = CompleteChapterOperation(doc,work);
|
||||
}
|
||||
private async Task CompleteChapterOperation(TrayDocument doc,ChapterWork work)
|
||||
{
|
||||
try{var result=await cloud.FinishChapters(doc.Book,new(){InstanceId=doc.Instance,SessionId=doc.Session,WordRevision=work.Revision,OperationId=work.Operation,ReviewChapterIds=work.Reviewed.Where(id=>id>0).ToArray(),HasIssues=work.Reviewed.Count>0||work.Manifest!.Chapters.Any(c=>!work.Checked.ContainsKey(c.ChapterId))},work.Context);lock(gate)if(CurrentChapterWork(doc,work)){work.Busy=false;work.Processing=false;work.CompleteMs=work.RecognitionMs+work.Elapsed.Elapsed.TotalMilliseconds;work.Completion=result;doc.ChapterProgress=result;doc.Status=result.Message;if(result.State=="Needs review" && work.ReviewReason.Length>0){result.Message=work.ReviewReason;}}}
|
||||
var completion=new ChapterFinish{InstanceId=doc.Instance,SessionId=doc.Session,WordRevision=work.Revision,OperationId=work.Operation,ReviewChapterIds=work.Reviewed.Where(id=>id>0).ToArray(),HasIssues=work.Reviewed.Count>0||work.Manifest!.Chapters.Any(c=>!work.Checked.ContainsKey(c.ChapterId))};CountChapterRequest(work,completion);
|
||||
try{var result=await cloud.FinishChapters(doc.Book,completion,work.Context);lock(gate)if(CurrentChapterWork(doc,work)){work.Busy=false;work.Processing=false;work.CompleteMs=work.RecognitionMs+work.Elapsed.Elapsed.TotalMilliseconds;work.Completion=result;doc.ChapterProgress=result;doc.Status=result.Message;if(result.State=="Needs review" && work.ReviewReason.Length>0){result.Message=work.ReviewReason;}}}
|
||||
catch(Exception e)when(NetworkFailure(e)){lock(gate)if(CurrentChapterWork(doc,work)){RetryChapterWork(doc,work,"Could not confirm chapter completion: "+e.Message);}}
|
||||
}
|
||||
private async Task ProcessChapter(TrayDocument doc,ChapterWork work,string text,string xml,string? identities,Guid command,int start,int end,string nextHeading,Guid operation,bool physicalPositions)
|
||||
@ -202,21 +208,30 @@ public sealed partial class TrayCoordinator
|
||||
lock(gate){if(!(CurrentChapterWork(doc,work)&&work.Command==command))return;if(work.IdentityAction=="live-text")work.LiveReads++;else work.XmlReads++;}
|
||||
ChapterManifest manifest;lock(gate){if(!(CurrentChapterWork(doc,work)&&work.Command==command))return;manifest=work.Manifest!;}
|
||||
if(physicalPositions&&!manifest.NativePositionsSupported)throw new ArgumentException("Update the Development server to validate native picture positions. Existing checkpoints are retained.");
|
||||
var hash=ChapterFingerprint.Content(rows.Select(p=>p.Text!));
|
||||
var hash=ChapterFingerprint.Content(rows.Select(p=>p.Text!));lock(gate){work.Calculated++;}
|
||||
var candidates=manifest.Chapters.Where(c=>c.HeadingNativeId==rows[0].NativeId).ToArray();
|
||||
if(candidates.Length==0&&work.Operation!=Guid.Empty)candidates=manifest.Chapters.Where(c=>c.HeadingNativeId==""&&c.ContentHash==hash&&c.ParagraphCount==rows.Length).ToArray();
|
||||
if(candidates.Length!=1){lock(gate){if(!(CurrentChapterWork(doc,work)&&work.Command==command))return;work.Busy=false;work.Reviewed.Add(-work.Start-1);work.ReviewReason="A chapter identity is unrecognised or ambiguous. Review its Word heading and saved mapping.";doc.Status=work.ReviewReason;AdvanceChapter(doc,work);}return;}
|
||||
var chapter=candidates[0];lock(gate){if(!(CurrentChapterWork(doc,work)&&work.Command==command))return;if(!work.Visited.Add(chapter.ChapterId)){work.Busy=false;if(!work.Checked.TryGetValue(chapter.ChapterId,out var earlier)||earlier.Start!=start||earlier.End!=end){work.Reviewed.Add(chapter.ChapterId);work.Checked.Remove(chapter.ChapterId);doc.Status="Duplicate chapter identity at another position; existing canonical structure is retained for review.";}AdvanceChapter(doc,work);return;}}var proof=new ChapterObservation{RequestId=command,OperationId=operation,InstanceId=doc.Instance,SessionId=doc.Session,ManuscriptId=doc.Manuscript,WordRevision=doc.Revision,BaseRevision=manifest.Revision,ChapterId=chapter.ChapterId,Start=start,End=end,NextHeadingId=nextHeading,ContentHash=hash,IdentityHash=ChapterFingerprint.Identity(rows),PositionHash=physicalPositions?ChapterWordPositions.Hash(rows):"",Paragraphs=rows.Select(p=>new ChapterParagraph{NativeId=p.NativeId,Length=p.Length,Outline=p.Outline,WordLength=p.WordLength,Anchors=p.Anchors}).ToArray()};
|
||||
lock(gate){work.VerificationMs+=verification.Elapsed.TotalMilliseconds;}
|
||||
if(candidates.Length!=1){lock(gate){if(!(CurrentChapterWork(doc,work)&&work.Command==command))return;work.Incompatible++;work.Busy=false;work.Reviewed.Add(-work.Start-1);work.ReviewReason="A chapter identity is unrecognised or ambiguous. Review its Word heading and saved mapping.";doc.Status=work.ReviewReason;AdvanceChapter(doc,work);}return;}
|
||||
var chapter=candidates[0];lock(gate){if(!(CurrentChapterWork(doc,work)&&work.Command==command))return;if(!work.Visited.Add(chapter.ChapterId)){work.Busy=false;if((!work.Checked.TryGetValue(chapter.ChapterId,out var earlier)||earlier.Start!=start||earlier.End!=end)&&(!work.PendingReuse.TryGetValue(chapter.ChapterId,out var pending)||pending.Start!=start||pending.End!=end)){work.Reviewed.Add(chapter.ChapterId);work.Checked.Remove(chapter.ChapterId);work.PendingReuse.Remove(chapter.ChapterId);doc.Status="Duplicate chapter identity at another position; existing canonical structure is retained for review.";}AdvanceChapter(doc,work);return;}}var proof=new ChapterObservation{RequestId=command,OperationId=operation,InstanceId=doc.Instance,SessionId=doc.Session,ManuscriptId=doc.Manuscript,WordRevision=doc.Revision,BaseRevision=manifest.Revision,ChapterId=chapter.ChapterId,Start=start,End=end,NextHeadingId=nextHeading,ContentHash=hash,IdentityHash=ChapterFingerprint.Identity(rows),PositionHash=physicalPositions?ChapterWordPositions.Hash(rows):"",Paragraphs=rows.Select(p=>new ChapterParagraph{NativeId=p.NativeId,Length=p.Length,Outline=p.Outline,WordLength=p.WordLength,Anchors=p.Anchors}).ToArray()};
|
||||
lock(gate){if(chapter.ContentHash!=proof.ContentHash)work.Mismatching++;else if(ChapterCheckpointReuse.Matches(chapter,proof))work.Matching++;else if(!chapter.DurableAccepted)work.Missing++;else work.Incompatible++;work.VerificationMs+=verification.Elapsed.TotalMilliseconds;}
|
||||
if(manifest.CheckpointReuseSupported&&ChapterCheckpointReuse.Matches(chapter,proof))
|
||||
{
|
||||
bool flush;lock(gate){if(!(CurrentChapterWork(doc,work)&&work.Command==command))return;flush=work.PendingReuse.Values.Sum(p=>p.Paragraphs.Length)+proof.Paragraphs.Length>20000||work.PendingReuse.Count>=64;}
|
||||
if(flush)await FlushReuse(doc,work);
|
||||
lock(gate){if(!(CurrentChapterWork(doc,work)&&work.Command==command))return;work.PendingReuse[chapter.ChapterId]=proof;}
|
||||
if(work.Checked.Count==0&&doc.Cursor>=start&&doc.Cursor<end)await FlushReuse(doc,work);
|
||||
lock(gate){if(!(CurrentChapterWork(doc,work)&&work.Command==command))return;work.Busy=false;work.Processing=false;AdvanceChapter(doc,work);}return;
|
||||
}
|
||||
CountChapterRequest(work,proof);
|
||||
var validation=System.Diagnostics.Stopwatch.StartNew();work.Submissions++;
|
||||
var result=await cloud.ValidateChapter(doc.Book,proof,doc.Authentication);
|
||||
if(!result.Accepted&&result.State=="Changed"&&result.AllowText){proof.Reconcile=true;proof.Paragraphs=rows;work.Submissions++;result=await cloud.ValidateChapter(doc.Book,proof,doc.Authentication);}
|
||||
lock(gate){if(!(CurrentChapterWork(doc,work)&&work.Command==command))return;work.ServerMs+=validation.Elapsed.TotalMilliseconds;work.Busy=false;
|
||||
if(!result.Accepted&&result.State=="Changed"&&result.AllowText){proof.Reconcile=true;proof.Paragraphs=rows;work.Submissions++;CountChapterRequest(work,proof);result=await cloud.ValidateChapter(doc.Book,proof,doc.Authentication);}
|
||||
lock(gate){if(!(CurrentChapterWork(doc,work)&&work.Command==command))return;work.ServerMs+=validation.Elapsed.TotalMilliseconds;if(result.Accepted&&proof.Reconcile&&proof.Paragraphs.Any(p=>p.Text!=null))work.Reconciled++;work.Busy=false;
|
||||
if(result.Accepted){work.Retries=0;work.Checked[chapter.ChapterId]=(start,end);manifest.Revision=result.Revision;if(result.State=="Needs review")work.Reviewed.Add(chapter.ChapterId);doc.LastPresenceKey="";doc.LastPresenceUtc=DateTime.MinValue;doc.Status=$"{work.Checked.Count}/{manifest.Chapters.Length} chapters accepted · "+result.Message;AdvanceChapter(doc,work);}
|
||||
else{work.Reviewed.Add(chapter.ChapterId);work.ReviewReason=result.Message;doc.Status=result.Message+" Accepted chapter repairs are retained.";AdvanceChapter(doc,work);}
|
||||
}
|
||||
}catch(Exception e)when(NetworkFailure(e)||e is ArgumentException or System.Xml.XmlException){lock(gate)if(CurrentChapterWork(doc,work)&&work.Command==command){work.Busy=false;
|
||||
if(e is HttpRequestException or OperationCanceledException||cloud.Status().Health?.Authentication!="verified"){work.Visited.Clear();RetryChapterWork(doc,work,"Chapter connection interrupted. Accepted checkpoints are retained.");}
|
||||
if(e is HttpRequestException or OperationCanceledException or ChapterReuseConflictException||cloud.Status().Health?.Authentication!="verified"){work.Visited.Clear();RetryChapterWork(doc,work,"Chapter connection interrupted. Accepted checkpoints are retained.");}
|
||||
else if(e is ArgumentException or System.Xml.XmlException&&end>start){ReviewChapterReadFailure(doc,work,start,end,"Chapter content needs review: "+e.Message);}
|
||||
else{work.FailedRevision=doc.Revision;doc.Status="Chapter needs review: "+e.Message+" Existing import is unchanged.";}}}
|
||||
finally{chapterProcessing.Release();}
|
||||
|
||||
47
PlotDirector.NativeCompanion/Agent/TrayCoordinator.Reuse.cs
Normal file
47
PlotDirector.NativeCompanion/Agent/TrayCoordinator.Reuse.cs
Normal file
@ -0,0 +1,47 @@
|
||||
using System.Diagnostics;
|
||||
using System.Text.Json;
|
||||
using PlotDirector.Companion.Protocol.Manuscript;
|
||||
namespace PlotDirector.Companion.Agent;
|
||||
public sealed partial class TrayCoordinator
|
||||
{
|
||||
private static void CountChapterRequest(ChapterWork work,object payload)
|
||||
{
|
||||
work.Requests++;work.RequestBytes+=JsonSerializer.SerializeToUtf8Bytes(payload,new JsonSerializerOptions(JsonSerializerDefaults.Web)).Length;
|
||||
}
|
||||
private async Task FlushReuse(TrayDocument doc,ChapterWork work)
|
||||
{
|
||||
ChapterReuseRequest request;ChapterManifest manifest;
|
||||
lock(gate)
|
||||
{
|
||||
if(!CurrentChapterWork(doc,work)||work.FailedRevision==doc.Revision||doc.WordSaved!=true)throw new InvalidOperationException("Word changed during checkpoint verification.");
|
||||
if(work.PendingReuse.Count==0)return;
|
||||
manifest=work.Manifest??throw new InvalidOperationException("Accepted manifest changed.");
|
||||
request=new(){Chapters=work.PendingReuse.Values.ToArray()};
|
||||
foreach(var proof in request.Chapters)proof.BaseRevision=manifest.Revision;
|
||||
CountChapterRequest(work,request);work.ReuseRequests++;
|
||||
}
|
||||
var timer=Stopwatch.StartNew();var reply=await cloud.ReuseChapters(doc.Book,request,work.Context);
|
||||
lock(gate)
|
||||
{
|
||||
if(!CurrentChapterWork(doc,work)||work.FailedRevision==doc.Revision||doc.WordSaved!=true||!ReferenceEquals(work.Manifest,manifest))return;
|
||||
if(reply.Revision!=work.Manifest!.Revision||!reply.ChapterIds.Order().SequenceEqual(request.Chapters.Select(p=>p.ChapterId).Order()))throw new InvalidDataException("Incomplete checkpoint reuse acknowledgement.");
|
||||
foreach(var proof in request.Chapters){work.Checked[proof.ChapterId]=(proof.Start,proof.End);work.PendingReuse.Remove(proof.ChapterId);}
|
||||
work.Reused+=reply.ChapterIds.Length;work.ServerMs+=timer.Elapsed.TotalMilliseconds;work.ReuseReadMs+=reply.ReadMs;work.ReuseProcessingMs+=reply.ProcessingMs;work.ReuseValidationMs+=reply.ValidationMs;work.ReusePersistenceMs+=reply.PersistenceMs;
|
||||
doc.LastPresenceKey="";doc.LastPresenceUtc=DateTime.MinValue;
|
||||
doc.Status=$"{work.Checked.Count}/{work.Manifest.Chapters.Length} chapter mappings verified; {work.Reused} reused without reconciliation.";
|
||||
}
|
||||
}
|
||||
private async Task CompleteReuseAndChapters(TrayDocument doc,ChapterWork work)
|
||||
{
|
||||
var manifest=work.Manifest;
|
||||
try
|
||||
{
|
||||
await FlushReuse(doc,work);
|
||||
lock(gate){if(!CurrentChapterWork(doc,work)||work.FailedRevision==doc.Revision||!ReferenceEquals(work.Manifest,manifest))return;work.ReuseFinishing=false;work.Processing=false;CompleteChapters(doc,work);}
|
||||
}
|
||||
catch(Exception e)when(NetworkFailure(e))
|
||||
{
|
||||
lock(gate)if(CurrentChapterWork(doc,work)&&ReferenceEquals(work.Manifest,manifest))RetryChapterWork(doc,work,"Checkpoint reuse interrupted; accepted mappings are retained. "+e.Message);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -1 +1 @@
|
||||
<Project><PropertyGroup><ApplicationVersion>1.0.0.30</ApplicationVersion></PropertyGroup></Project>
|
||||
<Project><PropertyGroup><ApplicationVersion>1.0.0.31</ApplicationVersion></PropertyGroup></Project>
|
||||
|
||||
@ -162,10 +162,12 @@ public static class ChapterFingerprint
|
||||
|
||||
public sealed class ChapterManifest
|
||||
{
|
||||
public bool NativePositionsSupported{get;set;}public int BookId{get;set;}public Guid ManuscriptId{get;set;}public long Revision{get;set;}public string Mode{get;set;}="Manual";public ChapterManifestItem[] Chapters{get;set;}=Array.Empty<ChapterManifestItem>();
|
||||
public bool CheckpointReuseSupported{get;set;}public bool NativePositionsSupported{get;set;}public int BookId{get;set;}public Guid ManuscriptId{get;set;}public long Revision{get;set;}public string Mode{get;set;}="Manual";public ChapterManifestItem[] Chapters{get;set;}=Array.Empty<ChapterManifestItem>();
|
||||
}
|
||||
public sealed class ChapterManifestItem
|
||||
{
|
||||
public bool DurableAccepted{get;set;}public int Order{get;set;}public long AcceptedRevision{get;set;}
|
||||
public string Algorithm{get;set;}="";public string MappingHash{get;set;}="";public string PositionHash{get;set;}="";public string NextHeadingId{get;set;}="";
|
||||
public int ChapterId{get;set;}public string Title{get;set;}="";public string HeadingNativeId{get;set;}="";public string ContentHash{get;set;}="";public string IdentityHash{get;set;}="";public int Start{get;set;}public int End{get;set;}public int ParagraphCount{get;set;}public string State{get;set;}="Not yet checked";
|
||||
}
|
||||
public sealed class ChapterSyncReply
|
||||
@ -190,3 +192,17 @@ public sealed class ChapterFinish
|
||||
public Guid InstanceId{get;set;}public Guid SessionId{get;set;}public long WordRevision{get;set;}public Guid OperationId{get;set;}public bool HasIssues{get;set;}public int[] ReviewChapterIds{get;set;}=Array.Empty<int>();
|
||||
}
|
||||
public sealed class ChapterRepairRequested {public Guid OperationId{get;set;}public string Message{get;set;}="";}
|
||||
|
||||
public sealed class ChapterReuseRequest
|
||||
{
|
||||
public ChapterObservation[] Chapters{get;set;}=Array.Empty<ChapterObservation>();
|
||||
}
|
||||
public sealed class ChapterReuseReply
|
||||
{
|
||||
public int[] ChapterIds{get;set;}=Array.Empty<int>();public long Revision{get;set;}
|
||||
public double ReadMs{get;set;}public double ProcessingMs{get;set;}public double ValidationMs{get;set;}public double PersistenceMs{get;set;}
|
||||
}
|
||||
public static class ChapterCheckpointReuse
|
||||
{
|
||||
public static bool Matches(ChapterManifestItem c,ChapterObservation p)=>c.DurableAccepted&&c.Algorithm==ChapterFingerprint.Version&&p.Algorithm==c.Algorithm&&c.ContentHash==p.ContentHash&&c.IdentityHash==p.IdentityHash&&c.PositionHash==p.PositionHash&&c.NextHeadingId==p.NextHeadingId&&c.ParagraphCount==p.Paragraphs.Length;
|
||||
}
|
||||
|
||||
73
PlotDirector.NativeCompanion/Tests/ChapterHandshakeTests.cs
Normal file
73
PlotDirector.NativeCompanion/Tests/ChapterHandshakeTests.cs
Normal file
@ -0,0 +1,73 @@
|
||||
using System.Net;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using PlotDirector.Companion.Agent;
|
||||
using PlotDirector.Companion.Protocol;
|
||||
using PlotDirector.Companion.Protocol.Manuscript;
|
||||
internal static class ChapterHandshakeTests
|
||||
{
|
||||
private static void Check(bool value,string name){if(!value)throw new Exception(name);Console.WriteLine("PASS "+name);}
|
||||
public static async Task Run()
|
||||
{
|
||||
foreach(var scenario in new[]{(Edited:Array.Empty<int>(),Missing:-1,Geometry:-1),(Edited:new[]{17},Missing:-1,Geometry:-1),(Edited:new[]{7,22,47},Missing:-1,Geometry:-1),(Edited:Array.Empty<int>(),Missing:31,Geometry:-1),(Edited:Array.Empty<int>(),Missing:-1,Geometry:47),(Edited:Array.Empty<int>(),Missing:-2,Geometry:-1)})
|
||||
{
|
||||
var changed=scenario.Edited;var fallback=(scenario.Missing>=0?1:0)+(scenario.Geometry>=0?1:0);var handler=new Handler(changed,scenario.Missing,scenario.Geometry);using var cloud=new CloudGateway(handler,_=>{});cloud.Connect("https://handshake.test/");await Until(()=>cloud.Status().Books.Any());await cloud.CheckConnection();
|
||||
var sessions=new SessionManager();using var ai=new ChapterAiWork(cloud);var tray=new TrayCoordinator(sessions,cloud,ai);var instance=Guid.NewGuid();var session=Guid.NewGuid();var lease=Guid.NewGuid();long sequence=0;var pendingCommands=new Queue<AdapterCommand>();
|
||||
sessions.Attach(instance,lease,chapters:true,liveChapterText:true);tray.Attach(instance,lease,chapters:true);
|
||||
Message Send(Message m){m.WordInstanceId=instance;m.SessionId=session;m.Revision=1;m.Sequence=++sequence;var answer=tray.Exchange(instance,m,sessions.Apply(lease,m),lease);if(answer.Command?.Kind=="chapter-check")pendingCommands.Enqueue(answer.Command);return answer;}
|
||||
Send(new(){Kind="document",Documents=[new(){SessionId=session,ManuscriptId=handler.Manuscript,Revision=1,Title="Synthetic reopen.docx"}]});tray.SelectBook(session,3,false);Send(new(){Kind="active"});Send(new(){Kind="selection",WordSaved=true});
|
||||
using var stop=new CancellationTokenSource();var heartbeats=tray.Heartbeat(stop.Token);var watch=System.Diagnostics.Stopwatch.StartNew();
|
||||
try
|
||||
{
|
||||
for(var c=0;c<48;c++)
|
||||
{
|
||||
AdapterCommand? command=null;await Until(()=>{Send(new(){Kind="selection",WordSaved=true});if(pendingCommands.Count>0)command=pendingCommands.Dequeue();return command!=null;});
|
||||
var body=handler.Current[c];var start=handler.Starts[c];
|
||||
Send(new(){Kind="chapter-begin",SnapshotId=command!.Id,BookId=3,Start=start,End=start+body.Length,DocumentEnd=handler.Starts[47]+handler.Current[47].Length,WordSaved=true,ChapterTitle=c==47?"":((c+1)*2+1).ToString("X8")});
|
||||
void Chunks(string action,string value){for(var offset=0;offset<value.Length;offset+=2048)Send(new(){Kind="chapter-chunk",SnapshotId=command.Id,Action=action,Start=offset,OperationMessage=value.Substring(offset,Math.Min(2048,value.Length-offset))});}
|
||||
Chunks("text",body);var heading=$"Chapter {c}\r";Chunks("live-text",(c*2+1).ToString("X8")+heading.Length.ToString("X8")+"00000001"+(c*2+2).ToString("X8")+(body.Length-heading.Length).ToString("X8")+"0000000A");
|
||||
Send(new(){Kind="chapter-end",SnapshotId=command.Id});
|
||||
if(c==0){await Until(()=>handler.Reused==1);await Until(()=>tray.PresentationDocuments.Single().SceneId.HasValue);Check(handler.Finishes==0,"Writing Context is available before the other 47 chapters are acknowledged");}
|
||||
}
|
||||
if(scenario.Missing==-2)
|
||||
{
|
||||
await Until(()=>handler.ReuseRequests==2);Send(new(){Kind="close"});handler.ReleaseSecond.SetResult();await Task.Delay(100);
|
||||
Check(tray.PresentationDocuments.All(d=>d.Session!=session),"Closing during final batch rejects the late reuse acknowledgement");
|
||||
Check(handler.Finishes==0,"Interrupted reuse cannot report whole-manuscript completion after close");continue;
|
||||
}
|
||||
await Until(()=>tray.ChapterProgressForDisplay(session)?.State=="Synchronised");await Until(()=>tray.PresentationDocuments.Single().SceneId.HasValue);
|
||||
Check(handler.ReuseRequests==2&&handler.Reused==48-changed.Length-fallback,"Matching chapters use two bounded acknowledgements, including early current-chapter readiness");
|
||||
Check(handler.AcceptRequests==changed.Length*2+fallback&&handler.Reconciled==changed.Length,"Actual request counts prove only changed chapters submit reconciliation prose");
|
||||
Check(tray.ChapterProgressForDisplay(session)?.State=="Synchronised","Batch reuse reaches independently confirmed Up to date");
|
||||
Check(tray.ChapterDiagnostics(session).Contains($"reused={48-changed.Length-fallback}")&&tray.ChapterDiagnostics(session).Contains($"reconciled={changed.Length}"),"Diagnostics distinguish reused, submitted and reconciled chapters");
|
||||
Console.WriteLine($"MEASURE agent HTTP-contract fixture: chapters=48 changed={changed.Length} reuseRequests={handler.ReuseRequests} acceptanceRequests={handler.AcceptRequests} reconciled={handler.Reconciled} payloadBytes={handler.Bytes} totalMs={watch.Elapsed.TotalMilliseconds:F1}; HTTP in-memory, no Word/real network/SQL.");
|
||||
}
|
||||
finally{stop.Cancel();try{await heartbeats;}catch(OperationCanceledException){}}
|
||||
}
|
||||
}
|
||||
private static async Task Until(Func<bool> ready){for(var n=0;n<3000;n++){if(ready())return;await Task.Delay(5);}throw new Exception("Handshake fixture timed out");}
|
||||
private sealed class Handler:HttpMessageHandler
|
||||
{
|
||||
public readonly Guid Manuscript=Guid.NewGuid();public readonly string[] Current;public readonly int[] Starts;private readonly string[] hashes;private readonly int missing,geometry;private long revision=1;
|
||||
public readonly TaskCompletionSource ReleaseSecond=new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
public int ReuseRequests,Reused,AcceptRequests,Reconciled,Finishes;public long Bytes;private bool currentReady;
|
||||
public Handler(int[] changed,int missing,int geometry)
|
||||
{
|
||||
this.missing=missing;this.geometry=geometry;
|
||||
var original=Enumerable.Range(0,48).Select(c=>$"Chapter {c}\r"+string.Join(" ",Enumerable.Repeat("synthetic",3187))+"\r").ToArray();
|
||||
Current=original.Select((s,c)=>changed.Contains(c)?s.Replace("synthetic","different"):s).ToArray();Starts=new int[48];for(var c=1;c<48;c++)Starts[c]=Starts[c-1]+Current[c-1].Length;
|
||||
hashes=original.Select((s,c)=>ChapterFingerprint.Content([$"Chapter {c}\r",s[($"Chapter {c}\r").Length..]])).ToArray();
|
||||
}
|
||||
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,CancellationToken cancellation)
|
||||
{
|
||||
var path=request.RequestUri!.AbsolutePath;HttpResponseMessage Json(object value)=>new(HttpStatusCode.OK){Content=JsonContent.Create(value)};
|
||||
if(path.EndsWith("/pair"))return Json(new{code="00112233445566778899AABB"});if(path.EndsWith("/token"))return Json(new{accessToken="fixture"});if(path.EndsWith("/books"))return Json(new[]{new{bookId=3,title="Synthetic book"}});if(path.EndsWith("/connection"))return Json(new{state="Connected",authentication="verified",server="online",expiresUtc=DateTime.UtcNow.AddHours(4)});
|
||||
if(path.EndsWith("/presence")){var p=(await request.Content!.ReadFromJsonAsync<NativePresence>(cancellation))!;p.ChapterSyncSupported=true;p.ParagraphRevision=revision;if(currentReady){p.ChapterId=1;p.SceneId=10;p.ChapterTitle="Chapter 0";p.SceneTitle="Verified scene";}return Json(p);}
|
||||
if(path.EndsWith("/chapter-sync"))return Json(new ChapterManifest{CheckpointReuseSupported=true,NativePositionsSupported=true,BookId=3,Mode="OnSave",ManuscriptId=Manuscript,Revision=revision,Chapters=Enumerable.Range(0,48).Select(c=>new ChapterManifestItem{ChapterId=c+1,DurableAccepted=c!=missing,PositionHash=c==geometry?new string('A',64):"",Algorithm=ChapterFingerprint.Version,HeadingNativeId=(c*2+1).ToString("X8"),ContentHash=hashes[c],IdentityHash=ChapterFingerprint.Identity([new(){NativeId=(c*2+1).ToString("X8"),Length=($"Chapter {c}\r").Length,Outline=1},new(){NativeId=(c*2+2).ToString("X8"),Length=Current[c].Length-($"Chapter {c}\r").Length,Outline=10}]),NextHeadingId=c==47?"":((c+1)*2+1).ToString("X8"),Start=Starts[c],End=Starts[c]+Current[c].Length,ParagraphCount=2}).ToArray()});
|
||||
if(path.EndsWith("/reuse")){var data=await request.Content!.ReadAsByteArrayAsync(cancellation);Bytes+=data.Length;var batch=JsonSerializer.Deserialize<ChapterReuseRequest>(data,new JsonSerializerOptions(JsonSerializerDefaults.Web))!;if(batch.Chapters.Any(p=>p.Paragraphs.Any(r=>r.Text!=null)))throw new Exception("Reuse leaked prose");ReuseRequests++;if(missing==-2&&ReuseRequests==2)await ReleaseSecond.Task.WaitAsync(cancellation);Reused+=batch.Chapters.Length;if(batch.Chapters.Any(p=>p.ChapterId==1))currentReady=true;return Json(new ChapterReuseReply{ChapterIds=batch.Chapters.Select(p=>p.ChapterId).ToArray(),Revision=revision});}
|
||||
if(path.EndsWith("/validate")){var data=await request.Content!.ReadAsByteArrayAsync(cancellation);Bytes+=data.Length;AcceptRequests++;var p=JsonSerializer.Deserialize<ChapterObservation>(data,new JsonSerializerOptions(JsonSerializerDefaults.Web))!;if(p.ContentHash==hashes[p.ChapterId-1])return Json(new ChapterSyncReply{Accepted=true,State="Synchronised",Revision=revision,ChapterId=p.ChapterId});if(p.Paragraphs.All(r=>r.Text==null))return Json(new ChapterSyncReply{State="Changed",AllowText=true,Revision=revision,ChapterId=p.ChapterId});Reconciled++;hashes[p.ChapterId-1]=p.ContentHash;return Json(new ChapterSyncReply{Accepted=true,State="Synchronised",Revision=++revision,ChapterId=p.ChapterId});}
|
||||
if(path.EndsWith("/finish")){Finishes++;return Json(new ChapterSyncProgress{State="Synchronised",Matching=48,Total=48});}
|
||||
return Json(new{});
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -3,7 +3,7 @@ using PlotDirector.Companion.Agent;
|
||||
using PlotDirector.Companion.Client;
|
||||
using PlotDirector.Companion.Protocol;
|
||||
|
||||
if(args.Contains("--chapter-sync")){ChapterReopenTests.Run();await ChapterAgentTests.Run();return;}
|
||||
if(args.Contains("--chapter-sync")){ChapterReopenTests.Run();await ChapterAgentTests.Run();await ChapterHandshakeTests.Run();return;}
|
||||
if(args.Contains("--native-capture-upload")){await NativeCaptureUploadTests.Run();return;}
|
||||
var passed = 0;
|
||||
void Check(bool value,string name) {if(!value)throw new Exception(name);passed++;Console.WriteLine("PASS "+name);}
|
||||
|
||||
@ -3,6 +3,6 @@ using System.Runtime.InteropServices;
|
||||
[assembly: AssemblyTitle("PlotDirector Word Companion — Native development")]
|
||||
[assembly: AssemblyCompany("Nick Beckley")]
|
||||
[assembly: AssemblyProduct("PlotDirector")]
|
||||
[assembly: AssemblyVersion("1.0.0.30")]
|
||||
[assembly: AssemblyFileVersion("1.0.0.30")]
|
||||
[assembly: AssemblyVersion("1.0.0.31")]
|
||||
[assembly: AssemblyFileVersion("1.0.0.31")]
|
||||
[assembly: ComVisible(false)]
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
{
|
||||
"version": "1.0.0.30",
|
||||
"msiVersion": "1.0.30",
|
||||
"productCode": "{4E2DA176-5A36-4C05-89A7-5BAB66700FB2}",
|
||||
"version": "1.0.0.31",
|
||||
"msiVersion": "1.0.31",
|
||||
"productCode": "{9E8E1907-7842-4001-99F4-EE1BE9FD35FA}",
|
||||
"upgradeCode": "{641A087B-9779-458C-B290-BCBBAD49319A}",
|
||||
"atlasBaseline": "9fed339879887964d526cff00772ffc4dc522c5d",
|
||||
"baselineProductCode": "{98F46939-764D-407F-BD1F-1D88315D010A}",
|
||||
|
||||
@ -12,6 +12,22 @@ let reply=await observe(1000);assert.equal(reply.navigation,null,'automatic reop
|
||||
const proofs=evidence.Proofs.map(p=>({...p,InstanceId:instance,SessionId:session,WordRevision:wordRevision,OperationId:'00000000-0000-0000-0000-000000000000',RequestId:crypto.randomUUID(),Reconcile:false}));
|
||||
for(const proof of proofs){const accepted=await validate(proof);assert.equal(accepted.accepted,true);await validate(proof);const cursor=proof.Start+proof.Paragraphs[0].Length;reply=await observe(cursor);assert.equal(reply.chapterId,proof.ChapterId);assert.equal(reply.sceneId,scope.Scenes[proofs.indexOf(proof)]);assert.equal(reply.navigation,null);}
|
||||
r=await page.request.post(endpoint+'/finish',{headers,data:{instanceId:instance,sessionId:session,wordRevision}});assert.equal(r.status(),200);assert.equal((await r.json()).state,'Synchronised');console.log('PASS deployed authenticated cross-session chapter adoption, current positions across chapters, idempotent retry, no automatic full capture/navigation and server-confirmed progress');
|
||||
// Focused reuse qualification avoids unrelated recovery/UI work.
|
||||
if(process.argv.includes('--reuse-only')){
|
||||
const freshSession=crypto.randomUUID(),freshInstance=crypto.randomUUID(),freshPresence=base+`/api/native-companion/instances/${freshInstance}/documents/${freshSession}/presence`;let freshSequence=0;
|
||||
async function freshObserve(){const result=await page.request.post(freshPresence,{headers,data:{bookId:scope.Book,manuscriptId:scope.Manuscript,revision:0,sequence:++freshSequence,wordAvailable:true,wordRunning:true,wordSaved:true,canChapterSync:true,cursorStart:proofs[0].Start+proofs[0].Paragraphs[0].Length}});assert.equal(result.status(),200);return result.json();}
|
||||
assert.equal((await freshObserve()).sceneId,null,'new-session positions are not inherited');
|
||||
let result=await page.request.get(endpoint+`?session=${freshSession}&wordRevision=0`,{headers});assert.equal(result.status(),200);const index=await result.json();assert.equal(index.checkpointReuseSupported,true);assert.equal(index.chapters.filter(c=>c.durableAccepted).length,2);
|
||||
const reused=proofs.map(p=>({...p,InstanceId:freshInstance,SessionId:freshSession,RequestId:crypto.randomUUID()}));
|
||||
const body={chapters:reused};const start=performance.now();result=await page.request.post(endpoint+'/reuse',{headers,data:body});assert.equal(result.status(),200,await result.text());const ack=await result.json();assert.equal(ack.chapterIds.length,2);
|
||||
assert.equal((await freshObserve()).sceneId,scope.Scenes[0],'reused positions resolve the existing canonical scene');
|
||||
result=await page.request.post(endpoint+'/reuse',{headers,data:body});assert.equal(result.status(),200,'same batch resumes idempotently');
|
||||
result=await page.request.post(endpoint+'/reuse',{headers,data:{chapters:[{...reused[0],BaseRevision:0}]}});assert.equal(result.status(),409,'stale source is refused');
|
||||
result=await page.request.post(endpoint+'/reuse',{headers,data:{chapters:[{...reused[0],PositionHash:'A'.repeat(64)}]}});assert.equal(result.status(),409,'structural geometry mismatch cannot reuse');
|
||||
result=await page.request.post(endpoint+'/finish',{headers,data:{instanceId:freshInstance,sessionId:freshSession,wordRevision:0}});assert.equal(result.status(),200);assert.equal((await result.json()).state,'Synchronised');
|
||||
console.log(`PASS deployed authenticated checkpoint reuse: fresh-session isolation, one batch/two chapters, zero reconciliation calls in reuse phase, existing Context scene, idempotence, stale and geometry rejection; validation=${ack.validationMs.toFixed(1)}ms persistence=${ack.persistenceMs.toFixed(1)}ms total=${(performance.now()-start).toFixed(1)}ms payload=${Buffer.byteLength(JSON.stringify(body))} bytes. Includes negative requests; not Word timing.`);
|
||||
await page.request.delete(freshPresence,{headers});await page.request.delete(presence,{headers});return;
|
||||
}
|
||||
// Same live revision cannot acquire contradictory ranges.
|
||||
await validate({...proofs[0],RequestId:crypto.randomUUID(),Start:proofs[0].Start+1,End:proofs[0].End+1},409);
|
||||
await validate({...proofs[0],RequestId:crypto.randomUUID(),BaseRevision:0},409);
|
||||
|
||||
@ -22,6 +22,7 @@ internal static class ChapterAcceptanceDevelopmentTests
|
||||
{
|
||||
if (!OperatingSystem.IsLinux() || args.Length != 2 || !int.TryParse(args[1], out var user) || user <= 0)
|
||||
throw new InvalidOperationException("Use --chapter-acceptance-dev <development-fixture-owner-id>");
|
||||
var reuseMode=args[0]=="--chapter-reuse-dev";
|
||||
var start = new ProcessStartInfo("sudo") { RedirectStandardOutput = true };
|
||||
foreach (var value in new[] { "-n", "cat", "/etc/plotdirector/plotdirector.env" }) start.ArgumentList.Add(value);
|
||||
using var process = Process.Start(start)!;
|
||||
@ -72,8 +73,8 @@ internal static class ChapterAcceptanceDevelopmentTests
|
||||
var firstOrdinal = rows.Count;
|
||||
for (var n = 0; n < count; n++)
|
||||
{
|
||||
var text = n == 0 ? $"Synthetic chapter {chapter}\r" : $"Synthetic paragraph {rows.Count}: " + new string('x', 420) + "\r";
|
||||
rows.Add(new() { Ordinal = rows.Count, Start = position, End = position + text.Length, Text = text, Outline = n == 0 ? 1 : 10 });
|
||||
var text = n == 0 ? $"Synthetic chapter {chapter}\r" : reuseMode?string.Join(" ",Enumerable.Repeat("synthetic",18))+"\r":$"Synthetic paragraph {rows.Count}: " + new string('x', 420) + "\r";
|
||||
rows.Add(new() { NativeId=reuseMode?(rows.Count+1).ToString("X8"):"", Ordinal = rows.Count, Start = position, End = position + text.Length, Text = text, Outline = n == 0 ? 1 : 10 });
|
||||
position += text.Length;
|
||||
}
|
||||
spans.Add(new() { ChapterId = canonicalChapters[chapter], SceneId = canonicalScenes[chapter], Start = firstOrdinal + 2, End = rows.Count, Title = "Synthetic scene " + chapter });
|
||||
@ -111,6 +112,13 @@ internal static class ChapterAcceptanceDevelopmentTests
|
||||
var evidence = part.Rows.Select(p => new ChapterParagraph { NativeId = p.Occurrence.NativeId.Length > 0 ? p.Occurrence.NativeId : (p.Occurrence.Ordinal + 1).ToString("X8"), Length = p.Occurrence.Text.Length, Outline = p.Occurrence.Outline }).ToArray();
|
||||
return new() { InstanceId = instance, SessionId = session, ManuscriptId = original.ManuscriptId, BaseRevision = state.Revision, ChapterId = part.Chapter.CanonicalId, Start = part.Rows[0].Occurrence.Start, End = part.Rows[^1].Occurrence.End, NextHeadingId = part.End < state.Paragraphs.Count ? (state.Paragraphs[part.End].Occurrence.NativeId.Length > 0 ? state.Paragraphs[part.End].Occurrence.NativeId : (part.End + 1).ToString("X8")) : "", ContentHash = ChapterFingerprint.Content(part.Rows.Select(p => p.Occurrence.Text)), IdentityHash = ChapterFingerprint.Identity(evidence), Paragraphs = evidence };
|
||||
}
|
||||
if(reuseMode)
|
||||
{
|
||||
original.ChapterCheckpoints=ChapterCheckpointEngine.Build(original,original.Revision).ToList();
|
||||
foreach(var c in original.ChapterCheckpoints){c.Status="Synchronised";c.LastSuccessfulSyncUtc=DateTime.UtcNow;}
|
||||
original=await repository.Save(user,original,original.Revision,Guid.NewGuid());
|
||||
Observe();await ChapterReuseDevelopmentTests.Run(user,book,grant,original,service,repository,checkpoints,presence,Proof);return;
|
||||
}
|
||||
Observe();
|
||||
var repair = await service.Repair(user, book, instance, session);
|
||||
var first = Proof(original, 0); first.OperationId = repair;
|
||||
|
||||
64
PlotLine.Tests/ChapterReuseDevelopmentTests.cs
Normal file
64
PlotLine.Tests/ChapterReuseDevelopmentTests.cs
Normal file
@ -0,0 +1,64 @@
|
||||
using System.Diagnostics;
|
||||
using System.Text.Json;
|
||||
using PlotDirector.Companion.Protocol.Manuscript;
|
||||
using PlotLine.Data;
|
||||
using PlotLine.Models;
|
||||
using PlotLine.Services.Manuscript;
|
||||
using PlotLine.Services.NativeCompanion;
|
||||
|
||||
internal static class ChapterReuseDevelopmentTests
|
||||
{
|
||||
public static async Task Run(int user,int book,string grant,ParagraphManuscript state,ChapterSyncService service,IParagraphManuscriptRepository repository,IChapterSyncRepository positions,NativePresenceStore presence,Func<ParagraphManuscript,int,ChapterObservation> proof)
|
||||
{
|
||||
Console.WriteLine($"SCALE chapters=48 paragraphs={state.Paragraphs.Count} words={state.Paragraphs.Sum(p=>p.Occurrence.Text.Split((char[]?)null,StringSplitOptions.RemoveEmptyEntries).Length)}");
|
||||
void Check(bool value,string name){if(!value)throw new Exception(name);Console.WriteLine("PASS "+name);}
|
||||
async Task Refuse(Func<Task> action,string name){try{await action();}catch(Exception e)when(e is InvalidOperationException or ArgumentException or UnauthorizedAccessException or Microsoft.Data.SqlClient.SqlException){Check(true,name);return;}throw new Exception(name);}
|
||||
var first=proof(state,0);var original=JsonSerializer.Serialize(state);var total=Stopwatch.StartNew();
|
||||
var timer=Stopwatch.StartNew();var manifest=await service.Manifest(user,book,first.SessionId,0);var manifestMs=timer.Elapsed.TotalMilliseconds;
|
||||
Check(manifest.CheckpointReuseSupported&&manifest.Chapters.Count(c=>c.DurableAccepted)==48,"Manifest exposes all valid durable checkpoints independently of new-session state");
|
||||
Check(manifest.Chapters.All(c=>c.State!="Synchronised"),"A durable checkpoint alone does not claim current-session readiness");
|
||||
timer.Restart();var observations=Enumerable.Range(0,48).Select(c=>proof(state,c)).ToArray();
|
||||
Check(observations.All(p=>ChapterCheckpointReuse.Matches(manifest.Chapters.Single(c=>c.ChapterId==p.ChapterId),p)),"All 48 native fingerprints directly match accepted manifest evidence");
|
||||
var fingerprintMs=timer.Elapsed.TotalMilliseconds;var bytes=observations.Sum(p=>JsonSerializer.SerializeToUtf8Bytes(p,new JsonSerializerOptions(JsonSerializerDefaults.Web)).Length);
|
||||
timer.Restart();foreach(var p in observations)
|
||||
{
|
||||
presence.Put(user,grant,DateTimeOffset.UtcNow.AddHours(1),p.InstanceId,p.SessionId,new(){BookId=book,ManuscriptId=state.ManuscriptId,Revision=0,Sequence=DateTime.UtcNow.Ticks,WordAvailable=true,WordRunning=true,WordSaved=true,CanChapterSync=true});
|
||||
Check((await service.Accept(user,grant,book,p)).Accepted,"Baseline individual unchanged proof accepted");
|
||||
}
|
||||
var baselineMs=timer.Elapsed.TotalMilliseconds;
|
||||
Console.WriteLine($"MEASURE baseline real Development SQL: manifest={manifestMs:F1}ms fingerprints={fingerprintMs:F1}ms individualRequests=48 reconciliationRequests=0 payloadBytes={bytes} validationRoundTrip={baselineMs:F1}ms total={total.Elapsed.TotalMilliseconds:F1}ms. In-process service plus real SQL, excludes HTTP/Word.");
|
||||
// A different session must establish its own positions; no old source offsets are trusted.
|
||||
var session=Guid.NewGuid();var instance=Guid.NewGuid();
|
||||
void Observe(bool saved=true,long revision=0)=>Check(presence.Put(user,grant,DateTimeOffset.UtcNow.AddHours(1),instance,session,new(){BookId=book,ManuscriptId=state.ManuscriptId,Revision=revision,Sequence=DateTime.UtcNow.Ticks,WordAvailable=true,WordRunning=true,WordSaved=saved,CanChapterSync=true}),"Scoped synthetic presence accepted");
|
||||
Observe();state=(await repository.Get(user,book))!;var beforeReuse=JsonSerializer.Serialize(state);
|
||||
ChapterObservation[] Batch()=>Enumerable.Range(0,48).Select(c=>{var p=proof(state,c);p.InstanceId=instance;p.SessionId=session;return p;}).ToArray();
|
||||
observations=Batch();total.Restart();timer.Restart();manifest=await service.Manifest(user,book,session,0);manifestMs=timer.Elapsed.TotalMilliseconds;
|
||||
timer.Restart();foreach(var p in observations)Check(ChapterCheckpointReuse.Matches(manifest.Chapters.Single(c=>c.ChapterId==p.ChapterId),p),"Corrected local comparison selects checkpoint reuse");fingerprintMs=timer.Elapsed.TotalMilliseconds;
|
||||
var current=new ChapterReuseRequest{Chapters=[observations[0]]};var rest=new ChapterReuseRequest{Chapters=observations.Skip(1).ToArray()};
|
||||
var reused=await service.Reuse(user,grant,book,current);
|
||||
var mapped=ChapterCheckpointEngine.Validate(state,observations[0],DateTime.UtcNow).Positions.First(p=>p.SceneId.HasValue);
|
||||
Check((await positions.Position(user,book,state.ManuscriptId,session,0,mapped.Start))?.SceneID==mapped.SceneId,"Writing Context resolves first reused chapter before the rest of the book is acknowledged");var contextMs=total.Elapsed.TotalMilliseconds;
|
||||
var remainder=await service.Reuse(user,grant,book,rest);
|
||||
Check(reused.ChapterIds.Length+remainder.ChapterIds.Length==48,"Two reuse requests register 48 chapters without any individual acceptance request");
|
||||
var finish=await service.Finish(user,grant,book,new(){InstanceId=instance,SessionId=session,WordRevision=0});
|
||||
Check(finish.State=="Synchronised"&&finish.Matching==48,"Completion independently confirms all reused current-session positions");
|
||||
Check(JsonSerializer.Serialize((await repository.Get(user,book))!)==beforeReuse,"Reuse leaves the entire durable source/checkpoint payload byte-equivalent under typed serialization");
|
||||
Console.WriteLine($"MEASURE corrected real Development SQL: manifest={manifestMs:F1}ms compare={fingerprintMs:F1}ms reuseRequests=2 individualRequests=0 reconciliationRequests=0 reusePayloadBytes={JsonSerializer.SerializeToUtf8Bytes(current).Length+JsonSerializer.SerializeToUtf8Bytes(rest).Length} serverReadWait={reused.ReadMs+remainder.ReadMs:F1}ms serverProcessing={reused.ProcessingMs+remainder.ProcessingMs:F1}ms serverValidation={reused.ValidationMs+remainder.ValidationMs:F1}ms serverPersistence={reused.PersistenceMs+remainder.PersistenceMs:F1}ms context={contextMs:F1}ms total={total.Elapsed.TotalMilliseconds:F1}ms. In-process plus real SQL, excludes HTTP/Word.");
|
||||
await service.Reuse(user,grant,book,rest);Check((await positions.List(user,book,session,0)).Count==48,"Repeated batch acknowledgement is idempotent and supports interrupted resume");
|
||||
var stale=Batch();stale[0].BaseRevision--;await Refuse(()=>service.Reuse(user,grant,book,new(){Chapters=[stale[0]]}),"Stale accepted revision rejects reuse");
|
||||
var renamed=Batch();renamed[0].ContentHash=ChapterFingerprint.Content(["renamed heading\r"]);await Refuse(()=>service.Reuse(user,grant,book,new(){Chapters=[renamed[0]]}),"Changed heading/text cannot enter reuse");
|
||||
var geometry=Batch();geometry[47].PositionHash=new string('A',64);await Refuse(()=>service.Reuse(user,grant,book,new(){Chapters=[geometry[47]]}),"Floating-anchor geometry change without text change requires detailed validation");
|
||||
var shifted=Batch();shifted[0].Start++;shifted[0].End++;await Refuse(()=>service.Reuse(user,grant,book,new(){Chapters=[shifted[0]]}),"Conflicting same-session same-revision positions are refused transactionally");
|
||||
var mixed=Batch();mixed[0].SessionId=Guid.NewGuid();await Refuse(()=>service.Reuse(user,grant,book,new(){Chapters=mixed}),"Copied document cannot inherit another live session's authority");
|
||||
Observe(false);await Refuse(()=>service.Reuse(user,grant,book,current),"Unsaved Word edits cannot reuse checkpoints");Observe();
|
||||
var empty=new ChapterReuseRequest();await Refuse(()=>service.Reuse(user,grant,book,empty),"Missing checkpoint evidence is refused");
|
||||
await Refuse(()=>service.Reuse(user,"foreign-grant",book,current),"Another installation grant cannot reuse a live session");
|
||||
var forged=Batch()[0];forged.SessionId=Guid.NewGuid();var valid=ChapterCheckpointEngine.Validate(state,forged,DateTime.UtcNow);
|
||||
var other=ChapterCheckpointEngine.Validate(state,Batch()[1],DateTime.UtcNow).Positions[0];
|
||||
await Refuse(()=>positions.Reuse(user,book,state,[forged],[new ChapterValidationResult(valid.Checkpoint,[],[..valid.Positions,other])]),"SQL independently rejects an extra cross-chapter position instead of silently filtering it");
|
||||
Check((await positions.List(user,book,forged.SessionId,0)).Count==0,"Rejected position batch leaves no partial session rows");
|
||||
var next=Guid.NewGuid();foreach(var p in observations){p.SessionId=next;p.RequestId=Guid.NewGuid();}
|
||||
Check(presence.Put(user,grant,DateTimeOffset.UtcNow.AddHours(1),instance,next,new(){BookId=book,ManuscriptId=state.ManuscriptId,Revision=0,Sequence=DateTime.UtcNow.Ticks,WordAvailable=true,WordSaved=true,CanChapterSync=true}),"Save As/new-session fixture registered independently");
|
||||
await service.Reuse(user,grant,book,new(){Chapters=[observations[0]]});Check((await positions.List(user,book,next,0)).Count==1,"New Word session reuses durable identity while independently verifying its own positions");
|
||||
}
|
||||
}
|
||||
@ -15,7 +15,7 @@ using PlotLine.Models;
|
||||
using PlotLine.Services;
|
||||
using PlotLine.ViewModels;
|
||||
|
||||
if(args.Contains("--chapter-acceptance-dev")){await ChapterAcceptanceDevelopmentTests.Run(args);return;}
|
||||
if((args.Contains("--chapter-acceptance-dev")||args.Contains("--chapter-reuse-dev"))){await ChapterAcceptanceDevelopmentTests.Run(args);return;}
|
||||
if(args.Contains("--chapter-sync-dev")){await ChapterSyncDevelopmentTests.Run(args);return;}
|
||||
if(args.Contains("--chapter-sync")){ChapterSynchronisationTests.Run();return;}
|
||||
#pragma warning disable CS8321
|
||||
|
||||
@ -17,6 +17,8 @@ public sealed class NativeChapterSyncController(ChapterSyncService chapters,ILog
|
||||
logger?.LogInformation("Native chapter observation received Trace={Trace} Book={Book} Chapter={Chapter} Request={Request} Session={Session}",HttpContext.TraceIdentifier,book,observation.ChapterId,observation.RequestId,observation.SessionId);
|
||||
return await Run(async()=>await chapters.Accept(Author,User.FindFirstValue("NativeCompanion.Grant")??"",book,observation));
|
||||
}
|
||||
[HttpPost("reuse"),RequestSizeLimit(4*1024*1024)]
|
||||
public async Task<IActionResult> Reuse(int book,ChapterReuseRequest request)=>await Run(async()=>await chapters.Reuse(Author,User.FindFirstValue("NativeCompanion.Grant")??"",book,request));
|
||||
[HttpPost("repair")]
|
||||
public async Task<IActionResult> Repair(int book,ChapterFinish selected)=>await Run(async()=>new ChapterRepairRequested{OperationId=await chapters.Repair(Author,book,selected.InstanceId,selected.SessionId,selected.WordRevision),Message="Chapter repair requested; accepted import and author decisions are retained."});
|
||||
[HttpPost("finish")]
|
||||
|
||||
@ -7,6 +7,7 @@ using PlotDirector.Companion.Protocol.Manuscript;
|
||||
namespace PlotLine.Data;
|
||||
public interface IChapterSyncRepository
|
||||
{
|
||||
Task Reuse(int user,int book,ParagraphManuscript state,ChapterObservation[] observations,ChapterValidationResult[] validated)=>throw new NotSupportedException("Checkpoint reuse unavailable.");
|
||||
Task<ChapterSceneAnchor?> SceneStart(int user,int book,int scene,Guid paragraph,Guid manuscript,Guid session,long wordRevision);
|
||||
Task FlagReview(int user,int book,int chapter,long revision);
|
||||
Task<ParagraphManuscript> Accept(int user,int book,ChapterObservation observation,ChapterValidationResult result);
|
||||
@ -17,6 +18,11 @@ public sealed class ChapterSceneAnchor{public long Revision{get;set;}public int
|
||||
public sealed class ChapterLiveValidation{public int ChapterID{get;set;}public int StartPosition{get;set;}public int EndPosition{get;set;}public Guid SessionID{get;set;}public long WordRevision{get;set;}public string ContentHash{get;set;}="";public string IdentityHash{get;set;}="";public string MappingHash{get;set;}="";public long SourceRevision{get;set;}public DateTime ValidatedUtc{get;set;}}
|
||||
public sealed class ChapterSyncRepository(ISqlConnectionFactory factory):IChapterSyncRepository
|
||||
{
|
||||
public async Task Reuse(int user,int book,ParagraphManuscript state,ChapterObservation[] observations,ChapterValidationResult[] validated)
|
||||
{
|
||||
var batch=observations.Select((p,i)=>new{p.ChapterId,p.RequestId,Checkpoint=validated[i].Checkpoint,Positions=validated[i].Positions}).ToArray();
|
||||
using var db=factory.CreateConnection();await db.ExecuteAsync("dbo.BookChapterReuse",new{UserID=user,BookID=book,SessionID=observations[0].SessionId,ManuscriptID=state.ManuscriptId,WordRevision=observations[0].WordRevision,ExpectedRevision=state.Revision,SnapshotHash=state.SnapshotHash,Chapters=JsonSerializer.Serialize(batch)},commandType:CommandType.StoredProcedure);
|
||||
}
|
||||
public async Task<ChapterSceneAnchor?> SceneStart(int user,int book,int scene,Guid paragraph,Guid manuscript,Guid session,long wordRevision){using var db=factory.CreateConnection();return await db.QuerySingleOrDefaultAsync<ChapterSceneAnchor>("dbo.BookChapterSync",new{Action="scene-start",UserID=user,BookID=book,SceneID=scene,ParagraphID=paragraph,ManuscriptID=manuscript,SessionID=session,WordRevision=wordRevision},commandType:CommandType.StoredProcedure);}
|
||||
public async Task FlagReview(int user,int book,int chapter,long revision){using var db=factory.CreateConnection();await db.ExecuteAsync("dbo.BookChapterSync",new{Action="review",UserID=user,BookID=book,ChapterID=chapter,ExpectedRevision=revision},commandType:CommandType.StoredProcedure);}
|
||||
public async Task<ParagraphManuscript> Accept(int user,int book,ChapterObservation observation,ChapterValidationResult result){using var db=factory.CreateConnection();var json=await db.QuerySingleAsync<string>("dbo.BookChapterSync",new{Action="accept",UserID=user,BookID=book,ChapterID=observation.ChapterId,SessionID=observation.SessionId,ManuscriptID=observation.ManuscriptId,WordRevision=observation.WordRevision,ExpectedRevision=observation.BaseRevision,RequestID=observation.RequestId,Checkpoint=JsonSerializer.Serialize(result.Checkpoint),Positions=JsonSerializer.Serialize(result.Positions),Bindings=JsonSerializer.Serialize(result.Bindings),SnapshotHash=result.AdoptedSnapshotHash},commandType:CommandType.StoredProcedure);return JsonSerializer.Deserialize<ParagraphManuscript>(json)!;}
|
||||
|
||||
@ -42,17 +42,17 @@ public static class ChapterCheckpointEngine
|
||||
}).ToArray();
|
||||
}
|
||||
private static ChapterParagraph[] Evidence(ChapterPart part)=>part.Rows.Select(p=>new ChapterParagraph{NativeId=p.Occurrence.NativeId,Length=p.Occurrence.Text.Length,Outline=p.Occurrence.Outline}).ToArray();
|
||||
public static ChapterValidationResult Validate(ParagraphManuscript state,ChapterObservation proof,DateTime now)
|
||||
public static ChapterValidationResult Validate(ParagraphManuscript state,ChapterObservation proof,DateTime now,ChapterValidationIndex? index=null)
|
||||
{
|
||||
if(proof.Algorithm!=ChapterFingerprint.Version||proof.RequestId==Guid.Empty||proof.ManuscriptId!=state.ManuscriptId||proof.BaseRevision!=state.Revision||proof.SessionId==Guid.Empty||proof.WordRevision<0||proof.Start<0||proof.End<=proof.Start||proof.Paragraphs==null||proof.Paragraphs.Length==0)throw new InvalidOperationException("Stale or unsupported chapter evidence.");
|
||||
var part=Parts(state).SingleOrDefault(p=>p.Chapter.CanonicalId==proof.ChapterId)??throw new InvalidOperationException("The chapter is not in the accepted manuscript index.");
|
||||
var part=(index?.Parts??Parts(state)).SingleOrDefault(p=>p.Chapter.CanonicalId==proof.ChapterId)??throw new InvalidOperationException("The chapter is not in the accepted manuscript index.");
|
||||
if(part.Rows.Any(p=>p.ChapterId>0&&p.ChapterId!=proof.ChapterId))throw new InvalidOperationException("Existing chapter assignments disagree with chapter boundaries; review is required.");
|
||||
var identity=ChapterFingerprint.Identity(proof.Paragraphs);
|
||||
ChapterWordPositions.Validate(proof.Paragraphs,proof.Start,proof.End,proof.PositionHash);
|
||||
if(identity!=proof.IdentityHash)throw new ArgumentException("Chapter identity/position evidence is incomplete.");
|
||||
var all=Build(state,state.Revision);var checkpoint=all.Single(p=>p.ChapterId==proof.ChapterId);
|
||||
var all=index?.Checkpoints??Build(state,state.Revision);var checkpoint=System.Text.Json.JsonSerializer.Deserialize<ChapterCheckpoint>(System.Text.Json.JsonSerializer.Serialize(all.Single(p=>p.ChapterId==proof.ChapterId)))!;
|
||||
if(checkpoint.ContentHash!=proof.ContentHash||part.Rows.Length!=proof.Paragraphs.Length)throw new InvalidOperationException("Changed chapter; bounded chapter reconciliation is required. Accepted mappings are unchanged.");
|
||||
var nativeOwners=state.Paragraphs.Where(p=>p.Occurrence.NativeId!="").GroupBy(p=>p.Occurrence.NativeId).ToDictionary(g=>g.Key,g=>g.Select(p=>p.Occurrence.Id).ToHashSet());
|
||||
var nativeOwners=index?.NativeOwners??state.Paragraphs.Where(p=>p.Occurrence.NativeId!="").GroupBy(p=>p.Occurrence.NativeId).ToDictionary(g=>g.Key,g=>g.Select(p=>p.Occurrence.Id).ToHashSet());
|
||||
var bindings=new List<NativeParagraphBinding>();
|
||||
for(int n=0;n<part.Rows.Length;n++){
|
||||
var accepted=part.Rows[n].Occurrence;var observed=proof.Paragraphs[n];
|
||||
@ -87,3 +87,14 @@ public static class ChapterCheckpointEngine
|
||||
return rows;
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class ChapterValidationIndex
|
||||
{
|
||||
public ChapterPart[] Parts{get;}public ChapterCheckpoint[] Checkpoints{get;}
|
||||
public Dictionary<string,HashSet<Guid>> NativeOwners{get;}
|
||||
public ChapterValidationIndex(ParagraphManuscript state)
|
||||
{
|
||||
Parts=ChapterCheckpointEngine.Parts(state);Checkpoints=ChapterCheckpointEngine.Build(state,state.Revision);
|
||||
NativeOwners=state.Paragraphs.Where(p=>p.Occurrence.NativeId!="").GroupBy(p=>p.Occurrence.NativeId).ToDictionary(g=>g.Key,g=>g.Select(p=>p.Occurrence.Id).ToHashSet());
|
||||
}
|
||||
}
|
||||
|
||||
@ -12,14 +12,49 @@ public sealed class ChapterSyncService(IParagraphManuscriptRepository manuscript
|
||||
if(await access.GetBookStructureAsync(book,user)==null)throw new UnauthorizedAccessException();
|
||||
var state=await manuscripts.Get(user,book)??throw new InvalidOperationException("Finish the existing manuscript import first; no saved index is available.");
|
||||
var live=await checkpoints.List(user,book,session,wordRevision);var sources=ChapterCheckpointEngine.Build(state,state.Revision);
|
||||
var manifest=new ChapterManifest(){NativePositionsSupported=true,BookId=book,ManuscriptId=state.ManuscriptId,Revision=state.Revision,Mode=state.Mode,Chapters=ChapterCheckpointEngine.Parts(state).Select(part=>{
|
||||
var manifest=new ChapterManifest(){CheckpointReuseSupported=true,NativePositionsSupported=true,BookId=book,ManuscriptId=state.ManuscriptId,Revision=state.Revision,Mode=state.Mode,Chapters=ChapterCheckpointEngine.Parts(state).Select(part=>{
|
||||
var source=sources.Single(c=>c.ChapterId==part.Chapter.CanonicalId);var accepted=live.FirstOrDefault(c=>c.ChapterID==source.ChapterId&&c.ContentHash==source.ContentHash&&c.IdentityHash==source.IdentityHash&&c.MappingHash==source.MappingHash);
|
||||
return new ChapterManifestItem{ChapterId=source.ChapterId,Title=part.Chapter.Title,HeadingNativeId=source.NativeHeadingId,ContentHash=source.ContentHash,IdentityHash=source.IdentityHash,Start=accepted?.StartPosition??part.Rows[0].Occurrence.Start,End=accepted?.EndPosition??part.Rows[^1].Occurrence.End,ParagraphCount=source.ParagraphCount,State=accepted!=null&&source.Status!="Needs review"?"Synchronised":source.Status};
|
||||
var durable=state.ChapterCheckpoints.FirstOrDefault(c=>c.ChapterId==source.ChapterId&&c.Status=="Synchronised"&&c.ContentHash==source.ContentHash&&c.IdentityHash==source.IdentityHash&&c.MappingHash==source.MappingHash&&c.NextHeadingId==source.NextHeadingId&&c.Algorithm==ChapterFingerprint.Version);
|
||||
return new ChapterManifestItem{DurableAccepted=durable!=null&&source.Status!="Needs review",Algorithm=source.Algorithm,AcceptedRevision=source.AcceptedRevision,Order=source.Order,MappingHash=source.MappingHash,PositionHash=source.PositionHash,NextHeadingId=source.NextHeadingId,ChapterId=source.ChapterId,Title=part.Chapter.Title,HeadingNativeId=source.NativeHeadingId,ContentHash=source.ContentHash,IdentityHash=source.IdentityHash,Start=accepted?.StartPosition??part.Rows[0].Occurrence.Start,End=accepted?.EndPosition??part.Rows[^1].Occurrence.End,ParagraphCount=source.ParagraphCount,State=accepted!=null&&source.Status!="Needs review"?"Synchronised":source.Status};
|
||||
}).ToArray()};
|
||||
var lease=presence.Read(user,book).SingleOrDefault(l=>l.Session==session&&l.Position.Revision==wordRevision&&l.Position.CanChapterSync);
|
||||
if(lease!=null){var count=manifest.Chapters.Count(c=>c.State=="Synchronised");presence.RecordChapterProgress(user,book,lease.Instance,session,wordRevision,new(){Total=manifest.Chapters.Length,Checked=count,Matching=count,Repaired=presence.RepairedChapters(user,book,lease.Instance,session,wordRevision),State="Checking",Message=$"{count}/{manifest.Chapters.Length} chapter mappings accepted for this session."});}
|
||||
return manifest;
|
||||
}
|
||||
public async Task<ChapterReuseReply> Reuse(int user,string grant,int book,ChapterReuseRequest request)
|
||||
{
|
||||
RequireFeature();var timer=System.Diagnostics.Stopwatch.StartNew();
|
||||
var proofs=request?.Chapters??[];
|
||||
if(proofs.Length==0||proofs.Length>256||proofs.Any(p=>p==null||p.Paragraphs==null||p.Paragraphs.Length==0||p.Paragraphs.Length>ChapterFingerprint.MaxParagraphs||p.Paragraphs.Any(r=>r==null||r.Text!=null)||p.Reconcile)||proofs.Sum(p=>(long)p.Paragraphs.Length)>100000||proofs.Select(p=>p.ChapterId).Distinct().Count()!=proofs.Length||proofs.Select(p=>p.RequestId).Distinct().Count()!=proofs.Length)throw new ArgumentException("Complete bounded metadata-only reuse proofs are required.");
|
||||
if(await access.GetBookStructureAsync(book,user)==null)throw new UnauthorizedAccessException();
|
||||
var status=await manuscripts.Status(user,book);if(status?.CanWrite!=true)throw new UnauthorizedAccessException();if(status.Paused)throw new InvalidOperationException("Existing import or analysis is active.");
|
||||
void RequireLease()
|
||||
{
|
||||
if(proofs.Any(p=>!presence.Read(user,book).Any(l=>l.Grant==grant&&l.Instance==p.InstanceId&&l.Session==p.SessionId&&l.Position.CanChapterSync&&l.Position.WordAvailable&&l.Position.WordSaved==true&&l.Position.ManuscriptId==p.ManuscriptId&&l.Position.Revision==p.WordRevision)))throw new InvalidOperationException("Word document changed or disconnected during checkpoint reuse.");
|
||||
}
|
||||
RequireLease();var state=await manuscripts.Get(user,book)??throw new InvalidOperationException("Missing manuscript.");
|
||||
var first=proofs[0];
|
||||
if(proofs.Any(p=>p.InstanceId!=first.InstanceId||p.SessionId!=first.SessionId||p.WordRevision!=first.WordRevision||p.ManuscriptId!=state.ManuscriptId||p.BaseRevision!=state.Revision))throw new InvalidOperationException("Stale or mixed-session checkpoint reuse.");
|
||||
var readMs=timer.Elapsed.TotalMilliseconds;var processing=System.Diagnostics.Stopwatch.StartNew();
|
||||
var index=new ChapterValidationIndex(state);var validated=new List<ChapterValidationResult>();
|
||||
foreach(var proof in proofs)
|
||||
{
|
||||
var source=index.Checkpoints.SingleOrDefault(c=>c.ChapterId==proof.ChapterId)??throw new InvalidOperationException("Unknown chapter.");
|
||||
var durable=state.ChapterCheckpoints.SingleOrDefault(c=>c.ChapterId==proof.ChapterId);
|
||||
if(durable==null||durable.Status!="Synchronised"||source.Status=="Needs review"||durable.Algorithm!=proof.Algorithm||source.ContentHash!=proof.ContentHash||source.IdentityHash!=proof.IdentityHash||durable.ContentHash!=source.ContentHash||durable.IdentityHash!=source.IdentityHash||durable.MappingHash!=source.MappingHash||durable.NextHeadingId!=proof.NextHeadingId||durable.PositionHash!=proof.PositionHash)throw new InvalidOperationException("Checkpoint changed or needs detailed validation; refresh the manifest.");
|
||||
var value=ChapterCheckpointEngine.Validate(state,proof,clock.GetUtcNow().UtcDateTime,index);
|
||||
if(value.Bindings.Length!=0||value.Checkpoint.Status!="Synchronised")throw new InvalidOperationException("Checkpoint requires detailed acceptance.");
|
||||
validated.Add(value);
|
||||
}
|
||||
var ordered=validated.Select(v=>(Start:v.Positions[0].Start,End:v.Positions[^1].End)).OrderBy(v=>v.Start).ToArray();
|
||||
for(var i=1;i<ordered.Length;i++)if(ordered[i].Start<ordered[i-1].End)throw new InvalidOperationException("Overlapping chapter evidence.");
|
||||
var processingMs=processing.Elapsed.TotalMilliseconds;RequireLease();var validation=timer.Elapsed.TotalMilliseconds;timer.Restart();
|
||||
await checkpoints.Reuse(user,book,state,proofs,validated.ToArray());
|
||||
RequireLease();
|
||||
logger?.LogInformation("Chapter checkpoint reuse Book={Book} Session={Session} Count={Count} ValidationMs={ValidationMs} PersistenceMs={PersistenceMs}",book,first.SessionId,proofs.Length,validation,timer.Elapsed.TotalMilliseconds);
|
||||
return new(){ChapterIds=proofs.Select(p=>p.ChapterId).ToArray(),Revision=state.Revision,ReadMs=readMs,ProcessingMs=processingMs,ValidationMs=validation,PersistenceMs=timer.Elapsed.TotalMilliseconds};
|
||||
}
|
||||
|
||||
public async Task<ChapterSyncProgress> Finish(int user,string grant,int book,ChapterFinish completion)
|
||||
{
|
||||
RequireFeature();
|
||||
@ -74,6 +109,7 @@ public sealed class ChapterSyncService(IParagraphManuscriptRepository manuscript
|
||||
if(presence.Read(user,book).Count(l=>l.Position.WordAvailable&&l.Position.ManuscriptId==proof.ManuscriptId)>1)throw new InvalidOperationException("Competing Word copies are connected to this book. Close the other copy before reconciling changed prose; existing mappings are preserved.");
|
||||
stage="reconciliation";
|
||||
state=await reconciliation.ReconcileChapter(user,book,proof);proof.BaseRevision=state.Revision;
|
||||
logger?.LogInformation("Chapter reconciliation persisted Book={Book} Chapter={Chapter} Request={Request} Session={Session} Revision={Revision} ElapsedMs={ElapsedMs}",book,proof.ChapterId,proof.RequestId,proof.SessionId,state.Revision,elapsed.ElapsedMilliseconds);
|
||||
}
|
||||
// Native adoption is explicit repair only; ordinary hash checks cannot mint trust.
|
||||
proof.Reconcile=presence.CanRepairChapter(user,lease,proof.OperationId);
|
||||
|
||||
61
PlotLine/Sql/251_ChapterCheckpointReuse.sql
Normal file
61
PlotLine/Sql/251_ChapterCheckpointReuse.sql
Normal file
@ -0,0 +1,61 @@
|
||||
-- Register fresh session positions for already accepted checkpoints without rewriting source JSON.
|
||||
SET ANSI_NULLS ON;
|
||||
SET QUOTED_IDENTIFIER ON;
|
||||
GO
|
||||
CREATE OR ALTER PROCEDURE dbo.BookChapterReuse
|
||||
@UserID int,@BookID int,@SessionID uniqueidentifier,@ManuscriptID uniqueidentifier,@WordRevision bigint,
|
||||
@ExpectedRevision bigint,@SnapshotHash char(64),@Chapters nvarchar(max)
|
||||
AS
|
||||
BEGIN
|
||||
SET NOCOUNT ON;SET XACT_ABORT ON;
|
||||
IF @SessionID IS NULL OR @ManuscriptID IS NULL OR @WordRevision IS NULL OR @WordRevision<0 OR @ExpectedRevision IS NULL OR @SnapshotHash IS NULL
|
||||
OR ISJSON(@Chapters)<>1 OR DATALENGTH(@Chapters)>8*1024*1024 THROW 51000,'Invalid checkpoint reuse evidence',1;
|
||||
IF NOT EXISTS(SELECT 1 FROM dbo.Books b JOIN dbo.ProjectUserAccess a ON a.ProjectID=b.ProjectID AND a.UserID=@UserID AND a.IsActive=1 AND a.AccessRole=N'Owner' WHERE b.BookID=@BookID) THROW 51000,'Project owner authority required',1;
|
||||
IF EXISTS(SELECT 1 FROM dbo.UserOnboardingState WHERE BookID=@BookID AND OnboardingCompletedUtc IS NULL)
|
||||
OR EXISTS(SELECT 1 FROM dbo.StoryIntelligenceJobs WHERE BookID=@BookID AND Status IN ('Pending','Queued','Running','Processing','Preparing','ReadingScenes','AnalysingCharacters','AnalysingRelationships','AnalysingLocations','AnalysingAssets','AnalysingTimeline','Finalising')) THROW 51000,'Active import or analysis protected',1;
|
||||
BEGIN TRANSACTION;
|
||||
DECLARE @Payload nvarchar(max),@Revision bigint;
|
||||
SELECT @Payload=Payload,@Revision=Revision FROM dbo.BookParagraphManuscripts WITH(UPDLOCK,HOLDLOCK) WHERE BookID=@BookID;
|
||||
IF @Revision IS NULL OR @Revision<>@ExpectedRevision OR ISNULL(JSON_VALUE(@Payload,'$.SnapshotHash'),'')<>@SnapshotHash OR TRY_CONVERT(uniqueidentifier,JSON_VALUE(@Payload,'$.ManuscriptId'))<>@ManuscriptID THROW 51000,'Accepted manuscript changed; reuse refused',1;
|
||||
DECLARE @Batch TABLE(ChapterID int PRIMARY KEY,RequestID uniqueidentifier UNIQUE,ContentHash char(64),IdentityHash char(64),MappingHash char(64),PositionHash varchar(64),NextHeadingID varchar(8),Positions nvarchar(max),StartPosition int,EndPosition int);
|
||||
INSERT @Batch
|
||||
SELECT ChapterId,RequestId,ContentHash,IdentityHash,MappingHash,COALESCE(PositionHash,''),COALESCE(NextHeadingID,''),Positions,p.StartPosition,p.EndPosition
|
||||
FROM OPENJSON(@Chapters) WITH(ChapterId int,RequestId uniqueidentifier,ContentHash char(64) '$.Checkpoint.ContentHash',IdentityHash char(64) '$.Checkpoint.IdentityHash',MappingHash char(64) '$.Checkpoint.MappingHash',PositionHash varchar(64) '$.Checkpoint.PositionHash',NextHeadingID varchar(8) '$.Checkpoint.NextHeadingId',Positions nvarchar(max) AS JSON) b
|
||||
CROSS APPLY(SELECT MIN(StartPosition) StartPosition,MAX(EndPosition) EndPosition FROM OPENJSON(b.Positions) WITH(StartPosition int '$.Start',EndPosition int '$.End')) p;
|
||||
IF (SELECT COUNT(*) FROM @Batch) NOT BETWEEN 1 AND 256 OR EXISTS(SELECT 1 FROM @Batch WHERE RequestID IS NULL OR StartPosition IS NULL OR EndPosition IS NULL OR StartPosition<0 OR EndPosition<=StartPosition) THROW 51000,'Incomplete chapter reuse batch',1;
|
||||
-- Materialise accepted checkpoint and paragraph indices exactly once per bounded batch.
|
||||
DECLARE @Sources TABLE(ChapterID int PRIMARY KEY,ContentHash char(64),IdentityHash char(64),MappingHash char(64),PositionHash varchar(64),NextHeadingID varchar(8),Status varchar(50));
|
||||
INSERT @Sources SELECT ChapterId,ContentHash,IdentityHash,MappingHash,COALESCE(PositionHash,''),COALESCE(NextHeadingId,''),Status
|
||||
FROM OPENJSON(@Payload,'$.ChapterCheckpoints') WITH(ChapterId int,ContentHash char(64),IdentityHash char(64),MappingHash char(64),PositionHash varchar(64),NextHeadingId varchar(8),Status varchar(50));
|
||||
IF EXISTS(SELECT 1 FROM @Batch b LEFT JOIN @Sources c ON c.ChapterID=b.ChapterID LEFT JOIN dbo.Chapters ch ON ch.ChapterID=b.ChapterID AND ch.BookID=@BookID AND ch.IsArchived=0
|
||||
WHERE ch.ChapterID IS NULL OR c.ChapterID IS NULL OR c.Status<>'Synchronised' OR b.ContentHash IS NULL OR b.IdentityHash IS NULL OR b.MappingHash IS NULL OR c.ContentHash<>b.ContentHash OR c.IdentityHash<>b.IdentityHash OR c.MappingHash<>b.MappingHash OR c.PositionHash<>b.PositionHash OR c.NextHeadingID<>b.NextHeadingID) THROW 51000,'Checkpoint no longer reusable',1;
|
||||
DECLARE @Scenes TABLE(SceneGUID uniqueidentifier PRIMARY KEY,ChapterID int,CanonicalID int);
|
||||
INSERT @Scenes SELECT Id,ChapterID,CASE WHEN CanonicalID>0 THEN CanonicalID END FROM OPENJSON(@Payload,'$.Scenes') WITH(Id uniqueidentifier,CanonicalID int '$.CanonicalId',ChapterID int '$.ChapterId',Retired bit) WHERE Retired=0;
|
||||
DECLARE @Accepted TABLE(ParagraphID uniqueidentifier PRIMARY KEY,ChapterID int,SceneID int,Verified bit);
|
||||
INSERT @Accepted SELECT p.ParagraphID,p.ChapterID,s.CanonicalID,p.Verified
|
||||
FROM OPENJSON(@Payload,'$.Paragraphs') WITH(ParagraphID uniqueidentifier '$.Occurrence.Id',ChapterID int '$.ChapterId',SceneGUID uniqueidentifier '$.SceneId',Verified bit '$.PositionVerified') p
|
||||
LEFT JOIN @Scenes s ON s.SceneGUID=p.SceneGUID AND s.ChapterID=p.ChapterID;
|
||||
DECLARE @Positions TABLE(ChapterID int,ParagraphID uniqueidentifier PRIMARY KEY,StartPosition int,EndPosition int,SceneID int,Verified bit);
|
||||
INSERT @Positions SELECT b.ChapterID,p.ParagraphID,p.StartPosition,p.EndPosition,p.SceneID,p.Verified FROM @Batch b
|
||||
CROSS APPLY OPENJSON(b.Positions) WITH(ParagraphID uniqueidentifier '$.ParagraphId',ChapterID int '$.ChapterId',StartPosition int '$.Start',EndPosition int '$.End',SceneID int '$.SceneId',Verified bit) p
|
||||
WHERE p.ChapterID=b.ChapterID;
|
||||
IF (SELECT COUNT(*) FROM @Positions)>100000 OR EXISTS(SELECT 1 FROM @Positions p LEFT JOIN @Accepted a ON a.ParagraphID=p.ParagraphID WHERE a.ParagraphID IS NULL OR a.ChapterID<>p.ChapterID OR p.StartPosition<0 OR p.EndPosition<=p.StartPosition OR p.StartPosition IS NULL OR p.EndPosition IS NULL OR p.Verified IS NULL OR p.Verified<>a.Verified OR ISNULL(p.SceneID,-1)<>ISNULL(a.SceneID,-1))
|
||||
OR EXISTS(SELECT 1 FROM @Batch b WHERE (SELECT COUNT(*) FROM @Positions p WHERE p.ChapterID=b.ChapterID)<>(SELECT COUNT(*) FROM @Accepted a WHERE a.ChapterID=b.ChapterID)) THROW 51000,'Incomplete or conflicting canonical paragraph positions',1;
|
||||
IF EXISTS(SELECT 1 FROM (SELECT ChapterID,StartPosition,LAG(EndPosition) OVER(PARTITION BY ChapterID ORDER BY StartPosition) PriorEnd FROM @Positions) p WHERE PriorEnd IS NOT NULL AND StartPosition<>PriorEnd)
|
||||
OR EXISTS(SELECT 1 FROM @Batch a JOIN @Batch b ON a.ChapterID<b.ChapterID AND a.StartPosition<b.EndPosition AND a.EndPosition>b.StartPosition) THROW 51000,'Noncontiguous or overlapping chapter positions',1;
|
||||
DECLARE @Prior TABLE(ChapterID int PRIMARY KEY,WordRevision bigint,ContentHash char(64),IdentityHash char(64),MappingHash char(64),Positions nvarchar(max),StartPosition int,EndPosition int);
|
||||
INSERT @Prior SELECT v.ChapterID,v.WordRevision,v.ContentHash,v.IdentityHash,v.MappingHash,v.Positions,p.StartPosition,p.EndPosition FROM dbo.BookChapterValidations v
|
||||
CROSS APPLY(SELECT MIN(StartPosition) StartPosition,MAX(EndPosition) EndPosition FROM OPENJSON(v.Positions) WITH(StartPosition int '$.Start',EndPosition int '$.End')) p
|
||||
WHERE v.BookID=@BookID AND v.UserID=@UserID AND v.SessionID=@SessionID AND v.ExpiresUtc>SYSUTCDATETIME();
|
||||
IF EXISTS(SELECT 1 FROM @Prior a JOIN @Batch b ON a.ChapterID<>b.ChapterID AND a.WordRevision=@WordRevision AND a.StartPosition<b.EndPosition AND a.EndPosition>b.StartPosition)
|
||||
OR EXISTS(SELECT 1 FROM @Prior a JOIN @Batch b ON a.ChapterID=b.ChapterID AND a.WordRevision=@WordRevision WHERE a.ContentHash<>b.ContentHash OR a.IdentityHash<>b.IdentityHash OR a.MappingHash<>b.MappingHash OR a.Positions<>b.Positions)
|
||||
OR EXISTS(SELECT 1 FROM dbo.BookChapterValidations v JOIN @Batch b ON b.RequestID=v.RequestID WHERE v.BookID=@BookID AND v.UserID=@UserID AND (v.ChapterID<>b.ChapterID OR v.SessionID<>@SessionID OR v.WordRevision<>@WordRevision OR v.Positions<>b.Positions)) THROW 51000,'Conflicting evidence for the same live Word revision',1;
|
||||
DELETE dbo.BookChapterValidations WHERE BookID=@BookID AND ExpiresUtc<SYSUTCDATETIME();
|
||||
UPDATE v SET ManuscriptID=@ManuscriptID,WordRevision=@WordRevision,RequestID=b.RequestID,ContentHash=b.ContentHash,IdentityHash=b.IdentityHash,MappingHash=b.MappingHash,Positions=b.Positions,SourceRevision=@Revision,ValidatedUtc=SYSUTCDATETIME(),ExpiresUtc=DATEADD(hour,12,SYSUTCDATETIME())
|
||||
FROM dbo.BookChapterValidations v JOIN @Batch b ON b.ChapterID=v.ChapterID WHERE v.BookID=@BookID AND v.UserID=@UserID AND v.SessionID=@SessionID;
|
||||
INSERT dbo.BookChapterValidations(BookID,ChapterID,UserID,SessionID,ManuscriptID,WordRevision,RequestID,ContentHash,IdentityHash,MappingHash,Positions,SourceRevision,ValidatedUtc,ExpiresUtc)
|
||||
SELECT @BookID,b.ChapterID,@UserID,@SessionID,@ManuscriptID,@WordRevision,b.RequestID,b.ContentHash,b.IdentityHash,b.MappingHash,b.Positions,@Revision,SYSUTCDATETIME(),DATEADD(hour,12,SYSUTCDATETIME()) FROM @Batch b
|
||||
WHERE NOT EXISTS(SELECT 1 FROM dbo.BookChapterValidations v WHERE v.BookID=@BookID AND v.ChapterID=b.ChapterID AND v.UserID=@UserID AND v.SessionID=@SessionID);
|
||||
COMMIT;
|
||||
END;
|
||||
GO
|
||||
62
PlotLine/Sql/252_ChapterReuseStrictPositionRows.sql
Normal file
62
PlotLine/Sql/252_ChapterReuseStrictPositionRows.sql
Normal file
@ -0,0 +1,62 @@
|
||||
-- Forward hardening: reject cross-chapter/extra position rows before storing the original batch JSON.
|
||||
-- Migration 251 is retained unchanged; no source manuscript or checkpoint is rewritten.
|
||||
SET ANSI_NULLS ON;
|
||||
SET QUOTED_IDENTIFIER ON;
|
||||
GO
|
||||
CREATE OR ALTER PROCEDURE dbo.BookChapterReuse
|
||||
@UserID int,@BookID int,@SessionID uniqueidentifier,@ManuscriptID uniqueidentifier,@WordRevision bigint,
|
||||
@ExpectedRevision bigint,@SnapshotHash char(64),@Chapters nvarchar(max)
|
||||
AS
|
||||
BEGIN
|
||||
SET NOCOUNT ON;SET XACT_ABORT ON;
|
||||
IF @SessionID IS NULL OR @ManuscriptID IS NULL OR @WordRevision IS NULL OR @WordRevision<0 OR @ExpectedRevision IS NULL OR @SnapshotHash IS NULL
|
||||
OR ISJSON(@Chapters)<>1 OR DATALENGTH(@Chapters)>8*1024*1024 THROW 51000,'Invalid checkpoint reuse evidence',1;
|
||||
IF NOT EXISTS(SELECT 1 FROM dbo.Books b JOIN dbo.ProjectUserAccess a ON a.ProjectID=b.ProjectID AND a.UserID=@UserID AND a.IsActive=1 AND a.AccessRole=N'Owner' WHERE b.BookID=@BookID) THROW 51000,'Project owner authority required',1;
|
||||
IF EXISTS(SELECT 1 FROM dbo.UserOnboardingState WHERE BookID=@BookID AND OnboardingCompletedUtc IS NULL)
|
||||
OR EXISTS(SELECT 1 FROM dbo.StoryIntelligenceJobs WHERE BookID=@BookID AND Status IN ('Pending','Queued','Running','Processing','Preparing','ReadingScenes','AnalysingCharacters','AnalysingRelationships','AnalysingLocations','AnalysingAssets','AnalysingTimeline','Finalising')) THROW 51000,'Active import or analysis protected',1;
|
||||
BEGIN TRANSACTION;
|
||||
DECLARE @Payload nvarchar(max),@Revision bigint;
|
||||
SELECT @Payload=Payload,@Revision=Revision FROM dbo.BookParagraphManuscripts WITH(UPDLOCK,HOLDLOCK) WHERE BookID=@BookID;
|
||||
IF @Revision IS NULL OR @Revision<>@ExpectedRevision OR ISNULL(JSON_VALUE(@Payload,'$.SnapshotHash'),'')<>@SnapshotHash OR TRY_CONVERT(uniqueidentifier,JSON_VALUE(@Payload,'$.ManuscriptId'))<>@ManuscriptID THROW 51000,'Accepted manuscript changed; reuse refused',1;
|
||||
DECLARE @Batch TABLE(ChapterID int PRIMARY KEY,RequestID uniqueidentifier UNIQUE,ContentHash char(64),IdentityHash char(64),MappingHash char(64),PositionHash varchar(64),NextHeadingID varchar(8),Positions nvarchar(max),StartPosition int,EndPosition int);
|
||||
INSERT @Batch
|
||||
SELECT ChapterId,RequestId,ContentHash,IdentityHash,MappingHash,COALESCE(PositionHash,''),COALESCE(NextHeadingID,''),Positions,p.StartPosition,p.EndPosition
|
||||
FROM OPENJSON(@Chapters) WITH(ChapterId int,RequestId uniqueidentifier,ContentHash char(64) '$.Checkpoint.ContentHash',IdentityHash char(64) '$.Checkpoint.IdentityHash',MappingHash char(64) '$.Checkpoint.MappingHash',PositionHash varchar(64) '$.Checkpoint.PositionHash',NextHeadingID varchar(8) '$.Checkpoint.NextHeadingId',Positions nvarchar(max) AS JSON) b
|
||||
CROSS APPLY(SELECT MIN(StartPosition) StartPosition,MAX(EndPosition) EndPosition FROM OPENJSON(b.Positions) WITH(StartPosition int '$.Start',EndPosition int '$.End')) p;
|
||||
IF (SELECT COUNT(*) FROM @Batch) NOT BETWEEN 1 AND 256 OR EXISTS(SELECT 1 FROM @Batch WHERE RequestID IS NULL OR StartPosition IS NULL OR EndPosition IS NULL OR StartPosition<0 OR EndPosition<=StartPosition) THROW 51000,'Incomplete chapter reuse batch',1;
|
||||
-- Materialise accepted checkpoint and paragraph indices exactly once per bounded batch.
|
||||
DECLARE @Sources TABLE(ChapterID int PRIMARY KEY,ContentHash char(64),IdentityHash char(64),MappingHash char(64),PositionHash varchar(64),NextHeadingID varchar(8),Status varchar(50));
|
||||
INSERT @Sources SELECT ChapterId,ContentHash,IdentityHash,MappingHash,COALESCE(PositionHash,''),COALESCE(NextHeadingId,''),Status
|
||||
FROM OPENJSON(@Payload,'$.ChapterCheckpoints') WITH(ChapterId int,ContentHash char(64),IdentityHash char(64),MappingHash char(64),PositionHash varchar(64),NextHeadingId varchar(8),Status varchar(50));
|
||||
IF EXISTS(SELECT 1 FROM @Batch b LEFT JOIN @Sources c ON c.ChapterID=b.ChapterID LEFT JOIN dbo.Chapters ch ON ch.ChapterID=b.ChapterID AND ch.BookID=@BookID AND ch.IsArchived=0
|
||||
WHERE ch.ChapterID IS NULL OR c.ChapterID IS NULL OR ISNULL(c.Status,'')<>'Synchronised' OR b.ContentHash IS NULL OR b.IdentityHash IS NULL OR b.MappingHash IS NULL OR c.ContentHash<>b.ContentHash OR c.IdentityHash<>b.IdentityHash OR c.MappingHash<>b.MappingHash OR c.PositionHash<>b.PositionHash OR c.NextHeadingID<>b.NextHeadingID) THROW 51000,'Checkpoint no longer reusable',1;
|
||||
DECLARE @Scenes TABLE(SceneGUID uniqueidentifier PRIMARY KEY,ChapterID int,CanonicalID int);
|
||||
INSERT @Scenes SELECT Id,ChapterID,CASE WHEN CanonicalID>0 THEN CanonicalID END FROM OPENJSON(@Payload,'$.Scenes') WITH(Id uniqueidentifier,CanonicalID int '$.CanonicalId',ChapterID int '$.ChapterId',Retired bit) WHERE Retired=0;
|
||||
DECLARE @Accepted TABLE(ParagraphID uniqueidentifier PRIMARY KEY,ChapterID int,SceneID int,Verified bit);
|
||||
INSERT @Accepted SELECT p.ParagraphID,p.ChapterID,s.CanonicalID,p.Verified
|
||||
FROM OPENJSON(@Payload,'$.Paragraphs') WITH(ParagraphID uniqueidentifier '$.Occurrence.Id',ChapterID int '$.ChapterId',SceneGUID uniqueidentifier '$.SceneId',Verified bit '$.PositionVerified') p
|
||||
LEFT JOIN @Scenes s ON s.SceneGUID=p.SceneGUID AND s.ChapterID=p.ChapterID;
|
||||
IF EXISTS(SELECT 1 FROM @Batch b CROSS APPLY OPENJSON(b.Positions) WITH(ParagraphID uniqueidentifier '$.ParagraphId',ChapterID int '$.ChapterId',StartPosition int '$.Start',EndPosition int '$.End') p WHERE p.ParagraphID IS NULL OR p.ChapterID IS NULL OR p.ChapterID<>b.ChapterID OR p.StartPosition IS NULL OR p.EndPosition IS NULL OR p.StartPosition<0 OR p.EndPosition<=p.StartPosition) THROW 51000,'Cross-chapter or invalid position row',1;
|
||||
DECLARE @Positions TABLE(ChapterID int,ParagraphID uniqueidentifier PRIMARY KEY,StartPosition int,EndPosition int,SceneID int,Verified bit);
|
||||
INSERT @Positions SELECT b.ChapterID,p.ParagraphID,p.StartPosition,p.EndPosition,p.SceneID,p.Verified FROM @Batch b
|
||||
CROSS APPLY OPENJSON(b.Positions) WITH(ParagraphID uniqueidentifier '$.ParagraphId',ChapterID int '$.ChapterId',StartPosition int '$.Start',EndPosition int '$.End',SceneID int '$.SceneId',Verified bit) p;
|
||||
IF (SELECT COUNT(*) FROM @Positions)>100000 OR EXISTS(SELECT 1 FROM @Positions p LEFT JOIN @Accepted a ON a.ParagraphID=p.ParagraphID WHERE a.ParagraphID IS NULL OR a.ChapterID<>p.ChapterID OR p.StartPosition<0 OR p.EndPosition<=p.StartPosition OR p.StartPosition IS NULL OR p.EndPosition IS NULL OR p.Verified IS NULL OR p.Verified<>a.Verified OR ISNULL(p.SceneID,-1)<>ISNULL(a.SceneID,-1))
|
||||
OR EXISTS(SELECT 1 FROM @Batch b WHERE (SELECT COUNT(*) FROM @Positions p WHERE p.ChapterID=b.ChapterID)<>(SELECT COUNT(*) FROM @Accepted a WHERE a.ChapterID=b.ChapterID)) THROW 51000,'Incomplete or conflicting canonical paragraph positions',1;
|
||||
IF EXISTS(SELECT 1 FROM (SELECT ChapterID,StartPosition,LAG(EndPosition) OVER(PARTITION BY ChapterID ORDER BY StartPosition) PriorEnd FROM @Positions) p WHERE PriorEnd IS NOT NULL AND StartPosition<>PriorEnd)
|
||||
OR EXISTS(SELECT 1 FROM @Batch a JOIN @Batch b ON a.ChapterID<b.ChapterID AND a.StartPosition<b.EndPosition AND a.EndPosition>b.StartPosition) THROW 51000,'Noncontiguous or overlapping chapter positions',1;
|
||||
DECLARE @Prior TABLE(ChapterID int PRIMARY KEY,WordRevision bigint,ContentHash char(64),IdentityHash char(64),MappingHash char(64),Positions nvarchar(max),StartPosition int,EndPosition int);
|
||||
INSERT @Prior SELECT v.ChapterID,v.WordRevision,v.ContentHash,v.IdentityHash,v.MappingHash,v.Positions,p.StartPosition,p.EndPosition FROM dbo.BookChapterValidations v
|
||||
CROSS APPLY(SELECT MIN(StartPosition) StartPosition,MAX(EndPosition) EndPosition FROM OPENJSON(v.Positions) WITH(StartPosition int '$.Start',EndPosition int '$.End')) p
|
||||
WHERE v.BookID=@BookID AND v.UserID=@UserID AND v.SessionID=@SessionID AND v.ExpiresUtc>SYSUTCDATETIME();
|
||||
IF EXISTS(SELECT 1 FROM @Prior a JOIN @Batch b ON a.ChapterID<>b.ChapterID AND a.WordRevision=@WordRevision AND a.StartPosition<b.EndPosition AND a.EndPosition>b.StartPosition)
|
||||
OR EXISTS(SELECT 1 FROM @Prior a JOIN @Batch b ON a.ChapterID=b.ChapterID AND a.WordRevision=@WordRevision WHERE a.ContentHash<>b.ContentHash OR a.IdentityHash<>b.IdentityHash OR a.MappingHash<>b.MappingHash OR a.Positions<>b.Positions)
|
||||
OR EXISTS(SELECT 1 FROM dbo.BookChapterValidations v JOIN @Batch b ON b.RequestID=v.RequestID WHERE v.BookID=@BookID AND v.UserID=@UserID AND (v.ChapterID<>b.ChapterID OR v.SessionID<>@SessionID OR v.WordRevision<>@WordRevision OR v.Positions<>b.Positions)) THROW 51000,'Conflicting evidence for the same live Word revision',1;
|
||||
DELETE dbo.BookChapterValidations WHERE BookID=@BookID AND ExpiresUtc<SYSUTCDATETIME();
|
||||
UPDATE v SET ManuscriptID=@ManuscriptID,WordRevision=@WordRevision,RequestID=b.RequestID,ContentHash=b.ContentHash,IdentityHash=b.IdentityHash,MappingHash=b.MappingHash,Positions=b.Positions,SourceRevision=@Revision,ValidatedUtc=SYSUTCDATETIME(),ExpiresUtc=DATEADD(hour,12,SYSUTCDATETIME())
|
||||
FROM dbo.BookChapterValidations v JOIN @Batch b ON b.ChapterID=v.ChapterID WHERE v.BookID=@BookID AND v.UserID=@UserID AND v.SessionID=@SessionID;
|
||||
INSERT dbo.BookChapterValidations(BookID,ChapterID,UserID,SessionID,ManuscriptID,WordRevision,RequestID,ContentHash,IdentityHash,MappingHash,Positions,SourceRevision,ValidatedUtc,ExpiresUtc)
|
||||
SELECT @BookID,b.ChapterID,@UserID,@SessionID,@ManuscriptID,@WordRevision,b.RequestID,b.ContentHash,b.IdentityHash,b.MappingHash,b.Positions,@Revision,SYSUTCDATETIME(),DATEADD(hour,12,SYSUTCDATETIME()) FROM @Batch b
|
||||
WHERE NOT EXISTS(SELECT 1 FROM dbo.BookChapterValidations v WHERE v.BookID=@BookID AND v.ChapterID=b.ChapterID AND v.UserID=@UserID AND v.SessionID=@SessionID);
|
||||
COMMIT;
|
||||
END;
|
||||
GO
|
||||
Loading…
x
Reference in New Issue
Block a user