Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
82 changes: 82 additions & 0 deletions docs/GZIP_CACHE_MEASUREMENTS.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
# Gzip fallback cache measurements (#281)

Measured on Linux x86-64, GCC 15.2.0, Release (`-O3 -DNDEBUG`), 2026-10-25.
Both executables enable `_GLIBCXX_ASSERTIONS` and `-ftrivial-auto-var-init=pattern`.
These are local timing observations, not performance assertions or cross-platform guarantees.
The benchmark calls the real `RequestHandler` with an in-memory compressed provider: URI
parsing, provider reads, negotiation, decoding/cache lookup and response construction are
included; network I/O, browser decompression and filesystem latency are excluded.

The before executable uses `HTTPServer.hpp` from commit `642a435`, with a counter added at
its `decodeGzip` call. The after executable uses the new cache and its decode-attempt and
retained-byte counters. Each row performs **200 requests**. Repeated rows use one handler
and include its first cold request; cold rows create a fresh handler for every request.
The optional target also runs the new handler with retention disabled as an uncached control.
No decoder algorithm or gzip validation change is included in #281.

The neutral fixed/dynamic/optional fixtures are from `test/unit/GzipFixtures.hpp`. The
application input is the generated developer compiler bundle `build-distribution/compiler.mjs`,
compressed with Python's `gzip.compress(bytes, mtime=0)`. It is an application bundle,
not a restored core provider. Its SHA-256 is listed below so regenerated bundle changes
cannot silently be mistaken for the same workload.

## Sizes and retained memory

| Asset | Compressed bytes | Decoded bytes | Before retained bytes | After retained bytes |
| --- | ---: | ---: | ---: | ---: |
| fixed | 499 | 23768 | 0 | 24357 |
| dynamic | 453 | 23768 | 0 | 24311 |
| optional | 476 | 23768 | 0 | 24334 |
| application | 22902 | 78508 | 0 | 101500 |

Retained bytes include both string capacities and terminators, entry metadata and list links
(90 bytes of accounted overhead per entry on this libstdc++ build). GET and HEAD retain the
same entry. This measures cache retention, **not peak process memory**: provider/input bytes,
response buffers, decoder temporaries and allocator bookkeeping are outside these figures.
Every cold request still allocates a bounded decoded representation; admission temporarily
constructs a retained copy. An evicted/disabled/oversized entry retains zero bytes.

## Timing and decode counts

Before: **200 decodes** in every row. After: **1 decode** for repeated requests and
**200 decodes** for cold requests. With cache retention disabled: **200 decodes**, zero
retained bytes. Tests separately verify mixed GET/HEAD reuse and a smaller active output
budget, content replacement, invalid streams, admission limits, eviction and shutdown.

| Asset | Method | Repeated before (µs/request) | Repeated after | Cold before | Cold after |
| --- | --- | ---: | ---: | ---: | ---: |
| fixed | GET | 74.60 | 2.30 | 76.30 | 76.14 |
| fixed | HEAD | 75.14 | 1.83 | 77.19 | 76.45 |
| dynamic | GET | 75.11 | 2.27 | 76.58 | 75.71 |
| dynamic | HEAD | 75.22 | 1.81 | 76.17 | 75.75 |
| optional | GET | 75.80 | 2.28 | 76.52 | 76.40 |
| optional | HEAD | 75.21 | 1.82 | 75.57 | 76.17 |
| application | GET | 921.80 | 32.54 | 934.22 | 916.78 |
| application | HEAD | 907.11 | 31.15 | 894.37 | 913.72 |

The improvement comes from eliminating repeat validation, including CRC32 and DEFLATE.
Cold application decoding remains about 0.9 ms here, on the I/O thread; #283 must address
that occupancy. The warm application cost still includes reading and comparing 22.9 KiB of
compressed bytes; #282 can use the cold rows as a decoder baseline. Small timing differences
between cold before/after runs include allocation and host scheduling noise.

## Reproduction

With the normal CEF-off test build configured:

