Skip to content

Update Metadata on Many Work Items Safely

A records team must correct a department code on 10,000 work items after a reorganization. The app updates a few hundred at a time, and some of the items are still moving through workflows. The team needs a job that changes only what is wrong, never doubles up, survives a crash, and stays out of the way of the workflow engine.

At a glance

  • Extension point REST API from your own code (C# with the KL.APIClient client, or Python)
  • You need A token with Manage Work Items; a CSV file of work item ids, or a value to search for with QueryWorkState; the field key to change
  • Teaches Idempotent upserts, dry runs, lock retries with a growing wait, collect-then-change paging, and a resumable log
graph TD
    A["CSV of ids or QueryWorkState pages"] --> B["GetWorkItem"]
    B --> C{"Value already right?"}
    C -->|"yes"| L["Log: unchanged"]
    C -->|"no, dry run"| D["Log: would update"]
    C -->|"no, apply"| E["UpsertWorkItemMetadata and UpsertDocumentMetadata"]
    E -->|"412 locked"| R["Wait 2, 4, 8 s and retry"]
    R --> E
    E --> U["Log: updated"]

Set it up

  1. Give the service account Manage Work Items and create a token. See Authentication.
  2. For C#, create a console app (dotnet new console) and generate KL.APIClient from your tenant's spec and reference it. See Generate the client. For Python, install Python 3.9 or later and run pip install requests.
  3. Set KL_BASE_URL (for example https://yourcompany.knowledgelake.io/api) and KL_API_TOKEN in the environment.
  4. Either make a CSV file with a WorkItemId column, or decide the Index value that finds the items with QueryWorkState.
  5. Edit BUCKET, KEY, OLD_VALUE and NEW_VALUE at the top of the script (Bucket, Key, OldValue and NewValue in C#). This example changes Index.Department from Accounts Payable to Finance Operations on the work item and on each document.

This recipe is for work items, in a workflow or finished. For documents already released to a destination, use V1_RepositoryAPI/UpsertDocumentMetadata instead; search your tenant's spec for its shape.

The script

Program.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using KL.APIClient.Api;
using KL.APIClient.Client;
using KL.APIClient.Model;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

const string Bucket = "Index", Key = "Department", NewValue = "Finance Operations";
const string OldValue = "Accounts Payable";              // only change items that have this value
const string LogFile = "bulk-update-log.csv";
const int PageSize = 100;
var pause = TimeSpan.FromSeconds(0.25);                  // pause between calls
var cli = Environment.GetCommandLineArgs().Skip(1).ToArray();
bool dryRun = !cli.Contains("--apply");                  // default is a dry run

var config = new Configuration
{
    BasePath = Environment.GetEnvironmentVariable("KL_BASE_URL").TrimEnd('/'),
    Timeout = TimeSpan.FromSeconds(120)
};
config.AddApiKey("TempIdentityToken", Environment.GetEnvironmentVariable("KL_API_TOKEN"));
var workItems = new V1KWorkItemAPIApi(config);

string source = cli.Length > 0 && cli[0] != "--apply" ? cli[0] : null;
List<Guid> ids = source != null ? IdsFromCsv(source) : await IdsFromQuery();

var done = new HashSet<Guid>();
if (File.Exists(LogFile))
{
    foreach (var line in File.ReadLines(LogFile).Skip(1))
    {
        var cells = line.Split(',');
        if (cells.Length > 1 && (cells[1] == "updated" || cells[1] == "unchanged") && Guid.TryParse(cells[0], out var logged))
            done.Add(logged);
    }
}

Console.WriteLine($"{ids.Count} work item(s), {done.Count} already done, dry run = {dryRun}");
bool newLog = !File.Exists(LogFile);
using (var log = new StreamWriter(LogFile, append: true))
{
    if (newLog) log.WriteLine("WorkItemId,Result,Changes,Detail");
    for (int n = 1; n <= ids.Count; n++)
    {
        Guid workItemId = ids[n - 1];
        if (done.Contains(workItemId)) continue;
        try
        {
            int changes = await Update(workItemId);
            string result = changes > 0 ? (dryRun ? "would update" : "updated") : "unchanged";
            if (!dryRun || changes == 0) log.WriteLine($"{workItemId},{result},{changes},");
            Console.WriteLine($"{n}/{ids.Count} {workItemId} {result} ({changes})");
        }
        catch (ApiException e)
        {
            string detail = $"HTTP {e.ErrorCode}: {Messages(e)}";
            log.WriteLine($"{workItemId},failed,0,{Csv(detail)}");
            Console.WriteLine($"{n}/{ids.Count} {workItemId} FAILED {detail}");
        }
        log.Flush();
    }
}

// Send one call. Retry HTTP 412 (often a lock) and 500 with a growing wait.
// Any other status above 400 throws ApiException.
async Task<T> Call<T>(Func<Task<T>> send, int retries = 5)
{
    var wait = TimeSpan.FromSeconds(2);
    for (int attempt = 0; ; attempt++)
    {
        try
        {
            return await send();
        }
        catch (ApiException e) when ((e.ErrorCode == 412 || e.ErrorCode == 500) && attempt < retries)
        {
            await Task.Delay(wait);
            wait += wait;
        }
        finally
        {
            await Task.Delay(pause);
        }
    }
}

// HTTP 200 with Success false: throw the MessageKey the same way as a failed call.
void Check(bool success, string messageKey)
{
    if (!success) throw new ApiException(200, messageKey);
}

// Read Messages[].MessageKey from the failure envelope in the response body.
string Messages(ApiException e)
{
    string body = e.ErrorContent?.ToString();
    if (string.IsNullOrEmpty(body)) return e.Message;
    try
    {
        var envelope = JObject.Parse(body);
        var keys = (envelope["Messages"] as JArray ?? new JArray())
            .Select(m => (string)m["MessageKey"] ?? "").ToList();
        return keys.Count > 0 ? string.Join("; ", keys) : (string)envelope["MessageKey"] ?? "";
    }
    catch (JsonException)
    {
        return body.Length > 500 ? body.Substring(0, 500) : body;
    }
}

List<Guid> IdsFromCsv(string path)
{
    var lines = File.ReadAllLines(path);
    int column = lines[0].Split(',').Select(h => h.Trim().Trim('"')).ToList().IndexOf("WorkItemId");
    if (column < 0) throw new Exception(path + " has no WorkItemId column");
    return lines.Skip(1)
        .Where(row => row.Trim().Length > 0)
        .Select(row => Guid.Parse(row.Split(',')[column].Trim().Trim('"')))
        .ToList();
}

// Collect every page first, then update. Updating while paging can shift the pages.
async Task<List<Guid>> IdsFromQuery()
{
    var found = new List<Guid>();
    for (int skip = 0; ; skip += PageSize)
    {
        var page = await Call(() => workItems.V1KWorkItemAPIControllerQueryWorkStateAsync(new PaasWorkQueryParameter
        {
            Skip = skip,
            Take = PageSize,
            MetadataKeyFilter = Key,
            MetadataValueFilter = OldValue,
            FilterScope = FilterScope.WorkItem
        }));
        Check(page.Success, page.MessageKey);
        var rows = page.Data ?? new List<WorkItemInfoWithMetadata>();
        found.AddRange(rows.Select(row => row.WorkItem.WorkItemId));
        if (rows.Count < PageSize) return found;
    }
}

string ValueOf(Dictionary<string, Dictionary<string, string>> metadata, string bucket, string key) =>
    metadata != null && metadata.TryGetValue(bucket, out var values) && values != null
        && values.TryGetValue(key, out var value) ? value : null;

async Task<int> Update(Guid id)
{
    var wi = await Call(() => workItems.V1KWorkItemAPIControllerGetWorkItemAsync(new PaasWorkItemIdDTO { WorkItemId = id }));
    Check(wi.Success, wi.MessageKey);
    var newMetadata = new List<MetadataValueDTO> { new MetadataValueDTO { Bucket = Bucket, Key = Key, Value = NewValue } };
    int changes = 0;
    if (ValueOf(wi.Data.Metadata, Bucket, Key) == OldValue)
    {
        changes++;
        if (!dryRun)
        {
            var saved = await Call(() => workItems.V1KWorkItemAPIControllerUpsertWorkItemMetadataAsync(
                new UpsertPaasWorkItemMetadataParameter { WorkItemId = id, Metadata = newMetadata }));
            Check(saved.Success, saved.MessageKey);
        }
    }
    foreach (var doc in wi.Data.Documents)
    {
        if (ValueOf(doc.Metadata, Bucket, Key) == OldValue)
        {
            changes++;
            if (!dryRun)
            {
                var saved = await Call(() => workItems.V1KWorkItemAPIControllerUpsertDocumentMetadataAsync(
                    new UpsertPaasDocumentMetadataParameter { WorkItemId = id, DocumentId = doc.Id, Metadata = newMetadata }));
                Check(saved.Success, saved.MessageKey);
            }
        }
    }
    return changes;
}

string Csv(string text) =>
    text.IndexOfAny(new[] { ',', '"', '\r', '\n' }) >= 0 ? "\"" + text.Replace("\"", "\"\"") + "\"" : text;
bulk_update.py
import csv
import os
import sys
import time
import requests

BASE = os.environ["KL_BASE_URL"].rstrip("/")
HEADERS = {"TempIdentityToken": os.environ["KL_API_TOKEN"], "Content-Type": "application/json"}

BUCKET, KEY, NEW_VALUE = "Index", "Department", "Finance Operations"
OLD_VALUE = "Accounts Payable"          # only change items that have this value
DRY_RUN = "--apply" not in sys.argv     # default is a dry run
PAUSE_SECONDS = 0.25                    # pause between calls
PAGE_SIZE = 100

class ApiError(Exception):
    def __init__(self, status, text):
        super().__init__(f"HTTP {status}: {text}")
        self.status = status

def call(action, body, retries=5):
    """POST one action. Return Data. Retry HTTP 412 (often a lock) and 500 with a growing wait."""
    wait = 2
    for attempt in range(retries + 1):
        r = requests.post(f"{BASE}/{action}", headers=HEADERS, json=body, timeout=120)
        time.sleep(PAUSE_SECONDS)
        if r.status_code == 200:
            env = r.json()
            if env.get("Success"):
                return env.get("Data")
            raise ApiError(200, env.get("MessageKey"))
        if r.status_code in (412, 500) and attempt < retries:
            time.sleep(wait)
            wait *= 2
            continue
        try:
            env = r.json()
            text = "; ".join(m.get("MessageKey", "") for m in env.get("Messages", [])) or env.get("MessageKey", "")
        except ValueError:
            text = r.text[:500]
        raise ApiError(r.status_code, text)

def ids_from_csv(path):
    with open(path, newline="", encoding="utf-8") as f:
        for row in csv.DictReader(f):
            yield row["WorkItemId"].strip()

def ids_from_query():
    # Collect every page first, then update. Updating while paging can shift the pages.
    found, skip = [], 0
    while True:
        page = call("V1_KWorkItemAPI/QueryWorkState", {
            "Skip": skip, "Take": PAGE_SIZE,
            "MetadataKeyFilter": KEY, "MetadataValueFilter": OLD_VALUE, "FilterScope": "WorkItem",
        })
        found.extend(item["WorkItem"]["WorkItemId"] for item in page)
        if len(page) < PAGE_SIZE:
            return found
        skip += PAGE_SIZE

def value_of(metadata, bucket, key):
    return ((metadata or {}).get(bucket) or {}).get(key)

def update(work_item_id):
    wi = call("V1_KWorkItemAPI/GetWorkItem", {"WorkItemId": work_item_id})
    changes = 0
    if value_of(wi["Metadata"], BUCKET, KEY) == OLD_VALUE:
        changes += 1
        if not DRY_RUN:
            call("V1_KWorkItemAPI/UpsertWorkItemMetadata", {
                "WorkItemId": work_item_id,
                "Metadata": [{"Bucket": BUCKET, "Key": KEY, "Value": NEW_VALUE}],
            })
    for doc in wi["Documents"]:
        if value_of(doc["Metadata"], BUCKET, KEY) == OLD_VALUE:
            changes += 1
            if not DRY_RUN:
                call("V1_KWorkItemAPI/UpsertDocumentMetadata", {
                    "WorkItemId": work_item_id, "DocumentId": doc["Id"],
                    "Metadata": [{"Bucket": BUCKET, "Key": KEY, "Value": NEW_VALUE}],
                })
    return changes

def main():
    source = sys.argv[1] if len(sys.argv) > 1 and sys.argv[1] != "--apply" else None
    ids = list(ids_from_csv(source)) if source else ids_from_query()
    done = set()
    if os.path.exists("bulk-update-log.csv"):
        with open("bulk-update-log.csv", newline="", encoding="utf-8") as f:
            done = {row["WorkItemId"] for row in csv.DictReader(f) if row["Result"] in ("updated", "unchanged")}

    print(f"{len(ids)} work item(s), {len(done)} already done, dry run = {DRY_RUN}")
    new_log = not os.path.exists("bulk-update-log.csv")
    with open("bulk-update-log.csv", "a", newline="", encoding="utf-8") as log:
        writer = csv.writer(log)
        if new_log:
            writer.writerow(["WorkItemId", "Result", "Changes", "Detail"])
        for n, work_item_id in enumerate(ids, 1):
            if work_item_id in done:
                continue
            try:
                changes = update(work_item_id)
                result = ("would update" if DRY_RUN else "updated") if changes else "unchanged"
                if not DRY_RUN or not changes:
                    writer.writerow([work_item_id, result, changes, ""])
                print(f"{n}/{len(ids)} {work_item_id} {result} ({changes})")
            except ApiError as e:
                writer.writerow([work_item_id, "failed", 0, str(e)])
                print(f"{n}/{len(ids)} {work_item_id} FAILED {e}")
            log.flush()

if __name__ == "__main__":
    main()

Run it. For C#, run dotnet run in the folder of the console app; arguments go after --:

dotnet run -- workitems.csv            # dry run from a CSV file
dotnet run                             # dry run from QueryWorkState
dotnet run -- workitems.csv --apply    # make the changes
python bulk_update.py workitems.csv            # dry run from a CSV file
python bulk_update.py                          # dry run from QueryWorkState
python bulk_update.py workitems.csv --apply    # make the changes

How it works

The C# program and the Python script do the same steps. Where the names differ, the C# name follows in parentheses.

  • Dry run first. Without --apply the script only reports what it would change. Read the report and check a few items by hand.
  • Upsert, never append. UpsertWorkItemMetadata and UpsertDocumentMetadata set a fixed value and leave other keys alone. The script reads each item first and skips it when the value is already right, so a second run changes nothing.
  • One call at a time. The API has no general rate limiter, so the client must be polite. PAUSE_SECONDS (pause) keeps the load low next to the workflow engine.
  • Retry locks with a growing wait. Each upsert locks the work item. If a workflow step holds it, the call returns HTTP 412 (in C#, the client throws ApiException with ErrorCode 412). call (Call) waits 2, 4, 8 seconds and tries again, then logs the failure.
  • Collect, then change. With QueryWorkState, the script reads every page before it changes anything. Changing the filtered value while paging moves items out of the result and skips others.
  • Log and resume. bulk-update-log.csv records each id. A rerun skips ids already updated or unchanged.

Test it

  1. Make a CSV file with three work item ids. Run the dry run and read the report.
  2. Run with --apply. Check the three work items in Monitor, or with GetWorkItem.
  3. Run with --apply again.

You should see

updated for the three items on the first apply, the new value on the work item and on every document, and unchanged for all three on the second apply.

What can go wrong

What you see Cause and fix
QueryWorkState returns nothing It finds only work items in workflows the token's user can run, and MetadataKeyFilter looks only in the Index bucket, with an exact value. Use a CSV file of ids for other cases.
Many 412 failures in a row A workflow is working those items. Run the script when the queue is quiet, or skip items whose WorkStatus is BeingWorked.
HTTP 401 halfway through The token was rotated or the user lost a permission. Fix the token and rerun; the log lets you resume.
A route does not change after the update The work item already passed the route. Metadata changes do not move a work item back in its workflow.
A step later overwrites your value A later Custom Step or extraction step can write the same key. Update after that step, or change the step.
Values in the System bucket do not change The API drops System writes.

Variations

  • One in-flight work item. To stamp a value your ERP returned onto every document of one work item that waits in a task, reuse call from the script (Call and Check in C#). Write the routing value on the work item too, because routes read work item metadata:

    var waitingItemId = Guid.Parse("3f2b8c1e-0d5a-4c7e-9a43-6b1f2e8d9c10");   // the work item that waits in a task
    var item = await Call(() => workItems.V1KWorkItemAPIControllerGetWorkItemAsync(new PaasWorkItemIdDTO { WorkItemId = waitingItemId }));
    Check(item.Success, item.MessageKey);
    var approved = new List<MetadataValueDTO> { new MetadataValueDTO { Bucket = "Index", Key = "ApprovalStatus", Value = "Approved" } };
    foreach (var document in item.Data.Documents)
    {
        var docSaved = await Call(() => workItems.V1KWorkItemAPIControllerUpsertDocumentMetadataAsync(
            new UpsertPaasDocumentMetadataParameter { WorkItemId = waitingItemId, DocumentId = document.Id, Metadata = approved }));
        Check(docSaved.Success, docSaved.MessageKey);
    }
    var itemSaved = await Call(() => workItems.V1KWorkItemAPIControllerUpsertWorkItemMetadataAsync(
        new UpsertPaasWorkItemMetadataParameter { WorkItemId = waitingItemId, Metadata = approved }));
    Check(itemSaved.Success, itemSaved.MessageKey);
    
    wi = call("V1_KWorkItemAPI/GetWorkItem", {"WorkItemId": work_item_id})
    value = [{"Bucket": "Index", "Key": "ApprovalStatus", "Value": "Approved"}]
    for doc in wi["Documents"]:
        call("V1_KWorkItemAPI/UpsertDocumentMetadata",
             {"WorkItemId": work_item_id, "DocumentId": doc["Id"], "Metadata": value})
    call("V1_KWorkItemAPI/UpsertWorkItemMetadata", {"WorkItemId": work_item_id, "Metadata": value})
    
  • Wait for a state change. If you also wait with GetWorkState, call it no more often than every 1.5 seconds per work item.