Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions app/src/main/assets/runtime-descriptor.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"version": 1,
"runtimeId": "4d55973d407c171909e76d07f0b681de4069613944fb05e29cd38908e0984a26",
"runtimeId": "2f864e5a79925ca6185f961aba46325f4a6469551c789c3cdc4965c9fe4f988a",
"baseVersion": "10",
"dshVersion": "0.2.2-rc.1",
"launcherContract": "DSHA_ARM64_V2",
Expand Down Expand Up @@ -38,14 +38,14 @@
"backup/AutomaticBackupPruner.java": "47f1578c5306c7a1336e0840e74c84ad8708ffa7f044f6f987dd06481748d003",
"backup/AutomaticBackupService.java": "ef6dc7ef60a417ee7360723d6b7fc004443e3c2c9e1ef65b91fdd3de13e6ccdf",
"backup/AutomaticBackups.java": "0aebbf0c8024812ac5f0dabae4808871b9583916ed589d5fdbda2c6cae881c0f",
"backup/BackupArchive.java": "e58ed4cce5fcbb982bd685d1d52fdfb25c10c351dc54024d616b9493ee48e4b2",
"backup/BackupArchive.java": "e5ac2b8523c54758e579a61e252cd7762ae88734e43d8a7201668c46ae257291",
"backup/BackupControl.java": "4ead9fa1e423963c9d4bba7165f9035453cb979369de6743a39fd6a3dc105cf7",
"backup/BackupDirectoryTarget.java": "919ebf8119c8dd6f2737acd8bc832c1aaaffbcc861c1cd707db843085ba3123e",
"backup/BackupErrorCode.java": "89d2083f7598c56d9e2dc55dfdb2ec1d6bbcc2a8f82bf538fa0575e1c6fc2122",
"backup/BackupFailureDiagnostic.java": "4b0794790c2241f31bce3318f8095cbd4040a0fa0be5b90a535ddba7a75f5426",
"backup/BackupFailureDiagnostic.java": "7cc03be32d9635f1a71e818a5bdb41128a1f014ef3c5edc0274cc2f5a7b7432a",
"backup/BackupFileSystem.java": "d6ecbe7c2e0d02d0c608406e95df7030d2f6e241f90b868e430606b054c527f1",
"backup/BackupJson.java": "24839a2633247967fd37644e239f9430587eb0803df198ea8d48c949bbfb229a",
"backup/BackupLimits.java": "20ea4d678002c82fd6d1b815383a0d242fd66abcfd25688bda3aeb4d9cb2c1d9",
"backup/BackupLimits.java": "f19984c7e48e9569d9a1551769de76147a56a41e2878cc711355a9c7e9114aa6",
"backup/BackupOperationDiagnostics.java": "50b202d68ea4797a9441433372cf991bd751fe5da025b057d96073cff347b106",
"backup/BackupPreview.java": "7880b097bc81649e47487d93c3308448e9c8b7e94b91382d10ffd151ca3faebf",
"backup/BackupSource.java": "5dd846282c0ab73e48d2c10f0ecf5afdfaf2cf45906122f2d42675f60af98775",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -326,10 +326,17 @@ private static final class Index {

void add(Record record, int length) throws IOException {
if (++count > BackupLimits.ENTRIES) throw new IOException("ENTRY_LIMIT");
metadata = (int) BackupLimits.add(metadata, length, BackupLimits.METADATA);
bytes = BackupLimits.add(bytes, record.size, BackupLimits.BYTES);
metadata =
(int)
BackupLimits.add(
metadata, length, BackupLimits.METADATA, BackupLimits.Measure.METADATA_BYTES);
bytes =
BackupLimits.add(
bytes, record.size, BackupLimits.BYTES, BackupLimits.Measure.PAYLOAD_BYTES);
String key = BackupLimits.collisionKey(record.root, record.path);
keys = BackupLimits.add(keys, key.length() * 2L, 8L * 1024 * 1024);
keys =
BackupLimits.add(
keys, key.length() * 2L, 8L * 1024 * 1024, BackupLimits.Measure.PATH_INDEX_BYTES);
if (!paths.add(key)) throw new IOException("DUPLICATE_PATH");
roots.add(record.root);
scopes.computeIfAbsent(record.root, ignored -> new HashSet<>()).add(record.scope);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,10 @@
import java.util.Set;

/** Backup failure location without exception messages, source paths, URIs or user content. */
final class BackupFailureDiagnostic {
public final class BackupFailureDiagnostic {
private BackupFailureDiagnostic() {}

static String describe(String stage, Throwable error) {
public static String describe(String stage, Throwable error) {
StringBuilder result = new StringBuilder("stage=").append(code(stage));
Set<Throwable> seen = Collections.newSetFromMap(new IdentityHashMap<>());
append(result, error, "cause", seen);
Expand All @@ -19,6 +19,23 @@ private static void append(
StringBuilder result, Throwable at, String relation, Set<Throwable> seen) {
if (at == null || seen.size() >= 8 || !seen.add(at)) return;
result.append(' ').append(relation).append('=').append(symbol(at.getClass().getName()));
if (at instanceof BackupLimits.LimitExceeded limit) {
result
.append(" limitMeasure=")
.append(limit.measure == null ? "QUANTITY" : limit.measure.name())
.append(" limitCurrent=")
.append(limit.current)
.append(" limitIncrement=")
.append(limit.increment)
.append(" limitMaximum=")
.append(limit.maximum);
// 不相加请求总量:它可能溢出。无效计量不伪造一个超额值。
if (limit.current >= 0 && limit.maximum >= limit.current && limit.increment >= 0) {
long remaining = limit.maximum - limit.current;
if (limit.increment > remaining)
result.append(" limitExcess=").append(limit.increment - remaining);
}
}
if ("android.system.ErrnoException".equals(at.getClass().getName())) {
try {
result.append(" errno=").append(at.getClass().getField("errno").getInt(at));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,33 @@ public static String root(String value) throws IOException {
}

public static long add(long current, long next, long maximum) throws IOException {
if (next < 0 || current < 0 || next > maximum - current) throw new IOException("ARCHIVE_LIMIT");
return add(current, next, maximum, Measure.QUANTITY);
}

enum Measure {
QUANTITY,
METADATA_BYTES,
PAYLOAD_BYTES,
PATH_INDEX_BYTES
}

/** 只携带固定类型和计量,不从异常正文解析用户数据。 */
static final class LimitExceeded extends IOException {
final long current, increment, maximum;
final Measure measure;

LimitExceeded(long current, long increment, long maximum, Measure measure) {
super("ARCHIVE_LIMIT");
this.current = current;
this.increment = increment;
this.maximum = maximum;
this.measure = measure;
}
}

static long add(long current, long next, long maximum, Measure measure) throws IOException {
if (next < 0 || current < 0 || maximum < 0 || current > maximum || next > maximum - current)
throw new LimitExceeded(current, next, maximum, measure);
return current + next;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -244,6 +244,7 @@ static String rebuild(
try {
estimated = data.estimateBytes(workdir, control);
} catch (IOException unreadable) {
recordMaintenanceFailure(controller.context(), "REBUILD_PREFLIGHT_FAILURE", unreadable);
String hint = maintenanceFailureHint(unreadable);
throw new IOException(hint.isEmpty() ? unreadable.getMessage() : hint, unreadable);
}
Expand Down Expand Up @@ -366,6 +367,7 @@ public void accept(Long done, Long total) {
} catch (Exception retained) {
failure.addSuppressed(retained);
}
recordMaintenanceFailure(controller.context(), "REBUILD_FAILURE", failure);
String hint = maintenanceFailureHint(failure);
throw new IOException(
(hint.isEmpty() ? "" : hint + "\n")
Expand All @@ -378,6 +380,21 @@ public void accept(Long done, Long total) {
}
}

/** 记录失败也不能替换维护异常或妨碍原件保留;阶段只使用本机固定值。 */
static void recordMaintenanceFailure(
android.content.Context context, String stage, Throwable failure) {
String event =
"REBUILD_PREFLIGHT_FAILURE".equals(stage) ? "REBUILD_PREFLIGHT_FAILURE" : "REBUILD_FAILURE";
try {
DiagnosticLog.record(
context,
event,
com.deepseekharness.app.backup.BackupFailureDiagnostic.describe(event, failure));
} catch (RuntimeException unavailable) {
// 诊断尽力保存,原始失败及回滚结论由原调用链继续处理。
}
}

private static void requireSpace(File files, long required) throws IOException {
long available = files.getUsableSpace();
requireSpace(available, required);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,70 @@
import org.junit.Test;

public final class BackupFailureDiagnosticTest {
private static IOException exceeded(long current, long next, long maximum) {
try {
BackupLimits.add(current, next, maximum);
throw new AssertionError("Expected the existing archive limit to refuse");
} catch (IOException expected) {
return expected;
}
}

@Test
public void archiveLimitIncludesSafeQuantitiesWithoutChangingItsErrorCode() {
IOException failure = exceeded(10, 5, 12);
assertEquals("ARCHIVE_LIMIT", failure.getMessage());
assertEquals("ARCHIVE_LIMIT", BackupErrorCode.from(failure));
String diagnostic = BackupFailureDiagnostic.describe("CAPTURING", failure);
assertTrue(diagnostic, diagnostic.contains("limitCurrent=10"));
assertTrue(diagnostic, diagnostic.contains("limitIncrement=5"));
assertTrue(diagnostic, diagnostic.contains("limitMaximum=12"));
assertTrue(diagnostic, diagnostic.contains("limitExcess=3"));
}

@Test
public void wrappedArchiveLimitKeepsNumbersButOmitsPrivateOuterMessage() {
IOException outer = new IOException("/private/chat token=secret", exceeded(20, 8, 25));
String diagnostic = BackupFailureDiagnostic.describe("CAPTURING", outer);
assertTrue(diagnostic, diagnostic.contains("limitMaximum=25"));
assertTrue(diagnostic, diagnostic.contains("limitExcess=3"));
assertFalse(diagnostic.contains("secret"));
assertFalse(diagnostic.contains("/private"));
}

@Test
public void limitExcessDoesNotOverflowWhenRequestedTotalWouldOverflow() {
String diagnostic =
BackupFailureDiagnostic.describe(
"CAPTURING", exceeded(Long.MAX_VALUE - 2, 5, Long.MAX_VALUE));
assertTrue(diagnostic, diagnostic.contains("limitExcess=3"));
assertTrue(diagnostic, diagnostic.contains("limitMaximum=" + Long.MAX_VALUE));
}

@Test
public void fixedMeasuresIdentifyTheLimitWithoutReadingMessages() {
for (BackupLimits.Measure measure : BackupLimits.Measure.values()) {
try {
BackupLimits.add(2, 2, 3, measure);
fail("Expected limit refusal");
} catch (IOException expected) {
String diagnostic = BackupFailureDiagnostic.describe("CAPTURING", expected);
assertTrue(diagnostic, diagnostic.contains("limitMeasure=" + measure.name()));
assertEquals("ARCHIVE_LIMIT", BackupErrorCode.from(expected));
}
}
}

@Test
public void equalLimitSucceedsAndNegativeInputsRemainRefused() throws Exception {
assertEquals(12, BackupLimits.add(10, 2, 12));
for (long[] values : new long[][] {{-1, 1, 12}, {1, -1, 12}, {1, 0, Long.MIN_VALUE}}) {
IOException refused = exceeded(values[0], values[1], values[2]);
assertEquals("ARCHIVE_LIMIT", BackupErrorCode.from(refused));
assertFalse(BackupFailureDiagnostic.describe("CAPTURING", refused).contains("limitExcess="));
}
}

@Test
public void localizedFailureShowsProjectBoundaryWithoutMessageOrPath() {
IOException error = new IOException("等待 /private/user/conversation?token=secret 的进程停止");
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
package com.deepseekharness.app.core;

import static org.junit.Assert.*;
import android.content.Context;
import com.deepseekharness.app.backup.BackupLimits;
import java.io.IOException;
import java.lang.reflect.Method;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.annotation.Config;
import org.robolectric.annotation.Implementation;
import org.robolectric.annotation.Implements;

/** 只验证维护错误到安全诊断记录器的接线,不执行真实环境重建。 */
@RunWith(RobolectricTestRunner.class)
@Config(
sdk = 34,
manifest = Config.NONE,
application = android.app.Application.class,
shadows = EnvironmentMaintenanceFailureTest.Log.class)
public final class EnvironmentMaintenanceFailureTest {
@Implements(value = DiagnosticLog.class, isInAndroidSdk = false)
public static class Log {
static String stage, summary;
static boolean failWrite;

@Implementation
protected static void record(Context context, String event, String message) {
stage = event;
summary = message;
if (failWrite) throw new IllegalStateException("synthetic log failure");
}
}

private static void record(String stage, Throwable failure) throws Exception {
Method method;
try {
method =
EnvironmentMaintenance.class.getDeclaredMethod(
"recordMaintenanceFailure", Context.class, String.class, Throwable.class);
} catch (NoSuchMethodException missing) {
throw new AssertionError("MAINTENANCE_FAILURE_RECORDING_NOT_CONNECTED", missing);
}
method.setAccessible(true);
method.invoke(null, RuntimeEnvironment.getApplication(), stage, failure);
}

private static IOException limit() {
try {
BackupLimits.add(10, 5, 12);
throw new AssertionError("Expected archive limit");
} catch (IOException expected) {
return expected;
}
}

@Test
public void rebuildFailureRecordsSafeQuantitiesAndTheFixedStage() throws Exception {
Log.failWrite = false;
record("REBUILD_FAILURE", limit());
assertEquals("REBUILD_FAILURE", Log.stage);
assertTrue(Log.summary, Log.summary.contains("limitMaximum=12"));
assertTrue(Log.summary, Log.summary.contains("limitExcess=3"));
}

@Test
public void preflightDiagnosticRecordDoesNotReadPrivateExceptionMessage() throws Exception {
Log.failWrite = false;
IOException failure =
new IOException("private token=synthetic", limit()) {
@Override
public String getMessage() {
throw new AssertionError("Must not read exception message");
}
};
record("REBUILD_PREFLIGHT_FAILURE", failure);
assertEquals("REBUILD_PREFLIGHT_FAILURE", Log.stage);
assertTrue(Log.summary.contains("limitMaximum=12"));
assertFalse(Log.summary.contains("synthetic"));
assertFalse(Log.summary.contains("token="));
}

@Test
public void logFailureDoesNotReplaceTheOriginalOperationFailure() throws Exception {
IOException failure = limit();
Log.failWrite = true;
try {
record("REBUILD_FAILURE", failure);
assertEquals("ARCHIVE_LIMIT", failure.getMessage());
assertNull(failure.getCause());
} finally {
Log.failWrite = false;
}
}
}
19 changes: 19 additions & 0 deletions docs/backup-limit-diagnostics.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
# 归档限额的安全诊断(关联 #225)

`ARCHIVE_LIMIT` 是错误类别,不能直接解读为某个固定归档大小。当前源码的载荷字节数、元数据字节数和路径索引计量都可能触发该代码;仅凭报告中的归档体积无法判断触发项。本次不改变合法输入的原有限额,也不宣称复现旧发布包的重建现场。

`BackupLimits` 的加法限额失败保留 `IOException` 与 `ARCHIVE_LIMIT` 错误码,同时在固定类型中保存计量。安全诊断仅读取该最终类型的固定枚举与整数,不解析异常正文、源路径、URI、文件名或用户内容。

| 字段 | 含义 |
| --- | --- |
| `limitMeasure` | `METADATA_BYTES`、`PAYLOAD_BYTES`、`PATH_INDEX_BYTES`,其他调用为 `QUANTITY` |
| `limitCurrent` | 失败前累计值 |
| `limitIncrement` | 本次准备增加的值 |
| `limitMaximum` | 该计量上限 |
| `limitExcess` | 本次增加量超过剩余额度的差值,仅在非负有效计量时给出 |

`QUANTITY` 不保证单位为字节,不能将所有字段都显示成归档大小。计算差值时不相加请求总量,避免接近 long 上限时溢出。负计量或无效上限按失败处理,不伪造一个超额值。

环境重建的预估失败和主流程失败分别以 `REBUILD_PREFLIGHT_FAILURE`、`REBUILD_FAILURE` 写入私有诊断记录。日志尽力保存,记录端的普通运行时异常不会替换原来的维护失败;原有错误包装与回滚逻辑保留。备份作业也继续通过同一安全描述器记录线索。

此改动不包含 `LegacyTarReader` 直接抛出的头部限制、其他独立的 `ENTRY_LIMIT` 等错误,也不修复 #225 的 `PARENT_LINK`、新增放弃重建入口或修改保护阈值。源码回归不等于真实环境重建、数据恢复或设备验收;最终测试与审查证据见本 PR 的说明。
26 changes: 26 additions & 0 deletions docs/superpowers/plans/2026-12-03-archive-limit-diagnostics.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# 归档限额安全诊断计划(关联 #225)

目标:区分归档载荷、元数据和路径索引限制,并给出安全数值线索,不放宽上限,不读取异常正文,不宣称复现用户现场。

基线:官方 main cf2a6a9。独立分支 codex/issue225-limit-diagnostics-20261203;仅云端执行项目测试。

设计:BackupLimits 用固定错误码的专用 IOException 保存固定枚举和原始计量;BackupFailureDiagnostic 只读该最终类型的固定字段。在 BackupArchive 索引的三项上限处显式选择计量类型。超过值用 increment 减剩余额度计算,避免请求总量相加溢出。错误码仍为 ARCHIVE_LIMIT,限额和事务行为不变。

- [x] 核对报告与代码,确认同一错误码覆盖多个限制,报告体积不能直接确定触发项。
- [x] 添加三项使用现有生产入口的反例,8e8d204 已推送;自动 Source47031617752 运行中。
- [x] 确认实际拒绝断言失败后再实现:47031617752,4498 项中仅新增 3 项断言失败,0 errors/skips。
- [x] 实现固定类型、诊断字段和三项索引计量名称,补边界及隐私测试。9c5d986 / 47032810793 定向 24 项通过、0 failures/errors/skips。
- [x] 修复独立审查指出的 P1:环境重建预估及主失败 catch 未记录新增字段;增加安全日志适配器并覆盖隐私与记录异常。
- [ ] 官方格式化/描述符生成、定向与相关回归通过,全部 diff 独立审查后提交 PR。

不包含 PARENT_LINK、放弃重建入口、修改保护阈值或旧包修复。现有诊断对异常正文不取值的边界必须保留;不能把本地合成测试等同于真实设备重建验收。

Ruling: 合法非负计量的现有限额完全保持;额外拒绝负 maximum 和已越过 maximum 的计量,避免差值在无效输入下溢出后误放行。超额数仅在计量可解释时给出,不为负计量伪造超额值。

审查发现 BackupFailureDiagnostic 原来只在备份作业使用,不能用其单测声称重建失败已经可诊断。将类与 describe 暴露为纯逻辑安全入口,core 通过固定阶段的包级日志适配器调用。Robolectric 使用受控 DiagnosticLog 验证适配器,不声称完整重建或回滚链路的设备验收。

## 增量证据

- a0fa068 / [47033418917](https://github.com/lzh2034855417-beep/DSHA/actions/runs/47033418917):27 项中仅新增记录适配器的 3 项契约断言失败,0 errors/skips,属于接线 API 契约反例。
- f364bdb / [47034023852](https://github.com/lzh2034855417-beep/DSHA/actions/runs/47034023852):27 项全部通过,0 failures/errors/skips;官方规范化与描述符生成成功。规范化差异已逐文件检查;描述符仅改变三份 backup 源摘要及对应 runtimeId,输入资产和基础环境版本不变。
- EnvironmentMaintenance 的完整成功提示段落未改变。仅同步其已审查文案特例的整文件 SHA,不改变签名、次数或检查政策。此类精确摘要不能替代完整 APK 的身份。
Loading