```bash
cmake --build build --target gzip_cache_benchmark --parallel 2
# Without an argument, runs all three neutral fixtures.
build/test/unit/gzip_cache_benchmark
# Optionally use a generated application bundle, or any complete gzip asset under 4 MiB decoded.
python3 -c 'import gzip,pathlib; pathlib.Path("/tmp/wf-compiler.mjs.gz").write_bytes(gzip.compress(pathlib.Path("build-distribution/compiler.mjs").read_bytes(), mtime=0))'
build/test/unit/gzip_cache_benchmark /tmp/wf-compiler.mjs.gz
```

The CSV reports sizes, iterations, actual decode attempts, retained bytes and mean time per
request for both enabled and disabled retention. It is excluded from the normal build and
CTest; no timing threshold is imposed. Re-run on the target compiler/platform before using
the timings to justify decoder changes. For a historical before comparison, compile the same
harness against the pre-cache `RequestHandler` and count its `decodeGzip` calls.

Application bundle SHA-256: `5f36728943433f1b88eadcdc0db910133257b4502c8faec3357168b6739f70bc`.
66 changes: 49 additions & 17 deletions docs/HTTP_ASSETS.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@

HTTP asset negotiation and fallback apply to every frontend and to custom filesystem providers.

The embedded Jasmine, React, Babel and xterm JavaScript/CSS payloads use gzip.
The Jasmine favicon is served as its original PNG. If a client does not
accept gzip, the HTTP server decodes the asset and serves identity with the decoded `Content-Length` and no
Application providers generated by `wf embed` and custom filesystem providers can serve
gzip resources. The core assets are identity representations; see the current inventory in
[Embedded assets](EMBEDDED_ASSETS.md). If a client does not accept gzip, the HTTP server
decodes the asset and serves identity with the decoded `Content-Length` and no
`Content-Encoding`. Encoded responses carry `Vary: Accept-Encoding`; explicit `q=0`
exclusions are respected. Duplicate mentions accept a coding if any valid mention accepts it,
regardless of their order or which field contains them: `gzip;q=0, gzip` and `gzip, gzip;q=0`
Expand All @@ -24,38 +25,69 @@ coding nor identity is acceptable, or a custom provider uses an unsupported codi
(such as Brotli) the client does not accept, the server returns HTTP 406. Custom codings
can still be served directly to accepting clients.

