Skip to content
20 changes: 20 additions & 0 deletions .changeset/34864-seed-unknown-object-save-door.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
---
'@objectstack/metadata-protocol': minor
---

fix(metadata-protocol): the save door refuses a seed whose object does not exist, and the publish probe names a missing object instead of asking to publish again

Clause-②: no (narrowing)
Metadata-protocol: narrowed

**The save door refuses a seed bound to an unknown object.** `saveMetaItem` (the `PUT /api/v1/meta/seed/:name` door, the MCP draft save and every other caller) now answers `422 INVALID_METADATA` for a `seed` whose `object` no package registers and no stored or code-defined object carries, with one finding at `object` that names the seed, the object and the fix. Before this, such a seed was stored 200; its publish answered `published` while the load wrote nothing.

- A draft save also accepts an object that is itself only a draft (it is judged at the seed's publish, as before). A live save needs the object published.
- An object of a dependency package, or any object the registry serves, is accepted as before.
- Unchanged: the publish promotion and the restore doors do not refuse such a seed (the load reports it, and a publish keeps going), and a `migrate-stored` re-save is not judged.

Fix for a refused save: correct `object` to the object's full name (for example `crm_lead`, not `lead`), or create the object first, as a draft for a draft seed or published for a live one.

**The publish probe names a missing object.** When a published seed's object does not exist, the `seed_not_applied` finding now says so: `message` and `fix` name the missing object, and the person's sentence (`userMessage`, cause `missing`, in every platform locale) tells them to correct the object or create and publish it. A read that fails on an object that does exist still asks to publish again (cause `unreadable`).

<!-- adr-0087: registered seed-object-unknown-refused -->
50 changes: 50 additions & 0 deletions packages/metadata-protocol/src/build-probes-user-message.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,8 @@ const ITEMS: Record<string, unknown> = {
},
'object crm_project': { name: 'crm_project', label: PROJECTS, fields: { title: { type: 'text', label: 'Title' } } },
'seed crm_task_seed': { object: 'crm_task', records: [] },
// [#34864] A seed naming an object that does not exist.
'seed crm_nope_seed': { object: 'crm_nope', records: [] },
'view crm_task_list': { name: 'crm_task_list', label: VIEW, object: 'crm_task' },
'dashboard crm_board': {
name: 'crm_board',
Expand Down Expand Up @@ -143,6 +145,13 @@ const engineThrowing: ProbeEngine = {
throw new Error('no such table: crm_task');
},
};
/** [#34864] An engine that answers its registered objects, and registers none: every read is refused. */
const engineWithoutObjects: ProbeEngine = {
find: async (object) => {
throw new Error(`Object '${object}' not found`);
},
getSchema: () => undefined,
};

/** One `where` on one row: equality and `{ $in: [...] }`; any other operator or combinator is refused. */
const matches = (row: Record<string, unknown>, where: Record<string, unknown> | undefined): boolean =>
Expand Down Expand Up @@ -266,6 +275,13 @@ const CASES: readonly ProbeCase[] = [
params: () => ({ object: TASKS, cause: 'unreadable' }),
hidden: ['crm_task'],
},
{
title: 'a seed whose object does not exist',
code: 'seed_not_applied', // adr0112-ok: D6c build-probe diagnostics code
run: probe({ engine: engineWithoutObjects, published: [{ type: 'seed', name: 'crm_nope_seed' }] }),
params: () => ({ object: 'crm_nope', cause: 'missing' }),
hidden: [],
},
{
title: 'a view whose read throws',
code: 'view_read_failed', // adr0112-ok: D6c build-probe diagnostics code
Expand Down Expand Up @@ -550,6 +566,16 @@ describe('every probe finding carries the person\'s sentence, in the request\'s
'“Tasks”的示例数据没有加载成功,所以“Tasks”中还没有任何记录。请检查示例数据,然后重新发布。',
);

// [#34864] An object that does not exist: the sentence names it and the fix, not "publish again" alone.
const missing = byTitle('a seed whose object does not exist');
expect(onlyIssue(await missing.run(['en-US'])).userMessage).toBe(
'The sample data could not load, because "crm_nope" does not exist. Correct the object the sample data '
+ 'names, or create and publish "crm_nope", then publish again.',
);
expect(onlyIssue(await missing.run(['zh-CN'])).userMessage).toBe(
'示例数据无法加载,因为“crm_nope”不存在。请更正示例数据所指的对象,或先创建并发布“crm_nope”,然后重新发布。',
);

const empty = byTitle('a widget whose query returns nothing over an object that has rows');
expect(onlyIssue(await empty.run(['en-US'])).userMessage).toBe(
'The widget "Open tasks" on dashboard "Team board" shows no data, although "Tasks" has records. '
Expand Down Expand Up @@ -773,3 +799,27 @@ describe('the catalog holds exactly the probe\'s codes, each in every platform l
);
});
});

