Skip to content

feat: source-generated regexes, Native AOT, faster detection and real-world test catalog - #104

Draft
BenjaminAbt wants to merge 30 commits into
mainfrom
feat/generated-regex-aot-performance
Draft

BenjaminAbt wants to merge 30 commits into
mainfrom
feat/generated-regex-aot-performance

Conversation

@BenjaminAbt

@BenjaminAbt BenjaminAbt commented Nov 22, 2026 •

Copy link
Copy Markdown
Member

Changes

  • Move browser and platform detection to ordered token rules that operate directly on the header. The public regular expressions are source-generated, so trimmed and Native AOT applications can use them on .NET 8–11.
  • Recognize Amazon Silk and add 33 crawler rules. Check browser token boundaries and give specific mobile-device names priority over generic matches.
  • Make crawler rule changes take effect on the next lookup in both built-in cache providers. ASP.NET Core callers can pass an HttpContext directly or use IHttpContextAccessor through dependency injection.

4.0 migration. HttpUserAgentStatics.Robots is now a read-only property. Recompile consumers that used the array field and use SetRobots(...) to customize detection.

How parsing works

  1. Check the first crawler rule. Parse takes a snapshot of the configured crawler rules, trims the header and checks the highest-priority rule first. With the defaults, a Googlebot match returns immediately, even when its contact URL contains a +.
  2. Prepare the header once. IIS logs can encode spaces as +. The detectors share a decoded view, so Screaming+Frog+SEO+Spider matches the rule for Screaming Frog SEO Spider. The result retains the trimmed input as received.
  3. Narrow down the rules. For ASCII headers up to 255 characters, one scan looks up three-character sequences in a shared table and selects possible crawler, platform, device and browser rules. Each detector confirms its candidates in priority order. Longer headers and headers containing non-ASCII characters use the full rule set. Custom crawler lists use their own matcher and configured order.
  4. Build the result. A matching crawler returns immediately. Otherwise the parser identifies the platform and mobile device, then reads the first matching browser and version. For example, a header containing both Chrome/158.0.0.0 and Edg/158.0.0.0 returns Edge 158.0.0.0 because Edge has higher priority. If no browser matches, the result is classified as unknown and includes any platform or device already identified.

Verification

  • 2,826 tests passed across .NET 8–11. All three packages reached 100% line, branch and method coverage.

Performance on .NET 11

Change in mean time per uncached header. The shared 64 KiB rule table reduced full-catalog time by 39.5% versus the previous PR.

Workload Current vs. main Previous PR vs. main
Catalog browsers −26.2% −6.8%
Catalog crawlers −78.3% −57.3%
Full catalog −57.6% −30.7%
API snapshot −49.2% −27.6%
Googlebot −19.0% −19.3%
OAI-AdsBot −83.5% −69.7%

Full benchmark results

Earlier measurements across .NET 8–11 and individual headers

The earlier Googlebot optimization reduced its time from 22.526 ns to 7.280 ns (−67.7%, 0 B allocated). The table shows the earlier side-by-side Stopwatch comparison against main.

| Runtime | Browsers | Crawlers | Full catalog | Chrome on Windows | Unknown client |
| --- | ---: | ---: | ---: | ---: |
| .NET 8 | −23% | −56% | −37% | −16% | +3% |
| .NET 9 | −21% | −66% | −43% | −16% | −7% |
| .NET 10 | −20% | −61% | −39% | −9% | −8% |
| .NET 11 | −21% | −57% | −39% | −22% | −7% |

Earlier individual .NET 11 BenchmarkDotNet measurements: Chrome on Windows −24% · Firefox on Linux −6% · Chrome on Android −26% · Safari on iPhone −30% · Applebot −14% · Googlebot −14% · Unknown client −3%.

Closes #3, closes #5, closes #36.

…-world test catalog

- Replace the 121 runtime-compiled regexes of the public API with [GeneratedRegex],
  created on first access; the parser keeps its rules in HttpUserAgentRules
- Make all packages trimming and Native AOT compatible (IsAotCompatible) and
  add a Native AOT smoke test with a CI job for net8.0 to net11.0
- Speed up robot and mobile detection with grouped SearchValues, robot anchors
  and a snapshot check for replaced HttpUserAgentStatics.Robots entries
- Add Samsung Internet, Yandex Browser, UC Browser and 27 search engine, SEO and
  AI crawlers; restore the declared mobile device priority
- Add a real-world user agent catalog for tests and benchmarks, enforce 100%
  line, branch and method coverage
