Skip to contentSkip to conversation

sstate: Replay warnings and errors when restoring from sstate

RFC PATCH New Mathieu Dubois-Briand 1 participant 4 messages Nov 15

lore
Share & tools
lore
#0 lore raw

v2 cover sstate: Replay warnings and errors when restoring from sstate

The sstate cache mechanism currently has a blind spot: log messages shown while a task first runs are not replayed when the task output comes back from the cache. This is particularly true for warnings, which are effectively hidden unless the task is rebuilt.

This openembedded-core series saves each task's messages into the sstate cache and replays them when cached output is reused. Logs are also replayed for tasks that are not themselves sstate-covered but are dependencies of covered tasks. This requires the companion bitbake series.

---
Changes in v2:
- Bundle records of non-sstate tasks from other recipes, not only the same
recipe.
- Replay the records claimed through BB_SETSCENE_CLAIMED_TASKS, with runqueue ensuring each covered task is replayed exactly once.
- Extend the selftests with cross-recipe coverage.
- Link to v1: https://lore.kernel.org/r/[email protected]

---
Mathieu Dubois-Briand (3):
sstate: Replay warnings and errors when restoring from sstate
sstate: Replay the records of tasks covered by setscene oeqa/sstatetests: Add tests for sstate log replay

 .../recipes-test/log-replay/log-replay-dep.bb      |  18 +++
 .../log-replay/log-replay-error-test.bb            |  16 ++
 .../recipes-test/log-replay/log-replay-test.bb     |  34 ++++
 .../recipes-test/log-replay/log-replay-user.bb     |  32 ++++
 meta/classes-global/sstate.bbclass                 | 156 ++++++++++++++++++-
 meta/lib/oeqa/selftest/cases/sstatetests.py        | 171 +++++++++++++++++++++
 6 files changed, 424 insertions(+), 3 deletions(-)

---
base-commit: 34991d0ce3cc5f38dd29e824af7579512d2b917e
change-id: 20261023-mathieu-debug-replay-v4-535c89baa72c

Best regards,

Signature · 1 line
Mathieu Dubois-Briand <[email protected]>
#1 lore raw

RFC PATCH v2 1/3 sstate: Replay warnings and errors when restoring from sstate

Save the messages logged by an sstate task into its sstate package (sstate-log.json, with build-specific paths replaced by @VAR@ placeholders) and replay them when the package is restored from the sstate cache, substituting the paths of the build doing the replay. Errors are saved too, since bb.error() can be called without failing the task, so warnings which previously only appeared on the first build (e.g. QA messages) are now shown again on sstate reuse.

AI-Generated: Uses opencode (DeepSeek V4 Flash)

---
 meta/classes-global/sstate.bbclass | 91 ++++++++++++++++++++++++++++++++++++--
 1 file changed, 88 insertions(+), 3 deletions(-)
meta/classes-global/sstate.bbclass +88 -3
index c6d945918232..ed88dae17202 100644
@@ -101,6 +101,12 @@ SSTATEPREINSTFUNCS = ""
 SSTATEPOSTUNPACKFUNCS = "sstate_hardcode_path_unpack"
 EXTRA_STAGING_FIXMES ?= "HOSTTOOLS_DIR"
 
+# Build-specific paths substituted in replayed task log messages. Keep the
+# order longest-path-first: a shorter value is a prefix of the longer ones
+# (e.g. TOPDIR is a prefix of TMPDIR, HOME of both) and must be substituted
+# after them, or it would match inside their values.
+SSTATE_LOG_VARS ?= "TMPDIR DL_DIR SSTATE_DIR TOPDIR COREBASE HOME"
+
 # Check whether sstate exists for tasks that support sstate and are in the
 # locked signatures file.
 SIGGEN_LOCKEDSIGS_SSTATE_EXISTS_CHECK ?= 'error'
@@ -200,6 +206,73 @@ def sstate_state_fromvars(d, task = None):
     ss['fixmedir'] = fixmedir
     return ss
 
