Updating your price table doesn't update the price sentence already sitting in your vector index.
You refresh the listings, ask your assistant for a walnut sofa, and get a confident answer quoting an older discount. The ingestion job finished. The embarrassing sentence survived.
Lab note 208: can we keep descriptive furniture search without turning every price change into an embedding migration?
The catch: a captured offer is an observation, not a guarantee of present availability. Moving price out of the embedding text also won't help if a copied description still says “sale ends tonight.”
Give discovery and offer facts separate jobs
Embed descriptive product content, then join retrieved product IDs to the latest captured offer before composing an answer.
The vector index finds furniture that sounds right. The offer store supplies price and stock evidence with its observation time attached.
That boundary belongs in the corpus, before either kind of data reaches the answer composer:
captured listing ├── descriptive attributes → content hash → embedding └── offer + scrapedAt → snapshot history ↑ retrieved productId ───────────────────┘ answer context A price update can append an observation without changing the embedding input. A material or style change can change that input and trigger replacement.
Replacement matters. Inserting a revised vector while leaving its previous version searchable gives the stale document a second career.
Capture furniture without selecting only bargains
We use our furniture Actor as the worked example because its records carry descriptive attributes, commerce fields, identity, and a capture timestamp.
For a reusable discovery corpus, we'd leave onSaleOnly unset. Otherwise, admission depends on a temporary promotion, which is an awkward foundation for learning what furniture looks like.
This Example input requests descriptive enrichment without selecting for sale status:
import hashlib import json import math import os import re from datetime import datetime, timedelta, timezone from urllib.parse import urlsplit, urlunsplit from apify_client import ApifyClient import tiktoken run_input = { "mode": "collection", "collectionHandle": "sofas", "includeDetails": True, "maxItems": 50, } client = ApifyClient(os.environ["APIFY_TOKEN"]) run = client.actor( "vexaloom-labs/chairish-vintage-furniture-dimension-and-style" ).call(run_input=run_input) if run["status"] != "SUCCEEDED": raise RuntimeError(f"Capture did not succeed: {run['status']}") items = client.dataset(run["defaultDatasetId"]).list_items().items includeDetails opens each emitted product page to add attributes including full materials and style tags. It adds an extra request per emitted listing.
The cap makes this a bounded capture, not a complete inventory. An absent listing therefore isn't a sold flag: filtering, incomplete coverage, and removal can all leave a gap.
Keep that distinction when reconciling your index. A partial capture shouldn't quietly become a command to delete every product it didn't encounter.
Use the listing as the retrieval unit
For this corpus, we embed or label a product listing's descriptive document. Splitting every attribute into a separate chunk would scatter the relationship between a material, a style, and the furniture they describe.
There are no conversation parents to preserve here. The useful relationship is product identity to descriptive evidence to captured observations, with source links alongside it.
| Destination | Selected content | Purpose |
|---|---|---|
products.jsonl | Category, taxonomy, materials, styles, dimensions | Semantic discovery |
offers.jsonl | Price, discounts, stock, validity, capture time | Offer history and answer hydration |
| Separately governed raw layer | Original title and description | Review before admitting free text |
The exporter below creates the JSONL files. It doesn't retain the raw layer.
We exclude both title and description from the default embedding text because either can carry promotional claims. That costs useful language, especially when unusual construction details appear only in prose. We'd rather make that loss visible than quietly index an expired deal.
You can later admit reviewed descriptive passages under a separate policy. Removing currency symbols alone isn't enough: “reduced for immediate clearance” still makes a commerce claim.
The exported keys such as text, contentHash, and tokenCount belong to our corpus transformation. They aren't additional Actor fields.
Hash the text the model actually receives
A content hash should answer a narrow question: did the embedding input change?
Normalize whitespace, and normalize order only where order doesn't carry meaning. Materials and style tags can be treated as sets here; a taxonomy breadcrumb keeps its sequence.
The budget below admits complete attribute lines. It won't cut a measurement halfway through a token sequence.
ENCODER = tiktoken.get_encoding("cl100k_base") TOKEN_BUDGET = 256 POLICY = "attributes-v1" ATTRIBUTES = ( "category", "taxonomyPath", "material", "materials", "styleTags", "widthIn", "depthIn", "heightIn", ) PRICING = ( "price", "currency", "priceUnit", "priceValidUntil", "originalPrice", "discountAmount", "discountPercentage", "onSale", ) STOCK = ("productStatus", "quantity", "isPurchasable", "onHold") COMMERCE = re.compile( r"[$€£%]|\b(?:usd|sale|discount|shipping|available|availability|" r"stock|sold|purchase|price|dollars?)\b", re.IGNORECASE, ) def canonical(value): return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":"), allow_nan=False) def aware_time(value): try: parsed = datetime.fromisoformat(value.strip().replace("Z", "+00:00")) return parsed.astimezone(timezone.utc) if parsed.tzinfo else None except (AttributeError, TypeError, ValueError): return None def source_link(value): if not isinstance(value, str): return None try: parts = urlsplit(value) if parts.scheme in ("http", "https") and parts.hostname: return urlunsplit((parts.scheme, parts.hostname, parts.path, "", "")) except ValueError: pass return None def clean_attribute(value): if isinstance(value, str): text = " ".join(value.split()) return text if text and not COMMERCE.search(text) else None if isinstance(value, (int, float)) and not isinstance(value, bool): return value if math.isfinite(value) else None if isinstance(value, list): return [v for part in value if (v := clean_attribute(part)) is not None] or None return None def descriptive_document(row): lines, selected, omitted = [], [], [] for field in ATTRIBUTES: value = clean_attribute(row.get(field)) if value is None: continue if field in ("materials", "styleTags") and isinstance(value, list): unique = {canonical(part): part for part in value} value = [unique[key] for key in sorted(unique)] lines.append((field, f"{field}: {canonical(value)}")) for field, line in lines: candidate = "\n".join(selected + [line]) if len(ENCODER.encode(candidate, disallowed_special=())) <= TOKEN_BUDGET: selected.append(line) else: omitted.append(field) text = "\n".join(selected) fingerprint = canonical({"policy": POLICY, "text": text}) return { "productId": row["productId"], "text": text, "policy": POLICY, "contentHash": hashlib.sha256(fingerprint.encode()).hexdigest(), "tokenCount": len(ENCODER.encode(text, disallowed_special=())), "tokensBeforeBudget": len(ENCODER.encode( "\n".join(line for _, line in lines), disallowed_special=())), "omittedFields": omitted, } The commerce expression is a conservative screen, not a complete detector. It can reject useful attribute text and miss indirect promotional language. Keeping free-form descriptions outside this path does most of the boundary work.
Field order also becomes a ranking decision: earlier attributes get first access to the budget. Inspect omittedFields before deciding that a corpus supports dimension-sensitive retrieval.
For exact fit questions, use structured dimensions as filters or checks after retrieval. A vector match isn't evidence that a sofa fits through a doorway.
Compare contentHash with your embedding manifest before scheduling work. Provenance can change without requiring a new embedding, so update source metadata separately.
Different listings can share descriptive text. Reuse embedding computation if useful, but retain each product identity for offer joins.
Deduplicate observations without deleting history
Deduplication has different meanings on either side of the split.
For descriptive documents, retain the latest unambiguous version per product. For offers, collapse exact exported duplicates while preserving observations captured at different times, even when their prices agree.
Missing timestamps don't become “now.” That would promote undated evidence above records with a real observation time.
This builder retains source lineage, audits rejected rows, and quarantines conflicting descriptive versions tied at the latest capture time:
def build_corpus(rows): observations, candidates, lineage = {}, {}, {} audit = {"rejectedRows": 0, "descriptiveConflicts": 0} for row in rows: product_id = row.get("productId") captured = aware_time(row.get("scrapedAt")) if not isinstance(product_id, str) or not product_id.strip() or captured is None: audit["rejectedRows"] += 1 continue sources = sorted({ link for field in ("productUrl", "sourceUrl", "sourceListUrl") if (link := source_link(row.get(field))) is not None }) lineage.setdefault(product_id, set()).update(sources) snapshot = { "productId": product_id, "scrapedAt": captured.isoformat(), "sources": sources, "offer": {field: row[field] for field in PRICING + STOCK if field in row}, } if "recordType" in row: snapshot["recordType"] = row["recordType"] observations[canonical(snapshot)] = snapshot candidates.setdefault(product_id, []).append( (captured, descriptive_document(row))) documents = [] for product_id, versions in sorted(candidates.items()): newest = max(captured for captured, _ in versions) latest = {doc["contentHash"]: doc for captured, doc in versions if captured == newest} if len(latest) != 1: audit["descriptiveConflicts"] += 1 continue document = next(iter(latest.values())) if document["text"]: documents.append(document | {"sources": sorted(lineage[product_id])}) return documents, [observations[key] for key in sorted(observations)], audit documents, snapshots, corpus_audit = build_corpus(items) for filename, records in ( ("products.jsonl", documents), ("offers.jsonl", snapshots), ): with open(filename, "w", encoding="utf-8") as handle: for record in records: handle.write(canonical(record) + "\n") These files represent the current export batch. In persistent storage, merge offer batches using the canonical snapshot as an idempotency key; overwriting the file across captures would erase the history this design needs.
A repeated observation can matter even without a changed price. It records that the same state was captured again, rather than implying uninterrupted knowledge between captures.
The source sanitizer removes URL credentials, query strings, and fragments. It retains paths, so searches distinguished only by query parameters collapse to the same source link. Keep query-level provenance separately under an explicit access policy if your evaluation needs it.
For descriptive conflicts, quarantine the affected product in your index reconciliation. Otherwise, skipping its new export can accidentally leave an older vector serving indefinitely.
Join offer evidence before composing the answer
A retrieval hit should deliver descriptive evidence and separately labeled offer facts. The composer shouldn't have to infer which passage has authority.
The join chooses the latest captured observation without filling missing fields from older snapshots. A conflicting tie supplies no offer facts.
For priceValidUntil, the policy interprets only timezone-aware ISO timestamps. Date-only values and unsupported formats remain unknown; an absent expiry doesn't imply indefinite validity.
This code withholds pricing when a parsed validity timestamp has elapsed:
def hydrate(document, history, now): context = { "productId": document["productId"], "descriptiveEvidence": document["text"], "sources": document["sources"], "offerState": "no_captured_offer", "instruction": ( "Use descriptive evidence for matching. Attribute offer facts to " "their observation time; do not assert present availability." ), } matching = [s for s in history if s["productId"] == document["productId"] and aware_time(s["scrapedAt"]) is not None] if not matching: return context newest = max(aware_time(s["scrapedAt"]) for s in matching) tied = [s for s in matching if aware_time(s["scrapedAt"]) == newest] offers = {canonical(s["offer"]): s["offer"] for s in tied} if len(offers) != 1: return context | {"offerState": "conflicting_latest_observations"} offer = next(iter(offers.values())) expiry_raw = offer.get("priceValidUntil") expiry = aware_time(expiry_raw) validity = ( "unspecified" if expiry_raw is None else "unparsed_or_timezone_unspecified" if expiry is None else "elapsed" if expiry <= now else "not_elapsed_at_answer_time" ) return context | { "offerState": "captured_observation", "observedAt": newest.isoformat(), "priceValidity": validity, "priceValidUntilRaw": expiry_raw, "observedFacts": { field: value for field, value in offer.items() if validity != "elapsed" or field not in PRICING }, "offerSources": sorted({source for s in tied for source in s["sources"]}), } “Not elapsed” describes the parsed expiry boundary. It doesn't certify that the listing remains purchasable.
For larger histories, maintain an index keyed by product identity rather than scanning every snapshot during each answer. Preserve the tie handling and missing-value policy when changing storage.
The Chairish Vintage Furniture Dimension & Style Filter Scraper supplies the listing fields for this example. Your application owns the corpus boundary and the rules for answering from it.
The split still needs privacy and leakage checks
An answer can still fail if the composer ignores observation labels or the capture is old. A purchase action needs a fresh check appropriate to the application; snapshot hydration doesn't reserve furniture.
Privacy needs restraint before export. This code omits seller identity, locality, images, and raw descriptions, but product IDs and retained links can reconnect records to public listings. The corpus isn't anonymous.
Keep that distinction when sharing evaluation data. Removing a seller name while publishing a reversible listing URL doesn't meaningfully sever the connection.
Evaluation can leak through identity, too. Randomly splitting snapshots lets the same product appear in training and test with nearly identical descriptive evidence.
Group descriptive tasks by product identity, and consider grouping identical descriptive hashes across splits when the target is style or category. Retaining separate IDs for commerce doesn't make duplicate text independent evaluation evidence.
For temporal offer tasks, split by capture time and prevent later observations from entering earlier answer contexts. The answer-time join needs an evaluation cutoff, rather than unrestricted access to the newest snapshot.
The verdict is plain: separating offers removes a needless dependency between commerce refreshes and embedding updates. Descriptive changes still require index maintenance, and captured facts still need their timestamps.
Reproduce the boundary before adding retrieval
Use synthetic observations to inspect the join without involving a vector store.
This Example creates an older discount and a newer offer with elapsed price validity, then builds answer context without printing it:
example_now = datetime.now(timezone.utc) example_base = { "productId": "Example-product", "category": "sofas", "materials": ["walnut"], } example_rows = Source:https://dev.to/vexaloom-labs/chairish-vintage-furniture-rag-in-python-separate-offers-from-embeddings-4a3g Related posts
Building an All-Day Apple Watch Audio Recorder: 15-Min Chunking, Always-On UI & Sleeve-Stop Protection

Claude Code Deleted My Files. Here's How I Stop It Now
Where to host a Streamlit app in 2026 so it does not sleep: Community Cloud vs Hugging Face Spaces vs Render vs Modal
