From 3426236c6cfcece36e94642ae84d1843288f86d5 Mon Sep 17 00:00:00 2001 From: Steffen Date: Wed, 14 Oct 2026 00:38:08 +0200 Subject: [PATCH] Architecture is proposed and there are also alternative architectures proposed --- ArchitectureProposal/README.md | 51 ++ .../architecture-decisions.md | 47 ++ ArchitectureProposal/diagram-guide.md | 32 ++ .../diagrams/01-system-context.drawio | 44 ++ .../diagrams/02-logical-components.drawio | 77 +++ .../diagrams/03-domain-model.drawio | 144 ++++++ .../diagrams/04-conceptual-classes.drawio | 440 +++++++++++++++++ .../diagrams/05-data-ownership.drawio | 65 +++ .../diagrams/06-deployment.drawio | 85 ++++ .../diagrams/07-sequences.drawio | 461 ++++++++++++++++++ ArchitectureProposal/energy-hypotheses.md | 20 + ArchitectureProposal/input-inventory.md | 73 +++ .../requirements-and-constraints.md | 35 ++ .../requirements-traceability.md | 332 +++++++++++++ .../risks-and-open-questions.md | 23 + ArchitectureProposal/software-architecture.md | 146 ++++++ ArchitectureProposal/us16-revision.md | 19 + ArchitectureProposal/validation.md | 34 ++ ArchitectureSuggestions/README.md | 19 + .../diagrams/service-topology-options.drawio | 133 +++++ .../energy-recommendation.md | 62 +++ .../energy-with-independent-services.md | 115 +++++ .../requirements-and-compatibility.md | 40 ++ ArchitectureSuggestions/validation.md | 19 + 24 files changed, 2516 insertions(+) create mode 100644 ArchitectureProposal/README.md create mode 100644 ArchitectureProposal/architecture-decisions.md create mode 100644 ArchitectureProposal/diagram-guide.md create mode 100644 ArchitectureProposal/diagrams/01-system-context.drawio create mode 100644 ArchitectureProposal/diagrams/02-logical-components.drawio create mode 100644 ArchitectureProposal/diagrams/03-domain-model.drawio create mode 100644 ArchitectureProposal/diagrams/04-conceptual-classes.drawio create mode 100644 ArchitectureProposal/diagrams/05-data-ownership.drawio create mode 100644 ArchitectureProposal/diagrams/06-deployment.drawio create mode 100644 ArchitectureProposal/diagrams/07-sequences.drawio create mode 100644 ArchitectureProposal/energy-hypotheses.md create mode 100644 ArchitectureProposal/input-inventory.md create mode 100644 ArchitectureProposal/requirements-and-constraints.md create mode 100644 ArchitectureProposal/requirements-traceability.md create mode 100644 ArchitectureProposal/risks-and-open-questions.md create mode 100644 ArchitectureProposal/software-architecture.md create mode 100644 ArchitectureProposal/us16-revision.md create mode 100644 ArchitectureProposal/validation.md create mode 100644 ArchitectureSuggestions/README.md create mode 100644 ArchitectureSuggestions/diagrams/service-topology-options.drawio create mode 100644 ArchitectureSuggestions/energy-recommendation.md create mode 100644 ArchitectureSuggestions/energy-with-independent-services.md create mode 100644 ArchitectureSuggestions/requirements-and-compatibility.md create mode 100644 ArchitectureSuggestions/validation.md diff --git a/ArchitectureProposal/README.md b/ArchitectureProposal/README.md new file mode 100644 index 0000000..2383028 --- /dev/null +++ b/ArchitectureProposal/README.md @@ -0,0 +1,51 @@ +# Health App architecture proposal + +**Complete proposed design — 2026-10-13.** Select a modular monolith: one HTTPS application process with explicit API/access, Profile, Observations, Analytics, Overview and Guidance modules; one PostgreSQL database with owned health schemas; a transient administrative installation utility. + +The choice follows comparison with the existing five-service architecture and a reduced service topology. Energy efficiency is an important objective, expressed as reasoned hypotheses with counter-effects, not measured savings. Assumptions: modest interactive synthetic prototype workload, Linux/systemd default, no established independent-feature scaling or isolation requirement. Capacity, physical hosting, clinical review and production recovery targets remain recorded unknowns. + +The user selected clarification **3**, authorizing evaluation of all topologies and documentation of necessary US-16 revisions. The proposal preserves US-01–US-15 and common functional behaviour. It **does not satisfy original US-16 independent feature-service installation/topology clauses**; every affected criterion is explicitly recorded in the revision and traceability register. No original requirement has been edited. + +## Documents + +| Artifact | Purpose | +| --- | --- | +| [Software architecture](software-architecture.md) | Authoritative boundaries, responsibilities, contracts, domain, data/transactions, security, failures, deployment and runtime specification | +| [Input inventory](input-inventory.md) | All 63 supplied files, purpose and authority; application source links not followed | +| [Requirements and constraints](requirements-and-constraints.md) | Binding behaviours, selected/reconsidered design decisions, assumptions and unknowns | +| [Requirements traceability](requirements-traceability.md) | 146 individual common/US-01–US-15 acceptance entries, including outline cases; story/functional-rule mappings and explicit gaps | +| [Architectural decisions](architecture-decisions.md) | Three feasible alternatives, selection rationale and eight significant ADRs | +| [Energy hypotheses](energy-hypotheses.md) | Anticipated mechanisms/effects, assumptions/dependencies and counter-effects | +| [Risks and open questions](risks-and-open-questions.md) | Operational, clinical, behavioural and architectural trade-offs | +| [US-16 revision](us16-revision.md) | All nine original deployment ACs and installer-addendum compatibility/revision obligations | +| [Diagram guide and coverage](diagram-guide.md) | View conventions, domain and conceptual-class coverage; cross-page references | +| [Validation](validation.md) | Completed artefact, coverage, diagram, link and preservation verification; limits | + +## Editable diagrams + +Native uncompressed `.drawio` files contain individually editable text, shapes and connectors. Open directly in diagrams.net/Draw.io; page tabs separate views. Classes are design concepts, not existing source declarations. + +| File | Pages | +| --- | --- | +| [System context](diagrams/01-system-context.drawio) | Actors, system boundary and reviewed external reference sources | +| [Logical components](diagrams/02-logical-components.drawio) | One-process modules, responsibilities and typed interfaces/dependencies | +| [Domain model](diagrams/03-domain-model.drawio) | Identity/access; observations/selection; derived views/clinical provenance | +| [Conceptual classes](diagrams/04-conceptual-classes.drawio) | Access/Profile; Observations; Analytics; Overview/Guidance — 32 individual classifiers | +| [Data ownership](diagrams/05-data-ownership.drawio) | Owned schemas, controlled patient reference, runtime role and operational state | +| [Deployment](diagrams/06-deployment.drawio) | Default local Linux and optional separate database host | +| [Sequences](diagrams/07-sequences.drawio) | Login/create; actual-owner read/correction/deletion; snapshot calculations/overview; installation | + +## Quality gate + +- [x] Every functional requirement, user story and acceptance criterion is traceable; original US-16 incompatibilities and implementation acceptance dependencies are explicit. No requirement was silently omitted or changed. +- [x] Significant supplied constraints are classified as mandatory, assumed or optional; explicit user clarification and uncertainties are recorded. +- [x] Architecture satisfies the clarified design scope; decisions are justified independently of resemblance to existing designs. Original US-16 topology remains an acknowledged incompatibility. +- [x] Authoritative specification covers required concerns and agrees with all diagrams. +- [x] Domain and conceptual class views cover relevant concepts/relationships without source reverse engineering or unnecessary code-level detail. +- [x] Every component has clear responsibilities and data ownership, including operational configuration and transient derived results. +- [x] Communication, security/trust, installation/deployment, concurrency, freshness and failure handling are defined. +- [x] Energy expectations state mechanisms, assumptions and possible counter-effects; none is described as measured savings. +- [x] Seven Draw.io files, 16 pages, are native editable sources; XML/endpoints/geometry/text checks passed. GUI import/round-trip was unavailable and is not claimed. +- [x] No application source code was inspected/generated/modified, and all 63 input files remain byte-identical. Repository changes are confined to `ArchitectureProposal/`. + +Verification is of the architecture deliverables. No application tests, deployments, clinical validation or energy measurements were performed. See [validation](validation.md) for the exact checks and remaining limits. diff --git a/ArchitectureProposal/architecture-decisions.md b/ArchitectureProposal/architecture-decisions.md new file mode 100644 index 0000000..766b479 --- /dev/null +++ b/ArchitectureProposal/architecture-decisions.md @@ -0,0 +1,47 @@ +# Architectural decisions + +2026-10-13. Functional US-01–US-15 behaviour is binding. User clarification `3` permits all topology alternatives and explicit US-16 revision. Decisions are proposed designs, not statements about existing source. + +## Alternatives and drivers + +Drivers: atomic profile/account lifecycle; actual-owner and assigned read-only access; current selected calculations; complete context; public guidance; installability; reproducibility; synthetic prototype scope; energy overhead at idle and per request. Workload, hardware, team size, availability target and numerical assessment expense are unknown. Assume modest interactive use for selection, not a measured production load. + +| Feasible under clarified scope | Strengths | Weaknesses / energy hypothesis | Selection | +| --- | --- | --- | --- | +| Five independent services, gateway-routed calls, separate databases, optionally colocated | Directly preserves US-16; per-feature deployment/scaling; process isolation; clear physical owners | Multiple runtimes/listeners/pools; gateway callback serialization/network/TLS; aggregate failure chains. Colocation and one PostgreSQL server can reduce host overhead. Independent scale can outperform consolidation under skewed load | Feasible baseline; rejected for default because prototype requirements do not justify its operational/call overhead | +| Reduced service topology: one API/profile/observation service, one analytics/overview service; direct private HTTPS with trusted identity delegation; one shared PostgreSQL server with owned databases | Keeps expensive assessment isolation/scaling; fewer hops than baseline; separates transactional writes from CPU-heavy reads | Still needs inter-process authorization/delegation, certificates, contract versioning and freshness handling; duplicates idle runtime and transports selected series | Feasible alternative; retain as reconsideration option if analytics workload/isolation becomes a driver | +| Modular monolith with owned schemas in one database | In-process composition; single deployment; atomic association; shared snapshots; no internal serialization; one app runtime/pool | Whole-app deployment/failure/scaling; logical module ownership does not isolate compromise; loss of original US-16 service installation | Selected conditionally on modest workload, clarified topology freedom and prototype scope | + +An unstructured monolith would lose useful ownership/replaceability without another topology benefit. Event-driven projections, CQRS stores or scheduled precomputation add a broker/state/refresh mechanism to satisfy freshness already achieved by direct reads; unsupported for this workload. Serverless could reduce application idle runtime on a compatible platform, but introduces platform constraints/cold starts/DB connection behaviour unsupported by the documented Linux installation setting. These are rejected options, not asserted impossible designs. + +## ADR-01 — Consolidate runtime, retain logical modules + +Decision: single application process with API/access, Profile, Observations, Analytics, Overview and Guidance modules. Alternative comparison above determines selection independently of similarity to baseline. Consequences: simplify deployment and calls; whole-process failure and co-scaling; retain module interfaces/private repositories. Revisiting independent rollout, sustained analytics dominance or mandatory isolation can favour either service alternative. US-16 changes are explicit in [revision](us16-revision.md). + +## ADR-02 — One database, module-owned schemas + +Choose PostgreSQL for continuity with the installer constraint and transactional lifecycle, not because a particular version is required. Use profile/observations schemas and controlled FK with restricted deletion; runtime DML role and separate migration ownership. Separate DBs remain viable for future extraction but complicate consistent overview snapshots and add pool/configuration management. No generic shared clinical repository. Logical ownership does not equal security isolation. One PostgreSQL server with two databases could already share server idle overhead; merging databases alone promises no significant energy effect. + +## ADR-03 — Durable association in the Profile aggregate + +Unique account ID and profile information commit atomically; retry after lost success reports existing profile. Alternatives: an access-store mapping or saga requires coordination/recovery state; external static mapping cannot satisfy initial lifecycle. Profile-less accounts retain login/create access. No response reports creation before commit. + +## ADR-04 — Logical API edge and framework tokens + +Retain standardized ASP.NET Core normalized identities/policies and established password hashing; choose framework-protected opaque tickets with persistent keys and configurable 30-minute default. No separate gateway process or identity server. JWT is feasible but brings issuer/audience/signing contract that no external token consumer requires here; server-held sessions add state/restart coordination. No bespoke crypto. Actual ownership/assignments are evaluated separately on each protected request and never trusted from a caller/header/token patient identifier. + +## ADR-05 — Current data, bounded snapshot lifetime, no result cache + +Capture authorized current immutable source values in a repeatable-read snapshot, including overview's distinct latest/insight bases; close DB transaction before calculation/transfer. No generated-result persistence or asynchronous invalidation. Alternatives: independent read-committed queries can interleave edits; versioned caching could help highly repetitive expensive queries but needs freshness/access/content-version keys. Current selected data and simple correctness outweigh unproven cache benefit. No silent history truncation. + +## ADR-06 — Keep analytics and clinical interpretation separate + +Versioned deterministic mathematical policy uses full-period evidence and temporal sufficiency; ClinicalPolicy requires reviewed claim-specific references; Guidance owns public reference provenance. Do not inherit a specific baseline trend formula solely from as-built documentation. No diagnostic score or arbitrary clinical variation cutoff. Missing irrelevant preparation does not suppress a supported reference comparison. Content review and reproducible method details are future implementation acceptance obligations. + +## ADR-07 — Context is an observation-owned value + +Flatten optional context within the observation record; clear means Unknown, omission preserves. Keep independent selection dimensions and original text/note. Separate context tables/entities would add lifecycle/joins without an independent domain need. Do not infer structured context from ambiguous historical prose. Preserve conflicting evidence and expose interpretation limits. + +## ADR-08 — Simple native Linux deployment + +One systemd application service; optional remote PostgreSQL; transient provisioning tool. Auto-provision credentials/certificates/configuration and verify representative operations. No containers/orchestration required. Existing five-process rollout and Windows/macOS implementations are inputs, not mandatory default targets. Hardware sharing and colocation may reduce overhead but have failure/contention effects. No measurement procedure or claimed saving is specified. diff --git a/ArchitectureProposal/diagram-guide.md b/ArchitectureProposal/diagram-guide.md new file mode 100644 index 0000000..2ea8119 --- /dev/null +++ b/ArchitectureProposal/diagram-guide.md @@ -0,0 +1,32 @@ +# Diagram conventions and model coverage + +The [specification](software-architecture.md) is authoritative; diagrams express its selected design. All files are native editable Draw.io XML. No diagram is an image-only export. Colour distinguishes responsibility boxes (blue), domain/derived values (green), owned storage (purple) and explanatory constraints/state (yellow). Shape kind/labels, not colour alone, convey meaning. + +Context shows the Health App application/database boundary, two authorized client roles, administrator and clinical publishers. Public guidance/login use the same HTTPS edge without granting patient access. Publisher relationships mean reviewed content provenance, never request-time network calls. Client applications are external, not a new frontend deliverable. + +Logical components are all in one application process. Dashed arrows denote typed in-process dependencies. Profile and Observations own private adapters. Infrastructure owns transactions/pool lifecycle, not clinical policy. Overview composes module query values; Analytics obtains current selected observations through Observations, not direct SQL. Access-policy resolution uses privileged internal owner/association lookups and does not disclose their result before authorization. + +## Domain coverage + +| Concepts | Domain page / constraints | Conceptual classifiers | +| --- | --- | --- | +| Account, authentication grant, professional assignment, patient profile | Identity/access; Patient account 1 to profile 0..1; each created profile one account; many-to-many assignments; grants contain no health data | Account, AuthenticatedIdentity, ProfessionalAssignment, PatientProfile, CredentialVerifier, AccessPolicy, ProfileQueries, ProfileCommands | +| Observation and measurement context | Observations/selection; patient 1 to observation 0..*; observation composes one context; required positives/time; immutable owner/original recording; unknown and text retained | BloodPressureObservation, MeasurementContext, ObservationChange, ObservationCommands, ObservationQueries, ObservationRepository | +| Period and context selection | Observations/selection; inclusive/equal bounds, UTC interpretation, independent optional AND predicates, explicit Unknown | Period, ContextSelection | +| Numerical insight | Derived views; one or more current selected raw observations; means/BP extrema/count/basis; transient | HealthInsight, SummaryPolicy, AnalyticsQueries | +| Trend, three metric assessments, comparability | Derived views; exactly three metric values and one evidence value; current selection/period, unavailable parts/reversals/full-period evidence | TrendAssessment, MetricAssessment, ComparabilityEvidence, TrendPolicy, ClinicalPolicy | +| Clinical reference and source | Derived views; zero/one applicable reference per metric; source provenance, applicability/prerequisites; thresholds not targets | ClinicalReference, ReferenceSource, ReferenceCatalog | +| Overview | Derived views; profile 1, latest 0..1, insight 0..1; latest overall separate from selected insight; no trend | HealthOverview, OverviewQueries; immutable ProfileSnapshot/ObservationSnapshot contract references | +| Guidance and ordered instruction | Derived views; available verified content has source provenance; instructions 0..* (empty when unavailable); no patient association/compliance lifecycle | GuidanceResult, GuidanceInstruction, GuidanceQueries | + +32 conceptual classifiers are shown individually with separate name, attribute and responsibility/operation compartments. Interfaces/policies/application services are labelled explicitly. Dashed arrows indicate design dependencies; plain associations have no arrowhead; a filled diamond means composition with dependent lifecycle. Multiplicities are written on relationships. Conceptual operations describe responsibilities and are not an instruction to generate these exact source classes or method signatures. + +Cross-page reference types (ProfileSnapshot, ObservationSnapshot, AuthorizedPatientContext and ReadSnapshot/WriteTransaction) are contracts/infrastructure concepts described in specification §§2 and 5, not additional domain entities. Read snapshots carry immutable profile/observation values, authorized patient context carries a policy-approved patient/action scope, and transaction types coordinate participating private adapters. Domain arrows never imply repositories/controllers belong in the business domain. Device/cuff descriptions do not imply independently managed device entities. + +## Storage and deployment coverage + +Data ownership shows one database with Profile and Observation schemas, an intentional controlled FK, separate migration ownership and one DML role. The diagram explicitly distinguishes logical ownership from security isolation. No clinical result table/database or detached context storage exists. Protected account/assignment/key/configuration files and the reviewed reference bundle have explicit owners. + +Deployment has two supported placements: one Linux host with independently managed application and PostgreSQL processes, or one application host plus a remote verified-TLS database. There are no independently deployed feature modules, internal HTTPS service listeners or gateway callback credentials. The transient installer is administrative. This is why original US-16 needs revision, rather than a claim of preserving its independent-service topology. + +Sequences cover durable initial creation, actual-owner authorization and atomic mutation, current calculations and distinct overview bases, and native installation verification. Their participants are logical modules/infrastructure within the application unless labelled external. For read composition the snapshot begins with access resolution, all DB reads share it, and capture ends before calculation/transfer. Sequence arrows use native editable connectors and lifelines. Numbered self-messages denote local policy/calculation work, not recursive HTTP calls. diff --git a/ArchitectureProposal/diagrams/01-system-context.drawio b/ArchitectureProposal/diagrams/01-system-context.drawio new file mode 100644 index 0000000..125e266 --- /dev/null +++ b/ArchitectureProposal/diagrams/01-system-context.drawio @@ -0,0 +1,44 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/ArchitectureProposal/diagrams/02-logical-components.drawio b/ArchitectureProposal/diagrams/02-logical-components.drawio new file mode 100644 index 0000000..d32af8c --- /dev/null +++ b/ArchitectureProposal/diagrams/02-logical-components.drawio @@ -0,0 +1,77 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/ArchitectureProposal/diagrams/03-domain-model.drawio b/ArchitectureProposal/diagrams/03-domain-model.drawio new file mode 100644 index 0000000..ea2b6a8 --- /dev/null +++ b/ArchitectureProposal/diagrams/03-domain-model.drawio @@ -0,0 +1,144 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/ArchitectureProposal/diagrams/04-conceptual-classes.drawio b/ArchitectureProposal/diagrams/04-conceptual-classes.drawio new file mode 100644 index 0000000..277ee6c --- /dev/null +++ b/ArchitectureProposal/diagrams/04-conceptual-classes.drawio @@ -0,0 +1,440 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/ArchitectureProposal/diagrams/05-data-ownership.drawio b/ArchitectureProposal/diagrams/05-data-ownership.drawio new file mode 100644 index 0000000..1e63449 --- /dev/null +++ b/ArchitectureProposal/diagrams/05-data-ownership.drawio @@ -0,0 +1,65 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/ArchitectureProposal/diagrams/06-deployment.drawio b/ArchitectureProposal/diagrams/06-deployment.drawio new file mode 100644 index 0000000..1b5ced4 --- /dev/null +++ b/ArchitectureProposal/diagrams/06-deployment.drawio @@ -0,0 +1,85 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/ArchitectureProposal/diagrams/07-sequences.drawio b/ArchitectureProposal/diagrams/07-sequences.drawio new file mode 100644 index 0000000..3903b66 --- /dev/null +++ b/ArchitectureProposal/diagrams/07-sequences.drawio @@ -0,0 +1,461 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/ArchitectureProposal/energy-hypotheses.md b/ArchitectureProposal/energy-hypotheses.md new file mode 100644 index 0000000..c11a94a --- /dev/null +++ b/ArchitectureProposal/energy-hypotheses.md @@ -0,0 +1,20 @@ +# Energy-related design hypotheses + +These are anticipated mechanisms, not measured results. No numerical savings, energy measurement procedures, code tuning, compiler flags or algorithm replacement are proposed. Energy is distinct from CPU utilization, memory, throughput and latency. Equal behaviour/data/access guarantees remain necessary when comparing architectures. + +| Decision | Mechanism and anticipated effect | Assumptions / dependencies | Counter-effects and limits | +| --- | --- | --- | --- | +| ADR-01 single application runtime | Removes duplicated runtime/listener/housekeeping work and internal calls; may lower idle and request energy | Baseline processes actually consume avoidable resources; host power responds to released resources or capacity can be consolidated | Same always-on host may draw similar power; co-scaling entire app can cost more than scaling only analytics; shared GC/contention can extend active time | +| In-process module composition | Removes JSON copies, TLS and loopback/remote HTTP on internal legs, including gateway callbacks | Equivalent validation/access and result semantics; internal contract calls replace real network legs | External TLS and DB work remain; fewer hops/less latency do not prove lower energy; network equipment may have high fixed consumption | +| ADR-02 database/schema consolidation | Shared connection management and transactions avoid coordination and duplicated pools; source snapshot may avoid repeat reads | One app/database is acceptable; baseline uses separate databases/configuration | A baseline single PostgreSQL server already shares server overhead; one combined pool/snapshot can create contention; FK/index writes have costs | +| ADR-03 one atomic association | Avoids separate association network/persistence step and recovery coordination | Profile owns account association; DB uniqueness/transaction capability | Unique index, locks and failed concurrent attempts still perform work; baseline already used one row so no relative saving necessarily exists | +| ADR-05 on-demand results | Avoids periodic wakes, projection writes, broker and stored-result invalidation on corrections/deletions | Interactive queries modest; fresh data required; results not repeatedly expensive | Repeated large trend queries may cost more than a correct versioned cache or projection; concurrency admission can lengthen waits | +| Request-local snapshot/reuse | Captures selected series once for overview insight; avoids duplicated owner/data reads where safely reusable in same snapshot | No cross-request reuse; preserve actual-owner authorization; request datasets manageable | Repeatable-read snapshot may retain DB versions and increase resource pressure; materializing full series costs memory; snapshot consistency is mainly a correctness benefit | +| Bounded pooled DB connections | Reuses connection/authentication setup rather than reconnecting per operation | Pool sized for deployment; secure remote transport when needed | Idle sockets/connections consume resources; excessive pool capacity increases footprint; scarce pools can prolong work; no asserted energy result | +| Patient/time indexes | Reduces unnecessary data access for current patient/period/latest queries | Selective queries and adequate table size; index remains useful | Extra writes, storage and maintenance; small tables may gain little. Additional context indexes are conditional, not automatic | +| Reviewed static guidance/reference bundle | Avoids request-time publisher calls and always-on content refresh service; immutable content may be cached publicly | Versioned review/release process maintains applicability | Review/redeployment has costs; outdated content risks correctness; availability of static data does not establish clinical validity | +| Tokens verified per request, password checked at login | Avoids expensive password verification on every business call while preserving policy checks | Same account/expiry behaviour; protected keys persist securely | Logins/expiry/validation still cost work; shorter lifetime increases login frequency; this retained baseline mechanism may offer no architectural delta | +| ADR-08 colocated app/DB default | Can avoid unnecessary extra hosts/network paths; administrative tool exits after installation | Modest resource demand, supported Linux, acceptable shared failure domain | Virtual hosts may share physical hardware already; remote shared DB can be more efficient at scale; contention can prolong activity; energy depends on physical placement | +| No always-on broker/gateway/provisioner | Avoids added runtime/services for responsibilities served in-process or only at install time | No external integration/event durability or independent gateway requirement | Loss of isolation and platform-specific optimizations; a shared existing gateway could have negligible marginal overhead | + +Selection balances these hypotheses with security, clinical correctness, maintainability and deployability. Unknown workload, active/idle balance, repeated-query frequency, physical host sharing and peak analytics demand prevent a universal energy ranking. The reduced service or five-service alternatives can be preferable where independent scaling or isolation offsets their overhead. No power/energy evidence was gathered in this architecture assignment. diff --git a/ArchitectureProposal/input-inventory.md b/ArchitectureProposal/input-inventory.md new file mode 100644 index 0000000..189e40e --- /dev/null +++ b/ArchitectureProposal/input-inventory.md @@ -0,0 +1,73 @@ +# Input inventory + +All supplied inputs are under `Docs/`. Read requirements/common/addendum/authentication/reconciliation and as-built narrative/decision/coverage/evidence documentation; inspected editable diagram labels/relationships and supplied JPEGs. Source links in descriptive documentation were not followed; application source was not inspected. Historical backups and duplicate diagrams were inspected for supersession, not elevated to requirements. + +`AGENT.md` was read completely. User clarification option 3 supersedes topology retention for this assignment and requires documenting US-16 revision. + +| Input | Role / authority | +| --- | --- | +| [Docs/Architecture/.$04_class_observation_service.drawio.bkp](<../Docs/Architecture/.$04_class_observation_service.drawio.bkp>) | Historical/backup design; current diagram/correction supersession applies | +| [Docs/Architecture/.$05_class_insights_service.drawio.bkp](<../Docs/Architecture/.$05_class_insights_service.drawio.bkp>) | Historical/backup design; current diagram/correction supersession applies | +| [Docs/Architecture/.$06_class_health_overview_service.drawio.bkp](<../Docs/Architecture/.$06_class_health_overview_service.drawio.bkp>) | Historical/backup design; current diagram/correction supersession applies | +| [Docs/Architecture/.$08_er_observation_service.drawio.bkp](<../Docs/Architecture/.$08_er_observation_service.drawio.bkp>) | Historical/backup design; current diagram/correction supersession applies | +| [Docs/Architecture/.$09_er_insights_service.drawio.bkp](<../Docs/Architecture/.$09_er_insights_service.drawio.bkp>) | Historical/backup design; current diagram/correction supersession applies | +| [Docs/Architecture/01_domain_model.jpg](<../Docs/Architecture/01_domain_model.jpg>) | Historical/backup design; current diagram/correction supersession applies | +| [Docs/Architecture/02_microservice_architecture.jpg](<../Docs/Architecture/02_microservice_architecture.jpg>) | Historical/backup design; current diagram/correction supersession applies | +| [Docs/Architecture/03_class_patient_profile_service.jpg](<../Docs/Architecture/03_class_patient_profile_service.jpg>) | Historical/backup design; current diagram/correction supersession applies | +| [Docs/Architecture/04_class_observation_service.drawio](<../Docs/Architecture/04_class_observation_service.drawio>) | Existing architecture choices; reconsiderable; current diagrams override corresponding old snapshots | +| [Docs/Architecture/04_class_observation_service.jpg](<../Docs/Architecture/04_class_observation_service.jpg>) | Historical/backup design; current diagram/correction supersession applies | +| [Docs/Architecture/05_class_insights_service.drawio](<../Docs/Architecture/05_class_insights_service.drawio>) | Existing architecture choices; reconsiderable; current diagrams override corresponding old snapshots | +| [Docs/Architecture/05_class_insights_service.jpg](<../Docs/Architecture/05_class_insights_service.jpg>) | Historical/backup design; current diagram/correction supersession applies | +| [Docs/Architecture/06_class_health_overview_service.drawio](<../Docs/Architecture/06_class_health_overview_service.drawio>) | Existing architecture choices; reconsiderable; current diagrams override corresponding old snapshots | +| [Docs/Architecture/06_class_health_overview_service.jpg](<../Docs/Architecture/06_class_health_overview_service.jpg>) | Historical/backup design; current diagram/correction supersession applies | +| [Docs/Architecture/07_er_patient_profile_service.jpg](<../Docs/Architecture/07_er_patient_profile_service.jpg>) | Historical/backup design; current diagram/correction supersession applies | +| [Docs/Architecture/08_er_observation_service.drawio](<../Docs/Architecture/08_er_observation_service.drawio>) | Existing architecture choices; reconsiderable; current diagrams override corresponding old snapshots | +| [Docs/Architecture/08_er_observation_service.jpg](<../Docs/Architecture/08_er_observation_service.jpg>) | Historical/backup design; current diagram/correction supersession applies | +| [Docs/Architecture/09_er_insights_service-overruled no persistence here to give an idea of what data is needed to be able to use from other services or calculate.jpg](<../Docs/Architecture/09_er_insights_service-overruled no persistence here to give an idea of what data is needed to be able to use from other services or calculate.jpg>) | Historical/backup design; current diagram/correction supersession applies | +| [Docs/Architecture/09_er_insights_service.drawio](<../Docs/Architecture/09_er_insights_service.drawio>) | Existing architecture choices; reconsiderable; current diagrams override corresponding old snapshots | +| [Docs/Architecture/10_er_health_overview_service-overruled no persistence here to give an idea of what data is needed to be able to use from other services or calculate.jpg](<../Docs/Architecture/10_er_health_overview_service-overruled no persistence here to give an idea of what data is needed to be able to use from other services or calculate.jpg>) | Historical/backup design; current diagram/correction supersession applies | +| [Docs/Architecture/README.md](<../Docs/Architecture/README.md>) | Existing architecture choices; reconsiderable; current diagrams override corresponding old snapshots | +| [Docs/Architecture/personal_health_measurement_all_diagrams-Domain Model.jpg](<../Docs/Architecture/personal_health_measurement_all_diagrams-Domain Model.jpg>) | Historical/backup design; current diagram/correction supersession applies | +| [Docs/Architecture/us10-insights-correction.md](<../Docs/Architecture/us10-insights-correction.md>) | Existing architecture choices; reconsiderable; current diagrams override corresponding old snapshots | +| [Docs/AsBuiltArchitecture/README.md](<../Docs/AsBuiltArchitecture/README.md>) | Descriptive baseline; implementation declarations/evidence are context, not required design classes | +| [Docs/AsBuiltArchitecture/architecture-decisions.md](<../Docs/AsBuiltArchitecture/architecture-decisions.md>) | Descriptive baseline; implementation declarations/evidence are context, not required design classes | +| [Docs/AsBuiltArchitecture/class-diagram-coverage.md](<../Docs/AsBuiltArchitecture/class-diagram-coverage.md>) | Descriptive baseline; implementation declarations/evidence are context, not required design classes | +| [Docs/AsBuiltArchitecture/diagrams/01-system-context.drawio](<../Docs/AsBuiltArchitecture/diagrams/01-system-context.drawio>) | Descriptive baseline; implementation declarations/evidence are context, not required design classes | +| [Docs/AsBuiltArchitecture/diagrams/02-logical-services.drawio](<../Docs/AsBuiltArchitecture/diagrams/02-logical-services.drawio>) | Descriptive baseline; implementation declarations/evidence are context, not required design classes | +| [Docs/AsBuiltArchitecture/diagrams/03-domain-model.drawio](<../Docs/AsBuiltArchitecture/diagrams/03-domain-model.drawio>) | Descriptive baseline; implementation declarations/evidence are context, not required design classes | +| [Docs/AsBuiltArchitecture/diagrams/04-class-ApiGateway.drawio](<../Docs/AsBuiltArchitecture/diagrams/04-class-ApiGateway.drawio>) | Descriptive baseline; implementation declarations/evidence are context, not required design classes | +| [Docs/AsBuiltArchitecture/diagrams/04-class-HealthOverviewService.drawio](<../Docs/AsBuiltArchitecture/diagrams/04-class-HealthOverviewService.drawio>) | Descriptive baseline; implementation declarations/evidence are context, not required design classes | +| [Docs/AsBuiltArchitecture/diagrams/04-class-InsightsService.drawio](<../Docs/AsBuiltArchitecture/diagrams/04-class-InsightsService.drawio>) | Descriptive baseline; implementation declarations/evidence are context, not required design classes | +| [Docs/AsBuiltArchitecture/diagrams/04-class-ObservationService.drawio](<../Docs/AsBuiltArchitecture/diagrams/04-class-ObservationService.drawio>) | Descriptive baseline; implementation declarations/evidence are context, not required design classes | +| [Docs/AsBuiltArchitecture/diagrams/04-class-PatientProfileService.drawio](<../Docs/AsBuiltArchitecture/diagrams/04-class-PatientProfileService.drawio>) | Descriptive baseline; implementation declarations/evidence are context, not required design classes | +| [Docs/AsBuiltArchitecture/diagrams/04-design-classes.drawio](<../Docs/AsBuiltArchitecture/diagrams/04-design-classes.drawio>) | Descriptive baseline; implementation declarations/evidence are context, not required design classes | +| [Docs/AsBuiltArchitecture/diagrams/05-data-ownership.drawio](<../Docs/AsBuiltArchitecture/diagrams/05-data-ownership.drawio>) | Descriptive baseline; implementation declarations/evidence are context, not required design classes | +| [Docs/AsBuiltArchitecture/diagrams/06-deployment.drawio](<../Docs/AsBuiltArchitecture/diagrams/06-deployment.drawio>) | Descriptive baseline; implementation declarations/evidence are context, not required design classes | +| [Docs/AsBuiltArchitecture/diagrams/07-sequences.drawio](<../Docs/AsBuiltArchitecture/diagrams/07-sequences.drawio>) | Descriptive baseline; implementation declarations/evidence are context, not required design classes | +| [Docs/AsBuiltArchitecture/discrepancies.md](<../Docs/AsBuiltArchitecture/discrepancies.md>) | Descriptive baseline; implementation declarations/evidence are context, not required design classes | +| [Docs/AsBuiltArchitecture/evidence-inventory.md](<../Docs/AsBuiltArchitecture/evidence-inventory.md>) | Descriptive baseline; implementation declarations/evidence are context, not required design classes | +| [Docs/AsBuiltArchitecture/requirements-traceability.md](<../Docs/AsBuiltArchitecture/requirements-traceability.md>) | Descriptive baseline; implementation declarations/evidence are context, not required design classes | +| [Docs/AsBuiltArchitecture/software-architecture.md](<../Docs/AsBuiltArchitecture/software-architecture.md>) | Descriptive baseline; implementation declarations/evidence are context, not required design classes | +| [Docs/AsBuiltArchitecture/validation.md](<../Docs/AsBuiltArchitecture/validation.md>) | Descriptive baseline; implementation declarations/evidence are context, not required design classes | +| [Docs/Design/authentication-and-access-control-design.md](<../Docs/Design/authentication-and-access-control-design.md>) | Access/security intent binding; existing structure and open mechanisms are design choices | +| [Docs/Requirements/00-common-requirements.md](<../Docs/Requirements/00-common-requirements.md>) | Binding functional behaviour and acceptance criteria | +| [Docs/Requirements/US16 easy installation and deployment installer.txt](<../Docs/Requirements/US16 easy installation and deployment installer.txt>) | Binding functional/common criteria; US-16 topology clauses revised only under explicit user clarification | +| [Docs/Requirements/us01-create-patient-profile.md](<../Docs/Requirements/us01-create-patient-profile.md>) | Binding functional behaviour and acceptance criteria | +| [Docs/Requirements/us02-view-patient-profile.md](<../Docs/Requirements/us02-view-patient-profile.md>) | Binding functional behaviour and acceptance criteria | +| [Docs/Requirements/us03-update-patient-profile.md](<../Docs/Requirements/us03-update-patient-profile.md>) | Binding functional behaviour and acceptance criteria | +| [Docs/Requirements/us04-record-observation.md](<../Docs/Requirements/us04-record-observation.md>) | Binding functional behaviour and acceptance criteria | +| [Docs/Requirements/us05-view-observation.md](<../Docs/Requirements/us05-view-observation.md>) | Binding functional behaviour and acceptance criteria | +| [Docs/Requirements/us06-latest-observation.md](<../Docs/Requirements/us06-latest-observation.md>) | Binding functional behaviour and acceptance criteria | +| [Docs/Requirements/us07-observation-history.md](<../Docs/Requirements/us07-observation-history.md>) | Binding functional behaviour and acceptance criteria | +| [Docs/Requirements/us08-update-observation.md](<../Docs/Requirements/us08-update-observation.md>) | Binding functional behaviour and acceptance criteria | +| [Docs/Requirements/us09-delete-observation.md](<../Docs/Requirements/us09-delete-observation.md>) | Binding functional behaviour and acceptance criteria | +| [Docs/Requirements/us10-calculated-insight.md](<../Docs/Requirements/us10-calculated-insight.md>) | Binding functional behaviour and acceptance criteria | +| [Docs/Requirements/us11-health-trend.md](<../Docs/Requirements/us11-health-trend.md>) | Binding functional behaviour and acceptance criteria | +| [Docs/Requirements/us12-health-overview.md](<../Docs/Requirements/us12-health-overview.md>) | Binding functional behaviour and acceptance criteria | +| [Docs/Requirements/us13-patient-authentication.md](<../Docs/Requirements/us13-patient-authentication.md>) | Binding functional behaviour and acceptance criteria | +| [Docs/Requirements/us14-professional-access.md](<../Docs/Requirements/us14-professional-access.md>) | Binding functional behaviour and acceptance criteria | +| [Docs/Requirements/us15-measurement-guidance.md](<../Docs/Requirements/us15-measurement-guidance.md>) | Binding functional behaviour and acceptance criteria | +| [Docs/Requirements/us16-addendum](<../Docs/Requirements/us16-addendum>) | Binding functional/common criteria; US-16 topology clauses revised only under explicit user clarification | +| [Docs/requirements-reconciliation-changelog.md](<../Docs/requirements-reconciliation-changelog.md>) | Requirement reconciliation and source supersession authority | + +Missing information: workload/capacity, physical hosting/idle behaviour, availability/recovery targets, mandatory runtime isolation, clinical content review owner, supported Linux distribution matrix and precise future mathematical method. These are recorded with reversible assumptions in [risks](risks-and-open-questions.md); no invented numerical requirements are introduced. diff --git a/ArchitectureProposal/requirements-and-constraints.md b/ArchitectureProposal/requirements-and-constraints.md new file mode 100644 index 0000000..b897ca1 --- /dev/null +++ b/ArchitectureProposal/requirements-and-constraints.md @@ -0,0 +1,35 @@ +# Requirements and constraints register + +Sources are indexed in [input inventory](input-inventory.md). Paths below are relative to repository root. Functional behaviours and every acceptance scenario are mapped in [traceability](requirements-traceability.md). + +| ID / source | Classification | Binding meaning / treatment | +| --- | --- | --- | +| FR01 `Docs/Requirements/us01-create-patient-profile.md` | Mandatory | Authenticated own initial creation, required name/birth, generated ID, zero-to-one association, durable/retry/concurrent/recovery correctness; no professional creation | +| FR02 `Docs/Requirements/us02-view-patient-profile.md` | Mandatory | ID/name/birth/contact retrieval and absent-resource outcome after authorization | +| FR03 `Docs/Requirements/us03-update-patient-profile.md` | Mandatory | Existing profile correction preserves identifier; missing profile never created | +| FR04 `Docs/Requirements/us04-record-observation.md` | Mandatory | Positive three readings and timestamp; existing patient; later retrieval; independently recorded setting/activity, partial/absent context, departures, original narrative retained, invalid categories rejected | +| FR05 `Docs/Requirements/us05-view-observation.md` | Mandatory | Specific observation/current measurements/time/context, known versus unknown and preserved text; missing/unauthorized outcomes | +| FR06 `Docs/Requirements/us06-latest-observation.md` | Mandatory | Greatest measurement instant then original recording instant, deterministic complete tie; edits/context suitability never alter precedence | +| FR07 `Docs/Requirements/us07-observation-history.md` | Mandatory | Ascending inclusive patient history; independent/combined/Unknown selection; no selection excludes nothing on context alone; empty result, unsupported selection rejection | +| FR08 `Docs/Requirements/us08-update-observation.md` | Mandatory | Numeric/context correction/clear; omitted values preserved; invalid update atomic rejection; subsequent reads/calculations use current values | +| FR09 `Docs/Requirements/us09-delete-observation.md` | Mandatory | Delete observation/owned context from later reads/history/calculations; other observations unaffected; missing/unauthorized outcomes | +| FR10 `Docs/Requirements/us10-calculated-insight.md` | Mandatory | Current selected arithmetic means, final half-up two decimals, BP extrema, one sufficient/zero unavailable; count/basis/context limits | +| FR11 `Docs/Requirements/us11-health-trend.md` | Mandatory | Three metrics/units; full-period direction and variation/reversals; appropriate references and cautious separate interpretations; comparability evidence/conflicts/missing facts; temporal sufficiency, current corrections/deletions, reproducible ordering-independent methods | +| FR12 `Docs/Requirements/us12-health-overview.md` | Mandatory | Profile/latest overall/selected-period numerical insight only; preserve context and distinct bases; absence retains available parts; no trend added | +| FR13 `Docs/Requirements/us13-patient-authentication.md` | Mandatory | Valid/generic invalid login; protected own-data access, missing/invalid/expired auth rejection; profile-less login/create; synthetic pre-created accounts | +| FR14 `Docs/Requirements/us14-professional-access.md` | Mandatory | Pre-created professionals/predefined many-to-many assignments; own assignment list, assigned read-only all data/context/calculations; no unassigned data or writes; patient cannot use professional-only operations | +| FR15 `Docs/Requirements/us15-measurement-guidance.md` | Mandatory | Public sourced/reviewed ordered setting-appropriate guidance, required topics/pulse limits, actual circumstances; optional/non-certifying/no side effects; unavailability explanation; no medication recommendations | +| FR16 `Docs/Requirements/00-common-requirements.md` | Mandatory | All data operations share actual-owner/access and lifecycle rules; inclusive/equal/reversed period semantics, measurement-instant normalization, AND selections, Unknown distinction, context preservation, guidance evidence, acceptance-state independence | +| D16 `Docs/Requirements/US16 easy installation and deployment installer.txt`, `us16-addendum` | Originally mandatory; topology revision explicitly authorized | Independent feature processes/configuration/distribution/separate DB ownership are incompatible with selection. Every AC and addendum clause is classified in [US-16 revision](us16-revision.md); installer automation/security/verification intent retained at app granularity | +| SEC `Docs/Design/authentication-and-access-control-design.md` §§2–9 | Mandatory access/security intent; optional structural mechanism | Tokens time limited and trusted identity normalized; no password validation each business request/custom crypto; actual owner and assignment policy; HTTPS/secrets; replaceable identity; no bypass. Gateway becomes logical API edge; no internal network trust required. Framework integration retained; token choice/keys/ownership elaborated | +| SEC open choices, same source §10 and final paragraph | Optional/unfinished input design | Format, lifetime, account-association persistence, recovery, internal protection and exact contracts require design selection, not assumption of approved existing implementations. ADR-03/04 and specification supply proposal | +| BASE `Docs/Architecture/README.md`, `us10-insights-correction.md`, current diagrams | Optional baseline topology/persistence/classes | Five processes, all calls gateway-routed, separate persistent service DBs, controller/application/repository structure are reconsiderable under user option 3. Retain logical responsibilities and on-demand fresh results; no stored summaries/trends chosen independently | +| HIST historical JPEGs, `.bkp` backups | Optional/historical | Current Draw.io/correction overrides old summary/overview persistence; old omissions never remove accounts/context/trends/guidance requirements | +| AB all `Docs/AsBuiltArchitecture/` | Descriptive, not binding | Existing route/field/error documentation used as external compatibility target; code-specific classes/versions/OS adapters/pooling/timestamp type/phrase detector/OLS are not new requirements. Source links not followed | +| NFR energy objective, `AGENT.md` and user request | Mandatory design objective | Compare alternatives; mechanisms/assumptions/counter-effects only, no invented measurements, quantitative savings or measurement procedures | +| NFR correctness/security/maintainability/deployability, `AGENT.md` | Mandatory design considerations | Explicit boundaries, ownership/transactions, access, failures, deployability and testable contract responsibilities; energy cannot excuse behavioural weakening | +| A1 workload/hosting | Assumed, reversible | Modest interactive synthetic prototype; Linux/systemd baseline; single app/local DB default, remote DB supported. No numerical load/SLA claim | +| A2 implementation framework/storage | Selected optional design | Retain ASP.NET Core framework integration and PostgreSQL; no specific package/runtime version prescription or source inspection | +| A3 runtime security isolation/HA | Unknown, recorded | No mandatory independent fault isolation/HA/SLA found; if required, revisit selection rather than claim logical modules supply it | + +Clinical applicability is binding when a clinical claim is made; no particular threshold or new clinical formula is selected here. Missing optional facts limit only claims depending on them. Formula freedom permits documented reproducible implementation methods, not arbitrary clinical labels. The architecture identifies the policies/content records and validation obligations required to preserve these rules. diff --git a/ArchitectureProposal/requirements-traceability.md b/ArchitectureProposal/requirements-traceability.md new file mode 100644 index 0000000..7ee8227 --- /dev/null +++ b/ArchitectureProposal/requirements-traceability.md @@ -0,0 +1,332 @@ +# Requirements traceability + +Architecture-level coverage, not executed application acceptance. All source criteria remain visible; US-16 incompatibilities are authorized by user option 3 and listed separately. Every result must additionally pass US-13/14 and common access rules. Specification section references below refer to [software-architecture.md](software-architecture.md). + +## Story and functional-rule coverage + +See [requirements register](requirements-and-constraints.md) FR01–FR16 for every story’s functional rules and [US-16 revision](us16-revision.md) for deployment clauses. The authoritative specification defines the domain, operations, ownership, interactions and error outcomes; the following register maps each acceptance scenario and named AC individually. + +| Source / story | Components | Specification | Interaction / mechanism | +| --- | --- | --- | --- | +| [Common](../Docs/Requirements/00-common-requirements.md) | API/access; Observations; Analytics; Overview | §§3–6 | Shared Period/Selection validation and patient authorization; one source snapshot per result; inclusive predicates precede operation-specific sufficiency. | +| [US-01](../Docs/Requirements/us01-create-patient-profile.md) | API/access; Profile | §§3–5 | Claim-derived account; required profile fields; durable single-row transaction plus account uniqueness; existing-profile conflict and own-profile recovery. | +| [US-02](../Docs/Requirements/us02-view-patient-profile.md) | API/access; Profile | §§4–5,8 | Authorize actual patient; ProfileQueries returns saved ID/name/birth/contact or authorized absence. | +| [US-03](../Docs/Requirements/us03-update-patient-profile.md) | API/access; Profile | §§4–5 | Owner-only atomic update preserves identity/association; absent row is never an insert. | +| [US-04](../Docs/Requirements/us04-record-observation.md) | API/access; Profile; Observations | §§3–5,7 | Validate positive required values/time/categories; verify patient; commit observation and owned context together; unknown/partial details and original text remain retrievable. | +| [US-05](../Docs/Requirements/us05-view-observation.md) | API/access; Observations | §§3–5,8 | Resolve actual owner within snapshot; authorize before serializing current observation and attached known/unknown context; preserve legacy text. | +| [US-06](../Docs/Requirements/us06-latest-observation.md) | API/access; Observations | §§3–5 | LatestQuery uses measurement instant, immutable original recording instant, greatest UUID-byte tie; never substitutes for context completeness; authorized absence explicit. | +| [US-07](../Docs/Requirements/us07-observation-history.md) | API/access; Observations | §§3–5,7 | Inclusive patient/period query with independently optional AND context predicates; explicit Unknown; ascending time/UUID and applied metadata; complete empty collection allowed. | +| [US-08](../Docs/Requirements/us08-update-observation.md) | API/access; Observations | §§4–5,7 | Locked atomic patch; absent/preserve versus explicit clear; validate all changes first; immutable owner/ID/original recording; current later snapshots change selection membership. | +| [US-09](../Docs/Requirements/us09-delete-observation.md) | API/access; Observations; Analytics | §§5–8 | Atomic row/context deletion with actual-owner authorization; later snapshots and derived results cannot include removed data; other rows unaffected. | +| [US-10](../Docs/Requirements/us10-calculated-insight.md) | API/access; Observations; Analytics | §§3–6 | Capture current filtered raw series; SummaryPolicy arithmetic means/final two-decimal half-up and raw BP extrema; count/selection/context explanation; one sufficient, zero no insight. | +| [US-11](../Docs/Requirements/us11-health-trend.md) | API/access; Observations; Analytics; Guidance | §§3–6 | Current selected full-period series; deterministic TrendPolicy with distinct-time sufficiency, raw variation and reversals; separate metric results; claim-specific ClinicalPolicy and comparability evidence. | +| [US-12](../Docs/Requirements/us12-health-overview.md) | API/access; Profile; Observations; Analytics; Overview | §§4–6 | Single snapshot composition; unfiltered latest overall and its own context; period/selection applies only to insight; retain profile/latest when insight absent, with distinct bases; no trend. | +| [US-13](../Docs/Requirements/us13-patient-authentication.md) | API/access; Profile | §§4–5,8 | Established login/token validation; generic credential failure and expiry; per-request actual-owner policy; profile-less login/create allowed; never disclose another patient. | +| [US-14](../Docs/Requirements/us14-professional-access.md) | API/access; Profile; Observations; Analytics; Overview | §§4–5,8 | Trusted Professional role; own predefined assignment list; actual-owner assigned reads only; forbid every write; empty/missing and unauthorized cases remain distinct without disclosure. | +| [US-15](../Docs/Requirements/us15-measurement-guidance.md) | API/access; Guidance; Observations | §§4,6,8 | Public reviewed ordered setting-labelled content with source/date and pulse limits; no observation write/certification/defaulting/submission dependency; unsupported verified content unavailable. | + +## Individual acceptance criteria + +Outline example rows are explicitly retained. The outcome column preserves all Then/And obligations after the When. State setup is independent; architectural responsibilities do not require running another story first. + +### Common period criteria + +Source: [00-common-requirements.md](../Docs/Requirements/00-common-requirements.md). Responsible: **API/access; Observations; Analytics; Overview**, specification §§3–6. + +Shared Period/Selection validation and patient authorization; one source snapshot per result; inclusive predicates precede operation-specific sufficiency. + +| Local criterion ID / source title | Required outcome and cases | Design responsibility | +| --- | --- | --- | +| 00-AC-01: Include both boundaries | both boundary observations contribute; observations outside the period do not contribute. Outline cases: operation: history, numerical insight, trend assessment, overview insight | Shared Period/Selection validation and patient authorization; one source snapshot per result; inclusive predicates precede operation-specific sufficiency. | +| 00-AC-02: Equal bounds are valid | the period is accepted; only observations at that instant are selected; the operation applies its own data-sufficiency rules. Outline cases: operation: history, numerical insight, trend assessment, overview insight | Shared Period/Selection validation and patient authorization; one source snapshot per result; inclusive predicates precede operation-specific sufficiency. | +| 00-AC-03: Reject reversed bounds | the request is rejected. Outline cases: operation: history, numerical insight, trend assessment, overview insight | Shared Period/Selection validation and patient authorization; one source snapshot per result; inclusive predicates precede operation-specific sufficiency. | + +### US-01 + +Source: [us01-create-patient-profile.md](../Docs/Requirements/us01-create-patient-profile.md). Responsible: **API/access; Profile**, specification §§3–5. + +Claim-derived account; required profile fields; durable single-row transaction plus account uniqueness; existing-profile conflict and own-profile recovery. + +| Local criterion ID / source title | Required outcome and cases | Design responsibility | +| --- | --- | --- | +| 01-AC-01: Create a patient with valid information | the patient profile is created successfully; a patient identifier is assigned; the identifier is associated with the authenticated account | Claim-derived account; required profile fields; durable single-row transaction plus account uniqueness; existing-profile conflict and own-profile recovery. | +| 01-AC-02: A patient name is required | the patient profile is rejected | Claim-derived account; required profile fields; durable single-row transaction plus account uniqueness; existing-profile conflict and own-profile recovery. | +| 01-AC-03: A date of birth is required | the patient profile is rejected | Claim-derived account; required profile fields; durable single-row transaction plus account uniqueness; existing-profile conflict and own-profile recovery. | +| 01-AC-04: Reject a second profile | the request reports that a profile already exists; no second profile is created and the association is unchanged | Claim-derived account; required profile fields; durable single-row transaction plus account uniqueness; existing-profile conflict and own-profile recovery. | +| 01-AC-05: Persistent account association | the same associated profile is returned | Claim-derived account; required profile fields; durable single-row transaction plus account uniqueness; existing-profile conflict and own-profile recovery. | +| 01-AC-06: Retry after a successful creation response was lost | the result indicates that the profile already exists; no duplicate profile or replacement association is created | Claim-derived account; required profile fields; durable single-row transaction plus account uniqueness; existing-profile conflict and own-profile recovery. | +| 01-AC-07: Concurrent initial creation | at most one profile is created and associated with the account; no request reports a second profile as created | Claim-derived account; required profile fields; durable single-row transaction plus account uniqueness; existing-profile conflict and own-profile recovery. | +| 01-AC-08: Recovery after interrupted creation | the operation recovers to one accessible associated profile or reports that creation remains incomplete; it neither produces duplicate profiles nor reports an inaccessible profile as successfully created | Claim-derived account; required profile fields; durable single-row transaction plus account uniqueness; existing-profile conflict and own-profile recovery. | +| 01-AC-09: Unauthenticated initial creation | the request is rejected and no profile is created | Claim-derived account; required profile fields; durable single-row transaction plus account uniqueness; existing-profile conflict and own-profile recovery. | + +### US-02 + +Source: [us02-view-patient-profile.md](../Docs/Requirements/us02-view-patient-profile.md). Responsible: **API/access; Profile**, specification §§4–5,8. + +Authorize actual patient; ProfileQueries returns saved ID/name/birth/contact or authorized absence. + +| Local criterion ID / source title | Required outcome and cases | Design responsibility | +| --- | --- | --- | +| 02-AC-01: Retrieve an existing patient | the patient profile is returned; the returned patient identifier matches the requested patient; the patient's name is included; the patient's date of birth is included; the patient's contact information is included | Authorize actual patient; ProfileQueries returns saved ID/name/birth/contact or authorized absence. | +| 02-AC-02: Request a patient that does not exist | the request reports that the patient does not exist | Authorize actual patient; ProfileQueries returns saved ID/name/birth/contact or authorized absence. | + +### US-03 + +Source: [us03-update-patient-profile.md](../Docs/Requirements/us03-update-patient-profile.md). Responsible: **API/access; Profile**, specification §§4–5. + +Owner-only atomic update preserves identity/association; absent row is never an insert. + +| Local criterion ID / source title | Required outcome and cases | Design responsibility | +| --- | --- | --- | +| 03-AC-01: Update an existing patient | the update succeeds; the patient identifier is unchanged; the patient profile contains contact information "new@example.test" | Owner-only atomic update preserves identity/association; absent row is never an insert. | +| 03-AC-02: Update a patient that does not exist | the update is rejected; no new patient is created | Owner-only atomic update preserves identity/association; absent row is never an insert. | + +### US-04 + +Source: [us04-record-observation.md](../Docs/Requirements/us04-record-observation.md). Responsible: **API/access; Profile; Observations**, specification §§3–5,7. + +Validate positive required values/time/categories; verify patient; commit observation and owned context together; unknown/partial details and original text remain retrievable. + +| Local criterion ID / source title | Required outcome and cases | Design responsibility | +| --- | --- | --- | +| 04-AC-01: Record a valid observation | the observation is accepted; an observation identifier is assigned; the observation is associated with the patient; the observation can be retrieved later | Validate positive required values/time/categories; verify patient; commit observation and owned context together; unknown/partial details and original text remain retrievable. | +| 04-AC-02: Record an observation without optional fields | the observation is accepted | Validate positive required values/time/categories; verify patient; commit observation and owned context together; unknown/partial details and original text remain retrievable. | +| 04-AC-03: Reject an observation containing a non-positive measured value | the observation is rejected. Outline cases: columns (systolic, diastolic, pulse); cases (0, 82, 68), (-1, 82, 68), (128, 0, 68), (128, -1, 68), (128, 82, 0), (128, 82, -1) | Validate positive required values/time/categories; verify patient; commit observation and owned context together; unknown/partial details and original text remain retrievable. | +| 04-AC-04: Reject an observation without a measurement timestamp | the observation is rejected | Validate positive required values/time/categories; verify patient; commit observation and owned context together; unknown/partial details and original text remain retrievable. | +| 04-AC-05: Record an observation for a patient that does not exist | the observation is rejected | Validate positive required values/time/categories; verify patient; commit observation and owned context together; unknown/partial details and original text remain retrievable. | +| 04-AC-06: Record setting and condition independently | observation creation succeeds | Validate positive required values/time/categories; verify patient; commit observation and owned context together; unknown/partial details and original text remain retrievable. | +| 04-AC-07: Record partial context | observation creation succeeds | Validate positive required values/time/categories; verify patient; commit observation and owned context together; unknown/partial details and original text remain retrievable. | +| 04-AC-08: Retain support for absent context | observation creation succeeds | Validate positive required values/time/categories; verify patient; commit observation and owned context together; unknown/partial details and original text remain retrievable. | +| 04-AC-09: Record departure from routine | observation creation succeeds | Validate positive required values/time/categories; verify patient; commit observation and owned context together; unknown/partial details and original text remain retrievable. | +| 04-AC-10: Reject unsupported category | the operation is rejected with an explanation of the invalid category | Validate positive required values/time/categories; verify patient; commit observation and owned context together; unknown/partial details and original text remain retrievable. | +| 04-AC-11: Retrieve previously saved context | the returned observation contains those saved details associated with that observation | Validate positive required values/time/categories; verify patient; commit observation and owned context together; unknown/partial details and original text remain retrievable. | +| 04-AC-12: Reject another patient’s context submission | the operation is rejected | Validate positive required values/time/categories; verify patient; commit observation and owned context together; unknown/partial details and original text remain retrievable. | + +### US-05 + +Source: [us05-view-observation.md](../Docs/Requirements/us05-view-observation.md). Responsible: **API/access; Observations**, specification §§3–5,8. + +Resolve actual owner within snapshot; authorize before serializing current observation and attached known/unknown context; preserve legacy text. + +| Local criterion ID / source title | Required outcome and cases | Design responsibility | +| --- | --- | --- | +| 05-AC-01: Retrieve an existing observation | the observation is returned; the systolic value is 128; the diastolic value is 82; the pulse value is 68 | Resolve actual owner within snapshot; authorize before serializing current observation and attached known/unknown context; preserve legacy text. | +| 05-AC-02: Retrieve an observation that does not exist | the request reports that the observation does not exist | Resolve actual owner within snapshot; authorize before serializing current observation and attached known/unknown context; preserve legacy text. | +| 05-AC-03: Return complete saved context | its saved context is returned with its numerical measurements and timestamp | Resolve actual owner within snapshot; authorize before serializing current observation and attached known/unknown context; preserve legacy text. | +| 05-AC-04: Return partial context | Clinic is returned as the setting; activity condition is represented as unknown | Resolve actual owner within snapshot; authorize before serializing current observation and attached known/unknown context; preserve legacy text. | +| 05-AC-05: Preserve historical free text | the original text is returned; no definite setting or activity condition is invented | Resolve actual owner within snapshot; authorize before serializing current observation and attached known/unknown context; preserve legacy text. | +| 05-AC-06: Protect context | access is rejected; its context is not disclosed | Resolve actual owner within snapshot; authorize before serializing current observation and attached known/unknown context; preserve legacy text. | + +### US-06 + +Source: [us06-latest-observation.md](../Docs/Requirements/us06-latest-observation.md). Responsible: **API/access; Observations**, specification §§3–5. + +LatestQuery uses measurement instant, immutable original recording instant, greatest UUID-byte tie; never substitutes for context completeness; authorized absence explicit. + +| Local criterion ID / source title | Required outcome and cases | Design responsibility | +| --- | --- | --- | +| 06-AC-01: Return the most recent observation | the observation measured at "2026-09-12T08:00:00" is returned | LatestQuery uses measurement instant, immutable original recording instant, greatest UUID-byte tie; never substitutes for context completeness; authorized absence explicit. | +| 06-AC-02: Patient has no observations | the result indicates that no observation is available | LatestQuery uses measurement instant, immutable original recording instant, greatest UUID-byte tie; never substitutes for context completeness; authorized absence explicit. | +| 06-AC-03: Return context of latest observation | the newer observation is returned with its after-activity context | LatestQuery uses measurement instant, immutable original recording instant, greatest UUID-byte tie; never substitutes for context completeness; authorized absence explicit. | +| 06-AC-04: Do not substitute a more complete observation | the latest observation is returned; its context is represented as unknown | LatestQuery uses measurement instant, immutable original recording instant, greatest UUID-byte tie; never substitutes for context completeness; authorized absence explicit. | +| 06-AC-05: Preserve timestamp tie selection | the second observation is returned with its own setting | LatestQuery uses measurement instant, immutable original recording instant, greatest UUID-byte tie; never substitutes for context completeness; authorized absence explicit. | +| 06-AC-06: No observations | the system reports that no observation is available | LatestQuery uses measurement instant, immutable original recording instant, greatest UUID-byte tie; never substitutes for context completeness; authorized absence explicit. | +| 06-AC-07: Resolve a complete timestamp tie reproducibly | the same observation is returned under the documented final tie rule | LatestQuery uses measurement instant, immutable original recording instant, greatest UUID-byte tie; never substitutes for context completeness; authorized absence explicit. | + +### US-07 + +Source: [us07-observation-history.md](../Docs/Requirements/us07-observation-history.md). Responsible: **API/access; Observations**, specification §§3–5,7. + +Inclusive patient/period query with independently optional AND context predicates; explicit Unknown; ascending time/UUID and applied metadata; complete empty collection allowed. + +| Local criterion ID / source title | Required outcome and cases | Design responsibility | +| --- | --- | --- | +| 07-AC-01: Retrieve observations within a period | exactly 1 observation is returned; the returned observation was measured at "2026-09-05T08:00:00" | Inclusive patient/period query with independently optional AND context predicates; explicit Unknown; ascending time/UUID and applied metadata; complete empty collection allowed. | +| 07-AC-02: Return observations in chronological order | the observations are returned in chronological order by measurement timestamp | Inclusive patient/period query with independently optional AND context predicates; explicit Unknown; ascending time/UUID and applied metadata; complete empty collection allowed. | +| 07-AC-03: No observations exist within the requested period | an empty observation collection is returned | Inclusive patient/period query with independently optional AND context predicates; explicit Unknown; ascending time/UUID and applied metadata; complete empty collection allowed. | +| 07-AC-04: Reject an invalid period | the request is rejected | Inclusive patient/period query with independently optional AND context predicates; explicit Unknown; ascending time/UUID and applied metadata; complete empty collection allowed. | +| 07-AC-05: Select home observations | only home observations within the period are returned with their context | Inclusive patient/period query with independently optional AND context predicates; explicit Unknown; ascending time/UUID and applied metadata; complete empty collection allowed. | +| 07-AC-06: Combine setting and activity | only home-resting observations are returned | Inclusive patient/period query with independently optional AND context predicates; explicit Unknown; ascending time/UUID and applied metadata; complete empty collection allowed. | +| 07-AC-07: Select unknown context | only observations with unknown setting are returned | Inclusive patient/period query with independently optional AND context predicates; explicit Unknown; ascending time/UUID and applied metadata; complete empty collection allowed. | +| 07-AC-08: No selection excludes nothing on context alone | all those observations are returned in ascending measurement-time order | Inclusive patient/period query with independently optional AND context predicates; explicit Unknown; ascending time/UUID and applied metadata; complete empty collection allowed. | +| 07-AC-09: No matching observations | an empty collection is returned | Inclusive patient/period query with independently optional AND context predicates; explicit Unknown; ascending time/UUID and applied metadata; complete empty collection allowed. | +| 07-AC-10: Reject unsupported selection | the request is rejected with an explanation | Inclusive patient/period query with independently optional AND context predicates; explicit Unknown; ascending time/UUID and applied metadata; complete empty collection allowed. | +| 07-AC-11: Preserve patient and boundary rules | both boundary observations are returned; the outside-period and other-patient observations are excluded | Inclusive patient/period query with independently optional AND context predicates; explicit Unknown; ascending time/UUID and applied metadata; complete empty collection allowed. | + +### US-08 + +Source: [us08-update-observation.md](../Docs/Requirements/us08-update-observation.md). Responsible: **API/access; Observations**, specification §§4–5,7. + +Locked atomic patch; absent/preserve versus explicit clear; validate all changes first; immutable owner/ID/original recording; current later snapshots change selection membership. + +| Local criterion ID / source title | Required outcome and cases | Design responsibility | +| --- | --- | --- | +| 08-AC-01: Correct an existing observation | the update succeeds; the observation identifier is unchanged; the observation contains systolic value 128 | Locked atomic patch; absent/preserve versus explicit clear; validate all changes first; immutable owner/ID/original recording; current later snapshots change selection membership. | +| 08-AC-02: Reject an update containing a non-positive measured value | the update is rejected. Outline cases: columns (systolic, diastolic, pulse); cases (0, 82, 68), (128, 0, 68), (128, 82, 0) | Locked atomic patch; absent/preserve versus explicit clear; validate all changes first; immutable owner/ID/original recording; current later snapshots change selection membership. | +| 08-AC-03: Update an observation that does not exist | the update is rejected | Locked atomic patch; absent/preserve versus explicit clear; validate all changes first; immutable owner/ID/original recording; current later snapshots change selection membership. | +| 08-AC-04: Add context to historical observation | the update succeeds | Locked atomic patch; absent/preserve versus explicit clear; validate all changes first; immutable owner/ID/original recording; current later snapshots change selection membership. | +| 08-AC-05: Correct one context value | the update succeeds | Locked atomic patch; absent/preserve versus explicit clear; validate all changes first; immutable owner/ID/original recording; current later snapshots change selection membership. | +| 08-AC-06: Clear optional context | the update succeeds | Locked atomic patch; absent/preserve versus explicit clear; validate all changes first; immutable owner/ID/original recording; current later snapshots change selection membership. | +| 08-AC-07: Retrieve partially corrected observation | Clinic is returned; the original numerical values, timestamp, activity condition, and note are returned unchanged | Locked atomic patch; absent/preserve versus explicit clear; validate all changes first; immutable owner/ID/original recording; current later snapshots change selection membership. | +| 08-AC-08: Reject invalid context correction | the update is rejected | Locked atomic patch; absent/preserve versus explicit clear; validate all changes first; immutable owner/ID/original recording; current later snapshots change selection membership. | +| 08-AC-09: Nonexistent observation | the update is rejected | Locked atomic patch; absent/preserve versus explicit clear; validate all changes first; immutable owner/ID/original recording; current later snapshots change selection membership. | +| 08-AC-10: Unauthorised correction | the operation is rejected | Locked atomic patch; absent/preserve versus explicit clear; validate all changes first; immutable owner/ID/original recording; current later snapshots change selection membership. | + +### US-09 + +Source: [us09-delete-observation.md](../Docs/Requirements/us09-delete-observation.md). Responsible: **API/access; Observations; Analytics**, specification §§5–8. + +Atomic row/context deletion with actual-owner authorization; later snapshots and derived results cannot include removed data; other rows unaffected. + +| Local criterion ID / source title | Required outcome and cases | Design responsibility | +| --- | --- | --- | +| 09-AC-01: Delete an existing observation | the deletion succeeds; the observation can no longer be retrieved; the observation no longer appears in the patient's observation history | Atomic row/context deletion with actual-owner authorization; later snapshots and derived results cannot include removed data; other rows unaffected. | +| 09-AC-02: Delete an observation that does not exist | the request reports that the observation does not exist | Atomic row/context deletion with actual-owner authorization; later snapshots and derived results cannot include removed data; other rows unaffected. | +| 09-AC-03: Delete contextualised observation | deletion succeeds | Atomic row/context deletion with actual-owner authorization; later snapshots and derived results cannot include removed data; other rows unaffected. | +| 09-AC-04: History excludes previously deleted observation | the deleted observation and its context are absent; the remaining matching observations are returned | Atomic row/context deletion with actual-owner authorization; later snapshots and derived results cannot include removed data; other rows unaffected. | +| 09-AC-05: Assessment excludes deleted data | the deleted values and context do not contribute to the result | Atomic row/context deletion with actual-owner authorization; later snapshots and derived results cannot include removed data; other rows unaffected. | +| 09-AC-06: Reject unauthorised deletion | the operation is rejected | Atomic row/context deletion with actual-owner authorization; later snapshots and derived results cannot include removed data; other rows unaffected. | + +### US-10 + +Source: [us10-calculated-insight.md](../Docs/Requirements/us10-calculated-insight.md). Responsible: **API/access; Observations; Analytics**, specification §§3–6. + +Capture current filtered raw series; SummaryPolicy arithmetic means/final two-decimal half-up and raw BP extrema; count/selection/context explanation; one sufficient, zero no insight. + +| Local criterion ID / source title | Required outcome and cases | Design responsibility | +| --- | --- | --- | +| 10-AC-01: Calculate averages for a period | the average systolic value is 125; the average diastolic value is 82; the average pulse value is 65 | Capture current filtered raw series; SummaryPolicy arithmetic means/final two-decimal half-up and raw BP extrema; count/selection/context explanation; one sufficient, zero no insight. | +| 10-AC-02: Calculate minimum and maximum blood-pressure values | the minimum systolic value is 118; the maximum systolic value is 130; the minimum diastolic value is 76; the maximum diastolic value is 84 | Capture current filtered raw series; SummaryPolicy arithmetic means/final two-decimal half-up and raw BP extrema; count/selection/context explanation; one sufficient, zero no insight. | +| 10-AC-03: Insight uses only observations in the requested period | only observations within the requested period contribute to the calculated values | Capture current filtered raw series; SummaryPolicy arithmetic means/final two-decimal half-up and raw BP extrema; count/selection/context explanation; one sufficient, zero no insight. | +| 10-AC-04: No observations exist in the requested period | the result indicates that insufficient observation data is available for calculation | Capture current filtered raw series; SummaryPolicy arithmetic means/final two-decimal half-up and raw BP extrema; count/selection/context explanation; one sufficient, zero no insight. | +| 10-AC-05: Reject an invalid insight period | the request is rejected | Capture current filtered raw series; SummaryPolicy arithmetic means/final two-decimal half-up and raw BP extrema; count/selection/context explanation; one sufficient, zero no insight. | +| 10-AC-06: Calculate from selected context only | average systolic pressure is 125.00; the result identifies Home, At rest, and two contributing observations | Capture current filtered raw series; SummaryPolicy arithmetic means/final two-decimal half-up and raw BP extrema; count/selection/context explanation; one sufficient, zero no insight. | +| 10-AC-07: No filter preserves pooled calculation | all eligible observations contribute to the existing numerical calculations; the mixed or unknown context is made apparent | Capture current filtered raw series; SummaryPolicy arithmetic means/final two-decimal half-up and raw BP extrema; count/selection/context explanation; one sufficient, zero no insight. | +| 10-AC-08: One selected observation | each mean equals that observation’s corresponding value; each blood-pressure minimum and maximum equals its corresponding value | Capture current filtered raw series; SummaryPolicy arithmetic means/final two-decimal half-up and raw BP extrema; count/selection/context explanation; one sufficient, zero no insight. | +| 10-AC-09: No matching observations | the system reports that no insight can be calculated for the selection | Capture current filtered raw series; SummaryPolicy arithmetic means/final two-decimal half-up and raw BP extrema; count/selection/context explanation; one sufficient, zero no insight. | +| 10-AC-10: Correction changes membership | that observation does not contribute to the home-only calculation | Capture current filtered raw series; SummaryPolicy arithmetic means/final two-decimal half-up and raw BP extrema; count/selection/context explanation; one sufficient, zero no insight. | +| 10-AC-11: Reject unsupported selection | the request is rejected with an explanation | Capture current filtered raw series; SummaryPolicy arithmetic means/final two-decimal half-up and raw BP extrema; count/selection/context explanation; one sufficient, zero no insight. | +| 10-AC-12: Round a halfway mean upwards | the average systolic value is 120.13 | SummaryPolicy uses exact raw mean and final half-up rounding: halfway 120.125 → 120.13; repeating 120⅓ → 120.33. | +| 10-AC-13: Round a repeating fractional mean | the average systolic value is 120.33 | SummaryPolicy uses exact raw mean and final half-up rounding: halfway 120.125 → 120.13; repeating 120⅓ → 120.33. | + +### US-11 + +Source: [us11-health-trend.md](../Docs/Requirements/us11-health-trend.md). Responsible: **API/access; Observations; Analytics; Guidance**, specification §§3–6. + +Current selected full-period series; deterministic TrendPolicy with distinct-time sufficiency, raw variation and reversals; separate metric results; claim-specific ClinicalPolicy and comparability evidence. + +| Local criterion ID / source title | Required outcome and cases | Design responsibility | +| --- | --- | --- | +| 11-AC-01: Calculate a trend from observations | a trend result is returned; the trend is derived only from observations within the requested period | Current selected full-period series; deterministic TrendPolicy with distinct-time sufficiency, raw variation and reversals; separate metric results; claim-specific ClinicalPolicy and comparability evidence. | +| 11-AC-02: No observations exist for trend calculation | the result indicates that insufficient observation data is available for trend calculation | Current selected full-period series; deterministic TrendPolicy with distinct-time sufficiency, raw variation and reversals; separate metric results; claim-specific ClinicalPolicy and comparability evidence. | +| 11-AC-03: Reject an invalid trend period | the request is rejected | Current selected full-period series; deterministic TrendPolicy with distinct-time sufficiency, raw variation and reversals; separate metric results; claim-specific ClinicalPolicy and comparability evidence. | +| 11-AC-04: Assess a comparable selection | separate systolic, diastolic, and pulse assessments are returned; the result identifies the selection, contributing count, and recorded basis for comparability | Current selected full-period series; deterministic TrendPolicy with distinct-time sufficiency, raw variation and reversals; separate metric results; claim-specific ClinicalPolicy and comparability evidence. | +| 11-AC-05: Different conditions remain visible | the result identifies the differing conditions; explains limitations on interpreting their combined trajectory | Current selected full-period series; deterministic TrendPolicy with distinct-time sufficiency, raw variation and reversals; separate metric results; claim-specific ClinicalPolicy and comparability evidence. | +| 11-AC-06: Unknown details limit comparability | the explanation identifies the known similarities and missing details; does not certify that all measurement conditions were identical | Current selected full-period series; deterministic TrendPolicy with distinct-time sufficiency, raw variation and reversals; separate metric results; claim-specific ClinicalPolicy and comparability evidence. | +| 11-AC-07: Missing context preserves numerical information | supported numerical direction and variation are returned; the limitations on clinical interpretation and comparability are explained | Current selected full-period series; deterministic TrendPolicy with distinct-time sufficiency, raw variation and reversals; separate metric results; claim-specific ClinicalPolicy and comparability evidence. | +| 11-AC-08: Conflicting descriptions | the conflict is identified; an unsupported resting interpretation is not asserted | Preserve conflicting text/categories; ComparabilityEvidence identifies contradiction and ClinicalPolicy withholds unsupported resting claims; unresolved narrative meaning disclosed. | +| 11-AC-09: Compare labelled selections | each result identifies its own selection and contributing observations; a difference between settings alone is not labelled improvement or deterioration over time | Current selected full-period series; deterministic TrendPolicy with distinct-time sufficiency, raw variation and reversals; separate metric results; claim-specific ClinicalPolicy and comparability evidence. | +| 11-AC-10: Insufficient selected series | the result reports insufficient observations for temporal direction; does not use excluded observations to manufacture a trend | Current selected full-period series; deterministic TrendPolicy with distinct-time sufficiency, raw variation and reversals; separate metric results; claim-specific ClinicalPolicy and comparability evidence. | +| 11-AC-11: No temporal separation | temporal direction is reported as unavailable | Current selected full-period series; deterministic TrendPolicy with distinct-time sufficiency, raw variation and reversals; separate metric results; claim-specific ClinicalPolicy and comparability evidence. | +| 11-AC-12: No matching data | the result reports that no matching observations are available | Current selected full-period series; deterministic TrendPolicy with distinct-time sufficiency, raw variation and reversals; separate metric results; claim-specific ClinicalPolicy and comparability evidence. | +| 11-AC-13: Updated context is used | that observation no longer contributes to the result | Current selected full-period series; deterministic TrendPolicy with distinct-time sufficiency, raw variation and reversals; separate metric results; claim-specific ClinicalPolicy and comparability evidence. | +| 11-AC-14: Reject invalid selection | the request is rejected with an explanation | Current selected full-period series; deterministic TrendPolicy with distinct-time sufficiency, raw variation and reversals; separate metric results; claim-specific ClinicalPolicy and comparability evidence. | +| 11-AC-15: AC-11-A | the result presents each measurement separately; identifies its unit, observed level, direction, and variation | Separate three MetricAssessments with units/levels/direction/variation. | +| 11-AC-16: AC-11-B | only observations for that patient within the selected period contribute to the result | Patient/period filter precedes assessment. | +| 11-AC-17: AC-11-C | the result identifies the corresponding direction; bases that assessment on measurements throughout the period | Full-period temporal policy; no endpoint-only inference. | +| 11-AC-18: AC-11-D | the result describes the intermediate variation; does not describe the period as clinically stable merely because its endpoints are similar | Retain raw intermediate extrema/variation; no arbitrary clinical stability label. | +| 11-AC-19: AC-11-E | the explanation describes the reversal or mixed development; does not imply that all measurements follow one consistent direction | Expose reversals and mixed movements independently of overall tendency. | +| 11-AC-20: AC-11-F | the explanation identifies their position relative to the reference values; does not describe them as healthy solely because their variation is limited | Clinical reference comparison considers levels; limited variation cannot imply healthy. | +| 11-AC-21: AC-11-G | the explanation describes that development and its basis; distinguishes improvement from having reached an appropriate level | Only a reviewed applicable clinical development rule permits favourable wording; distinguish trajectory from reached level. | +| 11-AC-22: AC-11-H | the explanation describes the concern and its basis; does not treat a decrease as favourable solely because the values are falling | Only applicable evidence permits concerning wording; falling is not inherently favourable. | +| 11-AC-23: AC-11-I | the result explains the interpretation of each affected measurement; does not force them into a single favourable or concerning classification | Interpret each metric separately; no forced overall good/bad. | +| 11-AC-24: AC-11-J | the result presents the supported numerical information; explains that the clinical interpretation is limited by missing context | Preserve numerical descriptions; report which clinical prerequisites are missing. | +| 11-AC-25: AC-11-K | the result explicitly reports that direction cannot be determined; does not substitute an increasing, decreasing, or unchanged conclusion | Distinct-time sufficiency; explicit unavailable direction. | +| 11-AC-26: AC-11-L | the result identifies the reference values used; does not present a general reference threshold as an individual treatment target | Claim-specific reference applicability and source; no personal target. | +| 11-AC-27: AC-11-M | the assessment remains unchanged | Timestamp grouping/order-independent policy; storage order never determines direction. | +| 11-AC-28: AC-11-N | the result reflects the current observations | Current uncached snapshot after correction/deletion. | +| 11-AC-29: Supported reference comparison despite incomplete preparation details | the supported reference comparison is provided; the explanation identifies the remaining limits without rejecting all clinical interpretation | ClinicalPolicy checks prerequisites per claim; irrelevant missing optional preparation only limits stronger claims, not supported comparison. | + +### US-12 + +Source: [us12-health-overview.md](../Docs/Requirements/us12-health-overview.md). Responsible: **API/access; Profile; Observations; Analytics; Overview**, specification §§4–6. + +Single snapshot composition; unfiltered latest overall and its own context; period/selection applies only to insight; retain profile/latest when insight absent, with distinct bases; no trend. + +| Local criterion ID / source title | Required outcome and cases | Design responsibility | +| --- | --- | --- | +| 12-AC-01: View an overview for a patient with observations | the patient's profile is included; the latest blood-pressure observation is included; the calculated health insight is included | Single snapshot composition; unfiltered latest overall and its own context; period/selection applies only to insight; retain profile/latest when insight absent, with distinct bases; no trend. | +| 12-AC-02: View an overview for a patient without observations | the patient's profile is included; no latest blood-pressure observation is returned; the overview indicates that no calculated health insight is available | Single snapshot composition; unfiltered latest overall and its own context; period/selection applies only to insight; retain profile/latest when insight absent, with distinct bases; no trend. | +| 12-AC-03: Request an overview for a patient that does not exist | the request reports that the patient does not exist | Single snapshot composition; unfiltered latest overall and its own context; period/selection applies only to insight; retain profile/latest when insight absent, with distinct bases; no trend. | +| 12-AC-04: Reject an invalid overview period | the request is rejected | Single snapshot composition; unfiltered latest overall and its own context; period/selection applies only to insight; retain profile/latest when insight absent, with distinct bases; no trend. | +| 12-AC-05: Latest context and insight selection differ | the latest after-activity observation and its context are returned; the insight uses only matching home-resting observations; the result distinguishes their different bases | Single snapshot composition; unfiltered latest overall and its own context; period/selection applies only to insight; retain profile/latest when insight absent, with distinct bases; no trend. | +| 12-AC-06: No matching insight observations | the profile and latest observation remain available; the absence of insight for the selection is explained | Single snapshot composition; unfiltered latest overall and its own context; period/selection applies only to insight; retain profile/latest when insight absent, with distinct bases; no trend. | +| 12-AC-07: Unknown context remains unknown | its context is represented as unknown; no context is copied from other observations | Single snapshot composition; unfiltered latest overall and its own context; period/selection applies only to insight; retain profile/latest when insight absent, with distinct bases; no trend. | +| 12-AC-08: Default overview preserves context limitations | the original pooled insight is returned; its mixed-context explanation is included | Single snapshot composition; unfiltered latest overall and its own context; period/selection applies only to insight; retain profile/latest when insight absent, with distinct bases; no trend. | + +### US-13 + +Source: [us13-patient-authentication.md](../Docs/Requirements/us13-patient-authentication.md). Responsible: **API/access; Profile**, specification §§4–5,8. + +Established login/token validation; generic credential failure and expiry; per-request actual-owner policy; profile-less login/create allowed; never disclose another patient. + +| Local criterion ID / source title | Required outcome and cases | Design responsibility | +| --- | --- | --- | +| 13-AC-01: Successful authentication | the system recognises my account and Patient role; recognises its associated patient profile if one has been created | Established login/token validation; generic credential failure and expiry; per-request actual-owner policy; profile-less login/create allowed; never disclose another patient. | +| 13-AC-02: Access to my own information | access is permitted; the operation follows its existing acceptance criteria | Established login/token validation; generic credential failure and expiry; per-request actual-owner policy; profile-less login/create allowed; never disclose another patient. | +| 13-AC-03: Invalid credentials | authentication is rejected; the response does not reveal which part of the credentials was incorrect | Established login/token validation; generic credential failure and expiry; per-request actual-owner policy; profile-less login/create allowed; never disclose another patient. | +| 13-AC-04: Missing authentication | the request is rejected; no patient information is returned or changed | Established login/token validation; generic credential failure and expiry; per-request actual-owner policy; profile-less login/create allowed; never disclose another patient. | +| 13-AC-05: Invalid authentication information | the request is rejected; no patient information is returned or changed | Established login/token validation; generic credential failure and expiry; per-request actual-owner policy; profile-less login/create allowed; never disclose another patient. | +| 13-AC-06: Access to another patient’s information | access is rejected; none of that patient’s information is returned or changed | Established login/token validation; generic credential failure and expiry; per-request actual-owner policy; profile-less login/create allowed; never disclose another patient. | +| 13-AC-07: Own information does not yet exist | the system follows the existing behaviour for missing information; does not return another patient’s information | Established login/token validation; generic credential failure and expiry; per-request actual-owner policy; profile-less login/create allowed; never disclose another patient. | +| 13-AC-08: Login before profile creation | authentication succeeds and recognises my account and Patient role; I may create my initial profile under US-01; I gain no access to another patient’s information | Established login/token validation; generic credential failure and expiry; per-request actual-owner policy; profile-less login/create allowed; never disclose another patient. | +| 13-AC-09: Expired authentication | the request is rejected; no patient information is returned or changed | Established login/token validation; generic credential failure and expiry; per-request actual-owner policy; profile-less login/create allowed; never disclose another patient. | + +### US-14 + +Source: [us14-professional-access.md](../Docs/Requirements/us14-professional-access.md). Responsible: **API/access; Profile; Observations; Analytics; Overview**, specification §§4–5,8. + +Trusted Professional role; own predefined assignment list; actual-owner assigned reads only; forbid every write; empty/missing and unauthorized cases remain distinct without disclosure. + +| Local criterion ID / source title | Required outcome and cases | Design responsibility | +| --- | --- | --- | +| 14-AC-01: Successful authentication | the system recognises my identity and healthcare professional role | Trusted Professional role; own predefined assignment list; actual-owner assigned reads only; forbid every write; empty/missing and unauthorized cases remain distinct without disclosure. | +| 14-AC-02: View assigned patients | the system returns only patients assigned to me | Trusted Professional role; own predefined assignment list; actual-owner assigned reads only; forbid every write; empty/missing and unauthorized cases remain distinct without disclosure. | +| 14-AC-03: View an assigned patient’s information | access is permitted; the requested information is returned according to the existing retrieval requirements | Trusted Professional role; own predefined assignment list; actual-owner assigned reads only; forbid every write; empty/missing and unauthorized cases remain distinct without disclosure. | +| 14-AC-04: No assigned patients | the system indicates that no patients are assigned; does not return other patients | Trusted Professional role; own predefined assignment list; actual-owner assigned reads only; forbid every write; empty/missing and unauthorized cases remain distinct without disclosure. | +| 14-AC-05: Patient information does not yet exist | the system follows the existing behaviour for missing information | Trusted Professional role; own predefined assignment list; actual-owner assigned reads only; forbid every write; empty/missing and unauthorized cases remain distinct without disclosure. | +| 14-AC-06: Access to an unassigned patient | access is rejected; no information about that patient is returned | Trusted Professional role; own predefined assignment list; actual-owner assigned reads only; forbid every write; empty/missing and unauthorized cases remain distinct without disclosure. | +| 14-AC-07: Attempt to change patient information | the operation is rejected; the patient information remains unchanged | Trusted Professional role; own predefined assignment list; actual-owner assigned reads only; forbid every write; empty/missing and unauthorized cases remain distinct without disclosure. | +| 14-AC-08: Invalid credentials | authentication is rejected; the response does not reveal which part of the credentials was incorrect | Trusted Professional role; own predefined assignment list; actual-owner assigned reads only; forbid every write; empty/missing and unauthorized cases remain distinct without disclosure. | +| 14-AC-09: Missing or invalid authentication | the request is rejected; no patient information is returned | Trusted Professional role; own predefined assignment list; actual-owner assigned reads only; forbid every write; empty/missing and unauthorized cases remain distinct without disclosure. | +| 14-AC-10: Patient account attempts professional access | access is rejected; my existing access to my own information is unaffected | Trusted Professional role; own predefined assignment list; actual-owner assigned reads only; forbid every write; empty/missing and unauthorized cases remain distinct without disclosure. | + +### US-15 + +Source: [us15-measurement-guidance.md](../Docs/Requirements/us15-measurement-guidance.md). Responsible: **API/access; Guidance; Observations**, specification §§4,6,8. + +Public reviewed ordered setting-labelled content with source/date and pulse limits; no observation write/certification/defaulting/submission dependency; unsupported verified content unavailable. + +| Local criterion ID / source title | Required outcome and cases | Design responsibility | +| --- | --- | --- | +| 15-AC-01: Access guidance before first observation | preparation, measurement, and recording instructions are available; the source, applicability, and review date are identified | Public reviewed ordered setting-labelled content with source/date and pulse limits; no observation write/certification/defaulting/submission dependency; unsupported verified content unavailable. | +| 15-AC-02: Home measurement guidance | the instructions cover rest, equipment and cuff, positioning, repeated readings, and recording conditions; any numeric instructions follow the identified Danish or European guidance | Public reviewed ordered setting-labelled content with source/date and pulse limits; no observation write/certification/defaulting/submission dependency; unsupported verified content unavailable. | +| 15-AC-03: Unknown setting | its supported setting is identified; no measurement setting is saved or assumed on the user’s behalf | Public reviewed ordered setting-labelled content with source/date and pulse limits; no observation write/certification/defaulting/submission dependency; unsupported verified content unavailable. | +| 15-AC-04: Different measurement conditions | the guidance distinguishes it from a resting measurement; explains recording the actual conditions without relabelling the result as resting | Public reviewed ordered setting-labelled content with source/date and pulse limits; no observation write/certification/defaulting/submission dependency; unsupported verified content unavailable. | +| 15-AC-05: Pulse context | it explains recording the pulse value and relevant activity condition; does not describe the single pulse value as a rhythm assessment | Public reviewed ordered setting-labelled content with source/date and pulse limits; no observation write/certification/defaulting/submission dependency; unsupported verified content unavailable. | +| 15-AC-06: Guidance does not certify compliance | no observation is saved or altered; following the procedure is not recorded automatically | Public reviewed ordered setting-labelled content with source/date and pulse limits; no observation write/certification/defaulting/submission dependency; unsupported verified content unavailable. | +| 15-AC-07: Guidance is optional | creation succeeds | Public reviewed ordered setting-labelled content with source/date and pulse limits; no observation write/certification/defaulting/submission dependency; unsupported verified content unavailable. | +| 15-AC-08: Guidance unavailable | its unavailability is explained; unsupported instructions are not presented as verified guidance | Public reviewed ordered setting-labelled content with source/date and pulse limits; no observation write/certification/defaulting/submission dependency; unsupported verified content unavailable. | +| 15-AC-09: General guidance without login | the general guidance is available; no patient-specific information or assignment list is returned | Public reviewed ordered setting-labelled content with source/date and pulse limits; no observation write/certification/defaulting/submission dependency; unsupported verified content unavailable. | + +## US-16 and addendum + +All **AC-16-A through AC-16-I** are mapped individually with original/proposed status in [us16-revision.md](us16-revision.md). None is silently marked satisfied. The addendum’s selection/process granularity, PostgreSQL setup, generated credentials, protected secret/configuration storage, HTTPS/trust/replacement, service configuration, native registration/start, verification and same-binary deployment principle are mapped there and specified in §9. Original feature-service distribution, separate databases and internal network architecture are incompatible; automation/security/verification intent is retained for the new app unit. + +## Gaps and acceptance dependencies + +No US-01–US-15 or common functional behaviour has an unassigned architectural responsibility. US-16 has the explicitly authorized topology/installation gaps above. Clinical reference/rule review, general narrative conflict handling, final reproducible numerical method/fixtures and supported Linux installation proof remain future implementation acceptance obligations, tracked as R4–R6/R10. Coverage is a design allocation, not evidence that those behaviours already execute correctly. + +## Coverage total + +146 individually mapped scenario/outline/named AC entries from common requirements and US-01–US-15; nine US-16 ACs plus every addendum section mapped separately. Outline parameter cases remain in their rows. diff --git a/ArchitectureProposal/risks-and-open-questions.md b/ArchitectureProposal/risks-and-open-questions.md new file mode 100644 index 0000000..db2cc1d --- /dev/null +++ b/ArchitectureProposal/risks-and-open-questions.md @@ -0,0 +1,23 @@ +# Risks, assumptions and open questions + +No essential topology clarification remains: user option 3 explicitly permits consolidation with US-16 revisions. Open operational and implementation questions below do not prevent a precise architecture proposal; they limit claims and guide subsequent acceptance. + +| ID | Risk / unknown | Design treatment and reconsideration condition | +| --- | --- | --- | +| R1 | Request rate, concurrent users, history size, repeat-query frequency and active/idle mix unknown | Assume modest interactive synthetic prototype; no numerical capacity claim. Sustained expensive analytics/large histories could justify service extraction or explicit pagination contract | +| R2 | Physical hosts, VM sharing, DB colocation and hardware power response unknown | Default app/local PostgreSQL Linux placement; remote DB supported. No energy savings claimed; consolidation may not lower fixed host energy | +| R3 | Availability/recovery targets and mandatory isolation unknown | Single process/database failures affect whole app; no HA/SLA promise. Mandatory independent rollout/isolation overturns ADR-01 | +| R4 | Clinical references, allowed development claims and content review ownership | Required versioned reviewed claim catalog; claim-specific prerequisites; retain supported numerical information and explain unavailable interpretation. No new clinical thresholds prescribed here; domain review required before claiming implementation acceptance | +| R5 | Arbitrary free-text conflict semantics/negation | Preserve text and categories; expose recognized conflicts, unresolved narrative meaning and limits; absence of phrase matches is never certification. Validate US-11 exercise example and broader narrative handling during implementation | +| R6 | Numerical method exact formula/weighting not mandated | Architecture separates reproducible TrendPolicy from clinical rules and specifies full-period/tie/sufficiency constraints. Final mathematical method and fixtures must be documented before implementation acceptance, without treating a baseline algorithm as binding | +| R7 | Original US-16 not satisfied | Full criterion-level incompatibility register and suggested revision exist; originals unchanged. Independent feature installation is intentionally lost under user clarification | +| R8 | Single process/DB role increases compromise blast radius | Module boundaries logical; one runtime DML role cannot isolate compromise. Strict public authorization, private repositories and protected secrets; isolated services remain an alternative if required | +| R9 | Shared snapshot/materialized large series | Capture source values then end transaction; bounded admission/cancellation, complete history semantics. Peak memory, DB version retention and pooled-connection contention remain risks | +| R10 | Deployment support matrix unspecified | Linux/systemd baseline with explicit supported distributions selected during implementation; Windows/macOS historical support is optional. No claim that all Linux distributions install successfully | +| R11 | Baseline database import/schema compatibility | Future planned migration preserves IDs/account association/original times/text; detect duplicate accounts/orphans; no silent reassignment or inferred context. No data import executed | +| R12 | Token key rotation/certificate expiry/production key protection | Persist/restrict keys; allow externally supplied certificates; administrative rotation must preserve intended token validity or explicitly invalidate it. No refresh/revocation/production identity lifecycle promised | +| R13 | Concurrent changes and ambiguous writes | Atomic locked mutation; immutable owner/original time; defined snapshot freshness. Observation retry after ambiguous commit has no idempotency guarantee; profile retry has explicit recovery | +| R14 | Installation failure/upgrade/backup objectives | Stage-specific diagnostics, overwrite protection, privileged migration separate from runtime; no atomic installer rollback or unspecified recovery claim. Backup/retention/upgrade procedure requires operational decisions | +| R15 | Exact documented wire contracts versus proposed logical types | Existing documented external routes/field vocabulary/status semantics retained; internal service-key APIs removed. Validate adapters against documented snapshots, not source reverse engineering. No new product frontend required | + +The proposal does not promise production readiness, regulatory certification, diagnosis or energy improvement. It satisfies architecture-level functional coverage with the explicitly authorized US-16 incompatibilities; clinical method/content acceptance and native deployment proof belong to subsequent implementation work. diff --git a/ArchitectureProposal/software-architecture.md b/ArchitectureProposal/software-architecture.md new file mode 100644 index 0000000..05e1f10 --- /dev/null +++ b/ArchitectureProposal/software-architecture.md @@ -0,0 +1,146 @@ +# Health App architecture specification + +Status: complete proposed design, 2026-10-13; not an implementation or production certification. The user's clarification authorizes evaluating all topologies and documenting necessary US-16 revisions. Original requirements remain unchanged. [Traceability](requirements-traceability.md) explicitly records the resulting installation incompatibilities. + +## 1. Selection and boundaries + +Select a **modular monolith**: one Health App HTTPS application process, one PostgreSQL database with module-owned schemas, and an installation utility that runs only during administration. Keep API/access, Profile, Observations, Analytics, Overview and Guidance as logical modules. They communicate through typed in-process interfaces, never internal HTTP or another module's repository. There is no broker, periodic calculation worker, identity server, response cache, or generated-assessment store. + +The system provides the prototype backend. Patient and professional clients are external; a frontend, device integration and production clinical service are outside this assignment. Pre-created synthetic accounts and predefined many-to-many assignments remain. Account registration, recovery, MFA, refresh tokens, assignment administration, professional writes, medication advice and emergency access remain excluded. + +This choice is conditional on a modest interactive workload and no independent feature deployment requirement after the user's clarification. No throughput, availability SLA or energy saving has been established. Consolidation sacrifices process isolation and independent scaling. [Decisions](architecture-decisions.md) compares feasible alternatives without assuming that existing services are inherently unsuitable. + +Editable views: [context](diagrams/01-system-context.drawio), [components](diagrams/02-logical-components.drawio), [domain](diagrams/03-domain-model.drawio), [classes](diagrams/04-conceptual-classes.drawio), [ownership](diagrams/05-data-ownership.drawio), [deployment](diagrams/06-deployment.drawio), [sequences](diagrams/07-sequences.drawio). + +## 2. Components and dependency rules + +| Module | Responsibility and public internal interface | Data ownership | +| --- | --- | --- | +| API/access | HTTPS endpoints; credential verification/token validation; normalized identity; actual-owner and assignment policies; response mapping. `AccessPolicy.authorize(identity, operation, actualPatient)` | External account/assignment configuration and persistent token-protection keys; no health tables | +| Profile | Create initial profile and account association atomically; find by account/ID; update permitted profile information. `ProfileQueries`, `ProfileCommands` | `profile.patient`, including account association | +| Observations | Record, retrieve, latest, inclusive selected history, partial correction and deletion; context lifecycle and validation. `ObservationQueries`, `ObservationCommands` | `observations.observation` including its owned context | +| Analytics | On-demand numerical insights and three separate metric trends; context evidence, reference applicability and explanatory limitations. `AnalyticsQueries`, `SummaryPolicy`, `TrendPolicy`, `ClinicalPolicy` | Transient derived values only; versioned non-patient reference content supplied by Guidance | +| Overview | Compose profile, latest overall observation and selected-period insight; preserve distinct bases and absence reasons. `OverviewQueries` | Transient overview only | +| Guidance | Public ordered measurement instructions; reviewed applicability, source/date and unavailable states; reference catalog for clinical interpretation | Versioned reviewed guidance/reference bundle, no patient information | +| Infrastructure | Transaction/read-snapshot coordinator, module-specific persistence adapters, secret/key loading, error/logging boundary | Connection pool and lifecycle; never decides patient access or clinical meaning | +| Installation utility | Dependency detection, configuration, secrets/certificates, database/schema migration, systemd registration, verification | Protected administrative installation material; no continuously running service | + +API/access invokes module facades. AccessPolicy uses ProfileQueries to resolve patient-account association and ObservationQueries to resolve actual observation owner. Observations uses ProfileQueries for existence. Analytics uses ObservationQueries for one selected series and Guidance's reference catalog. Overview invokes ProfileQueries, ObservationQueries and AnalyticsQueries within one read snapshot. Modules cannot call back into API routing. This dependency graph is acyclic; access checks are the caller's responsibility, and every externally reachable operation must pass the API/access boundary. Internal query facades accept a trusted, request-scoped authorized patient context issued by AccessPolicy, except the narrowly scoped owner-resolution/profile-association operations used by that policy itself. These lookup operations never directly produce an external response. + +Do not share mutable domain objects across modules. Internal read models are immutable values; contracts carry patient ID, period, selections, counts and provenance where relevant. A common transport contract vocabulary does not grant persistence access. Module domain entities and repositories remain private. Transaction coordination is infrastructure shared by participating adapters, not permission for Analytics or Overview to run SQL against health schemas. + +## 3. Domain and invariants + +An Account has a stable account ID, credential hash and trusted Patient or HealthcareProfessional role. A Patient account has zero profiles before creation and exactly one afterwards. A PatientProfile contains generated UUID, account ID, required name and birth date, optional contact information, original creation and update instants. Its account association is immutable. Predefined Assignment associates one professional account with one patient ID; professionals and patients may each have many assignments. Assignments can refer to currently missing patient information and confer no writes. + +A BloodPressureObservation belongs to exactly one patient and has UUID, measurement instant, immutable original recording instant, current systolic/diastolic values in mmHg, pulse in beats/minute, original context text, note and one owned MeasurementContext. The required numerical values are positive; no new clinical plausibility ceiling is imposed. Context has no independent identity or lifecycle. Its independent categories are Setting {Home, Clinic, Other, Unknown} and Activity {AtRest, DuringActivity, AfterActivity, Unknown}; optional details are rest duration with unit, body position, measured arm, device, cuff and circumstances. Missing details remain unknown. Partial context, after-activity measurements and historical free text remain valid. Categories never arise by inference from text or similar readings. Conflicting category/text evidence is preserved and exposed in interpretation. + +Period is two inclusive measurement instants; equal bounds are valid, reversed bounds invalid. Offset-bearing times normalize to UTC; offset-free input denotes UTC independent of machine timezone. Preserve this existing documented interpretation. Wire examples may omit the offset, but consumers must use this rule. Birth date is a calendar date, not an instant. + +ContextSelection has optional setting and activity predicates. Omission means unrestricted; explicit Unknown matches unknown only; supplied dimensions combine with AND. Unsupported categories are rejected. The same selection semantics apply to history, insights, trends and the overview's insight. + +HealthInsight, TrendAssessment and HealthOverview are request-derived values without persisted identifiers. A trend owns exactly three MetricAssessments, one per measurement, and ComparabilityEvidence. Each metric records unit, descriptive levels, available direction/variation, explicit unavailable reasons, applicable reference and interpretation/hint. ClinicalReference includes scope, applicability prerequisites, operators/values, source URL and review date; it is distinct from an individual treatment target. MeasurementGuidance has ordered instructions, applicability, sources and review date; it never certifies compliance or changes an observation. + +## 4. Public contracts and access + +Retain the observable REST/JSON routes and semantics documented in `Docs/AsBuiltArchitecture/software-architecture.md` §4 as a compatibility target, without inspecting source. Authentication, field validation and error/absence behaviour remain as specified by the functional stories. No internal service-key endpoints are exposed. `/by-account` is an internal interface only. + +| Endpoint | Contract / result | +| --- | --- | +| `POST /api/authentication/login` | accountId/password → time-limited bearer identity/role; generic invalid-credential rejection | +| `GET /api/measurement-guidance` | optional setting/activity → ordered sourced guidance or explained unavailability; public | +| `GET /api/professionals/me/patients` | own predefined assignment IDs, including empty list; professional only | +| `POST /api/patients` | name/dateOfBirth/contactInfo → generated profile; identity derives solely from authenticated Patient account | +| `GET /api/patients/me`, `GET /api/patients/{patientId}` | associated/authorized profile or absent | +| `PUT /api/patients/{patientId}` | required name, optional contactInfo; preserve ID, account, birth date and original creation time | +| `POST /api/patients/{patientId}/observations` | timestamp, three positive measured values, optional context/text/note → assigned ID and retrievable observation | +| `GET /api/observations/{observationId}` | current observation including saved/unknown context after actual-owner authorization | +| `PUT /api/observations/{observationId}` | all three positive numerical values; preserve other fields | +| `PATCH /api/observations/{observationId}` | partial numeric/context/text/note correction; omitted ≠ cleared; invalid request changes nothing | +| `DELETE /api/observations/{observationId}` | delete observation and owned context; preserve all other observations | +| `GET /api/patients/{patientId}/observations/latest` | latest overall with its own context; none explicitly absent | +| `GET /api/patients/{patientId}/observations` | from/to and optional selection → full ascending history; empty array and applied-selection metadata | +| `GET /api/patients/{patientId}/insights` | from/to and selection → means/extrema/count/context explanation or insufficient-data result | +| `GET /api/patients/{patientId}/trends` | same selection → three metric results with supported descriptions and explicitly unavailable parts | +| `GET /api/patients/{patientId}/overview` | profile, nullable latest overall, nullable insight selected by period/context; no trend | + +Use the existing field vocabulary (`measurementContext`, `setting`, `activityCondition`, preparation fields, `context`, `note`, `from`, `to`) and enum tokens above. History carries applied selections in the documented `X-Measurement-Setting` and `X-Activity-Condition` headers; insight/trend/overview carry their basis in response values. Preserve existing response field names documented by the input class diagrams when implementing adapters; conceptual types here are not a rename mandate. + +PATCH omits untouched values. Explicit null clears optional details/text; clearing a category makes Unknown. Null entire structured context clears its structured details, preserving legacy text and numerical values. Required numerical fields cannot be cleared. Reject unsupported fields/categories and invalid values before atomic application. No observation patient reassignment is supported. All ID-based actions establish the actual persisted owner; a caller-supplied patient ID cannot override it. + +## 5. Interactions and consistency + +Login validates credentials with an established framework password-hashing facility and issues a framework-protected opaque bearer ticket. Choose a configurable 30-minute default lifetime as a design parameter, with standard expiry validation and no custom cryptography. Ticket scope is this application, contains stable account/role and issue/expiry information, and contains neither health data nor assignments/ownership. Persist compatible token-protection keys through restart. No refresh mechanism is added. Credential verification occurs at login; token validation and access policy run for every protected request. Provider replacement maps validated identity to the same stable application account and role; no automatic insecure fallback. + +Creation validates name/birth date and writes profile plus account ID in one database transaction/record, with a unique non-null account constraint. A uniqueness race returns existing-profile conflict. Success follows durable commit only. Interrupted uncommitted creation rolls back; retry creates one accessible profile. Lost success response leads to existing-profile result on retry and recovery through `/patients/me`. No distributed saga or separate association write is needed. + +A protected patient-ID request resolves account association or professional assignment before retrieval. An observation-ID request first resolves actual owner internally, then checks association/assignment, then accesses that owner-scoped observation. The lookup is never serialized externally before authorization. For mutation use one transaction with row locking: recheck owner, validate full proposed change, apply only specified fields, commit. Concurrent disjoint patches preserve one another; concurrent same-field valid updates serialize with the last committed update taking effect. Original recording time and patient association never change. Successful deletion removes the row/context; subsequent requests beginning after commit cannot include it. + +Record validates input and confirms an existing authorized profile inside the write transaction. Profile deletion is outside scope. Latest sorts descending by (measurement instant, original recording instant, UUID bytes); choose greatest lexicographic unsigned 16-byte UUID as the final documented tie rule. History sorts ascending measurement instant then ascending UUID bytes; filtering occurs before calculation. UUID ordering has no trend meaning. + +For insights/trends, capture current authorized selected observations in one repeatable-read snapshot. For overview, access-policy ownership resolution, profile, latest and selected series all participate in the same read snapshot; latest remains global for the patient, unrestricted by insight period/context. Retrieve selected series once, derive insight in memory, and preserve mixed/unknown explanations. For observation-ID reads authorize and retrieve within a snapshot. Configuration/assignment snapshot is fixed for the request. End the database transaction once required immutable source values have been captured, before numerical evaluation and JSON transmission, to avoid holding snapshots during client transfer. + +Freshness means each new request sees commits completed before its snapshot starts; a concurrent later commit is visible on the next request. No claim of observing writes after a request's snapshot is made. There is no asynchronous replication lag or cached derived result. Snapshot composition is a deliberate improvement over baseline interleaved reads, not a new user requirement. + +## 6. Calculation and clinical-content contracts + +Numerical insight uses all eligible raw observations: arithmetic means for the three metrics; systolic/diastolic minima and maxima; final two-decimal half-up means with no intermediate rounding. One observation suffices, zero reports no insight. Unknown context never prevents numerical calculation, but never matches a known selection. Include count, patient, normalized period, selections and explanation of differing/unknown conditions. The halfway example gives 120.13 for seven 120s and one 121; three values 120,120,121 give 120.33. + +TrendPolicy is separate from ClinicalPolicy so a missing clinical rule does not suppress supported numerical descriptions. The architectural method contract is deterministic and versioned: levels/extrema and observed variation retain every raw value; temporal analysis groups equal measurement instants reproducibly and considers the full ordered series, including intermediate changes and reversals. At least two distinct instants are required for temporal direction. An overall tendency cannot conceal reversal or excursions. Exactly one or equal-time-only data can still support descriptive levels/variation but no invented direction. Mathematical formula choice is an implementation decision, not an energy optimization or an inherited baseline constraint; its method documentation must state timestamp weighting, sufficiency, assumptions and reproducible examples before acceptance. No recording/retrieval ordering or final UUID tie determines trend direction. + +ComparabilityEvidence records supported similarities, known differences, missing relevant details and category/narrative conflicts. Matching broad categories or values never proves identical preparation. ClinicalPolicy evaluates each clinical claim's prerequisites independently: missing irrelevant optional details do not suppress supported reference comparison; unknown setting/rest or conflicting evidence blocks claims depending on those facts. It must disclose unresolved narrative meaning rather than treating failure to recognize a phrase as evidence of consistency. Recognized contradictory descriptions, including the US-11 exercise example, are explicitly identified. General narrative understanding is an implementation/validation risk, not silently promised by a finite keyword detector. + +Use a versioned, reviewed Danish/European content bundle, not live clinical-site calls per request. Each clinical rule records metric, context prerequisites, reference values/operators, source, review date and allowed inference. All potentially favourable/concerning development statements require an applicable documented rule; falling values, limited variation or similar endpoints alone never establish health. When unsupported, return CannotInterpret with reasons while retaining numerical information. Three measurements can differ in interpretation and are never forced into one good/bad label. Do not diagnose, invent clinical stability thresholds, advise medication changes or equate reference thresholds with personal targets. + +Guidance is ordered and sourced, distinguishing home and clinic applicability. Its content contract covers preparation/rest, validated equipment/cuff, posture/arm position, stillness, repeat readings/timing, recording actual conditions and device-reported pulse limitations. It distinguishes a planned home-monitoring protocol from a single recorded observation. Numeric guidance must derive from the identified source. Unknown setting is labelled without saving a default. After-activity readings remain recordable and are never relabelled as resting. Viewing or declining guidance neither writes nor blocks valid submissions. Unavailable verified content yields an explanation, never authoritative invented instructions. This architecture does not supply new medical thresholds; content review remains an implementation acceptance dependency. + +## 7. Storage, ownership and resource behaviour + +Use one PostgreSQL database, `profile` and `observations` schemas and one migration version per module. Profile owns its patient row; Observations owns its observation row with flattened context details. UUID patient reference is enforced by a database foreign key with deletion restricted; no cross-module SQL joins are used by application modules. This physical integration intentionally replaces separate-database ownership and requires the [US-16 revision](us16-revision.md). + +Database constraints enforce identifiers, unique account association, positive values, valid categories and required measurement/original recording times. Store instants with unambiguous UTC normalization; physical timestamp type may preserve legacy UTC-clock encoding if required for compatibility. Preserve IDs, original recording instants, values and text when importing baseline data; never infer missing context. Reject or quarantine ambiguous orphan references during a future migration rather than attaching them to another patient. No migration is performed in this assignment. + +One runtime DB role has only necessary read/write rights in both health schemas, no administrative or DDL rights. Separate schema migration owners are used only during installation/upgrades. Schema ownership is a maintainability boundary, **not runtime security isolation**: an application process compromise can reach both schemas. Repositories enforce module ownership by dependency structure. Credentials/hashes/assignments and token keys are protected external files; they do not require an extra account or session database. Guidance/reference content is immutable versioned application content, with review metadata. + +Use a bounded connection pool shared by request transactions; pool capacity and concurrent-request limits are deployment parameters, not an invented workload number. Index patient plus measurement instant/original recording/ID for latest/history. Evaluate additional context indexes only when observed workload justifies their storage/write footprint. No polling, precomputation, materialized clinical views or response cache is selected. Cache only immutable public content through versioned metadata; never patient data, authorization decisions or assignments across requests. Request-local reuse of an already captured value is permitted within its snapshot. + +History remains complete: no silent truncation, undocumented default period or pagination change. Capture all matching immutable data required by the request; bounded admission and cancellation protect resources. Very large histories are a known memory/CPU risk; future pagination must preserve full selection and require an explicit contract decision. CPU-heavy assessment admission must not exhaust authentication or public-guidance handling; separate logical concurrency budgets are allowed without extra worker processes. + +## 8. Security and failures + +The HTTPS API edge is the sole public trust boundary. There are no externally reachable internal module endpoints or gateway-service credentials. Untrusted headers never establish account, role or authorization. Policies use normalized identity and actual patient ownership. Public exceptions are only login and general guidance. Professional reads require predefined assignment; professional writes/profile creation and patient-only use of professional operations are rejected before mutation. Missing/invalid/expired authentication returns no protected data. A profile-less Patient can log in and create its initial profile, but receives unavailable information for other own-data requests without acquiring another patient's identity. + +Choose established ASP.NET Core authentication/policy integration as a retained design choice for prototype suitability, without prescribing package versions. TLS certificate/key material and token keys are externally provisioned, protected by service-account/root permissions and excluded from logs/repository. Pin the intended application trust scope and reject forged tickets. For remote DB placement require verified encrypted DB transport and certificate-name validation; local DB connections use OS/network access restrictions and dedicated credentials. Only the app's configured DB endpoint is reachable from its account; clients cannot reach it. + +| Condition | Public outcome / integrity rule | +| --- | --- | +| Invalid login; missing/invalid/expired ticket | 401, generic credential failure; no protected result/write | +| Professional write or forbidden role operation | 403; no mutation | +| Other patient's resource/unassigned patient | Uniform unavailable 404 without existence/context disclosure | +| Authorized missing profile/observation/latest | 404 absent information; no fabricated entity | +| Invalid category/value/body/reversed period | 400 with safe validation explanation; atomic no-change | +| Duplicate initial profile | 409 existing-profile result; immutable association | +| Empty history / no insight / insufficient trend | 200 empty history; 404 no insight; 200 trend with explicit unavailable parts | +| Empty overview insight/latest | 200 profile plus nullable parts and explained absence; missing profile 404 | +| DB unavailable, transaction failure, required content invalid | Fail closed; 503 dependency unavailable or 500 unexpected failure; no success before durable write; no false empty-data result | +| Deadline reached before response / cancelled request | 504 where a response remains possible; abort otherwise; rollback uncommitted work | +| Unsupported verified guidance | Explained unavailability; no unverified clinical instructions | +| Overload | 503 with retry indication; do not silently drop selected observations | + +No automatic mutation retry follows an ambiguous commit: clients may recover profile creation as above; observation-create retries can duplicate a reading because no requirement promises idempotency. Read failures may be retried by the caller; there is no background retry storm. Cancellation propagates through transaction and module work. Log correlation ID, operation and sanitized failure; omit credentials/tokens/health payloads and avoid logging identifying route values. Patient responses and login use no-store; public content can use versioned caching. Failures after response start cannot become a replacement error body. + +## 9. Deployment and installation + +Default: one supported Linux host with systemd, one dedicated Health App application identity/process and one PostgreSQL server. DB may be local or on a separately configured host; the same application executable and public API work in either layout. Application modules are neither independently installed nor separately addressable. Containers, Kubernetes, autoscaling and extra gateway/proxy processes are unnecessary for the default. Separate DB placement can increase network and idle cost but may improve database administration or resource sharing. + +The administrative installer preflights host support and settings; detects/installs runtime and required PostgreSQL dependency when local persistence is selected; provisions the database/schemas, least-privilege roles and generated credentials; generates or accepts HTTPS certificate/key material and relevant trust; writes protected configuration; runs versioned migrations; registers/enables/starts one systemd application unit; verifies PID, HTTPS, configured database and representative synthetic profile/observation/overview flows. It explicitly demonstrates stop/restart without stopping PostgreSQL. A remote DB choice must not unnecessarily install a local server. Normal installation requires no manual database, secret or certificate creation. Distributed application microservice installation is not offered. + +Configuration includes listener, HTTPS endpoint, DB host/credentials, keys, accounts, predefined assignments, token lifetime, content versions and concurrency/deadline limits. A generated prototype professional with no assignments is valid; an assigned workflow requires predefined fixture configuration, not a new management API. Prototype certificates can later be replaced by trusted supplied material. Client trust must be established separately; do not disable certificate validation. + +Report failed stage precisely and retain protected diagnostics; do not claim transactional installation rollback. Preflight refuses accidental overwrite. A future upgrade plan must back up health data and keys, apply compatible schema changes with the app stopped or explicitly coordinated, and validate integrity before switching. Backup retention, recovery objectives and HA are unresolved production concerns. No always-on provisioning daemon is added. Readiness distinguishes usable DB/content/key configuration from process liveness without publishing patient data. One process outage stops all modules, but public guidance can still work during DB-only outages. + +## 10. Design limits and acceptance + +[Energy hypotheses](energy-hypotheses.md) explains anticipated mechanisms and counter-effects; CPU, memory and latency are not energy measurements. Consolidation alone does not guarantee lower host energy, particularly on an always-on underutilized machine. Independent scaling becomes attractive if analytics load dominates or isolation becomes mandatory; module interfaces support an intentional later extraction, not a promised zero-cost switch. + +Architecture verification covers source requirement/criterion mapping, model/diagram agreement, ownership, security and error paths. It does not execute the application or establish clinical validity. Implementation acceptance must document reproducible mathematical methods, review clinical rule applicability and narrative-conflict handling, exercise access and concurrency scenarios, and validate the selected native deployment. The proposed architecture is complete; these are future implementation obligations, not missing architecture artefacts. diff --git a/ArchitectureProposal/us16-revision.md b/ArchitectureProposal/us16-revision.md new file mode 100644 index 0000000..54fb865 --- /dev/null +++ b/ArchitectureProposal/us16-revision.md @@ -0,0 +1,19 @@ +# US-16 compatibility and necessary revision + +The user chose option **3**: evaluate all topologies, including a modular monolith, and document necessary US-16 revision. This authorizes this proposal's departure; it does not edit or pretend to satisfy the original independently deployable-service criteria. US-01–US-15 and common rules remain binding. This file is a suggested reconciliation, not an alteration of `Docs/`. + +| Original criterion | Proposed design status | Necessary replacement meaning | +| --- | --- | --- | +| AC-16-A single selected service | Incompatible for original feature services | Install one complete Health App application; database may be external | +| AC-16-B multiple independent local processes | Incompatible | Logical modules reside in one application process; app and PostgreSQL have independent native lifecycles | +| AC-16-C all independent services/network interfaces | Incompatible | Complete installation exposes one HTTPS API and uses in-process module interfaces | +| AC-16-D independent service config | Changed granularity | One app configuration with module settings; DB may be independently configured | +| AC-16-E services on separate machines | Incompatible for application modules | Same app binary supports local or remote PostgreSQL with configured reachable endpoint; module distribution is not offered | +| AC-16-F independently manage each feature service | Incompatible | Independently manage application and DB; feature modules start/stop together | +| AC-16-G separate persistence ownership | Logical ownership retained; separate databases incompatible | One database, owned schemas and migration owners; one restricted application runtime role; no analytics/overview tables | +| AC-16-H installation preserves original topology | Incompatible | Installation preserves this newly selected topology in all supported placements | +| AC-16-I verify process/endpoints/dependencies/restart/workflow | Retained intent; changed process inventory | Verify one application PID/HTTPS, database/schema access, independent app stop/restart and representative complete flows | + +Addendum PostgreSQL automation, generated passwords, least privilege, protected configuration, HTTPS/certificate generation/replacement, dependency detection, migration, systemd registration/start and clear failure reporting remain required design capabilities. Replace specifically the two separate health databases/service credentials with two owned schemas/migration roles plus one application DML role. Inter-service communication credentials and per-module HTTPS listeners/trust are unnecessary after consolidation; app/database credentials and API certificate remain. Replace individual/multiple/all feature-service selection and five-machine example with application plus local/external DB choices. Installer is an administrative utility, never a new resident service. + +Revised installation must not require manual secret/database/certificate creation in the normal path. It must distinguish supported local and remote DB prerequisites, protect supplied administrative connections, verify selected configuration, and refuse accidental overwrite. No installer code, unit files or migrations are supplied by this architecture assignment. diff --git a/ArchitectureProposal/validation.md b/ArchitectureProposal/validation.md new file mode 100644 index 0000000..e17648d --- /dev/null +++ b/ArchitectureProposal/validation.md @@ -0,0 +1,34 @@ +# Architecture deliverable verification + +Completed 2026-10-13 against the supplied `Docs/` inputs, `AGENT.md` and user clarification option 3. This report concerns the proposed documentation and diagrams, not application execution. + +## Completeness and traceability + +All required files are present: README, authoritative specification, requirements traceability, decisions, energy hypotheses, risks/questions and seven native Draw.io sources. Supporting inventory, requirements/constraints register, US-16 revision and diagram/model guide are present. + +An independent scan of input scenario/outline titles and named AC-11-A through AC-11-N found **146 acceptance entries** across common requirements and US-01–US-15; every title is mapped with its required outcomes and responsible components/specification sections. Outline example rows are retained. Story/functional-rule coverage is separately recorded. All nine AC-16-A through AC-16-I and each installer-addendum section are mapped with explicit original/proposed status. Original topology incompatibilities are not labelled satisfied. + +Manual design review checked account/profile zero-to-one lifecycle; uniqueness/retry/restart/recovery; immutable owner and recording-time ties; partial context/unknown/text preservation; inclusive periods and AND selection; current corrections/deletions; precise summary rounding; temporal sufficiency and full-period evidence; separate numerical/clinical claims; actual-owner authorization and assigned read-only access; public side-effect-free guidance; overview's distinct bases/no-trend scope; install/runtime/data boundaries and failure-versus-absence semantics. + +The written design, component/domain/class/data/deployment views and sequence messages agree on one application process, owned schemas, no internal network calls, current snapshots and no result cache/store. The user-authorized departure from US-16 is explicit in README, traceability, register, decisions, risk R7, deployment and the revision document. + +## Diagram and document checks + +- Parsed all **7 uncompressed native `.drawio` XML files**, containing **16 pages**, **193 native vertices**, **138 native connectors/lifelines**, and **32 conceptual class classifiers**. +- Verified `mxfile` / `mxGraphModel` structure, unique per-page cell IDs, valid connector source/target IDs or explicit free-edge endpoint geometry, and positive vertex dimensions. +- Confirmed individually editable labels/shapes/connectors, no embedded raster-only diagram content, and separate attribute/operation compartments for each conceptual classifier. +- Checked that peer top-level boxes do not overlap; deliberate class compartments are contained by their parent classifier. +- Estimated wrapped label fit using local font metrics: no vertex label overflow found. Independently rendered geometry previews of logical/component and access/Profile class views were visually reviewed for readable boxes/compartments. These previews are **not Draw.io exports** and do not validate its automatic connector routing. +- Checked local Markdown file links resolve and code fences balance. Navigation covers all required diagram views and documents. + +The Draw.io GUI/CLI was unavailable. Application import/rendering/round-trip and every automatic edge-label routing case were not exercised. Native XML/editability, references and box/text geometry were verified; GUI rendering is not described as tested. + +## Preservation and scope + +A SHA-256 comparison confirms **all 63 supplied files under `Docs/` remain byte-identical** to the review snapshot. Git status shows only the new `ArchitectureProposal/` directory. No application source was opened, generated or modified; source references embedded in descriptive documents were not followed. No existing documentation, configuration, tests, migrations or deployment files changed. + +Temporary generators/checks and layout previews were kept under `/tmp/` solely for producing/verifying documentation; no implementation scripts or deployment artefacts were added to the repository. No application test or installer ran, and no live host or clinical publisher was queried. Energy expectations contain no numerical savings or measurement procedures. + +## Remaining evidence limits + +The architecture allocation is complete under the clarified scope. Clinical content/rule review, final reproducible mathematical method/fixtures, narrative-conflict behaviour, performance/capacity, actual energy effects and native installation evidence remain subsequent implementation/operational acceptance dependencies. Workload, hosting, isolation and recovery unknowns have explicit assumptions and reconsideration conditions; none is silently represented as an established requirement or measured result. diff --git a/ArchitectureSuggestions/README.md b/ArchitectureSuggestions/README.md new file mode 100644 index 0000000..100bf9c --- /dev/null +++ b/ArchitectureSuggestions/README.md @@ -0,0 +1,19 @@ +# Energy-conscious architectural suggestions + +2026-10-13. Separate exploratory supplement requested by the user after reviewing the modular-monolith proposal. **Keeping microservices is a valid option.** Lower energy use does not require consolidating all application functionality into one process. + +These suggestions do not replace the selected [architecture proposal](../ArchitectureProposal/README.md), alter original requirements, or authorize implementation. The user's request explicitly authorizes this separate folder. Application source was not inspected or changed. + +| Document | Purpose | +| --- | --- | +| [Suggestions and alternatives](energy-with-independent-services.md) | Nine architectural options, mechanisms, assumptions, counter-effects and a suggested sequence of decisions | +| [Energy recommendation](energy-recommendation.md) | Leading candidate, expected ranking, rationale, assumptions and conditions that could reverse the recommendation | +| [Behaviour and compatibility](requirements-and-compatibility.md) | Requirement safeguards, original US-16 compatibility, freshness/security constraints and unresolved questions | +| [Editable service topologies](diagrams/service-topology-options.drawio) | Five-service deployment with preserved routing; optional direct internal routing with explicit trust boundaries | +| [Validation](validation.md) | Documentation, diagram, links and preservation checks; evidence limits | + +The most conservative candidate retains the existing five independent services and gateway-routed communication, colocates services where suitable, uses one PostgreSQL server with **two separately owned databases/credentials**, and improves architectural resource management and request reuse. A more invasive candidate retains five processes but changes internal routing; it requires explicit communication/trust-design revisions. Conditional caching and selective scaling have workload-dependent trade-offs. + +The earlier monolith selection was based on architectural simplicity and plausible overhead reduction under a modest-workload assumption. It did **not** establish that a monolith consumes the least energy. These suggestions explain how independent services could address the same overheads and when their isolation or selective scaling could be advantageous. + +No energy saving is measured or quantified. No benchmark procedure, application code, deployment configuration, compiler tuning or replacement mathematical algorithm is supplied. Authentication, current data, context, clinical interpretation and complete results remain binding. diff --git a/ArchitectureSuggestions/diagrams/service-topology-options.drawio b/ArchitectureSuggestions/diagrams/service-topology-options.drawio new file mode 100644 index 0000000..4260a18 --- /dev/null +++ b/ArchitectureSuggestions/diagrams/service-topology-options.drawio @@ -0,0 +1,133 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/ArchitectureSuggestions/energy-recommendation.md b/ArchitectureSuggestions/energy-recommendation.md new file mode 100644 index 0000000..ffedf00 --- /dev/null +++ b/ArchitectureSuggestions/energy-recommendation.md @@ -0,0 +1,62 @@ +# Recommendation: the most likely lowest-energy Health App architecture + +2026-10-13. This recommendation compares the modular-monolith proposal with the service-preserving suggestions. It is a reasoned prediction for the documented prototype, **not an established energy result**. + +## Recommendation and scope + +My leading candidate is an **efficient modular monolith on one suitably sized Linux host with PostgreSQL**. Combine the topology with bounded connection pooling, request-local reuse of current source data and on-demand calculations. Retain explicit module responsibilities, private persistence adapters, secure authorization and the complete required results. + +The nine suggestions in this folder are mostly complementary architectural changes, rather than nine mutually exclusive complete architectures. Several apply to both a monolith and independent services. The meaningful comparison is therefore between complete combinations under equivalent behaviour, data, workload and hosting assumptions. + +This recommendation follows the previously authorized freedom to reconsider topology. It requires the [US-16 revisions](../ArchitectureProposal/us16-revision.md) already documented in the proposal. It does not claim to satisfy original independent-feature installation requirements or authorize implementation. The main [architecture specification](../ArchitectureProposal/software-architecture.md) remains authoritative. + +## Assumptions behind the prediction + +Assume modest, intermittent interactive use with synthetic patient data; profile and observation operations plus current insights/trends/overviews; no demonstrated need for independent feature scaling, separate deployment teams or mandatory process isolation. Assume one host can accommodate the application and database with appropriate operating headroom. Workload volume, history size, query repetition, hardware power response and physical host sharing remain unknown. + +The predicted advantage concerns total operational energy for equivalent useful work over equivalent periods, including idle operation. Fewer requests, incomplete results, stale assessments or weaker access protection cannot count as improvements. CPU utilization, memory, latency and throughput alone do not establish lower energy consumption. + +## Why this is the leading candidate + +| Architectural characteristic | Expected energy mechanism | Qualification | +| --- | --- | --- | +| One application runtime | Avoids duplicating application runtime, listener and housekeeping resources across five feature processes | Runtime footprint does not translate directly into a known energy saving; fixed host power may dominate | +| In-process module calls | Removes internal HTTP handling, serialization and TLS work, including gateway callback detours | External HTTPS and database communication remain; efficient colocated services may have a small marginal communication cost | +| Direct request composition through module interfaces | Captures current source values and reuses them within an authorized request, avoiding redundant retrieval where possible | This benefit can also be designed into microservices; do not attribute every avoided read exclusively to consolidation | +| Bounded shared connection management | Reuses database sessions and avoids duplicating unbounded per-service resource budgets | Idle pooled connections and contention still cost resources; efficiently bounded service pools may achieve similar benefits | +| On-demand calculations without an added broker/cache server/worker | Avoids extra resident components and unsolicited background work | The documented baseline already calculates on demand without these components, so this is a retained advantage over more elaborate variants, not a new saving against that baseline | +| One appropriately sized physical deployment | May avoid powering separate underused application/database hosts | If all five services already share the same host/PostgreSQL server, physical consolidation supplies no additional advantage | + +The strongest rationale is that this combination removes internal communication and duplicated application-runtime overhead without adding coordination machinery for a workload that does not yet justify it. Simpler deployment and transactions also support correctness and maintainability, although those benefits are not energy measurements. + +Physical hosting deserves separate attention. Static power and energy proportionality mean software work and host energy need not move in direct proportion. The [Green Software Foundation's energy-efficiency guidance](https://learn.greensoftware.foundation/energy-efficiency/) describes those mechanisms. Applying them to this Health App is an inference; the guidance does not demonstrate that this application's monolith beats its microservices. + +## Expected ranking under these assumptions + +| Expected position | Complete candidate | Reason and uncertainty | +| --- | --- | --- | +| 1 | Efficient modular monolith; one app host with local PostgreSQL; bounded pooling, request reuse, current on-demand results | Removes internal application-network calls and multiple runtime footprints. Leading candidate with limited confidence | +| 2 | Efficient colocated independent services; one suitable host and PostgreSQL server, two owned databases; bounded pools and safe duplicate-read removal | Retains process isolation and independent installation while addressing physical overhead and repeated work. Could be close to, or outperform, the monolith depending on resource behaviour | +| 3 | Independent services distributed across several dedicated, continuously powered hosts | Likely higher idle infrastructure cost at modest demand. This prediction does not apply automatically when those services instead share existing physical capacity or a more efficient hosting platform | + +This is an ordinal prediction, not a quantified ranking. It does not prescribe adding idle hosts to the service alternative, overprovisioning either candidate or comparing different security/result guarantees. Equal software behaviour on different hardware can also change the ordering. + +## Conditions that could change the recommendation + +**Heavy, uneven analytics demand:** Independent services can scale only Insights while leaving lightly used features small. A monolith may replicate the whole application to handle that load. If the avoided replication exceeds service communication and coordination overhead, service separation could use less energy. + +**Frequent repeated expensive queries:** Source-revision-validated result reuse could avoid repeated data transfer and calculation. It can apply to either architecture. A cached service design could outperform an uncached monolith, but that would not prove that service boundaries caused the difference. Cache memory, source revision checks, invalidation correctness and query repetition determine whether the mechanism is worthwhile. + +**Different physical hosting:** Five services on an already shared host may have little avoidable infrastructure overhead. Conversely, a dedicated oversized monolith host can be wasteful. Remote shared database capacity may be preferable to another mostly idle local server. Physical host count and suitability matter more than deployment labels alone. + +**Resource contention or isolation needs:** A shared process may experience contention or require excess headroom that isolated services avoid. Mandatory independent deployment/fault isolation can also make services the more suitable architecture even if a small energy penalty remains. The recommendation must continue to respect security, correctness and operational requirements. + +**Acceptable intermittent activation:** Hosting that can remove unused capacity may favour independently activated services for some workloads. Cold starts, dependency activation, availability and platform overhead require an explicit design decision; no scale-to-zero benefit is assumed here. + +## Practical recommendation + +For the current clarified architecture assignment, retain the efficient modular monolith as the **most plausible lowest-energy candidate**, while recording the efficient colocated five-service design as the strongest alternative. Confidence in the qualitative mechanisms is greater than confidence in the final energy ranking, because workload and hardware evidence are absent. + +If preserving original service installation/isolation is important, choose [Candidate A from the suggestions](energy-with-independent-services.md): it addresses several energy mechanisms without a runtime merger and requires fewer structural changes than direct-call delegation or distributed caching. Do not introduce brokers, cache servers, orchestration platforms or additional replicas solely on the assumption that they will save energy. + +No universal winner, numerical saving or energy measurement procedure is claimed. Current information supports a conditional recommendation; it does not establish actual consumption. Application code, original inputs and the architecture proposal remain unchanged by this document. diff --git a/ArchitectureSuggestions/energy-with-independent-services.md b/ArchitectureSuggestions/energy-with-independent-services.md new file mode 100644 index 0000000..7102a81 --- /dev/null +++ b/ArchitectureSuggestions/energy-with-independent-services.md @@ -0,0 +1,115 @@ +# Reducing energy use while retaining independent services + +Yes: process consolidation is one architectural lever among several. Physical deployment, repeated work, communication paths, connection lifecycles, data movement and scaling can all influence energy use while service boundaries remain intact. The choices below are **Health App design hypotheses**, not evidence of savings or a new implementation specification. + +The documented baseline has five independent processes, gateway-routed internal calls, two separately owned PostgreSQL databases, on-demand Insights and Overview without stored results, and pre-created account/assignment configuration. Generated DB connections disable pooling, and observation-ID authorization reads the observation before the forwarded operation reads it again. These findings come from [as-built documentation](../Docs/AsBuiltArchitecture/software-architecture.md), especially §§2, 5, 7–9; application source was not opened. Runtime HTTP-client reuse already exists, so it is not assumed to be a missing feature. + +## 1. Consolidate physical placement while keeping five processes + +**Design:** Run Gateway, Profile, Observation, Insights and Overview as separate systemd services on one suitably sized host, or on fewer hosts than a fully distributed installation. Keep their configured HTTPS interfaces, independent management and service identities. Use the same binaries/interfaces for separate-machine deployments. + +**Mechanism:** Fewer dedicated physical machines may remove avoidable idle server and network overhead while retaining deployment/process boundaries. Static power and energy proportionality make physical placement a different issue from application-process count. The [Green Software Foundation energy-efficiency guidance](https://learn.greensoftware.foundation/energy-efficiency/) explains this relationship; applying it to Health App is an architectural hypothesis. + +**Assumptions/dependencies:** Services fit with operating headroom; physical consolidation actually reduces powered capacity or enables resource sharing. This is already allowed by original US-16; no monolith or shared process is needed. + +**Counter-effects:** Five VMs may already share one physical machine, and moving them may remove no host. A permanently powered host may consume similar idle energy despite less software work. Resource contention, larger peaks and a shared host failure domain can reduce the benefit. Maximum utilization is not a design target when it harms responsiveness or correctness. + +## 2. Share the PostgreSQL server, preserve database ownership + +**Design:** One PostgreSQL server hosts a Profile database and an Observation database, each with its own credentials and restricted rights. Insights and Overview receive no database. Persistent services still access only their own data. + +**Mechanism:** Potentially avoid duplicating database-server/background resource footprints or dedicated DB hosts without merging databases or ownership. Original [US-16 addendum](../Docs/Requirements/us16-addendum) explicitly allows this arrangement. + +**Assumptions/dependencies:** The starting deployment actually uses multiple PostgreSQL servers or hosts, and their workloads can safely share capacity. + +**Counter-effects:** If the baseline already uses one PostgreSQL instance, there is no new server-consolidation benefit. Shared maintenance/I/O and host failure affect both owners. Separate databases do not make the server a distributed-transaction or cross-service snapshot mechanism. Never justify direct cross-database reads as an energy shortcut. + +## 3. Bound and reuse connections and concurrent work + +**Design:** Give Profile and Observation bounded application-side connection pools, preserving separate DB identities; place an overall connection budget across services/replicas. Maintain reusable authenticated HTTPS connections for internal requests rather than provisioning a separate proxy or pooler by default. Bound admitted expensive analytics work independently from lightweight operations; propagate cancellation and deadlines. + +**Mechanism:** Reusing database sessions may avoid repeated establishment/authentication work. A bounded budget limits unnecessary connection/process/resource growth and wasted work after callers cancel. PostgreSQL documents that its connection limit affects resource sizing, including shared memory. That supports the need for a resource budget, **not a claim of lower energy**. [PostgreSQL connection settings](https://www.postgresql.org/docs/current/runtime-config-connection.html). + +**Assumptions/dependencies:** Repeated DB establishment or excessive concurrency is meaningful in the actual deployment; pooled sessions preserve transaction cleanup and separate credentials. The documented generated `Pooling=false` makes DB lifecycle management a concrete candidate. Existing HTTP-client reuse must be considered rather than counted as a new saving. + +**Counter-effects:** Idle pooled connections consume resources; multiplying per-service pools by replicas can inflate the total. Too small a pool or overly strict admission increases waiting. An external pooler adds its own process and failure/configuration boundary; use only if that extra component has a justified role. These are architectural budgets/lifecycles, not prescribed tuning numbers or code-level optimizations. + +## 4. Remove duplicate reads within an authorized operation + +**Design:** For a specific observation GET, the Gateway already retrieves a protected observation to establish its actual owner. After successful authorization, it can return that same validated upstream representation rather than fetching the observation again. Buffer it privately until the policy decision; unauthorized callers never receive any part of it. Preserve response/context fields and safe error/absence semantics. + +Keep the reuse limited to that request. A PATCH/DELETE still needs an owner-scoped, atomic mutation at Observation; reusing a GET body does not establish that a write succeeded. Current immutable patient association makes ownership stable, but deletion and correction can race with a read as in any defined read snapshot. + +**Mechanism:** Avoid one upstream call, one DB read and duplicate serialization for the affected GET. This is request-local reuse, not cross-request caching of health data or authorization. + +**Assumptions/dependencies:** The owner lookup returns the full required observation representation, as documented; it is compatible with the external representation. Gateway can preserve status/headers without exposing data before authorization. + +**Counter-effects:** Buffering consumes memory and can require different response handling. A metadata-only owner endpoint can reduce payload for write authorization, but adding it changes an internal interface and does not remove the mutation's required DB work. Reusing Profile data across nested Overview callbacks would need explicit bounded request-context design; do not assume ordinary HTTP callbacks share request memory. + +## 5. Reduce unnecessary data movement through purpose-specific contracts + +**Design:** Keep period, patient and context selection at Observation, the source owner. Offer narrowly scoped internal read representations only where the consumer's complete functional needs are known. Index supported patient/time access paths at the owned datastore. Preserve full public history and context retrieval contracts. + +For numerical insight, a compact internal response could contain current count, exact sums, BP extrema and **complete context evidence needed for its explanation**, all from one source snapshot. Insights still owns final rounding/result interpretation. This changes the responsibility for numerical aggregation and internal contracts; it must be recorded rather than disguised as a harmless transport change. For trends, retain all timestamps/readings and relevant context/narrative evidence needed by the full-period method; endpoint values or averages are insufficient. + +**Mechanism:** Fewer unnecessary rows/fields/bytes may reduce DB reads, serialization, transfer and downstream materialization. Removing redundant work does not require removing process boundaries. + +**Assumptions/dependencies:** Relevant histories/payloads are large enough, and the new contract reproduces every required result under equal data. Patient/time indexing is missing in the documented baseline; index usefulness remains workload dependent. + +**Counter-effects:** Computation may simply move to the database; aggregate queries and indexes add CPU, writes, storage and maintenance. Extra internal contracts increase maintenance. Do not drop notes/conflicts, Unknown categories or preparation evidence. Do not silently cap history, substitute a selected-period latest for latest overall, or invent a new trend formula. Protocol replacement/compression is not presumed to save energy; retain existing HTTPS/JSON unless a separate justified contract decision is made. + +## 6. Shorten internal routes without merging services + +**Design:** Keep clients entering through Gateway. Let authenticated Overview call Profile, Observation and Insights directly on private HTTPS interfaces; let Insights read selected history directly from Observation and Observation verify patient existence with Profile. The same five independently runnable processes and separate DB owners remain. + +**Mechanism:** Remove gateway forwarding on internal legs, potentially reducing extra routing, serialization/HTTP handling and Gateway load. For example, an insight's internal source path changes from `Insights → Gateway → Observation` to `Insights → Observation`. + +**Assumptions/dependencies:** The extra hop is significant. Provide explicit source-side service authentication, operation allowlists and request-scoped authorization delegation. This revises the existing gateway-routed communication design and original AC-16-H interpretation; user topology freedom permits exploring it, but this document does not activate it. + +**Security boundary:** Each source verifies the receiving endpoint's TLS identity and the calling service's generated credentials or equivalent established service-authentication mechanism. A trusted Gateway-issued authorization scope must be bound to the current request, patient, permitted read/action and intended service; receivers reject mismatched scope and resolve actual ownership for ID-addressed resources. Use established framework protection rather than custom cryptography. Never treat a client header, correlation ID or a service credential alone as proof of a user's patient entitlement. No public backend route may bypass this control. Scope/transport/credential distribution is part of a future complete trust design, not an optional afterthought. + +**Counter-effects:** More trust relationships, backend checks, delegated context and certificate/credential distribution can outweigh the saved hop. Gateway becomes less of an internal bottleneck, but no cross-service atomic snapshot appears automatically. A service mesh would add sidecars/listeners and operational overhead; it is not required merely to permit these direct calls. [Microsoft's communication guidance](https://learn.microsoft.com/en-us/dotnet/architecture/microservices/architect-microservice-container-applications/communication-in-microservice-architecture) discusses synchronous dependencies and consistency trade-offs; the Health App routing proposal and energy expectation are our inference. + +## 7. Introduce freshness-safe reuse only when repetition justifies it + +**Design:** Start with public, immutable reviewed guidance/reference content, whose versions and applicability are explicit. The baseline already loads static content, so an internal memory cache may add no benefit; external conditional/public caching may avoid repeated transfers without exposing patients. + +For expensive repeated clinical-data calculations, an optional bounded **in-memory** Insights cache can use source-certified per-patient observation revision plus patient, normalized period, context selection, method version and reference-content version. Observation increments its revision atomically on every record, numeric/context correction, clearing and deletion. The source provides revision and selected data from the same consistent read when data is needed. Each request still authenticates/authorizes and validates the current source revision; failure to establish current state fails rather than serving an unverified result. A matching current revision allows reuse; a changed revision forces calculation from current selected data. Clinical/account/assignment updates must not be bypassed by cache hits. + +**Mechanism:** Potentially avoid repeated full-series retrieval/calculation while retaining immediate post-commit freshness for subsequent requests. This is useful only when saved repeated work exceeds revision checks, cache management and memory overhead. + +**Assumptions/dependencies:** Repeated identical expensive queries are common, methods/content are versioned, and source revision is correct and transactional. Every replica follows the same validation rule; request-time snapshot semantics are explicit. Cached results are protected internal derived health data, not public HTTP cache entries. + +**Counter-effects:** High write rates/low repetition yield few hits. Revision updates/checks, retained memory and extra contracts cost work. Requests concurrent with a write see their documented source-read point, not future data. A TTL alone or eventual invalidation event does not satisfy freshness; asynchronous replicas must not return stale latest results. No Redis/broker/persisted result store is necessary for this candidate, and none is proposed by default. Baseline no-cache architecture would need an explicit revision; no-persistence and original internal contract expectations remain recorded. + +## 8. Scale only the services that need capacity + +**Design:** Retain independent services and allocate additional instances only to a saturated feature, such as expensive Insights reads, instead of cloning the entire application. Keep source ownership/current reads and per-request access checks. Scale back redundant capacity when acceptable; preserve stable endpoint discovery and compatible service credentials. + +**Mechanism:** Under skewed demand, selective scaling can avoid replicating lightly used Gateway/Profile/Observation/Overview work. This is a genuine architectural advantage independent services can have over whole-application replication. + +**Assumptions/dependencies:** The load is sufficiently uneven and high to justify replicas, routing and coordination. Sufficient DB capacity exists; replica pools are included in a global budget. + +**Counter-effects:** Additional instances/load balancers/controllers cost idle resources and may amplify source load. Adding Kubernetes or an autoscaling control plane for a small prototype can be counterproductive. Full scale-to-zero introduces cold starts, dependency activation and availability complications; it is conditional on an explicit responsiveness/hosting decision, not the default. Scaling is not automatically lower energy just because throughput rises. + +## 9. Keep unsolicited and failed work bounded + +**Design:** Retain on-demand calculations and transient provisioning, rather than adding periodic summary recalculation, continuous content polling or a resident provisioning service. Where background administrative work becomes necessary, schedule only genuinely deferrable work without delaying user-visible record/read/correction/deletion semantics. Use propagated cancellation, bounded read retries/deadlines and fail-closed dependency errors; do not repeatedly retry an ambiguous write. + +**Mechanism:** Avoid work no user requested and limit amplification during cancellations/outages. The baseline already has no broker/periodic calculation worker, so preserving that absence is not an additional saving relative to it. + +**Assumptions/dependencies:** No acceptance criterion requires real-time push/background computation; the current synchronous model remains appropriate. + +**Counter-effects:** Repeated on-demand computations may cost more than a correct cache under highly repetitive load. Overly aggressive deadlines/retries can cause failures or repeated client work. Replacing synchronous current results with eventual projections creates freshness problems; a broker's cost is not justified by the word “asynchronous.” Moving work to a lower-carbon time/location may affect emissions without reducing energy, and is a separate objective. + +## Suggested architectural path + +| Candidate | Composition | Why consider it | Remaining trade-offs | +| --- | --- | --- | --- | +| A — Conservative independent services | Five processes, original gateway routing, one suitable host where possible, one PostgreSQL server/two DB owners; bounded pools/admission; safe request-local GET reuse | Addresses physical/resource/repeated-work overhead with minimal structural change; original independent-installation capability remains | Duplicate runtimes and internal network paths remain; host contention and pooled idle resources | +| B — Independent services with direct internal calls | A plus explicit private direct dependency APIs and scoped authorization delegation | Addresses gateway detours while preserving independent runtime/DB boundaries | Revises communication/trust design; credential/delegation complexity; independent failures remain | +| C — Workload-adaptive independent services | A or B plus only justified source-revision reuse/selective replicas | May be advantageous for repeated expensive queries or skewed feature demand | Highest correctness/coordination overhead; unsuitable as a default for an unknown small workload | + +For this prototype, **Candidate A is a reasonable alternative to evaluate before a runtime merger** if retaining services is valuable. Establish physical placement and documented resource lifecycles first; then remove avoidable repeated reads. Consider B when gateway detours matter, and C when the workload actually needs its extra machinery. This ordering expresses reversibility, requirement compatibility and complexity, not a measured ranking of energy savings. + +Combining mechanisms does not mean their savings add: colocation may already remove much network/host overhead; pooling, compact contracts and caching can address overlapping work. A monolith may still be appropriate for simplicity, while an efficient service deployment may outperform it under different load/hosting assumptions. Current documentation provides no universal energy winner. diff --git a/ArchitectureSuggestions/requirements-and-compatibility.md b/ArchitectureSuggestions/requirements-and-compatibility.md new file mode 100644 index 0000000..9da5e0e --- /dev/null +++ b/ArchitectureSuggestions/requirements-and-compatibility.md @@ -0,0 +1,40 @@ +# Requirement safeguards and compatibility + +This is a suggestion register, not a replacement architecture. Binding behaviours remain the [common requirements](../Docs/Requirements/00-common-requirements.md) and US-01–US-15. Original [US-16](<../Docs/Requirements/US16 easy installation and deployment installer.txt>) and its [addendum](../Docs/Requirements/us16-addendum) are assessed explicitly; earlier user clarification allows topology alternatives to be documented with necessary revision. + +## Constraints every candidate preserves + +| Behaviour | Architectural safeguard | +| --- | --- | +| US-01/02/03 account/profile lifecycle and retrieval | Atomic durable association, uniqueness and retry/recovery remain Profile-owned; no cross-service association cache replaces the source of truth | +| US-04/05/06 record/read/latest and context | Positive required values/time; actual existing patient; saved independent categories/text/details; latest uses measurement/original recording/deterministic tie, independent of context suitability | +| US-07 and shared periods/selections | Full inclusive patient history, equal bounds valid/reversed rejected, ascending measurement order, AND selected dimensions, Unknown distinct from omission; no silent truncation or default exclusions | +| US-08/09 updates/deletion | Atomic validation/mutation; omitted values preserved, clear makes Unknown; source revision (if added) changes in the same transaction; later source reads exclude deleted values/context | +| US-10 arithmetic insight | Exact raw contributions/count, three means with final half-up two decimals, BP extrema and one/zero sufficiency; mixed/unknown context visible. Aggregate transfer must preserve these obligations | +| US-11 trends | Full-period timestamp evidence, intermediate excursions/reversals, distinct-time sufficiency, separate metrics/units, current context, applicable reviewed references and claim-specific limits; no endpoint-only shortcut or replacement formula for energy | +| US-12 overview | Latest overall remains independent of insight period/selection; profile/latest retained for no insight; distinct bases and explanations; no trend added. Independent-service composition does not promise a cross-service snapshot | +| US-13/14 authentication and authorization | Validate current request identity, ownership and assignment before any result, including cache hits; professional reads only; actual observation owner, never caller patient ID; no direct API bypass, leaked tokens or public clinical caches | +| US-15 guidance | Public sourced/reviewed/applicability-labelled guidance; no record writes/certification/defaulting/submission dependency; unsupported verified content explained | +| Deployment/security | Separate feature processes/configuration and generated protected credentials/certificates when retained; remote origins supported; HTTPS trust verified; only owners access their databases | + +## Structural compatibility by suggestion + +| Suggestion | Five service processes? | Original US-16 / existing design status | +| --- | --- | --- | +| 1 physical colocation | Yes | Explicitly permitted; independent units/configuration and configured remote interfaces retained | +| 2 shared PostgreSQL server/two owned DBs | Yes | Explicitly permitted; never merge databases, credentials or owners | +| 3 bounded resource/connection lifecycle | Yes | Preserves boundaries and configuration semantics; resource policy is a revisable runtime design decision | +| 4 request-local observation GET reuse | Yes | Preserves processes/ownership/public results; recorded Gateway forwarding behaviour changes. A strict requirement to preserve every original call path requires explicitly documenting this reduction | +| 5 tailored internal data contracts/source aggregates | Yes | Selection/index decisions can remain within owners. New internal APIs/source aggregation change contracts or responsibilities and require corresponding architecture/AC-16-H reconciliation; not asserted fully compatible | +| 6 direct private service calls | Yes | Original gateway-routed design changes; AC-16-H communication-path interpretation and deployment/trust documentation require revision. Same service installability and separate DB ownership remain | +| 7 revision-validated memory result cache | Yes | Preserves current functional results if its transactional revision contract holds. Changes baseline no-cache/on-demand mechanism; internal metadata contracts/persistence fields require explicit revision. No generated-result database is required | +| 8 selective replicas / conditional activation | Yes | Optional runtime topology; per-service management retained. Added routing/credentials/global budgets require design; scale-to-zero is unresolved pending responsiveness/host constraints | +| 9 bounded/on-demand work | Yes | Retains baseline on-demand/no-worker behaviour. Any new deferral must leave synchronous acceptance semantics intact | + +Candidate A is compatible with the central independent-service/deployment constraints; request-local reuse is an optional refinement with its call-path delta identified. Candidates B/C require more significant recorded changes. None introduces direct SQL access by Insights/Overview or claims separate DBs give atomic multi-service reads. + +## Decisions still dependent on deployment/workload + +Physical host sharing and idle power response determine whether colocation releases any powered capacity. History size and repeated query patterns determine whether compact contracts/cache reuse pay for their complexity. Uneven load and isolation needs determine whether selective service scaling offers an advantage. Token/service trust, scope lifetime and cache revision contracts must be fully specified before implementing B/C. Availability and cold-start tolerance must be clarified before scale-to-zero. No numerical workload, savings, pool sizes or automatic-scaling thresholds are invented. + +External sources in the suggestions support general mechanisms and architectural concerns, not a Health App energy result. No changes to clinical guidance/reference values, original requirements, source or deployment configuration are made. diff --git a/ArchitectureSuggestions/validation.md b/ArchitectureSuggestions/validation.md new file mode 100644 index 0000000..26cdf3a --- /dev/null +++ b/ArchitectureSuggestions/validation.md @@ -0,0 +1,19 @@ +# Suggestion-document verification + +Completed 2026-10-13. This folder is an exploratory supplement requested by the user, not a second completed implementation architecture or a replacement of `ArchitectureProposal/`. + +The README, nine-option architectural discussion, requirement/compatibility register, this validation record and editable two-page topology diagram are present. Each option identifies its proposed change, energy mechanism, assumptions/dependencies and possible counter-effects. Baseline mechanisms already present are distinguished from possible new improvements. Candidate A preserves five-process installation and separate DB ownership; communication, contract, cache and activation changes are explicitly conditional/revision-requiring. + +The compatibility review covers US-01–US-15/common behavioural safeguards and original US-16 installation/ownership semantics. It specifically checks actual-owner authorization before request-local read reuse, no professional writes, complete history/context, current corrections/deletions, source-certified cache revision, clinical-method independence and latest-overall versus selected-insight distinction. Suggestions do not invent clinical thresholds, silently drop data, add an unneeded broker, or claim multi-service snapshot consistency. + +Primary external guidance was consulted for energy proportionality/static power, PostgreSQL connection resource sizing and microservice communication/consistency concerns. Links are attached to the relevant discussion. Those sources do not establish Health App energy savings; application-specific mechanisms and priorities are explicitly inferences/hypotheses. No numerical savings or energy measurement procedure is specified. + +Diagram verification parsed native uncompressed Draw.io XML with **2 pages, 21 editable vertices and 17 connectors**. Cell IDs are unique, all connector endpoints resolve, dimensions are positive, peer boxes do not overlap and font-metric estimates found no vertex label overflow. No raster-only diagram content is embedded. Draw.io GUI import/rendering/round-trip and automatic connector-label placement were not exercised; the GUI/CLI remains unavailable. + +Local Markdown file links and balanced fences were checked after all files were created. A SHA-256 comparison confirms all **81 existing `Docs/` and `ArchitectureProposal/` files remain unchanged**. Existing proposal documents and original sources were not edited; new repository work is confined to `ArchitectureSuggestions/`. No application source was inspected or modified, and no application tests or installer were run. Temporary documentation checks were outside the repository. + +Open workload, physical hosting, availability, query repetition and isolation questions remain assumptions, not blockers for this exploratory discussion. Direct-call delegation, source revision/cache metadata, compact aggregate contracts and conditional activation require detailed design before implementation. The completed deliverable is a documented menu of architectural alternatives with safeguards and editable topology sketches. + +## Recommendation supplement + +The [energy recommendation](energy-recommendation.md) records the efficient modular monolith as the leading candidate under modest/intermittent workload assumptions, with efficient colocated independent services as the strongest alternative. It distinguishes complementary changes from complete architectures, existing baseline behaviour from new benefits, and physical consolidation from process consolidation. The expected ranking explicitly accounts for hosting, repeated queries, selective scaling, contention and original US-16 incompatibility. It states limited confidence and makes no measured or quantified saving claim. Local links and input/proposal preservation were checked again after adding it; no existing diagrams or application artefacts changed.