Fallback decoding runs synchronously on the server I/O thread and is repeated for each
request, including HEAD to validate the stream and compute its decoded length. Decoded
assets are not cached. Stored DEFLATE blocks are copied in bulk and match copies grow the
output once per match; Huffman decoding still reads individual bits. Follow-ups track
[validated asset caching and HEAD metadata](https://github.com/ambroise-leclerc/WebFront/issues/281),
[buffered bit reads and benchmarks](https://github.com/ambroise-leclerc/WebFront/issues/282), and
[cold decoding off the I/O thread](https://github.com/ambroise-leclerc/WebFront/issues/283).
## Validated representation cache

Gzip remains the embedded format so fallback needs no compiled dependency or Brotli dictionary.
Pinned versions, reproducible generation and current stored/decoded resource checks are
documented in [Embedded browser dependencies](EMBEDDED_ASSETS.md). Returning them to Brotli
would require a separate decoder dependency and is deferred.
Each server owns a bounded LRU cache through its `RequestHandler`. It is destroyed after
server tasks have drained, with no global state, background work or extra shutdown join.
A copied handler starts with an empty cache; applications never implicitly share entries.
The server context serializes requests: a cold synchronous decode completes before another
request can miss on the same revision. There is no concurrent decode worker or in-flight table.
Moving cold decoding off the I/O thread remains [#283](https://github.com/ambroise-leclerc/WebFront/issues/283).

Keys contain the **complete compressed bytes**, rather than a pathname, borrowed pointer,
modification time, checksum alone or unvalidated ISIZE trailer. Every request still opens
and reads the provider. Changed bytes at the same path cause a new validation; identical
bytes at different paths or with the `x-gzip` alias share an entry. A custom provider needs
no revision API, but must keep its backing storage valid and stable throughout each read.
Older revisions remain eligible for LRU eviction; returning to exactly those bytes is safe.

Only successful full gzip validation creates an entry. It stores decoded content and thus
its validated length. GET reuses the content; HEAD reuses its length without copying decoded
content into the response. Each hit checks the **current** decoded output budget. Corrupt
streams and over-budget failures are never cached as successful representations. Pass-through
and 406 negotiation do not access the cache.

The default retention budget is **8 MiB per server**, allocated lazily. LRU eviction accounts
for both compressed and decoded string capacities plus their terminators, entry metadata and
two list links. Allocator bookkeeping is implementation-dependent and excluded. The fixed
cache object and counters, provider storage, request/response buffers and temporary cold
decoding allocations are outside this retention budget. Admission may temporarily construct
one additional entry before eviction, bounded by the same budget; the output limit separately
bounds cold decoded bytes. A representation too large to retain is still validated and served
under the output budget, without evicting useful entries; repeated requests decode it again.
There is no separate length-only cache for oversized HEAD responses.

Set `maxDecodedAssetCacheSize` on the buffer policy (or the sixth `CustomBuffersPolicy`
argument) to change retention. The retention budget is captured at handler construction;
the decoded output budget is read for every fallback request. Zero retention disables
caching, including HEAD metadata. Policies without this member inherit 8 MiB.
`RequestHandler::fallbackCacheStatistics()` exposes decode attempts, hits (including budget-rejected hits), entries and accounted retained bytes; read it
on the server context. The LRU lookup compares compressed bytes linearly across retained
entries; gzip pass-through remains independent of this cost. Decoder throughput and buffered
bit reads remain [#282](https://github.com/ambroise-leclerc/WebFront/issues/282).

See [gzip cache measurements](GZIP_CACHE_MEASUREMENTS.md) for cold/repeated GET and HEAD data
and the optional benchmark target.

## Fallback budget

The limit applies to the sum of decoded bytes across all gzip members, for GET and HEAD.
Gzip pass-through to an accepting client does not use this budget. A smaller budget reduces
the work and memory a fallback request can consume, but it is not an I/O-thread time limit.
All bundled assets fit under the 4 MiB default; custom applications can override it through
their existing buffer policy:
Applications can override decoding and retention through their buffer policy:

```cpp
#include <webfront/WebFront.hpp>
#include <cstddef>

struct AppBuffers : webfront::http::DefaultBuffersPolicy {
static constexpr std::size_t maxDecodedAssetSize = 1024 * 1024;
static constexpr std::size_t maxDecodedAssetCacheSize = 2 * 1024 * 1024;
};
using App = webfront::BasicWF<webfront::NetProvider, webfront::fs::DefaultFS, AppBuffers>;
```

`CustomBuffersPolicy` also accepts the limit as its fifth template argument. Policies without
`maxDecodedAssetSize` inherit the default. Zero permits only empty decoded assets. An asset
exceeding a smaller custom budget returns 500 when identity is needed; gzip pass-through is
unchanged. The follow-ups above address caching, decoder throughput and I/O-thread occupancy.
unchanged. Caching avoids repeated decoding; it does not bound cold decode time or provider read time.
10 changes: 8 additions & 2 deletions docs/PROJECT_STATUS.md
Original file line number Diff line number Diff line change
Expand Up @@ -511,10 +511,16 @@ The minimum demonstration milestone is deliberately narrower than the long-term
- Encoded HTTP assets (#274): accepted gzip is served unchanged; otherwise the server decodes
gzip to identity with the decoded length, no `Content-Encoding` and `Vary: Accept-Encoding`.
The default decoded-byte budget is 4 MiB and applications can override it through their buffer
policy. Other codings remain pass-through only. Fallback runs synchronously per request,
including HEAD; caching and byte-wise decoding remain follow-ups. See [HTTP asset encoding](HTTP_ASSETS.md)
policy. Other codings remain pass-through only. A server-owned 8 MiB LRU (#281) retains
validated identity bytes and HEAD lengths, keyed by complete compressed content and bounded
across keys and decoded storage. Each hit rechecks the active output budget; oversized
entries are served without retention. Cold fallback remains synchronous on the I/O thread
(#283); decoder throughput remains #282. See [HTTP asset encoding](HTTP_ASSETS.md)
for negotiation rules, errors, strict stream validation and budget configuration.
Regression tests and gzip/HTTP fuzzers cover decoding and encoding preferences.
Verified 2026-10-25 on Linux for #281: 275 CEF-off CTest cases and all 64 CEF/Xvfb
web-integration cases passed; cold/repeated GET/HEAD measurements are recorded in
[Gzip cache measurements](GZIP_CACHE_MEASUREMENTS.md).
Verified 2026-10-19 on Linux for #274: the CEF-off build/CTest suite, CEF/Xvfb integration and
WebKitGTK integration passed. The macOS results above describe earlier platform validation.
- First-party bridge/component text assets are embedded **verbatim rather than compressed**, so `HTTPServer` serves them without a `Content-Encoding` header. Deflate streams are not reproducible across the zlib builds on our macOS, Linux, and Windows runners, so a pre-compressed blob could not be verified by the staleness check. Restoring compression — either a reproducible build-time gzip or on-the-fly compression keyed on `Accept-Encoding` — is tracked as a follow-up. The fallback HTML and module have readable sources under `js/core/fallback/`; `favicon.ico` uses gzip. Legacy third-party Jasmine/React/Babel assets now use gzip for WKWebView local-HTTP compatibility (#258); their decoded payloads are unchanged. Regenerate the text headers with `cmake --build build --target webfront-embedded-assets`. Sources and generated headers use LF on every platform so the CTest freshness checks compare identical bytes.
Expand Down
23 changes: 19 additions & 4 deletions docs/adr/ADR-009-modules-et-assets-reproductibles.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,12 @@
| 2.1 | 2026-10-22 | Acceptée | Ambroise Leclerc | Assets embarqués limités à la liste normative de l'ADR-016 ; trajectoire de retrait de BabelFS, ReactFS, JasmineFS et des sources vendorisées. | [404fed2](https://github.com/ambroise-leclerc/WebFront/commit/404fed2c2145d4faba8efee035e10522ff87a91f) |
| 2.3 | 2026-10-24 | Acceptée | Ambroise Leclerc | `third_party/` est supprimé (#319) : `fflate` provient du paquet verrouillé du projet `wf`, aucune source tierce n'est vendorisée. | [1824271](https://github.com/ambroise-leclerc/WebFront/commit/18242715f14711e7871ea29aeccf661d5bef760f) |
| 2.2 | 2026-10-24 | Acceptée | Ambroise Leclerc | Les retraits annoncés sont réalisés (#312, #313, #318) : les en-têtes du cœur sont rendus et vérifiés par CMake seul (`js/core/EmbedAsset.cmake`), sans compression ni Node.js ; la compression gzip reproductible est celle de `wf embed`. | — |
| 2.4 | 2026-10-25 | Acceptée | Ambroise Leclerc | Cache LRU possédé par le serveur, clés par contenu gzip complet, contenu GET et longueur HEAD validés partagés, budgets et éviction bornés (#281). | — |

## État et chronologie

**Acceptée.** Décision initiale : **2023-03-16** (version 1.0).
Dernière révision : **2026-10-24** (version 2.3).
Dernière révision : **2026-10-25** (version 2.4).
Le présent texte expose la décision en vigueur ; le tableau retrace ses états antérieurs.

## Contexte
Expand Down Expand Up @@ -57,8 +58,9 @@ un échec de décodage ou dépassement du budget donne 500.

- **Bénéfice :** exécution locale et contrôle de fraîcheur des ressources réellement distribuées.
- **Coût accepté :** distributions et en-têtes volumineux versionnés, outils de maintenance dédiés.
- **Risque :** gzip→identity décode synchroniquement sur le thread I/O, à chaque requête, sans
cache. Le budget borne la sortie, pas le temps ; cache et déplacement du travail restent futurs.
- **Risque :** gzip→identity décode synchroniquement sur le thread I/O, sans
cache pour les révisions absentes ou trop grandes. Le budget borne la sortie, pas le temps ;
le déplacement du travail reste futur (#283). Voir le cache validé ci-dessous (#281).

### Révision de l'ADR-016

Expand All @@ -78,7 +80,20 @@ décision et ne s'appliquent plus qu'aux providers produits par `wf embed`.
- Que le lancement du programme C++ n’exige ni npm ni connexion réseau.
- Pour un nouvel asset, tester route, MIME, encodage, taille, lectures partielles et fraîcheur.
- Pour modifier la négociation, tester gzip, identity, exclusions et flux corrompus ; ne pas
affirmer que HEAD ou les ressources décodées sont déjà mis en cache.
contourner la validation complète du flux pour remplir le cache ou déduire HEAD d’ISIZE seul.

### Cache des représentations validées (#281)

Le serveur possède, via son `RequestHandler`, un LRU dont le budget par défaut de 8 MiB
compte clés compressées, contenu décodé et stockage des entrées. La clé est le contenu
compressé complet, indépendant du chemin et de la durée de vie du provider. Les lectures
restent nécessaires ; un changement des octets invalide implicitement la réutilisation.
GET et HEAD partagent une validation complète ; HEAD réutilise la longueur sans recopier
le corps. Le budget de sortie actif s'applique aussi aux hits. Une entrée trop grande
reste servie sans rétention ; les erreurs ne deviennent jamais des entrées valides.
Le contexte serveur sérialise les accès et validations ; aucune tâche de cache ne survit
au drainage. Les copies de handlers démarrent avec un cache vide. Les limites de rétention,
allocations temporaires et règles des providers sont précisées dans [HTTP_ASSETS](../HTTP_ASSETS.md).

## Sources et vérification

Expand Down
5 changes: 3 additions & 2 deletions docs/adr/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ verification evidence remain in [PROJECT_STATUS](../PROJECT_STATUS.md).
| [ADR-006](ADR-006-taches-structurees-et-arret.md) | Owning, cancelling and joining every task | Accepted | 2026-10-13 | 2.0 — 2026-10-18 |
| [ADR-007](ADR-007-frontends-explicites.md) | Explicit frontend selection and a shared lifecycle contract | Accepted | 2026-05-31 | 1.10 — 2026-10-20 |
| [ADR-008](ADR-008-contenu-de-confiance-et-origines.md) | Restricting bridge origins without promising a sandbox | Accepted | 2026-10-18 | 1.0 — 2026-10-18 |
| [ADR-009](ADR-009-modules-et-assets-reproductibles.md) | Serving modules locally and regenerating assets reproducibly | Accepted | 2023-03-16 | 2.3 — 2026-10-24 |
| [ADR-009](ADR-009-modules-et-assets-reproductibles.md) | Serving modules locally and regenerating assets reproducibly | Accepted | 2023-03-16 | 2.4 — 2026-10-25 |
| [ADR-010](ADR-010-composants-et-outils-optionnels.md) | Extending WebFront through optional components and development tools | Accepted | 2026-10-14 | 1.7 — 2026-10-23 |
| [ADR-011](ADR-011-diagnostics-optionnels.md) | Confining mddlog behind an optional diagnostics façade | Accepted | 2026-10-01 | 1.2 — 2026-10-02 |
| [ADR-012](ADR-012-preuves-et-tests.md) | Demonstrating contracts through deterministic tests and browser integration | Accepted | 2020-04-19 | 1.6 — 2026-10-19 |
Expand Down Expand Up @@ -108,7 +108,8 @@ Keep previous rows and update the current version in the index.
in both directions and identify exactly which part changes. A compatible clarification
may extend an existing ADR’s history without erasing its previous state.
- A future possibility mentioned here is not an accepted decision: general DOM abstractions,
tool isolation, response deadlines and a decoding cache require their own decisions.
tool isolation and response deadlines require their own decisions. The validated decoding
cache is specified in ADR-009 and `HTTP_ASSETS.md`.

## Chemins depuis la version 0.4

Expand Down
Loading
Loading