+def sstate_log_strip_paths(d, message):
+    import re
+
+    # Replace paths in log messages by placeholders, so we are not leaking
+    # build paths and can show consistent paths on replay.
+    # Escape literal '@' first.
+    message = message.replace('@', r'\@')
+    for var in d.getVar('SSTATE_LOG_VARS').split():
+        value = (d.getVar(var) or '').rstrip('/')
+        if value:
+            message = re.sub(re.escape(value) + r'(?!\w)', '@%s@' % var,
+                             message)
+
+    return message
+
+def sstate_log_expand_paths(d, message):
+    # Add back paths into the replayed log messages
+    for var in d.getVar('SSTATE_LOG_VARS').split():
+        value = (d.getVar(var) or '').rstrip('/')
+        if value:
+            message = message.replace('@%s@' % var, value)
+
+    message = message.replace(r'\@', '@')
+
+    return message
+
+def sstate_log_save(d, record):
+    # Raw logstore entry (a [levelno, message] pair) -> archived record
+    # (dict), with build paths replaced by placeholders. Inverse of
+    # sstate_log_expand.
+    levelno, message = record
+    return {'levelno': levelno, 'message': sstate_log_strip_paths(d, message)}
+
+def sstate_log_emit(d, logentry):
+    levelno = logentry.get('levelno', 0)
+    if levelno < bb.msg.BBLogFormatter.WARNONCE or "message" not in logentry:
+        return
+    message = sstate_log_expand_paths(d, logentry['message'])
+    if levelno >= bb.msg.BBLogFormatter.ERROR:
+        bb.error(message)
+    elif levelno == bb.msg.BBLogFormatter.ERRORONCE:
+        bb.erroronce(message)
+    elif levelno == bb.msg.BBLogFormatter.WARNONCE:
+        bb.warnonce(message)
+    else:
+        bb.warn(message)
+
+python sstate_save_task_log () {
+    import json
+
+    # Save the messages logged by this task, so they can be replayed when the
+    # task is restored from sstate. The records are written by bitbake right
+    # after the task body, before the postfuncs.
+    mytask = d.getVar('BB_RUNTASK')
+    recordsfn = os.path.join(d.getVar('T'), 'logrecords.%s.json' % mytask)
+    if not os.path.exists(recordsfn):
+        return
+    with open(recordsfn) as f:
+        records = json.load(f)
+
+    tasks = {mytask: [sstate_log_save(d, record) for record in records]}
+
+    logfn = os.path.join(d.getVar('SSTATE_BUILDDIR'), "sstate-log.json")
+    with open(logfn, 'w') as f:
+        json.dump({'tasks': tasks}, f)
+}
+
 def sstate_add(ss, source, dest, d):
     if not source.endswith("/"):
          source = source + "/"
@@ -387,11 +460,12 @@ def sstate_installpkg(ss, d):
         # All hooks should run in the SSTATE_INSTDIR
         bb.build.exec_func(f, d, (sstateinst,))
 
-    return sstate_installpkgdir(ss, d)
+    return sstate_installpkgdir(ss, d, replay=True)
 
-def sstate_installpkgdir(ss, d):
+def sstate_installpkgdir(ss, d, replay=False):
     import oe.path
     import subprocess
+    import json
 
     sstateinst = d.getVar("SSTATE_INSTDIR")
     d.setVar('SSTATE_FIXMEDIR', ss['fixmedir'])
@@ -402,6 +476,17 @@ def sstate_installpkgdir(ss, d):
 
     sstate_install(ss, d)
 
