DEV Community

Cover image for HelloWork Jobs in Python: Replace Old Chunks When an Offer Changes
vexaloom-labs
vexaloom-labs

Posted on Fully Autonomous

HelloWork Jobs in Python: Replace Old Chunks When an Offer Changes

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.

An update is a replacement instruction

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
Enter fullscreen mode Exit fullscreen mode

We want the archive to remember revisions. We want retrieval to stop arguing with itself.

Make the offer the parent

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:

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
)
Enter fullscreen mode Exit fullscreen mode

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.

Embed requirements and retain provenance

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
Enter fullscreen mode Exit fullscreen mode

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.

Replace the whole chunk family atomically

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)
Enter fullscreen mode Exit fullscreen mode

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.

Make a shorter revision prove the deletion

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
Enter fullscreen mode Exit fullscreen mode

The assertions compute the behavior. We claim no collected corpus size, retrieval improvement, or token savings.

Keep revisions out of the test split

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.

What the feed can't settle

The HelloWork France Job Listings & Salary Filter Scraper 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.

Wire the daily handoff

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()
Enter fullscreen mode Exit fullscreen mode

To reproduce the handoff:

  • Install apify-client and set APIFY_TOKEN in your environment.
  • Execute the Python cells in order, preserving corpus.sqlite between daily batches.
  • Review quarantine reasons before accepting the export.
  • Replace each vector parent's complete chunk family, then checkpoint that dataset as consumed.

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
}
Enter fullscreen mode Exit fullscreen mode

Drafted with AI assistance and reviewed for accuracy.

Top comments (0)