- Fix the core cache.size meter, keep Roslyn runtime assets out of tests and apps
- Update README and package readmes

Closes #3, closes #5, closes #36
Run the validation when a draft is marked as ready for review.
…o Get(HttpContext)

- Add IHttpUserAgentParserContextAccessor (extends IHttpUserAgentParserAccessor) with
  Get() and GetHttpContextUserAgent() for the current request
- Add HttpUserAgentParserContextAccessor and AddHttpUserAgentParserContextAccessor(),
  which registers IHttpContextAccessor and, unless already registered, IHttpUserAgentParserAccessor
- Cover both accessors in tests and in the Native AOT smoke test, document both options
- Browser version: read the version from the product token of the
  browser only (up to the next space, tab, ';', '(', ')' or ','), so an
  empty version no longer takes the version of the next product
  ("SamsungBrowser/ Chrome/131.0.0.0" is Chrome 131.0.0.0).
- Meters (all packages): create the instruments under a lock and
  publish them as one object, so no registration returns before its
  instruments exist. The last registered meter is used, the same meter
  again is a no-op, calls without a meter share one default meter.
- Robots: replace the pinned raw-reference snapshot with a managed key
  reference comparison; replaced values are honored on the fast path.
- .NET 8: use the robot anchor prefilter on all target frameworks.
- Native AOT smoke test: verify meter measurements (MeterListener) and
  EventCounters (EventListener, EventSourceSupport) of all packages.
- Docs: catalog counts (48 crawlers, 96 user agents), benchmark results
  per runtime, allocation note for untrimmed input, regex culture and
  Compiled semantics, meter registration, unbounded ConcurrentDictionary
  cache, precise Native AOT statement.
- Browser version: if a token has no version, check the next occurrence
  of the same token before the next rule ("Chrome/ Chrome/131.0" is
  Chrome 131.0). A separate version token (Version/, MSIE, rv:) only
  counts at the start of a token ("Opera/9.80 VendorVersion/120.0" is
  Opera 9.80).
- Meters: create the instruments once per meter (ConditionalWeakTable),
  so a meter registered again reuses them. The cache.size gauges report
  only while their meter is in use; a replaced meter no longer reports
  the cache size, and switching back no longer reports it twice.
- MemoryCache: use the user agent string as cache key. The reused
  thread-static CacheKey was stored as the key of new entries and
  changed by the next call on that thread, so entries were lost between
  threads. Keys are ordinal now (Equals ignored case, the hash did not).
- Browser version: later occurrences of a browser token only count at
  the start of a token ("ChromeHelper/1 MyChrome/2.0 Firefox/126.0" is
  Firefox 126.0); the first occurrence may still continue a word
  (HeadlessChrome). A token starts at the beginning or after a space,
  tab, ';', '(', ')' or ',' - the delimiters that end a product token -
  so "Vendor-Version/120.0" is no version token either.
- Version search: continue behind the product token examined before,
  so the time grows linearly with the length of the user agent
  (1,000,000 characters of "Chrome/a": 1.7 s before, 2 ms now).
- Cache size: providers register themselves weakly when created; the
  cache.size gauges and cache-size counters sum the live caches when
  observed. Entries cached before telemetry was enabled are counted,
  several core providers no longer overwrite each other, and nothing is
  counted on the parse path anymore.
- Meters: meters the packages create (default, prefix variants) are
  created once per name and disposed when replaced; caller meters are
  never disposed. Repeated prefix registrations keep one meter.
- ConcurrentDictionary cache: ordinal keys like the MemoryCache.
Parser
- Browser and version tokens only count at the start of a token (at
  the beginning or after a space, tab, '+', ';', '(', ')' or ','), for
  every occurrence: "Knowledge/1.0" is no Edge, "MyChrome/2.0" no
  Chrome. Headless Chrome and ELinks get rules of their own.
- '+' separates tokens like a space (URL-encoded logs such as IIS):
  Safari, Opera and Internet Explorer versions are read again.
- Rules with a version token accept "Token 1.2" (Opera 9.50, MSIE 6.0,
  several spaces, '+'); "MSIE MSIE 7.0" and "MSIE  6.0" work again.
- Platforms: "cros " instead of "cros" (Microsoft is no ChromeOS),
  "windows phone" before "android". Robot key "YouBot/" (ShowyouBot).
- Fast path: the inlined IndexOf stays in front of the token-start
  check, so rules that do not match cost what they did.