describe('[#34864] a seed\'s object that does not exist is not a read that failed', () => {
const SEED = [{ type: 'seed', name: 'crm_nope_seed' }];

it('names the missing object to the agent, with the fix, and says "missing" to the person', async () => {
const issue = onlyIssue(await runBuildProbes({ engine: engineWithoutObjects, getItem: readItems, published: SEED }));
expect(issue).toMatchObject({ code: 'seed_not_applied', ref: { type: 'object', name: 'crm_nope' } }); // adr0112-ok: D6c build-probe diagnostics code
expect(issue.message).toBe('Seed "crm_nope_seed" was published but loads into object "crm_nope", which does not exist — no record was loaded.');
expect(issue.fix).toBe("Correct the seed's `object` to the object's full name, or create and publish object \"crm_nope\", then republish the seed.");
expect(issue.userMessage).toBe(BUILD_PROBE_USER_TEXT.seed_not_applied.en({ object: 'crm_nope', cause: 'missing' }));
});

it.each<[string, ProbeEngine, GetItem]>([
['the engine registers the object, and its read fails', { ...engineWithoutObjects, getSchema: () => ({ name: 'crm_nope' }) }, readItems],
['the engine cannot answer for its objects (no `getSchema`)', engineThrowing, readItems],
['the engine answers none, but a published object of the name is held', engineWithoutObjects,
async (type, name) => (type === 'object' && name === 'crm_nope' ? { name: 'crm_nope', label: 'Nope' } : readItems(type, name))],
])('CONTROL: %s — still `unreadable`', async (_label, engine, getItem) => {
const issue = onlyIssue(await runBuildProbes({ engine, getItem, published: SEED }));
expect(issue.code).toBe('seed_not_applied'); // adr0112-ok: D6c build-probe diagnostics code
expect(issue.message.startsWith('Seed "crm_nope_seed" probe could not read object "crm_nope": ')).toBe(true);
expect(issue.userMessage).toContain('could not be read after publishing');
});
});
33 changes: 33 additions & 0 deletions packages/metadata-protocol/src/build-probes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -276,6 +276,20 @@ async function hasRows(
return Array.isArray(rows) && rows.length > 0;
}

/**
* [#34864] The engine registers no object of this name: it answers its
* registered objects (`getSchema`) and answers none for this one. An engine
* without the read, or whose read throws, cannot say so, and answers `false`.
*/
function objectIsMissing(engine: ProbeEngine, objectName: string): boolean {
if (typeof engine.getSchema !== 'function') return false;
try {
return !engine.getSchema(objectName);
} catch {
return false;
}
}

/** Rows sampled from an object by the data probes, and distinct values probed per column. */
const PROBE_SAMPLE_ROWS = 50;

