36 KiB
SQL Server performance and data-access audit — 18 November 2026
Initial audit boundary
Baseline collected on the existing shared branch at e7cd923, before optimisation. The unrelated canonical manuscript architecture assessment is preserved. Only Development and the separately restored PlotDirector_SQLAudit_20261118 verification database are authorised. No Production access, data resets, indiscriminate index maintenance or EF changes are part of this audit.
Development runs SQL Server 2025 Enterprise Developer 17.0.4006.2 on Linux, compatibility 170. Data file 904 MB; log 1096 MB; FULL recovery; CHECKSUM; auto-create/update statistics enabled, synchronous updates; Query Store READ_WRITE/AUTO (52 MB of 1000 MB); RCSI and snapshot isolation OFF. Server started 6 November. Developer has 16 visible schedulers, roughly 3991 MB committed at capture and an effectively unbounded max-server-memory setting. These are Development observations, not Production configuration claims.
The complete inventory contains 199 application tables, 446 index/heap entries, 362 trusted/enabled foreign keys and 719 procedures. Every table has a primary key. The connection factory creates pooled Microsoft.Data.SqlClient connections (15-second connection timeout, default pool 0–100, default command timeout 30 seconds). Selected import/restore operations explicitly use 120–180 seconds. Application access primarily uses Dapper 2.1.79 / SqlClient 7.0.1 and stored procedures. No EF/runtime alternate ORM dependency was found.
Query Store's seven-day observations identify expensive plot-line attribution and chapter-sync JSON work. Repeated warm read-only procedure benchmarks reproduce a large-project plot workspace median around 2335 ms (290 scenes), compared with 6–11 ms on 2-/48-scene projects. Candidate/evidence/event multiplication is a measured read hotspot. The audit found 33 actual executable inline SQL sites after manually excluding domain methods, stored-procedure helper calls, tests and administrative utilities from 49 scanner candidates. The existing scripts/admin utilities are not architectural violations.
Complete inventories accompany this report in SQL-Performance-Audit-20261118/. The remaining sections record the subsequent qualified changes and final findings.
Findings ranked by practical benefit
Audit began on 18 November and completed on 19 November UTC. Measurements are Development observations; this is not a Production performance assessment.
| Priority | Finding | Affected area | Evidence | Proposed improvement | Risk | Status |
|---|---|---|---|---|---|---|
| P1 | Candidate/evidence/event joins multiply rows before deduplication | Plot workspace, map Story membership, writing context plots | Reproduced 290-scene workload; approximately 2.3 seconds and 793k logical reads | Deduplicate candidate/scene associations once using UNION, then aggregate | Moderate; seven result-set contracts and scope must match | Implemented, migration 284; qualified |
| P1 | Nested OPENJSON overlap validation is expensive | Word chapter synchronisation | Query Store 15137: 113 executions, mean 1932 ms; repeated parsing of both interval sets | Materialise incoming/eligible intervals once; retain exact revision/session/expiry/overlap rules | High correctness risk for verified positions | Proposed separate qualification; not changed |
| P1 | Entire accepted book JSON travels to the application for chapter reads | Reader, accepted revisions, synchronisation | ParagraphManuscript get statement: 1124 executions, mean 124.83 ms; accepted payload table reserves about 229 MB |
First measure authorised chapter projections/request-local reuse; consider incremental storage separately | Moderate to architectural; heading windows, IDs and revision fences are essential | Not changed |
| P1 | Stored-procedure policy had 33 executable violations | Onboarding, derived intelligence, recovery/admin | Complete inspected call-site inventory | Migrate straightforward operations; freeze remaining exception fingerprints | Low for exact read replacements, higher for compound mutations | 15 fixed; 18 explicitly deferred |
| P2 | Related onboarding update/read made two RPCs | Writing-software reset | Six repeated clone samples per variant | Return the existing onboarding result from the update procedure | Low | Implemented; 2 → 1 round trips |
| P2 | Preference reads/writes checked and potentially altered columns at runtime | Story-memory preferences | Executable COL_LENGTH/ALTER batch before each get/set | Move exact nullable-column guards to controlled migration | Low with migration dependency | Implemented; read path 2 → 1 round trips |
| P2 | Very frequent idle job claims | Intelligence/synthesis/enrichment workers | Roughly 805,649 executions for several claim/readiness statements in seven-day Query Store window | Evaluate bounded idle backoff or related claim consolidation with job-start latency tests | Moderate; changing latency/fairness casually is unsafe | Recommendation only |
| P2 | Repeated related reads and full-payload requests | Writer authoring/Review, dashboards, map Story | Source call chains; see area matrix | Scoped read frames/QueryMultiple and conditional version reads, without global private-data caching | Moderate | Recommendations only |
| P2 | Large retained JSON copies | Restore points, manuscript/source storage | One restore point reserves about 163 MB; scene manuscript sources about 81 MB | Measure retention/growth; cold storage or retention policy requires approval | Architectural/data-retention risk | No deletion or format change |
| P2 | Stale-statistics candidates and material fragmentation exist | Positions, name reference data, illustration library | 1129 statistics inspected; relevant candidates below | Validate actual plan usage before targeted maintenance | Moderate operational risk | No blanket maintenance |
| P3 | Two same-key index overlap pairs | Scene characters, narrative candidates | Exact metadata and usage inventory | A/B test narrower indexes before considering removal | Low storage benefit; plan regression risk | No indexes dropped |
| P3 | 225 foreign-key leading-key coverage screens | Whole schema | Full 362-FK/index comparison; many small lookup/optional references | Review workload-supported cases, not a blanket index rollout | Write/storage overhead and unnecessary indexes | No automatic indexes added |
Schema and table inventory
All tables and complete columns, keys, indexes and foreign keys cover every application table. There are 199 clustered and 247 nonclustered indexes. Every table has a primary key; none of the existing foreign keys is disabled or untrusted. This does not prove that every conceivable business relationship should have a physical FK. Polymorphic activity references and external manuscript/occurrence IDs need their existing deletion and provenance semantics, rather than constraints inferred from column names.
Largest reserved allocations at baseline:
| Table | Rows | Reserved KB | Interpretation |
|---|---|---|---|
| BookParagraphManuscripts | 14 | 234256 | Large accepted JSON documents; small row count hides payload cost |
| ProjectRestorePoints | 1 | 167320 | Complete retained safety snapshot |
| SceneManuscriptSources | 868 | 82456 | Retained scene prose |
| NameUsages | 92010 | 50080 | Largest reference-data row count |
| StoryIntelligenceSceneResults | 290 | 47648 | Retained analysis audit source, not normal review-page reconstruction |
| StoryIntelligenceReviewCandidates | 9212 | 42976 | Persisted review pages/evidence |
| IllustrationLibraryItems | 1265 | 30968 | Shared illustration metadata/state |
| OnboardingManuscriptCaptures | 1 | 24280 | Retained import capture |
| BookChapterValidations | 419 | 24144 | Transient verified checkpoint JSON |
| BookParagraphPositions | 118399 | 5768 | Relational position lookup data |
Row counts are catalog/partition counts at capture, not a transactionally frozen census of the live site. Reserved size includes indexes/LOB allocation. Empty tables and small lookup tables are included in the inventory; they were not labelled performance defects merely because a scan exists. Wide nvarchar(max)/JSON fields are intentional in several contracts, but repeatedly returning whole snapshots is a measured opportunity. No type narrowing, JSON/native geometry conversion, uniqueness constraint, cascade change or obsolete-table removal was performed without a proven contract.
The new migration moves three existing nullable preference-column guards out of application requests. All three columns already existed in Development, so those guards were a no-op there. Earlier numbered migrations remain unchanged. Current live table/index counts remain 199/446; procedures increase from 719 to 733.
Index and statistics analysis
Complete index definitions/usage, same-key overlaps, FK coverage screens, and DMV/statistics/fragmentation evidence are retained.
No missing-index recommendation was promoted automatically. The ten missing-index DMV suggestions include account-deletion predicates on illustration approval/rejection actors and name-reference lookup shapes; their counters are cumulative since the instance restart and include administrative/test activity. They do not establish an interactive page bottleneck. The expensive plot-attribution plan had scans/sorts/spooling but no missing-index suggestion: its main problem was join multiplication. Removing that multiplication produced the measured gain without another permanent index or write cost.
Two overlap candidates deserve later A/B testing:
SceneCharacters.IX_SceneCharacters_SceneIDhas(SceneID, CharacterID), no INCLUDE, 64 KB, 218 recorded reads. The timeline index has the same keys and 13 included columns, 192 KB and 21,175 reads. The narrower index is actually used; it is not proven redundant.StoryIntelligenceNarrativeCandidates.IX_StoryIntelligenceNarrativeCandidates_Statushas(BookID, Status, CandidateType), no INCLUDE, 16 KB and zero recorded reads.IX_StoryIntelligenceNarrativeCandidates_Book_Status_Typehas the same keys plusWholeBookPlotSynthesisRunID, AcceptedPlotLineID, AcceptedPlotThreadID, also 16 KB and 201 reads. The observed storage saving is tiny, and the observation window does not cover every future workload.
If later approved after plan testing, exact removals and rollback definitions are:
-- NOT APPLIED. Offline index DDL can block; schedule and validate first.
DROP INDEX IX_SceneCharacters_SceneID ON dbo.SceneCharacters;
DROP INDEX IX_StoryIntelligenceNarrativeCandidates_Status ON dbo.StoryIntelligenceNarrativeCandidates;
-- Rollback/recovery:
CREATE INDEX IX_SceneCharacters_SceneID ON dbo.SceneCharacters(SceneID, CharacterID);
CREATE INDEX IX_StoryIntelligenceNarrativeCandidates_Status
ON dbo.StoryIntelligenceNarrativeCandidates(BookID, Status, CandidateType);
Expected benefit would be less duplicate index maintenance/storage, not a demonstrated latency improvement. Dropping a narrow used index may make its queries more expensive; recreating it also needs a maintenance window. No index was removed in this audit.
An experimental validation lookup index, not a recommendation to apply immediately, is:
CREATE INDEX IX_BookChapterValidations_ActorSessionRevisionExpiry
ON dbo.BookChapterValidations(BookID, UserID, SessionID, WordRevision, ExpiresUtc)
INCLUDE(ChapterID);
-- Rollback: DROP INDEX IX_BookChapterValidations_ActorSessionRevisionExpiry ON dbo.BookChapterValidations;
It targets the eligible-validation filters in BookChapterSync (including Query Store 15137). It could reduce visits to expired/other-session records; it cannot fix quadratic interval expansion. Positions JSON is deliberately excluded to avoid duplicating large payloads. Every checkpoint insert/expiry/revision update would maintain another index. Benefit and actual size are unmeasured: compare actual plans, logical reads and checkpoint write latency on a clone before approving it.
Of 23 index/LOB structures meeting the diagnostic page threshold, the largest manuscript/restore/source structures show 0% fragmentation. NameUsages.IX_NameUsages_QueryPath has 2001 pages and approximately 96.6% fragmentation; the illustration clustered index has 1265 pages and approximately 35.3%. These are targeted maintenance candidates, not evidence that fragmentation caused the slow plot page. No indiscriminate rebuild/reorganise occurred.
Statistics candidates include an auto statistic on BookParagraphPositions with a historic 8457-row sample and 669166 modifications, and modified scene-character/metric statistics. A high modification counter alone does not prove the statistic is currently used by a bad plan. Validate the relevant plan's statistics usage, sample quality and recompilation behaviour before a targeted update. Auto statistics remain enabled; no blanket UPDATE STATISTICS, plan-cache flush, forced plan or recompile hint was introduced.
Stored procedures and recorded workload
Procedure/caller inventory contains every baseline procedure, direct static application callers, SQL dependency callers, cached execution counters and structural flags. Post-change procedure inventory includes all 733 current procedures. No static caller is a review lead, not proof a module is obsolete: SQL dependencies, runtime definitions, variable procedure dispatch, CLI/admin use and external callers require consideration. Query Store metrics retain query/plan IDs and measurements without query text or compiled parameter values.
Seven-day statement CPU/read sums by owning procedure (not a per-call duration and not a Production workload):
| Procedure | CPU ms | Logical reads |
|---|---|---|
| BookChapterSync | 456582 | 50620661 |
| StoryIntelligenceRun_ClaimNextPendingFair | 281211 | 3222596 |
| WholeBookPlotSynthesisRun_ClaimNext | 159573 | 1611298 |
| CharacterEnrichmentRun_ClaimNext | 158617 | 1705093 |
| StoryIntelligenceBookPipeline_FindNextReadySceneAnalysis | 126800 | 1611298 |
| PlotLineWorkspace_Get | 113942 | 37892066 |
| ParagraphManuscript | 88835 | 11591250 |
| WriterDashboard_Scenes | 36064 | 9181235 |
| WordCompanion_Book_Structure | 25427 | 10478155 |
Important individual statements include plot attribution (Query Store 11462, 86 executions, mean 1247 ms), overlap validation (15137, mean 1932 ms), paragraph payload expansion (15305, about 39.8 million reads over 113 executions), and whole-payload retrieval (14638, mean 124.83 ms). Historical plans/parameters and test imports differ; current repeat benchmarks are the stronger evidence for the implemented plot change.
Plan inspection showed multiple plot plans/cardinality shapes and a costly candidate/evidence/event spool/nested-loop subtree. The replacement precomputes a distinct union of candidate/scene pairs using the same project/book/pending filters, then aggregates once. It preserves counts, NULL names, canonical membership, narrative order and all seven result sets. No isolation level, decision write, manuscript revision or transaction scope changed. Like the previous multi-statement read procedure, its result sets are not a single snapshot-isolation transaction.
The audit screened every procedure definition for JSON, cursors, SELECT *, dynamic execution and NOLOCK, and manually traced the expensive paths and their callers. Flags are review leads, not automatic defects. Metadata-driven restore legitimately uses a cursor and quoted identifiers. There are two actual dynamic-SQL procedures: ProjectRestore_ApplyGraph236 and ProjectRestore_InsertJsonTable. Their identifiers are derived from the restore table/column metadata and quoted with QUOTENAME; JSON values go through sp_executesql parameters. EXEC return-code assignments to application locks were excluded from the dynamic-SQL count. No user-value concatenation/injection defect was established by this audit; this is not a penetration-test certification. No NOLOCK was introduced and consistency was not weakened.
Query Store wait totals include approximately 110 seconds Network IO, 16 seconds Parallelism and 15 seconds Memory across the observation window. The blocking snapshot was empty. This does not establish that blocking never occurs. Read-committed writes, long JSON work inside accepted-revision transactions, and large client payloads warrant targeted request tracing before changing locking or enabling RCSI.
Complete inline SQL compliance inventory
All 33 inspected sites with operation, tables, method, proposal, migration compatibility, risk and disposition and machine-readable disposition are provided. The initial syntax scan produced 49 candidates: domain methods named Query/Execute, the NameIntelligence CommandDefinition helper and an administrative SQL runner were inspected and excluded. The confirmed application violations were:
| File | Initial sites | Fixed | Remaining |
|---|---|---|---|
| StoryMemoryRepository.cs | 23 | 12 | 11 |
| CharacterIntelligenceRepository.cs | 3 | 2 | 1 |
| OnboardingRepository.cs | 1 | 1 | 0 |
| IllustrationLibraryRepository.cs | 1 | 0 | 1 |
| StoryIntelligenceResultRepository.cs | 3 | 0 | 3 |
| StoryIntelligenceDevelopmentResetService.cs | 2 | 0 | 2 |
| Total | 33 | 15 | 18 |
Fourteen straightforward operations now call named, parameterised stored procedures. Ten are story-memory reads and one lists character profiles; the other three clear writing-software state, append character evidence and invalidate an assignment. SQL result contracts and public repository signatures are preserved. The fifteenth fix relocates the preference-column repair to migration 283 and removes its application call sites. Read conversions are architectural compliance changes: no individual speed gain is claimed merely because SQL moved into a procedure.
The remaining 18 sites are explicitly inventoried: compound story-memory upserts/deletion/supersession, profile MERGE, recovered-illustration failure supersession, the once-per-process known-character queue schema/procedure repair, and two Development reset batches. These preserve identity, monotonic evidence/version flags, recovery and deletion semantics. They require separate write/concurrency or legacy-schema qualification. Runtime queue DDL must move to a migration after comparing the current queue contracts, rather than blindly freezing potentially stale runtime definitions. The Development reset must retain its ownership checks, deletion sequence and verification; it was not invoked by this audit.
Executable C# across the web app, Word add-in and Native Companion was scanned; actual execution call sites were inspected. Client JavaScript/Razor and project dependencies were also searched. No EF or alternate runtime ORM was found. SQL migrations, tests, .appdata/SqlRunner, Tools/WritingSolver, Tools/PublicMarketingCapture and tools/RefreshRelationshipReviews are legitimate administrative/test utilities, not hidden web data-access exceptions. None of those administrative mutation utilities was run as an application optimisation. Existing user values in the inspected application SQL were already parameterised; this was primarily an architectural compliance gap.
Round trips and area-by-area assessment
| Area | Traced behaviour and evidence | Disposition |
|---|---|---|
| Writer / annotations | WriterAuthoringService serially fetches authoring sections, lookups/note types, chapter/scenes and, when selected, characters/threads/relationships/attachments. Review also reads the accepted Reader and intentions. These are related read-frame opportunities, not all N+1 loops. Annotation paging remains bounded. | No global author-data cache; propose scoped read frames and measure real request attribution. |
| Reader / accepted manuscript | ManuscriptReaderService.Read obtains a full authorised snapshot, book and chapter list, then projects the selected heading window. Check uses lightweight status but also book/chapter/Word metadata. | Preserve heading/blank-paragraph/ID rules; avoid a naive ChapterId-only projection. |
| Synchronisation | SaveCore retains previous/accepted state and activity append in one transaction; overlap checks repeatedly parse intervals. | Do not remove locks or split transactions without concurrency tests. |
| Timeline / plots | PlotLineWorkspaceRepository already consumes seven related result sets with QueryMultiple. The service may load a distinct unfiltered baseline for scoped health calculations. | Optimised the attribution query, not unrelated operations or baseline semantics. |
| Characters / relationships | CharacterIntelligenceService and story-memory preparation perform per-entity/evidence writes inside loops; some relationship journeys are deliberately in-memory. | Batch only related writes with identity/evidence parity tests. No paid analysis invoked. |
| Maps / locations | MapRepository already uses three related result sets; MapStoryService also requests plot membership. Full geometry/document saves retain revision checks. | Plot improvement benefits membership consumers. No spatial index is justified merely by JSON geometry when reads are by MapID; do not rewrite map storage blindly. |
| Guided Investigation / Problem Solver | Deterministic catalogue/state procedures and private investigation persistence; no leading measured hotspot in this capture. | Preserve recomputation/version/catalogue contracts; no engine or polling changes. |
| Project / book dashboards | WriterDashboard_Scenes has high cumulative reads but about 2.57 ms mean for the cited statement; shell/reference reads can add latency. | Obtain request-correlated attribution before claiming it is the main cause. |
| Import / export / backup | Full retained documents and snapshots are large; backup reads multiple feature families deliberately. Restore has metadata-driven SQL and dependency ordering. | Verified a physical backup/restore to a clone. No format, retention or cascade change. |
| Subscription / account | Existing actor/subscription procedures; account cleanup can generate misleading missing-index suggestions on optional illustration actor references. | Related onboarding update/read consolidated; entitlement/payment behaviour unchanged. |
No sensitive data was cached globally. Good existing QueryMultiple uses were retained. Reader polling, navigation acknowledgement cadence and worker claim fairness were not changed. Request-local reuse or immutable lookup/catalogue caches require explicit freshness/invalidation rules; permission checks must precede reuse. Large-data UI paging must not silently truncate full-state analysis or backup consumers.
SQL Server 2025 Express deployment considerations
Microsoft's SQL Server 2025 Linux edition matrix documents Express limits of the lesser of one socket/four cores, 1410 MB buffer pool, and 50 GB relational database size. The buffer-pool limit is not a total-process memory cap. Query Store, parameter-sensitive/optional-parameter optimisation and ordinary stored procedures/temp tables are supported. This change relies on ordinary T-SQL already used by the application, not Enterprise-only features. Developer's 16 schedulers and larger working set do not predict Express latency.
For a modest VPS, prioritise fewer page reads, smaller transfers and bounded concurrency over more covering indexes. Keep diagnostic permissions separate from the application principal. Use supported external scheduling for backups/maintenance; avoid reliance on SQL Agent or online index operations. Development's compressed copy-only backup is a verification artifact, not an assumption about Express backup-compression support. Current log-reuse wait was NOTHING; no log-backup timestamp was present in available msdb history, so verify the actual FULL-recovery backup/log schedule separately. No instance memory/DOP, recovery model, statistics option or maintenance schedule was changed.
Implemented changes, measurements and limits
Implementation commit: 390c449 on the existing shared branch. Migrations: 283_DataAccessAuditReads.sql, 284_PlotWorkspaceCandidateAssociations.sql. No existing numbered migration was edited, no index was added/dropped, and no canonical storage or backup format was changed.
The primary procedure benchmark uses a frozen restored clone and normal application SQL credentials. Both old and new procedures consume all result sets. Server CPU/read deltas come from separate administrator-only DMV observation; each sample verifies exactly one procedure execution. No private row contents or compiled parameter values are exported. Six samples per shape are retained; medians exclude the first sample. This is a warm-cache/plan experiment, not a cold-disk test. Caches were not flushed on a shared server. Small/large and archived-empty shapes are separately labelled.
| Workload | Before | After | Interpretation |
|---|---|---|---|
| 290-scene workspace elapsed | 2318.32 ms | 199.38 ms | About 91.4% lower in this controlled workload |
| Same workspace CPU | 2301.75 ms | 167.09 ms | About 92.7% lower |
| Same workspace logical reads | 792941 | 81966 | About 89.7% lower, including procedure-level reads |
| Same workspace application commands | 1 | 1 | Gain is query work, not fewer RPCs |
| Three-scene synthetic workspace elapsed | 11.23 ms | 12.35 ms | Approximately 1.1 ms overhead; no small-project speedup claimed |
| Three-scene logical reads | 2892 | 2971 | Slight extra preaggregation work |
| Writing-software reset | 2 round trips | 1 round trip | Measured; median approximately 1.37 → 1.11 ms in clone samples |
| Preference context read | 2 round trips | 1 round trip | Measured; request-time metadata batch removed |
Per-sample workspace measurements, after, onboarding, and preference reads retain timings, reads, counts and result fingerprints. Earlier independent repetitions also showed the same order-of-magnitude large-case gain. Candidate-name aggregation has no defined ordering contract; parity checks normalise that name list while preserving identities, counts and every other field. Project/book scope and valid/invalid scenario shapes were tested, including a reordered synthetic scenario.
Authenticated Development HTTP measurements on the small disposable fixture were:
| Request | Before median | After median |
|---|---|---|
| Plot workspace | 55.55 ms | 61.68 ms |
| Review Reader | 66.82 ms | 79.33 ms |
| Book dashboard | 38.88 ms | 51.96 ms |
| Maps | 40.38 ms | 49.13 ms |
These samples include network/render time and span a service restart; they did not demonstrate HTTP improvement and are not used to claim one. The fixture does not reproduce the expensive large-project proposal workload. The observed increases are retained rather than hidden, and require representative request profiling before attributing causality. Raw before and after explicitly leave per-request SQL count/time null: the current application has no HTTP-correlated SQL interceptor. Query Store cannot reconstruct that attribution. This audit measured command counts/database work for bounded operations separately from full HTTP durations; it does not invent total database time per web request. A bounded, value-free Development request/SqlClient trace is recommended as the next observability step.
Regression and acceptance
- Solution build: zero warnings/errors. Release publish passed.
- Executable regression harness: 625 PASS, exit 0, including the new architecture guard.
- Disposable clone suite: 80 checks passed. Legacy/read-procedure result parity covers existing and missing imports; real repository mapping is exercised. Seven-set plot parity covers project/book filters and valid/invalid/reordered scenarios. Onboarding consolidation, repeated assignment invalidation and evidence append are checked; test mutations roll back.
- Controlled procedure experiments verify matching result fingerprints and row counts; manuscript/revision/annotation/geometry tables are not modified by the plot read procedure.
- Plot map and health browser suites pass: Focus/Weave, shared scenes, associations, inspectors, health/evidence navigation and themes.
- Authenticated Development browser and simulated PWA checks pass on plot workspace, Reader, book dashboard and Maps; all routes return their intended 200 response, with no page errors. The 182 accepted-paragraph manuscript digest matches before/after in both modes.
writing-context-plots.cjsdid not pass: it times out waiting for the simulated native-presence beat at line 15. The unchanged fixture/client path does not execute the changed SQL. This is explicitly retained as a separate unresolved fixture/Word-follow acceptance item, not reported as passed.- Physical Windows/Word behaviour was not tested on Atlas. Existing native acknowledgement/security/revision regression coverage passed; synchronisation algorithms and native binaries were not changed.
Architectural regression protection
DatabaseArchitectureTests parses production C# syntax with the SDK's Roslyn compiler libraries, excluding legitimate test/administrative projects. It detects likely ad hoc/default-text execution, command definitions, interpolated/constructed SQL, CommandText assignments, EF imports/context inheritance and EF package dependencies. Stored-procedure calls through the current helper pattern are permitted. Detector self-tests cover safe calls, comments, default SQL, interpolation, variable SQL and constructed SQL. The libraries are test-only dependencies, not deployed web application dependencies.
The 18 remaining exceptions are exact file/member/operation/SQL fingerprints with occurrence counts. A new or changed violation fails with a location and migration guidance; an obsolete exception also fails and must be removed. Run dotnet run --project PlotLine.Tests -- --sql-architecture-check for a focused check; it also runs in the normal harness. This is practical regression protection for the current stack, not a security proof against deliberately disguised database access. JavaScript/Razor/alternate-library review remains part of code review.
The policy is enforceable for new detected code, with frozen explicit legacy debt. The application is not yet fully stored-procedure-only. Database-level denial of direct table access must wait for the remaining paths and dynamic restore ownership/permissions to be qualified; no application permissions were weakened or changed here.
Deployment, recovery and remaining work
The task-specific Development copy-only/checksum backup /var/opt/mssql/backup/sql-audit-20261118.bak passed VERIFYONLY and was actually restored to PlotDirector_SQLAudit_20261118, with separate data/log files. Before live migration, database identity, dependencies and the original workspace module hash were checked; active import/analysis guards passed. Scripts were applied separately. All 15 captured business-table counts/content hashes matched across the live migrations. Application-principal execute permissions were verified.
Development deployment only: release 390c449-20261119T000234Z, application informational version from commit 390c449, published/deployed DLL SHA-256 197e4b3f519d16b3e9379c99cb9317c4a00e77a74d37b255b9ced84f9c18a514. Configuration, data-protection keys, uploads and logs were preserved. Final service/cleanup receipts follow below. Production was not accessed or deployed.
Application rollback is /srv/apps/plotdirector-dev/current-before-390c449-20261119T000234Z (the preceding qualified Writer build). Added procedures/nullable columns remain compatible with it. To revert the read optimisation, use a new forward migration restoring the baseline procedure definition, rather than editing 284. The clone-only baseline definition records that body for review/reproduction; it deliberately refuses a live target. Do not restore the entire live database to undo a read-procedure change.
Next work needing separate approval/qualification: the 18 listed compound-write/runtime-reset migrations; interval-validation/accepted-payload redesign; request-correlated tracing and scoped batching/caching; retention/storage redesign; and any index removal/creation or targeted maintenance supported by additional workload tests. Do not treat screening inventories as a bulk work order.
Final handoff receipts
Service is active; local HTTP and public HTTPS GETs return 200. All fourteen new procedures have execute permission for the configured application principal. The published/deployed DLL hashes match. The application journal contains no fail/critical entries during acceptance; it does contain one HTTPS redirect-port warning from the local backend probe and two antiforgery cache-header override warnings. Public TLS succeeded; secure antiforgery no-store behaviour was retained. These warnings were not hidden or “fixed” by weakening caching/security settings.
The temporary browser author and its owned fixture project/books were deleted through the normal authenticated account-deletion workflow. Explicit queries confirm those fixtures are absent. The private credential JSON and temporary symlink are deleted. The exact disposable clone was dropped after checking its expected data/log paths; the local fixture host was stopped. Existing author data was not reset, truncated or restored. The verified backup and application rollback directory are retained. The unrelated untracked Docs/Investigations/CanonicalManuscriptArchitectureAssessment.md remains untouched.
Additional configuration recorded without modification: collation SQL_Latin1_General_CP1_CI_AS, forced parameterisation off, broker enabled, fixed 64 MB file growth, auto-close/auto-shrink off. Configuration snapshot and log snapshot are included.
Deployed visual smoke evidence: plot workspace, accepted Reader, book dashboard, Maps. Browser-mode captures accompany them. These are small disposable fixtures; they are not pictures of the large private project used in the controlled procedure benchmark.
Local reproducibility/receipt directory: /home/nick/sql-audit-20261118/ (restricted to the owner). It contains build/publish, regression, architecture, clone parity, browser, backup/migration, permission, preservation and cleanup logs. The committed inventories/measurements omit query text, credentials, compiled parameter values and author prose. To repeat clone tests, restore a separately named verification copy, apply the clone-only baseline procedure and the two new migrations, create the small fixture and scenario fixture, then run dotnet run --project PlotLine.Tests -- --sql-audit-database. That command refuses the configured live database as its test target and uses only the named clone. Never substitute Production or restore over Development.