{"slug": "hellowork-jobs-in-python-replace-old-chunks-when-an-offer-changes", "title": "HelloWork Jobs in Python: Replace Old Chunks When an Offer Changes", "summary": "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.", "body_md": "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.\n\nLab note 194: can we turn a daily change feed into a searchable corpus that remembers the current offer without serving its superseded requirements?\n\nThe catch comes first: a change feed isn't a complete inventory of live jobs. Silence doesn't tell your index to delete anything.\n\nFor 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.\n\nThose labels describe incoming events. They shouldn't become independent document identities.\n\n**In a current-state RAG corpus, every accepted offer event should replace that offer's entire chunk set.**\n\nThe parent identity comes from `offerId`, which identifies the underlying HelloWork offer. Scope it to the source so another feed can't collide with it.\n\nThe storage boundary looks like this:\n\n```\nIncremental event\n    ├──> event archive: retain the observation\n    └──> current offer: replace the complete chunk family\n                              |\n                              └──> retrieval\n```\n\nWe want the archive to remember revisions. We want retrieval to stop arguing with itself.\n\nReuse 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.\n\nExample collection settings for the daily feed:\n\n``` python\nimport hashlib\nimport json\nimport os\nimport re\nimport sqlite3\nimport textwrap\nimport unicodedata\n\nfrom apify_client import ApifyClient\n\nrun_input = {\n    \"mode\": \"search\",\n    \"searchQueries\": [\"developpeur python\"],\n    \"city\": \"Lyon\",\n    \"includeDetails\": True,\n    \"incrementalMode\": True,\n    \"stateKey\": \"lyon-python-current\",\n    \"maxItems\": 100,\n}\n\nclient = ApifyClient(os.environ[\"APIFY_TOKEN\"])\nrun = client.actor(\n    \"vexaloom-labs/hellowork-france-job-listings-and-salary-filter\"\n).call(run_input=run_input)\n\nif run[\"status\"] != \"SUCCEEDED\":\n    raise RuntimeError(f\"Collection ended with {run['status']}\")\n\nitems = client.dataset(run[\"defaultDatasetId\"]).list_items().items\nincoming_jsonl = \"\\n\".join(\n    json.dumps(item, ensure_ascii=False, sort_keys=True)\n    for item in items\n)\n```\n\nKeep 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.\n\nThe producer's state and your index's state have separate commit points. That little gap is where missing updates get comfortable.\n\nOur labeling unit is the offer. Our retrieval unit is a chunk of its description, linked back to that offer.\n\nKeep `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.\n\nThe table describes our consumer's choices, rather than additional source fields:\n\n| Material | Corpus treatment | Reason | \n|---|---|---|\n| `descriptionText` | Clean, then chunk | Requirements are the searchable evidence | \n| `offerId` | Build the source-scoped parent key | Revisions must meet at the same parent | \n| `url` , observation timestamps | Retain as metadata | Support citations and freshness inspection | \n| `searchQuery` | Retain as observation provenance | A query match is not a requirement | \n| Raw event | Store separately | Preserve the incoming revision for recovery | \n\nThe 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.\n\nWe 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.\n\nThis cell validates event identities, constructs the replacement document, and derives its complete chunk family:\n\n```\nCHANGE_TYPES = {\"NEW\", \"UPDATED\", \"REAPPEARED\"}\nCHUNK_CHARACTERS = 1200\nMETADATA_FIELDS = (\n    \"title\", \"company\", \"location\", \"url\", \"searchQuery\",\n    \"firstSeenAt\", \"lastSeenAt\", \"scrapedAt\",\n)\n\ndef clean_description(value):\n    if not isinstance(value, str):\n        raise ValueError(\"descriptionText must be text when present\")\n    text = unicodedata.normalize(\"NFC\", value)\n    text = re.sub(\n        r\"\\b[\\w.+-]+@[\\w.-]+\\.[A-Za-z]{2,}\\b\",\n        \"[email removed]\",\n        text,\n    )\n    text = re.sub(r\"https?://\\S+\", \"[link removed]\", text)\n    text = re.sub(r\"[^\\S\\n]+\", \" \", text)\n    return re.sub(r\"\\n{3,}\", \"\\n\\n\", text).strip()\n\ndef prepare_event(raw):\n    event = json.loads(raw)\n    if not isinstance(event, dict):\n        raise ValueError(\"event must be an object\")\n\n    offer_id = event.get(\"offerId\")\n    if not isinstance(offer_id, str) or not offer_id.strip():\n        raise ValueError(\"offerId must be a nonempty string\")\n    if event.get(\"changeType\") not in CHANGE_TYPES:\n        raise ValueError(\"unsupported changeType\")\n\n    text = clean_description(event.get(\"descriptionText\", \"\"))\n    document = {\"offerId\": offer_id, \"descriptionText\": text}\n    document.update({\n        field: event[field]\n        for field in METADATA_FIELDS\n        if field in event\n    })\n\n    chunks = []\n    for paragraph in text.split(\"\\n\\n\"):\n        chunks.extend(textwrap.wrap(\n            paragraph,\n            width=CHUNK_CHARACTERS,\n            break_long_words=True,\n            break_on_hyphens=False,\n        ))\n\n    parent = f\"hellowork:{offer_id}\"\n    body = json.dumps(document, ensure_ascii=False, sort_keys=True)\n    return parent, body, chunks\n```\n\nMissing descriptions produce no searchable chunks. That matters during replacement: keeping yesterday's text because today's record lacks text would silently invent continuity.\n\nThe metadata remains available in the local store for inspection.\n\nUpserting newly generated chunk IDs doesn't remove IDs that a shorter revision stops producing.\n\nDelete by parent, then insert the replacement family. The transaction must cover the entire operation, including the consumer's event checkpoint.\n\nThe store below deduplicates exact incoming lines, quarantines invalid events with a reason, and batches writes. Its SQL column names are local storage choices.\n\n```\nSCHEMA = \"\"\"\nCREATE TABLE IF NOT EXISTS journal (\n    digest TEXT PRIMARY KEY,\n    raw TEXT NOT NULL,\n    error TEXT\n);\nCREATE TABLE IF NOT EXISTS documents (\n    parent TEXT PRIMARY KEY,\n    body TEXT NOT NULL\n);\nCREATE TABLE IF NOT EXISTS chunks (\n    id TEXT PRIMARY KEY,\n    parent TEXT NOT NULL REFERENCES documents(parent),\n    text TEXT NOT NULL\n);\nCREATE INDEX IF NOT EXISTS chunks_parent ON chunks(parent);\n\"\"\"\n\ndef open_store(path):\n    connection = sqlite3.connect(path)\n    connection.execute(\"PRAGMA foreign_keys = ON\")\n    connection.executescript(SCHEMA)\n    return connection\n\ndef apply_batch(connection, jsonl):\n    entries = {\n        hashlib.sha256(line.encode(\"utf-8\")).hexdigest(): line\n        for line in jsonl.splitlines()\n        if line.strip()\n    }\n    if not entries:\n        return\n\n    placeholders = \",\".join(\"?\" for _ in entries)\n    with connection:\n        known = {\n            row[0]\n            for row in connection.execute(\n                f\"SELECT digest FROM journal \"\n                f\"WHERE digest IN ({placeholders})\",\n                tuple(entries),\n            )\n        }\n\n        archive = []\n        replacements = {}\n        for digest, raw in entries.items():\n            if digest in known:\n                continue\n            try:\n                parent, body, pieces = prepare_event(raw)\n            except (ValueError, TypeError) as error:\n                archive.append((digest, raw, str(error)))\n            else:\n                archive.append((digest, raw, None))\n                replacements[parent] = (body, pieces)\n\n        connection.executemany(\n            \"INSERT INTO journal VALUES (?, ?, ?)\", archive\n        )\n        if not replacements:\n            return\n\n        connection.executemany(\n            \"INSERT INTO documents VALUES (?, ?) \"\n            \"ON CONFLICT(parent) DO UPDATE SET body=excluded.body\",\n            [(parent, body) for parent, (body, _) in replacements.items()],\n        )\n\n        parent_slots = \",\".join(\"?\" for _ in replacements)\n        connection.execute(\n            f\"DELETE FROM chunks WHERE parent IN ({parent_slots})\",\n            tuple(replacements),\n        )\n        connection.executemany(\n            \"INSERT INTO chunks VALUES (?, ?, ?)\",\n            [\n                (f\"{parent}:{index}\", parent, piece)\n                for parent, (_, pieces) in replacements.items()\n                for index, piece in enumerate(pieces)\n            ],\n        )\n\nstore = open_store(\"corpus.sqlite\")\napply_batch(store, incoming_jsonl)\n```\n\nThis assumes a serialized consumer processing batches in collection order. Within a batch, the last accepted event for a parent wins.\n\nExact 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.\n\nFor 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.\n\nThe useful assertion isn't merely that the new text exists. It's that surplus old chunks disappear and replay leaves the replacement intact.\n\nThese are deliberately synthetic revisions in an isolated store, not collection results.\n\nExample synthetic events exercise shortening and replay without touching the collected corpus:\n\n```\ndemo = open_store(\":memory:\")\noriginal_event = {\n    \"offerId\": \"synthetic-offer\",\n    \"changeType\": \"NEW\",\n    \"descriptionText\": \"Example original requirement. \" * 200,\n}\nreplacement_event = {\n    \"offerId\": \"synthetic-offer\",\n    \"changeType\": \"UPDATED\",\n    \"descriptionText\": \"Example replacement requirement.\",\n}\noriginal_jsonl = json.dumps(original_event, sort_keys=True)\nreplacement_jsonl = json.dumps(replacement_event, sort_keys=True)\n\napply_batch(demo, original_jsonl)\noriginal_ids = {\n    row[0] for row in demo.execute(\"SELECT id FROM chunks\")\n}\n\napply_batch(demo, replacement_jsonl)\nreplacement_rows = demo.execute(\n    \"SELECT id, text FROM chunks ORDER BY id\"\n).fetchall()\nreplacement_ids = {row[0] for row in replacement_rows}\n\nassert original_ids - replacement_ids\nassert [row[1] for row in replacement_rows] == [\n    replacement_event[\"descriptionText\"]\n]\n\napply_batch(demo, replacement_jsonl)\napply_batch(demo, original_jsonl)\nassert demo.execute(\n    \"SELECT id, text FROM chunks ORDER BY id\"\n).fetchall() == replacement_rows\n```\n\nThe assertions compute the behavior. We claim no collected corpus size, retrieval improvement, or token savings.\n\nIf you later label requirements or evaluate retrieval, assign splits at the parent level before expanding offers into chunks.\n\nRandomly splitting chunks can put an earlier requirement in training and its lightly edited replacement in testing. The evaluation then rewards familiarity with the offer.\n\nGrouping 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.\n\nDon'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.\n\nThe [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.\n\nAn 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.\n\nLikewise, 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.\n\nWe 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.\n\nThe 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.\n\nThis cell writes JSONL without printing records:\n\n```\nwith open(\"current.jsonl\", \"w\", encoding=\"utf-8\") as current_file:\n    for (body,) in store.execute(\n        \"SELECT body FROM documents \"\n        \"WHERE EXISTS (\"\n        \"SELECT 1 FROM chunks WHERE chunks.parent=documents.parent\"\n        \") ORDER BY parent\"\n    ):\n        current_file.write(body + \"\\n\")\n\nwith open(\"events.jsonl\", \"w\", encoding=\"utf-8\") as archive_file:\n    for (raw,) in store.execute(\n        \"SELECT raw FROM journal ORDER BY rowid\"\n    ):\n        archive_file.write(raw + \"\\n\")\n\ndemo.close()\nstore.close()\n```\n\nTo reproduce the handoff:\n\n`apify-client` and set `APIFY_TOKEN` in your environment.`corpus.sqlite` between daily batches.\nExample exact Actor input, reused across scheduled collections:\n\n```\n{\n  \"mode\": \"search\",\n  \"searchQueries\": [\"developpeur python\"],\n  \"city\": \"Lyon\",\n  \"includeDetails\": true,\n  \"incrementalMode\": true,\n  \"stateKey\": \"lyon-python-current\",\n  \"maxItems\": 100\n}\n```\n\n*Drafted with AI assistance and reviewed for accuracy.*", "url": "https://wpnews.pro/news/hellowork-jobs-in-python-replace-old-chunks-when-an-offer-changes", "canonical_source": "https://dev.to/vexaloom-labs/hellowork-jobs-in-python-replace-old-chunks-when-an-offer-changes-3e42", "published_at": "2026-12-03 13:12:58+00:00", "updated_at": "2026-12-03 13:17:46.771602+00:00", "lang": "en", "topics": ["ai-agents", "ai-tools"], "entities": ["HelloWork", "Apify", "Lyon"], "also_reported_by": [], "takeaway": "In a current-state RAG corpus, replace an offer's full chunk family on every accepted change event and key it on a source-scoped offerId, keeping the raw event in a separate archive so retrieval never serves superseded requirements.", "recommendation": {"advice": "Replace each offer's entire chunk set on every accepted change event, key chunks to a source-scoped offerId, and archive raw events separately so retrieval never serves superseded requirements.", "playbook": "rag-retrieval", "playbook_url": "https://wpnews.pro/playbooks/rag-retrieval"}, "alternates": {"html": "https://wpnews.pro/news/hellowork-jobs-in-python-replace-old-chunks-when-an-offer-changes", "markdown": "https://wpnews.pro/news/hellowork-jobs-in-python-replace-old-chunks-when-an-offer-changes.md", "text": "https://wpnews.pro/news/hellowork-jobs-in-python-replace-old-chunks-when-an-offer-changes.txt", "jsonld": "https://wpnews.pro/news/hellowork-jobs-in-python-replace-old-chunks-when-an-offer-changes.jsonld"}}