Sub topic 15
Automated checks for drift and staleness
This chapter assumes you know basic HTML, can read JSON-LD, and have a single source of truth for product facts (see the earlier chapters on structured data, sitemaps, and caching). Here you build automated checks that catch facts which have drifted apart or gone stale. You run them on a schedule, so people don't have to find the problems by hand.
Why manual review is not enough
Review schedules and owners catch slow decay, such as an outdated guide. They do not catch fast drift. A price changed in the database at 09:00 can still appear in an old version of the page at 09:30, in the JSON-LD at 10:00, and in the feed until tomorrow. No human reviewer sees all of that.
Automated checks answer one question repeatedly: do all the places that state a fact agree with the source of truth, and is the fact recent enough?
Two kinds of problems
The checks fall into two groups. Keep them apart, because they have different causes and different fixes.
- Drift means two places disagree. Examples: the visible price says 89.00 EUR and the JSON-LD says 79.00 EUR. The sitemap says a page changed on 2026-11-20 but the page's
dateModifiedsays 2026-03-02. - Staleness means a fact is too old for its type. Examples: an article on shipping rules last reviewed 20 months ago, or a
priceValidUntildate that has already passed.
| Check | Problem type | Compares | Typical cause |
|---|---|---|---|
| Visible price vs JSON-LD price | Drift | Page text and markup | Markup hard-coded in a template |
| Page vs source record | Drift | Rendered HTML and database | Cache not invalidated |
| Feed vs page | Drift | Merchant feed and page | Feed refreshed less often than the site |
| `dateModified` vs sitemap `lastmod` | Drift | Two date signals | Sitemap generated from file times |
| `priceValidUntil` in the past | Staleness | Markup and today's date | Offer date never renewed |
| Review date older than limit | Staleness | Page metadata and policy | No owner, no schedule |
| Discontinued product still returns 200 with InStock | Drift | Status and markup | Retirement not wired to the page |
The architecture of an audit
An audit job has four steps. It runs on a schedule, for example every hour for prices and once a day for articles.
- Pick the URLs to check. Take them from the sitemap, or from a list of high-value pages such as best sellers.
- Fetch each page the way a crawler does, over HTTP, so that you see what caches and CDNs really serve.
- Extract the facts from the visible text, the JSON-LD, and the headers.
- Compare them with the source of truth and report differences.
Fetching over HTTP matters. If you only inspect your templates or database, you miss stale CDN copies, which is the most common cause of drift after a change.
A working price consistency check
The script below fetches a page, reads the Product JSON-LD, finds the visible price in an element marked with data-price, and compares both with the source record. It uses only the Python standard library.
For this to work, your template needs a marker on the visible price, for example <span data-price>89.00</span>. Adding such markers is a small change, and it makes both the audit and any later redesign safer.
import json
import re
from decimal import Decimal, InvalidOperation
from html.parser import HTMLParser
from urllib.request import Request, urlopen
class FactExtractor(HTMLParser):
"""Collects JSON-LD blocks and the text of elements with data-price."""
def __init__(self):
super().__init__()
self.jsonld = []
self.prices = []
self._in_jsonld = False
self._in_price = False
self._buffer = ""
def handle_starttag(self, tag, attrs):
attrs = dict(attrs)
if tag == "script" and attrs.get("type") == "application/ld+json":
self._in_jsonld = True
self._buffer = ""
elif "data-price" in attrs:
self._in_price = True
self._buffer = ""
def handle_data(self, data):
if self._in_jsonld or self._in_price:
self._buffer += data
def handle_endtag(self, tag):
if self._in_jsonld and tag == "script":
try:
self.jsonld.append(json.loads(self._buffer))
except json.JSONDecodeError:
self.jsonld.append(None)
self._in_jsonld = False
elif self._in_price and tag in ("span", "div", "p", "strong"):
self.prices.append(self._buffer.strip())
self._in_price = False
def to_decimal(text):
cleaned = re.sub(r"[^0-9.,-]", "", text).replace(",", ".")
try:
return Decimal(cleaned)
except InvalidOperation:
return None
def fetch(url):
req = Request(url, headers={"User-Agent": "fact-audit/1.0"})
with urlopen(req, timeout=10) as resp:
return resp.status, resp.read().decode("utf-8", errors="replace")
def audit_product(url, source):
"""Return a list of problems for one product page."""
problems = []
status, html = fetch(url)
if status != 200:
return [f"{url}: unexpected status {status}"]
parser = FactExtractor()
parser.feed(html)
expected = Decimal(source["price"])
visible = [to_decimal(p) for p in parser.prices]
if not visible:
problems.append("no visible price found (missing data-price marker?)")
elif any(v != expected for v in visible):
problems.append(f"visible price {visible} != source {expected}")
products = [b for b in parser.jsonld if isinstance(b, dict) and b.get("@type") == "Product"]
if not products:
problems.append("no Product JSON-LD found")
else:
offer = products[0].get("offers", {})
if to_decimal(str(offer.get("price", ""))) != expected:
problems.append(f"JSON-LD price {offer.get('price')} != source {expected}")
if offer.get("priceCurrency") != source["currency"]:
problems.append(f"JSON-LD currency {offer.get('priceCurrency')} != source {source['currency']}")
wanted = "InStock" if source["in_stock"] else "OutOfStock"
if not str(offer.get("availability", "")).endswith(wanted):
problems.append(f"JSON-LD availability {offer.get('availability')} != {wanted}")
return [f"{url}: {p}" for p in problems]
if __name__ == "__main__":
source_record = {"price": "89.00", "currency": "EUR", "in_stock": True}
for line in audit_product("https://example.com/p/trail-runner-2", source_record):
print(line)In a real job, source_record comes from your database or product API, one record per URL. Parsing prices as Decimal avoids floating point errors such as 89.0 versus 88.99999.
Staleness checks for dates
Drift checks need a source to compare with. Staleness checks need a policy: a maximum age per fact type. Use the decay rates you identified earlier.
| Content type | Example limit | Check |
|---|---|---|
| Price and stock | 1 hour | Page and feed match the source |
| `priceValidUntil` | Must be in the future | Date parse and compare |
| Policies (shipping, returns) | 90 days since review | Review date field |
| Guides and articles | 12 months since `dateModified` | Date compare |
| Evergreen reference | 24 months since review | Date compare |
The following script reads a sitemap and flags pages whose lastmod is older than a limit, and pages whose lastmod disagrees with the page's own dateModified.
import json
import re
import xml.etree.ElementTree as ET
from datetime import date, datetime, timedelta
from urllib.request import urlopen
NS = {"sm": "http://www.sitemaps.org/schemas/sitemap/0.9"}
MAX_AGE = timedelta(days=365)
LD_RE = re.compile(r'<script type="application/ld\+json">(.*?)</script>', re.S)
def sitemap_entries(sitemap_url):
with urlopen(sitemap_url, timeout=10) as resp:
tree = ET.fromstring(resp.read())
for url in tree.findall("sm:url", NS):
loc = url.findtext("sm:loc", namespaces=NS)
lastmod = url.findtext("sm:lastmod", namespaces=NS)
yield loc, lastmod
def page_date_modified(page_url):
with urlopen(page_url, timeout=10) as resp:
html = resp.read().decode("utf-8", errors="replace")
for block in LD_RE.findall(html):
try:
data = json.loads(block)
except json.JSONDecodeError:
continue
if isinstance(data, dict) and "dateModified" in data:
return datetime.fromisoformat(data["dateModified"]).date()
return None
def audit_dates(sitemap_url, today=None):
today = today or date.today()
for loc, lastmod in sitemap_entries(sitemap_url):
if not lastmod:
yield f"{loc}: no lastmod in sitemap"
continue
sitemap_date = datetime.fromisoformat(lastmod).date()
if today - sitemap_date > MAX_AGE:
yield f"{loc}: lastmod {sitemap_date} older than {MAX_AGE.days} days"
page_date = page_date_modified(loc)
if page_date and page_date != sitemap_date:
yield f"{loc}: sitemap {sitemap_date} != dateModified {page_date}"
if __name__ == "__main__":
for problem in audit_dates("https://example.com/sitemap.xml"):
print(problem)Note that an old date is not always a defect. A page that has not changed because nothing needed changing is correct. Treat the age limit as a prompt for an owner to review, not as a reason to edit the date.
Checking cache behavior
After a change, a cache can serve the old version for up to max-age plus the stale-while-revalidate window. With the example headers from the caching chapter (max-age=300, stale-while-revalidate=60), that is at most about six minutes.
An audit can verify this with a post-change test:
- Change a test product's price in the source.
- Trigger your normal invalidation.
- Poll the page every 30 seconds.
- Fail the test if the new price is not visible within your service target.
Run this test after deployments that touch caching or CDN configuration, not only on a schedule. Also check that Last-Modified and ETag change when content changes. A validator that never changes makes caches believe the page is unchanged.
Choosing thresholds and avoiding alert fatigue
An audit that reports 400 warnings daily will be ignored. Design the alerts deliberately.
- Severity. A price mismatch between page and markup is high severity: users and answer systems may quote the wrong number. A sitemap date that is a day behind is low.
- Grace periods. Prices can legitimately differ for a few minutes while a cache refreshes. Alert only when a mismatch persists across two consecutive runs.
- Grouping. If a template change breaks 2,000 pages, send one alert naming the template, not 2,000 alerts.
- Ownership. Each alert goes to the owner of that fact type. An alert without an owner is not acted on.
- Allow lists. Record intentional exceptions, such as a page showing a sale price with a struck-through original price, so the audit does not report them every day.
Common errors in audit scripts
- Comparing text, not numbers.
"89.00"and"89"differ as strings. Parse toDecimalfirst and agree on currency. - Checking only the raw HTML. If JavaScript renders the price, a plain HTTP fetch sees the template placeholder. Either server-render the facts that matter for search, or audit with a headless browser as well.
- Auditing only your own origin. A CDN or a regional edge can serve different content. Fetch through the public hostname, and from more than one location if you use several regions.
- Ignoring variants. One product page may list several SKUs with different prices. Compare each variant's offer, not only the first one.
- No test for the audit itself. Keep a deliberately broken test page and confirm that the audit reports it. Otherwise a silent parsing failure looks like a clean result.
- Reporting only failures. Also record the number of pages checked. A drop from 5,000 to 12 checked pages is itself a failure.
Putting the audit in the change workflow
Run lighter versions of the same checks earlier in the process.
- Pre-publish. In the content system, block publishing when required fields (price, currency, availability, review date) are missing or invalid.
- Post-deploy. After each release, run the drift check on a sample of pages across every template.
- Scheduled. Run the full audit hourly or daily, depending on the fact type.
- Periodic review. Once a quarter, read the audit history. Recurring failures in one place point to a missing single source of truth or a broken invalidation step, which you fix once instead of repeatedly.
Exercise
Your audit shows that the visible price and the JSON-LD price both say 79.00 EUR, but the source database says 89.00 EUR, and this has lasted three hours. Is this drift between page and markup, a cache problem, or something else? Name the first thing you check.
Show answer
The page and markup agree with each other, so this is not markup drift. They disagree with the source, which points to a stale cached copy or a failed render or invalidation step. First check the response headers (Cache-Control, Age, ETag, Last-Modified) for the page, and compare what the origin returns with what the CDN returns. If the origin also shows 79.00, the template reads from somewhere other than the source of truth.
Exercise
A sitemap check reports that 300 articles have a lastmod of today, though no editor changed them. What is the likely cause, and what should the check compare to confirm it?
Show answer
The sitemap generator probably uses file or build timestamps, so every deployment makes all pages look modified. Compare each article's sitemap lastmod with its dateModified in the JSON-LD or its content revision history. If those are old and only the sitemap is new, change the generator to read the last meaningful content change from the source record.