HelloWork Jobs in Python: Replace Old Chunks When an Offer Changes A developer working with HelloWork France job listings built an incremental RAG ingestion pipeline that replaces an offer's entire chunk set whenever a change feed reports it as new, updated, or reappeared, rather than appending new chunks alongside stale ones. The approach keys each offer on a source-scoped offerId, keeps a content hash per job under a reusable stateKey, and separates an event archive from the current-state corpus so retrieval serves only the latest requirements. The writeup notes that a change feed is not a complete inventory, so silence in the feed cannot be treated as a signal to delete jobs. Appending a changed job to your index can leave your assistant answering from incompatible requirements. Yesterday's chunk asks for one skill set. Today's chunk asks for another. Both look perfectly citable. Lab note 194: can we turn a daily change feed into a searchable corpus that remembers the current offer without serving its superseded requirements? The catch comes first: a change feed isn't a complete inventory of live jobs. Silence doesn't tell your index to delete anything. For this worked example, the Actor keeps a content hash per job under your stateKey . Incremental mode emits NEW , UPDATED , and REAPPEARED records while skipping unchanged jobs. Those labels describe incoming events. They shouldn't become independent document identities. In a current-state RAG corpus, every accepted offer event should replace that offer's entire chunk set. The parent identity comes from offerId , which identifies the underlying HelloWork offer. Scope it to the source so another feed can't collide with it. The storage boundary looks like this: Incremental event ├── event archive: retain the observation └── current offer: replace the complete chunk family | └── retrieval We want the archive to remember revisions. We want retrieval to stop arguing with itself. Reuse the same stateKey across scheduled runs, and keep the collection settings stable. Changing the search deserves an explicit decision about whether it belongs in the same corpus. Example collection settings for the daily feed: python import hashlib import json import os import re import sqlite3 import textwrap import unicodedata from apify client import ApifyClient run input = { "mode": "search", "searchQueries": "developpeur python" , "city": "Lyon", "includeDetails": True, "incrementalMode": True, "stateKey": "lyon-python-current", "maxItems": 100, } client = ApifyClient os.environ "APIFY TOKEN" run = client.actor "vexaloom-labs/hellowork-france-job-listings-and-salary-filter" .call run input=run input if run "status" = "SUCCEEDED": raise RuntimeError f"Collection ended with {run 'status' }" items = client.dataset run "defaultDatasetId" .list items .items incoming jsonl = "\n".join json.dumps item, ensure ascii=False, sort keys=True for item in items Keep the dataset ID with your ingestion checkpoint. If collection finishes but your consumer fails, retry ingestion from that dataset. Starting another incremental run isn't a substitute for recovering the previous batch. The producer's state and your index's state have separate commit points. That little gap is where missing updates get comfortable. Our labeling unit is the offer. Our retrieval unit is a chunk of its description, linked back to that offer. Keep url and observation timestamps beside the text. Keep titles, companies, and locations available for display and filtering. Don't mix ingestion timestamps into the passage you embed. The table describes our consumer's choices, rather than additional source fields: | Material | Corpus treatment | Reason | |---|---|---| | descriptionText | Clean, then chunk | Requirements are the searchable evidence | | offerId | Build the source-scoped parent key | Revisions must meet at the same parent | | url , observation timestamps | Retain as metadata | Support citations and freshness inspection | | searchQuery | Retain as observation provenance | A query match is not a requirement | | Raw event | Store separately | Preserve the incoming revision for recovery | The cleaner below removes email addresses and web links from embedded text. It's a starter scrub, not a privacy guarantee: names, telephone numbers, and addresses still need a release policy. We use a character budget here. It preserves Unicode characters, but it doesn't promise a token budget or sentence boundaries. Measure chunks with your embedding model's tokenizer before indexing them. This cell validates event identities, constructs the replacement document, and derives its complete chunk family: CHANGE TYPES = {"NEW", "UPDATED", "REAPPEARED"} CHUNK CHARACTERS = 1200 METADATA FIELDS = "title", "company", "location", "url", "searchQuery", "firstSeenAt", "lastSeenAt", "scrapedAt", def clean description value : if not isinstance value, str : raise ValueError "descriptionText must be text when present" text = unicodedata.normalize "NFC", value text = re.sub r"\b \w.+- +@ \w.- +\. A-Za-z {2,}\b", " email removed ", text, text = re.sub r"https?://\S+", " link removed ", text text = re.sub r" ^\S\n +", " ", text return re.sub r"\n{3,}", "\n\n", text .strip def prepare event raw : event = json.loads raw if not isinstance event, dict : raise ValueError "event must be an object" offer id = event.get "offerId" if not isinstance offer id, str or not offer id.strip : raise ValueError "offerId must be a nonempty string" if event.get "changeType" not in CHANGE TYPES: raise ValueError "unsupported changeType" text = clean description event.get "descriptionText", "" document = {"offerId": offer id, "descriptionText": text} document.update { field: event field for field in METADATA FIELDS if field in event } chunks = for paragraph in text.split "\n\n" : chunks.extend textwrap.wrap paragraph, width=CHUNK CHARACTERS, break long words=True, break on hyphens=False, parent = f"hellowork:{offer id}" body = json.dumps document, ensure ascii=False, sort keys=True return parent, body, chunks Missing descriptions produce no searchable chunks. That matters during replacement: keeping yesterday's text because today's record lacks text would silently invent continuity. The metadata remains available in the local store for inspection. Upserting newly generated chunk IDs doesn't remove IDs that a shorter revision stops producing. Delete by parent, then insert the replacement family. The transaction must cover the entire operation, including the consumer's event checkpoint. The store below deduplicates exact incoming lines, quarantines invalid events with a reason, and batches writes. Its SQL column names are local storage choices. SCHEMA = """ CREATE TABLE IF NOT EXISTS journal digest TEXT PRIMARY KEY, raw TEXT NOT NULL, error TEXT ; CREATE TABLE IF NOT EXISTS documents parent TEXT PRIMARY KEY, body TEXT NOT NULL ; CREATE TABLE IF NOT EXISTS chunks id TEXT PRIMARY KEY, parent TEXT NOT NULL REFERENCES documents parent , text TEXT NOT NULL ; CREATE INDEX IF NOT EXISTS chunks parent ON chunks parent ; """ def open store path : connection = sqlite3.connect path connection.execute "PRAGMA foreign keys = ON" connection.executescript SCHEMA return connection def apply batch connection, jsonl : entries = { hashlib.sha256 line.encode "utf-8" .hexdigest : line for line in jsonl.splitlines if line.strip } if not entries: return placeholders = ",".join "?" for in entries with connection: known = { row 0 for row in connection.execute f"SELECT digest FROM journal " f"WHERE digest IN {placeholders} ", tuple entries , } archive = replacements = {} for digest, raw in entries.items : if digest in known: continue try: parent, body, pieces = prepare event raw except ValueError, TypeError as error: archive.append digest, raw, str error else: archive.append digest, raw, None replacements parent = body, pieces connection.executemany "INSERT INTO journal VALUES ?, ?, ? ", archive if not replacements: return connection.executemany "INSERT INTO documents VALUES ?, ? " "ON CONFLICT parent DO UPDATE SET body=excluded.body", parent, body for parent, body, in replacements.items , parent slots = ",".join "?" for in replacements connection.execute f"DELETE FROM chunks WHERE parent IN {parent slots} ", tuple replacements , connection.executemany "INSERT INTO chunks VALUES ?, ?, ? ", f"{parent}:{index}", parent, piece for parent, , pieces in replacements.items for index, piece in enumerate pieces , store = open store "corpus.sqlite" apply batch store, incoming jsonl This assumes a serialized consumer processing batches in collection order. Within a batch, the last accepted event for a parent wins. Exact replay is skipped through the journal. An unseen, delayed historical event is a different problem: these event labels don't establish a total revision order. Don't feed concurrent backfills into this consumer without an ordering policy. For a separate vector service, the local transaction can't protect remote reads. Stage a complete version and activate it through a parent manifest, or use the service's transactional replacement mechanism. Otherwise, a failed delete-and-insert sequence can expose mixed versions. The useful assertion isn't merely that the new text exists. It's that surplus old chunks disappear and replay leaves the replacement intact. These are deliberately synthetic revisions in an isolated store, not collection results. Example synthetic events exercise shortening and replay without touching the collected corpus: demo = open store ":memory:" original event = { "offerId": "synthetic-offer", "changeType": "NEW", "descriptionText": "Example original requirement. " 200, } replacement event = { "offerId": "synthetic-offer", "changeType": "UPDATED", "descriptionText": "Example replacement requirement.", } original jsonl = json.dumps original event, sort keys=True replacement jsonl = json.dumps replacement event, sort keys=True apply batch demo, original jsonl original ids = { row 0 for row in demo.execute "SELECT id FROM chunks" } apply batch demo, replacement jsonl replacement rows = demo.execute "SELECT id, text FROM chunks ORDER BY id" .fetchall replacement ids = {row 0 for row in replacement rows} assert original ids - replacement ids assert row 1 for row in replacement rows == replacement event "descriptionText" apply batch demo, replacement jsonl apply batch demo, original jsonl assert demo.execute "SELECT id, text FROM chunks ORDER BY id" .fetchall == replacement rows The assertions compute the behavior. We claim no collected corpus size, retrieval improvement, or token savings. If you later label requirements or evaluate retrieval, assign splits at the parent level before expanding offers into chunks. Randomly splitting chunks can put an earlier requirement in training and its lightly edited replacement in testing. The evaluation then rewards familiarity with the offer. Grouping by offerId prevents that direct overlap. It doesn't catch reposts under different IDs or copied employer templates. For a stronger holdout, inspect normalized-text similarity across the proposed boundary. Don't globally merge identical descriptions during ingestion. Different offers can share boilerplate while differing in location or contract terms. Content deduplication can save embedding work, but retain each offer's identity and metadata. The HelloWork France Job Listings & Salary Filter Scraper https://apify.com/vexaloom-labs/hellowork-france-job-listings-and-salary-filter supplies the change events. Our consumer supplies their retrieval semantics. An offer absent from a batch isn't evidence that it expired. Unchanged jobs are skipped, collection can stop after pages without changes, and maxItems caps emitted records. Retirement needs a separate reconciliation policy. Likewise, an unchanged offer's refreshed producer state doesn't become a new consumer observation. Don't label your stored lastSeenAt as proof that the consumer checked the offer during every scheduled run. We would replace whole offers for current-state search and retain revisions separately. Appending everything is useful for history; it makes a poor default for answering which requirements apply now. The export includes only documents with searchable chunks. The journal export retains incoming events, including quarantined records, so restrict its access and retention separately from the cleaned corpus. This cell writes JSONL without printing records: with open "current.jsonl", "w", encoding="utf-8" as current file: for body, in store.execute "SELECT body FROM documents " "WHERE EXISTS " "SELECT 1 FROM chunks WHERE chunks.parent=documents.parent" " ORDER BY parent" : current file.write body + "\n" with open "events.jsonl", "w", encoding="utf-8" as archive file: for raw, in store.execute "SELECT raw FROM journal ORDER BY rowid" : archive file.write raw + "\n" demo.close store.close To reproduce the handoff: apify-client and set APIFY TOKEN in your environment. corpus.sqlite between daily batches. Example exact Actor input, reused across scheduled collections: { "mode": "search", "searchQueries": "developpeur python" , "city": "Lyon", "includeDetails": true, "incrementalMode": true, "stateKey": "lyon-python-current", "maxItems": 100 } Drafted with AI assistance and reviewed for accuracy.