+    if replay:
+        logfp = os.path.join(sstateinst, "sstate-log.json")
+        if os.path.exists(logfp):
+            with open(logfp, 'r') as logfile:
+                logdata = json.load(logfile)
+            records = logdata.get('tasks', {}).get(d.getVar('BB_RUNTASK').removesuffix('_setscene'), [])
+            for logentry in records:
+                sstate_log_emit(d, logentry)
+
+        bb.utils.remove(logfp)
+
     return True
 
 python sstate_hardcode_path_unpack () {
@@ -686,7 +771,7 @@ def sstate_package(ss, d):
     if d.getVar('SSTATE_SKIP_CREATION') == '1':
         return
 
-    sstate_create_package = ['sstate_report_unihash', 'sstate_create_and_sign_package']
+    sstate_create_package = ['sstate_report_unihash', 'sstate_save_task_log', 'sstate_create_and_sign_package']
 
     for f in (d.getVar('SSTATECREATEFUNCS') or '').split() + \
              sstate_create_package + \
Signature · 1 line
2.47.3
#2 lore raw

RFC PATCH v2 2/3 sstate: Replay the records of tasks covered by setscene

In reply to Mathieu Dubois-Briand

Tasks which are not sstate tasks (do_configure, do_compile, do_install) are skipped when covered by a setscene task, so their messages were never shown again on sstate reuse.

When creating an sstate package, also bundle the records of the non-sstate tasks this task depends on, from this recipe or from others, read from the location returned by logrecords_path(). On install, replay the records of the covered tasks bitbake assigned to this setscene task through BB_SETSCENE_CLAIMED_TASKS, so each covered task is replayed exactly once even when several setscene tasks cover it.

AI-Generated: Uses opencode (DeepSeek V4 Flash)

---
 meta/classes-global/sstate.bbclass | 103 ++++++++++++++++++++++++++++++-------
 1 file changed, 84 insertions(+), 19 deletions(-)
meta/classes-global/sstate.bbclass +84 -19
index ed88dae17202..c7a21310003c 100644
@@ -206,6 +206,10 @@ def sstate_state_fromvars(d, task = None):
     ss['fixmedir'] = fixmedir
     return ss
 
+def sstate_logrecords_path(d, tid):
+    recordfn, taskname = tid.rsplit(':', 1)
+    return bb.utils.logrecords_path(d, recordfn, taskname)
+
 def sstate_log_strip_paths(d, message):
     import re
 
@@ -239,6 +243,11 @@ def sstate_log_save(d, record):
     levelno, message = record
     return {'levelno': levelno, 'message': sstate_log_strip_paths(d, message)}
 
+def sstate_log_expand(d, logentry):
+    # Archived record (dict) -> raw logstore entry, with path placeholders
+    # expanded back. Inverse of sstate_log_save.
+    return [logentry['levelno'], sstate_log_expand_paths(d, logentry['message'])]
+
 def sstate_log_emit(d, logentry):
     levelno = logentry.get('levelno', 0)
     if levelno < bb.msg.BBLogFormatter.WARNONCE or "message" not in logentry:
@@ -253,24 +262,84 @@ def sstate_log_emit(d, logentry):
     else:
         bb.warn(message)
 
-python sstate_save_task_log () {
+def sstate_replay_logs(d, logdata):
+    """Replay the log records of the tasks this setscene task was handed via
+    BB_SETSCENE_CLAIMED_TASKS, plus its own task.
+
+    Fold each task's records back into the shared logstore (always, even
+    empty, to clear a stale entry from an earlier native run), so an sstate
+    archive created later in this build still bundles them although the
+    tasks were restored rather than run natively. Then emit them for the
+    user.
+    """
     import json
 
-    # Save the messages logged by this task, so they can be replayed when the
-    # task is restored from sstate. The records are written by bitbake right
-    # after the task body, before the postfuncs.
-    mytask = d.getVar('BB_RUNTASK')
-    recordsfn = os.path.join(d.getVar('T'), 'logrecords.%s.json' % mytask)
-    if not os.path.exists(recordsfn):
-        return
-    with open(recordsfn) as f:
-        records = json.load(f)
+    claimed = (d.getVar('BB_SETSCENE_CLAIMED_TASKS') or '').split()
+    filename = d.getVar('BB_FILENAME', False)
+    claimed.append((filename + ":" if filename else "") +
+                   d.getVar('BB_RUNTASK').removesuffix('_setscene'))
+
+    records = []
+    for task in claimed:
+        taskrecords = logdata.get('tasks', {}).get(task, [])
+        logrecordsfn = sstate_logrecords_path(d, task)
+        bb.utils.mkdirhier(os.path.dirname(logrecordsfn))
+        with open(logrecordsfn, 'w') as f:
+            json.dump([sstate_log_expand(d, e)
+                       for e in taskrecords
+                       if 'levelno' in e and 'message' in e], f)
+        records += taskrecords
+    for logentry in records:
+        sstate_log_emit(d, logentry)
+
+sstate_replay_logs[vardepsexclude] = "BB_SETSCENE_CLAIMED_TASKS BB_FILENAME BB_RUNTASK"
 
-    tasks = {mytask: [sstate_log_save(d, record) for record in records]}
+python sstate_save_task_log () {
+    import json
 
-    logfn = os.path.join(d.getVar('SSTATE_BUILDDIR'), "sstate-log.json")
-    with open(logfn, 'w') as f:
-        json.dump({'tasks': tasks}, f)
+    # Also bundle the messages of the non-sstate tasks we depend on, from this
+    # recipe or from others: they are skipped when restored from sstate, and
+    # bitbake picks which setscene task claims them (BB_SETSCENE_CLAIMED_TASKS).
+    taskdepdata = d.getVar('BB_TASKDEPDATA', False) or {}
+    sstatetasks = d.getVar('SSTATETASKS').split()
+    mytask = d.getVar('BB_RUNTASK')
+    # The running task is always an entry in taskdepdata, under its own tid.
+    # Reconstruct that tid from BB_FILENAME and BB_RUNTASK.
+    filename = d.getVar('BB_FILENAME', False)
+    start = filename + ":" + mytask if filename else None
+    if start not in taskdepdata:
+        bb.fatal("sstate: cannot identify task %s in taskdepdata" % start)
+
+    loggedtasks = {start}
+    seen = {start}
+    todo = [start]
+    while todo:
+        for dep in taskdepdata[todo.pop()].deps:
+            t = taskdepdata[dep]
+            if dep in seen or t.taskname in sstatetasks:
+                continue
+            seen.add(dep)
+            todo.append(dep)
+            loggedtasks.add(dep)
+
+    # Every task writes its records right after its body, before its postfuncs, to
+    # the location returned by logrecords_path(), so the files of all dependencies,
+    # including from other recipes, exist here.
+    tasklogs = {}
+    for tid in loggedtasks:
+        recordsfn = sstate_logrecords_path(d, tid)
+        if os.path.exists(recordsfn):
+            with open(recordsfn) as f:
+                tasklogs[tid] = json.load(f)
+
+    tasks = {}
+    for tid, records in tasklogs.items():
+        tasks[tid] = [sstate_log_save(d, record) for record in records]
+
+    if tasks:
+        logfn = os.path.join(d.getVar('SSTATE_BUILDDIR'), "sstate-log.json")
+        with open(logfn, 'w') as f:
+            json.dump({'tasks': tasks}, f)
 }
 
 def sstate_add(ss, source, dest, d):
@@ -480,11 +549,7 @@ def sstate_installpkgdir(ss, d, replay=False):
         logfp = os.path.join(sstateinst, "sstate-log.json")
         if os.path.exists(logfp):
             with open(logfp, 'r') as logfile:
-                logdata = json.load(logfile)
-            records = logdata.get('tasks', {}).get(d.getVar('BB_RUNTASK').removesuffix('_setscene'), [])
-            for logentry in records:
-                sstate_log_emit(d, logentry)
-
+                sstate_replay_logs(d, json.load(logfile))
         bb.utils.remove(logfp)
 
     return True
Signature · 1 line
2.47.3
#3 lore raw

RFC PATCH v2 3/3 oeqa/sstatetests: Add tests for sstate log replay

In reply to Mathieu Dubois-Briand

Add a selftest suite covering the sstate log replay feature:

- warnings saved by a task are replayed once, with their severity and odd content (newlines, '@', non-ASCII) intact;
- warnings of non-sstate tasks (do_compile) are replayed exactly once even when several setscene tasks cover them;
- warnings of a task from another recipe, covered only by a given sstate task, are replayed;
- error and erroronce messages are replayed at ERROR level and fail the build;
- paths in replayed messages refer to the build doing the replay, not the one that populated the sstate cache.

Four selftest recipes emit the messages, including a shell task (do_emit_shell_log) to cover bbwarn output.

AI-Generated: Uses opencode (DeepSeek V4 Flash)

---
 .../recipes-test/log-replay/log-replay-dep.bb      |  18 +++
 .../log-replay/log-replay-error-test.bb            |  16 ++
 .../recipes-test/log-replay/log-replay-test.bb     |  34 ++++
 .../recipes-test/log-replay/log-replay-user.bb     |  32 ++++
 meta/lib/oeqa/selftest/cases/sstatetests.py        | 171 +++++++++++++++++++++
 5 files changed, 271 insertions(+)
meta-selftest/recipes-test/log-replay/log-replay-dep.bb new file +18 -0
new file mode 100644
index 000000000000..53f473f78109
@@ -0,0 +1,18 @@
+SUMMARY = "Recipe emitting a warning from a task covered by another recipe's setscene, used to test sstate log replay"
+LICENSE = "MIT"
+LIC_FILES_CHKSUM = "file://${COMMON_LICENSE_DIR}/MIT;md5=0835ade698e0bcf8506ecda2f7b4f302"
+
+inherit native nospdx
+
+INHIBIT_DEFAULT_DEPS = "1"
+EXCLUDE_FROM_WORLD = "1"
+
+do_patch[noexec] = "1"
+do_patch[depends] = ""
+
+# This recipe has no sstate tasks of its own: when log-replay-user is
+# rebuilt from sstate, this task can only be restored (covered) by the user
+# recipe's setscene, which must replay its warning.
+python do_compile() {
+    bb.warn("log-replay-dep-warn")
+}
meta-selftest/recipes-test/log-replay/log-replay-error-test.bb new file +16 -0
new file mode 100644
index 000000000000..d95d8d1c6f42
@@ -0,0 +1,16 @@
+SUMMARY = "Recipe emitting error-level logs, used to test sstate log replay severity"
+LICENSE = "MIT"
+LIC_FILES_CHKSUM = "file://${COMMON_LICENSE_DIR}/MIT;md5=0835ade698e0bcf8506ecda2f7b4f302"
+
+inherit native nospdx
+
+INHIBIT_DEFAULT_DEPS = "1"
+EXCLUDE_FROM_WORLD = "1"
+
+do_patch[noexec] = "1"
+do_patch[depends] = ""
+
+python do_populate_sysroot:append() {
+    bb.error("log-replay-error-plain")
+    bb.erroronce("log-replay-erroronce")
+}
meta-selftest/recipes-test/log-replay/log-replay-test.bb new file +34 -0
new file mode 100644
index 000000000000..56e43021de13
@@ -0,0 +1,34 @@
+SUMMARY = "Recipe emitting log messages, used to test sstate log replay"
+LICENSE = "MIT"
+LIC_FILES_CHKSUM = "file://${COMMON_LICENSE_DIR}/MIT;md5=0835ade698e0bcf8506ecda2f7b4f302"
+
+inherit native nospdx
+
+INHIBIT_DEFAULT_DEPS = "1"
+EXCLUDE_FROM_WORLD = "1"
+
+do_patch[noexec] = "1"
+do_patch[depends] = ""
+
+python do_compile() {
+    bb.warn("log-replay-compile-warn")
+}
+
+python do_populate_sysroot:append() {
+    bb.warn("log-replay-python-warn tmpdir=%s dl_dir=%s" % (d.getVar("TMPDIR"), d.getVar("DL_DIR")))
+    bb.warnonce("log-replay-python-warnonce")
+    bb.warn("log-replay-odd: line1\nline2 with @ sign and caf\u00e9")
+}
+
+do_emit_shell_log() {
+    bbwarn "log-replay-shell-warn"
+}
+do_emit_shell_log[sstate-inputdirs] = ""
+do_emit_shell_log[sstate-outputdirs] = ""
+addtask emit_shell_log after do_install before do_build
+
+SSTATETASKS += "do_emit_shell_log"
+python do_emit_shell_log_setscene() {
+    sstate_setscene(d)
+}
+addtask do_emit_shell_log_setscene
meta-selftest/recipes-test/log-replay/log-replay-user.bb new file +32 -0
new file mode 100644
index 000000000000..b83940eabb29
@@ -0,0 +1,32 @@
+SUMMARY = "Recipe depending on log-replay-dep, used to test cross-recipe sstate log replay"
+LICENSE = "MIT"
+LIC_FILES_CHKSUM = "file://${COMMON_LICENSE_DIR}/MIT;md5=0835ade698e0bcf8506ecda2f7b4f302"
+
+inherit native nospdx
+
+INHIBIT_DEFAULT_DEPS = "1"
+EXCLUDE_FROM_WORLD = "1"
+
+do_patch[noexec] = "1"
+do_patch[depends] = ""
+
+DEPENDS = "log-replay-dep"
+
+# Pull log-replay-dep's do_compile into this recipe's dependency closure, so
+# it is covered by this recipe's setscene and replayed when restored.
+do_compile[depends] += "log-replay-dep:do_compile"
+
+# An sstate task of its own, so a rebuild of this recipe is served from the
+# sstate cache by its setscene.
+do_sstate_data() {
+    :
+}
+do_sstate_data[sstate-inputdirs] = ""
+do_sstate_data[sstate-outputdirs] = ""
+addtask sstate_data after do_compile before do_build
+
+SSTATETASKS += "do_sstate_data"
+python do_sstate_data_setscene() {
+    sstate_setscene(d)
+}
+addtask do_sstate_data_setscene
meta/lib/oeqa/selftest/cases/sstatetests.py +171 -0

177 lines not on this page · raw message

Signature · 1 line
2.47.3