跳到主要内容
非官方简体中文翻译,内容版权归 Mastra 所有,遵循 Apache-2.0 许可。

Memory.settled()

The .settled() method resolves once background work the Memory instance started has finished. Some memory work continues after an agent run returns:

  • Observational memory cycles (buffered observation and reflection, including the nested agent runs they spawn)
  • Vector cleanup started by deleteThread() and deleteMessages()

Await this method before closing a storage connection you own. Without it, background statements can run against a closed connection. A scoped call can return while other threads still use the store, so call settled() without a scope before closing shared storage.

The method is declared on the base memory class, so it's also available on the MastraMemory instance returned by agent.getMemory(). The scope parameter is only on Memory from @mastra/memory.

Usage example
Usage example的直接链接

await agent.generate('Hello', {
memory: { thread: 'thread-123', resource: 'user-456' },
})

await memory.settled()
await store.close()

Parameters
Parameters的直接链接

scope?:

{ threadId?: string | null; resourceId?: string | null }
Waits only for observational memory work on this thread (or resource, when observational memory uses resource scope). If the scope omits the id observational memory is keyed on (threadId for thread scope, resourceId for resource scope), it waits for all work. Vector cleanup is always included.

Returns
Returns的直接链接

void:

Promise<void>
A promise that resolves when the requested background memory work has finished (all work, if unscoped). Background work that fails does not reject this promise.

Wait for one conversation
Wait for one conversation的直接链接

On a busy server, waiting for all work can take a long time because other threads keep starting new work. Pass a scope to wait for less. When observational memory uses thread scope, the call below waits for thread-123 only. When it uses resource scope, it waits for every thread under user-456:

await memory.settled({ threadId: 'thread-123', resourceId: 'user-456' })

Extended usage example
Extended usage example的直接链接

Test suites and short-lived processes are the most common places to need this, since they close the store immediately after a run finishes.

src/test-memory.ts
import { Memory } from '@mastra/memory'
import { PostgresStore } from '@mastra/pg'

const store = new PostgresStore({ connectionString })
const memory = new Memory({ storage: store })

// ... run your agent ...

// Wait for observational memory and vector cleanup to finish before closing.
await memory.settled()
await store.close()
备注

settled() joins the work that had started by the time you called it, plus any work that work enqueues. It doesn't prevent new work from starting afterwards, so call it once the agent runs you care about have returned.