Expand Down Expand Up @@ -545,6 +559,25 @@ export async function runBuildProbes(opts: RunBuildProbesOptions): Promise<Build
});
}
} catch (e) {
// [#34864] An object that does not exist is not a read that
// failed: publishing again cannot help, so the finding names the
// missing object and the fix instead. Missing only when the
// engine can answer for its registered objects and answers none,
// and no published object of the name is held either; anything
// else stays `unreadable`.
if (objectIsMissing(engine, objectName) && (await readItem('object', objectName)) === undefined) {
issues.push({
layer: 'runtime',
severity: 'error',
artifact: { type: 'seed', name: p.name },
ref: { type: 'object', name: objectName },
code: 'seed_not_applied',
message: `Seed "${p.name}" was published but loads into object "${objectName}", which does not exist — no record was loaded.`,
fix: `Correct the seed's \`object\` to the object's full name, or create and publish object "${objectName}", then republish the seed.`,
userMessage: say('seed_not_applied', { object: objectName, cause: 'missing' }),
});
continue;
}
issues.push({
layer: 'runtime',
severity: 'error',
Expand Down
61 changes: 48 additions & 13 deletions packages/metadata-protocol/src/build-probes.user-text.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@
*
* | code | params | names |
* |---|---|---|
* | `seed_not_applied` | `object`, `cause` (`no-rows` · `unreadable`) | the seeded object's label; the seed has none |
* | `seed_not_applied` | `object`, `cause` (`no-rows` · `unreadable` · `missing`) | the seeded object's label; the seed has none. `missing` names the object by the API name the seed carries: there is no object to read a label from |
* | `view_read_failed` | `view`, `object` | both labels |
* | `object_field_ref_unknown` | `object` | the object's label |
* | `object_field_ref_rule_failed` | `object` | the object's label |
Expand Down Expand Up @@ -80,68 +80,103 @@ const WIDGET_ON_DASHBOARD: Readonly<Record<PlatformLocaleTag, (p: UserTextParams
ko: (p) => `대시보드 "${p.dashboard}"의 위젯 "${p.widget}"`,
};

/** `seed_not_applied`: the sample data did not land (`no-rows`), or the probe could not look (`unreadable`). */
/**
* `seed_not_applied`: the sample data did not land (`no-rows`), the probe could not look (`unreadable`), or
* [#34864] the object the seed names does not exist (`missing`), so publishing again cannot help.
*/
const SEED_NOT_APPLIED: UserTextEntry = {
en: (p) =>
p.cause === 'unreadable'
p.cause === 'missing'
? `The sample data could not load, because "${p.object}" does not exist. Correct the object the sample ` +
`data names, or create and publish "${p.object}", then publish again.`
: p.cause === 'unreadable'
? `The sample data for "${p.object}" could not be checked, because "${p.object}" could not be read after ` +
`publishing. Publish again, and contact your administrator if it happens again.`
: `The sample data for "${p.object}" did not load, so "${p.object}" has no records yet. Check the sample ` +
`data, then publish again.`,
'zh-Hans': (p) =>
p.cause === 'unreadable'
p.cause === 'missing'
? `示例数据无法加载,因为“${p.object}”不存在。请更正示例数据所指的对象,或先创建并发布“${p.object}”,然后重新发布。`
: p.cause === 'unreadable'
? `无法检查“${p.object}”的示例数据,因为发布后无法读取“${p.object}”。请重新发布;如果问题再次出现,请联系管理员。`
: `“${p.object}”的示例数据没有加载成功,所以“${p.object}”中还没有任何记录。请检查示例数据,然后重新发布。`,
'zh-Hant': (p) =>
p.cause === 'unreadable'
p.cause === 'missing'
? `示例資料無法載入,因為「${p.object}」不存在。請更正示例資料所指的物件,或先建立並發布「${p.object}」,然後重新發布。`
: p.cause === 'unreadable'
? `無法檢查「${p.object}」的示例資料,因為發布後無法讀取「${p.object}」。請重新發布;如果問題再次出現,請聯絡管理員。`
: `「${p.object}」的示例資料沒有載入成功,所以「${p.object}」中還沒有任何記錄。請檢查示例資料,然後重新發布。`,
es: (p) =>
p.cause === 'unreadable'
p.cause === 'missing'
? `Los datos de ejemplo no se pudieron cargar, porque "${p.object}" no existe. Corrija el objeto que indican ` +
`los datos de ejemplo, o cree y publique "${p.object}", y vuelva a publicar.`
: p.cause === 'unreadable'
? `No se pudieron comprobar los datos de ejemplo de "${p.object}", porque no se pudo leer "${p.object}" ` +
`después de publicar. Vuelva a publicar y, si ocurre de nuevo, póngase en contacto con su administrador.`
: `Los datos de ejemplo de "${p.object}" no se cargaron, por lo que "${p.object}" aún no tiene registros. ` +
`Revise los datos de ejemplo y vuelva a publicar.`,
ar: (p) =>
p.cause === 'unreadable'
p.cause === 'missing'
? `تعذّر تحميل البيانات التجريبية، لأن "${p.object}" غير موجود. صحّح الكائن الذي تشير إليه البيانات التجريبية، ` +
`أو أنشئ "${p.object}" وانشره، ثم أعد النشر.`
: p.cause === 'unreadable'
? `تعذّر التحقق من البيانات التجريبية لـ "${p.object}"، لأنه تعذّرت قراءة "${p.object}" بعد النشر. ` +
`أعد النشر، وإذا تكرر ذلك فتواصل مع المسؤول.`
: `لم يتم تحميل البيانات التجريبية لـ "${p.object}"، لذلك لا يحتوي "${p.object}" على أي سجلات بعد. ` +
`راجع البيانات التجريبية ثم أعد النشر.`,
fr: (p) =>
p.cause === 'unreadable'
p.cause === 'missing'
? `Les données d’exemple n’ont pas pu être chargées, car « ${p.object} » n’existe pas. Corrigez l’objet ` +
`indiqué par les données d’exemple, ou créez et publiez « ${p.object} », puis publiez à nouveau.`
: p.cause === 'unreadable'
? `Les données d’exemple de « ${p.object} » n’ont pas pu être vérifiées, car « ${p.object} » n’a pas pu ` +
`être lu après la publication. Publiez à nouveau et, si cela se reproduit, contactez votre administrateur.`
: `Les données d’exemple de « ${p.object} » n’ont pas été chargées ; « ${p.object} » ne contient donc ` +
`encore aucun enregistrement. Vérifiez les données d’exemple, puis publiez à nouveau.`,
'pt-BR': (p) =>
p.cause === 'unreadable'
p.cause === 'missing'
? `Os dados de exemplo não puderam ser carregados, porque "${p.object}" não existe. Corrija o objeto ` +
`indicado nos dados de exemplo, ou crie e publique "${p.object}", e publique novamente.`
: p.cause === 'unreadable'
? `Não foi possível verificar os dados de exemplo de "${p.object}", porque não foi possível ler ` +
`"${p.object}" após a publicação. Publique novamente e, se acontecer de novo, entre em contato com o ` +
`administrador.`
: `Os dados de exemplo de "${p.object}" não foram carregados, então "${p.object}" ainda não tem registros. ` +
`Verifique os dados de exemplo e publique novamente.`,
ru: (p) =>
p.cause === 'unreadable'
p.cause === 'missing'
? `Примеры данных не удалось загрузить: объекта «${p.object}» не существует. Исправьте объект, указанный ` +
`в примерах данных, или создайте и опубликуйте «${p.object}», затем опубликуйте снова.`
: p.cause === 'unreadable'
? `Не удалось проверить примеры данных для объекта «${p.object}»: после публикации объект «${p.object}» ` +
`не удалось прочитать. Опубликуйте снова, а если это повторится, обратитесь к администратору.`
: `Примеры данных для объекта «${p.object}» не загрузились, поэтому в объекте «${p.object}» пока нет ` +
`записей. Проверьте примеры данных и опубликуйте снова.`,
de: (p) =>
p.cause === 'unreadable'
p.cause === 'missing'
? `Die Beispieldaten konnten nicht geladen werden, weil „${p.object}“ nicht existiert. Korrigieren Sie das ` +
`Objekt, das die Beispieldaten nennen, oder erstellen und veröffentlichen Sie „${p.object}“, und ` +
`veröffentlichen Sie dann erneut.`
: p.cause === 'unreadable'
? `Die Beispieldaten für „${p.object}“ konnten nicht geprüft werden, weil „${p.object}“ nach dem ` +
`Veröffentlichen nicht gelesen werden konnte. Veröffentlichen Sie erneut und wenden Sie sich an Ihren ` +
`Administrator, wenn das wieder passiert.`
: `Die Beispieldaten für „${p.object}“ wurden nicht geladen, daher enthält „${p.object}“ noch keine ` +
`Datensätze. Prüfen Sie die Beispieldaten und veröffentlichen Sie dann erneut.`,
ja: (p) =>
p.cause === 'unreadable'
p.cause === 'missing'
? `「${p.object}」が存在しないため、サンプルデータを読み込めませんでした。サンプルデータが指すオブジェクトを` +
`修正するか、「${p.object}」を作成して公開してから、もう一度公開してください。`
: p.cause === 'unreadable'
? `公開後に「${p.object}」を読み取れなかったため、「${p.object}」のサンプルデータを確認できませんでした。` +
`もう一度公開し、再び発生する場合は管理者にお問い合わせください。`
: `「${p.object}」のサンプルデータが読み込まれなかったため、「${p.object}」にはまだレコードがありません。` +
`サンプルデータを確認してから、もう一度公開してください。`,
ko: (p) =>
p.cause === 'unreadable'
p.cause === 'missing'
? `"${p.object}"이(가) 존재하지 않아 샘플 데이터를 불러오지 못했습니다. 샘플 데이터가 가리키는 개체를 ` +
`수정하거나 "${p.object}"을(를) 만들어 게시한 다음 다시 게시하세요.`
: p.cause === 'unreadable'
? `게시 후 "${p.object}"을(를) 읽을 수 없어 "${p.object}"의 샘플 데이터를 확인하지 못했습니다. ` +
`다시 게시하고, 문제가 반복되면 관리자에게 문의하세요.`
: `"${p.object}"의 샘플 데이터를 불러오지 못해 "${p.object}"에 아직 레코드가 없습니다. ` +
Expand Down
Loading
Loading