Telemetry
- Own meters are created once per name and reused, not disposed when
  replaced: no measurement is lost during a switch.
- The core and the MemoryCache package reject a shared meter (same
  instrument names, the values mixed silently).
- Meter prefixes: ASCII letters or digits followed by '.'.

Providers, DI, ASP.NET Core
- MemoryCache entries get all CacheEntryOptions (absolute expiration,
  priority, tokens, eviction callbacks, size).
- HttpUserAgentParserMemoryCachedProvider implements IDisposable and
  disposes its MemoryCache.
- Accessor registrations use TryAdd (idempotent in any order); an
  empty or white-space User-Agent header returns null.
- Docs: readme snippets that did not compile, regex creation, token
  rules, allocation statement, URL-encoded user agents.
…ters

Telemetry
- A meter that the core or the MemoryCache package has used stays
  reserved for it while the meter lives: both create cache.hit,
  cache.miss and cache.size, and a meter keeps its instruments, so a
  handover after a switch mixed the series. The reservation is made
  before the instruments are created, which also covers a registration
  from a listener callback and a listener that throws.
- If a listener throws while instruments are published, the meter in
  use stays active and a new own meter is disposed.
- A replaced own meter (default or prefix) is disposed again, so
  changing prefixes keeps one meter; measurements racing with that
  switch are best effort. Meters of the caller are never disposed.

Parser
- The version tokens of Opera ("Version/") and Internet Explorer
  ("rv:") only count after the browser token.
- ChromeOS: "cros+" for URL-encoded logs next to "cros ".
- Robot key " YouBot/" so "ShowyouBot/1.0" is no YouBot.
Telemetry (one registration implementation for all packages)
- .NET calls MeterListener callbacks while instruments are created
  and while a meter is disposed. Both happen outside the registration
  lock now; the lock only switches the state. Mutual registrations of
  the core and MemoryCache packages from listener callbacks no longer
  deadlock, and a nested registration of another own meter leaves no
  meter behind.
- Each meter gets one instrument container before any instrument is
  created. After a listener threw, a later registration only adds the
  missing instruments: cache.size exists at most once per meter and
  reports while its meter is in use.
- Passing the own meter in use keeps it (no disposal).

Robots
- "YouBot/" matches again at any position; ShowyouBot has an entry of
  its own before it.
- HttpUserAgentStatics.Robots is a read-only list now; SetRobots
  replaces the robots the parser detects (atomically, for all
  following parses), DefaultRobots holds the defaults. Writing into
  the array is no longer possible.
- The parser works on an immutable robot set (list, anchor prefilter,
  grouped matcher) and reads it once per parse. The check that the
  keys of the public array were unchanged (95 reference comparisons,
  17 ns on .NET 11 for every user agent) and the slow paths for
  replaced keys are gone.
- Benchmarks: BenchmarkDotNet 0.16.0-preview.2 runs every case in its
  own process on .NET 11 as well, so --inProcess is no longer needed;
  in one process Dynamic PGO adapted the code to the cases measured
  before (Googlebot 9 ns alone, 20 ns after the other user agents).
  The library comparison uses the ShortRun job out of process, too.
feat(tests): add EventCounterTestListener and MeterTestListener
refactor(tests): update HttpUserAgentParserMemoryCachedProvider tests
fix(tests): improve assertions in HttpUserAgentInformationExtensionsTests
chore(tests): clean up UserAgentCatalogTests and related tests
@BenjaminAbt
BenjaminAbt requested a review from gfoidl November 23, 2026 22:15
@BenjaminAbt BenjaminAbt self-assigned this Nov 23, 2026

@gfoidl gfoidl left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Well...I review the product code but not at 100% detail, and just skimmed over the tests.

The points should be addressed for the whole PR, even when I didn't comment all places.

The packages contained the 512x512 logo (251 KB), while the DLLs are about
20 KB each. NuGet shows the icon at 128x128, so the packages now contain a
128x128 icon (30 KB). The readme keeps the 512x512 logo. The myCSharp.de
NuGet logo is no longer used and is removed.
NuGet splits tags at spaces, so "User Agent" became the tags "User" and
"Agent" on NuGet.org. The tags are now single words that describe what the
packages detect, for example user-agent, browser-detection and
bot-detection. useragent is kept. Console, ASP and Desktop are removed,
because they do not describe the packages.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Offer alternative to IHttpContextAccessor Revise usage of dictionaries in HttpUserAgentStatics Re-evaluate the usage of RegexOptions.Compiled

2 participants